repository.rb 30.3 KB
Newer Older
R
Robert Speicher 已提交
1 2 3 4 5 6 7
require 'tempfile'
require 'forwardable'
require "rubygems/package"

module Gitlab
  module Git
    class Repository
8
      include Gitlab::Git::RepositoryMirroring
9
      include Gitlab::EncodingHelper
10
      include Gitlab::Utils::StrongMemoize
R
Robert Speicher 已提交
11 12

      SEARCH_CONTEXT_LINES = 3
13
      REV_LIST_COMMIT_LIMIT = 2_000
14 15 16
      # In https://gitlab.com/gitlab-org/gitaly/merge_requests/698
      # We copied these two prefixes into gitaly-go, so don't change these
      # or things will break! (REBASE_WORKTREE_PREFIX and SQUASH_WORKTREE_PREFIX)
17 18
      REBASE_WORKTREE_PREFIX = 'rebase'.freeze
      SQUASH_WORKTREE_PREFIX = 'squash'.freeze
19
      GITALY_INTERNAL_URL = 'ssh://gitaly/internal.git'.freeze
20
      GITLAB_PROJECTS_TIMEOUT = Gitlab.config.gitlab_shell.git_timeout
21
      EMPTY_REPOSITORY_CHECKSUM = '0000000000000000000000000000000000000000'.freeze
R
Robert Speicher 已提交
22

23
      NoRepository = Class.new(StandardError)
24
      InvalidRepository = Class.new(StandardError)
25 26
      InvalidBlobName = Class.new(StandardError)
      InvalidRef = Class.new(StandardError)
27
      GitError = Class.new(StandardError)
28
      DeleteBranchError = Class.new(StandardError)
29
      CreateTreeError = Class.new(StandardError)
30
      TagExistsError = Class.new(StandardError)
31
      ChecksumError = Class.new(StandardError)
R
Robert Speicher 已提交
32

33
      class << self
34 35 36 37 38 39 40 41 42 43 44 45
        def create_hooks(repo_path, global_hooks_path)
          local_hooks_path = File.join(repo_path, 'hooks')
          real_local_hooks_path = :not_found

          begin
            real_local_hooks_path = File.realpath(local_hooks_path)
          rescue Errno::ENOENT
            # real_local_hooks_path == :not_found
          end

          # Do nothing if hooks already exist
          unless real_local_hooks_path == File.realpath(global_hooks_path)
R
Rémy Coutable 已提交
46 47 48 49 50 51
            if File.exist?(local_hooks_path)
              # Move the existing hooks somewhere safe
              FileUtils.mv(
                local_hooks_path,
                "#{local_hooks_path}.old.#{Time.now.to_i}")
            end
52 53 54

            # Create the hooks symlink
            FileUtils.ln_sf(global_hooks_path, local_hooks_path)
55 56 57 58 59 60
          end

          true
        end
      end

R
Robert Speicher 已提交
61 62 63
      # Directory name of repo
      attr_reader :name

64 65 66
      # Relative path of repo
      attr_reader :relative_path

67
      attr_reader :storage, :gl_repository, :relative_path
J
Jacob Vosmaer 已提交
68

69 70
      # This initializer method is only used on the client side (gitlab-ce).
      # Gitaly-ruby uses a different initializer.
71
      def initialize(storage, relative_path, gl_repository)
J
Jacob Vosmaer 已提交
72
        @storage = storage
73
        @relative_path = relative_path
74
        @gl_repository = gl_repository
75 76

        @name = @relative_path.split("/").last
R
Robert Speicher 已提交
77 78
      end

J
Jacob Vosmaer 已提交
79
      def ==(other)
80
        [storage, relative_path] == [other.storage, other.relative_path]
J
Jacob Vosmaer 已提交
81 82
      end

83
      # This method will be removed when Gitaly reaches v1.1.
84
      def path
85
        File.join(
86 87 88 89
          Gitlab.config.repositories.storages[@storage].legacy_disk_path, @relative_path
        )
      end

R
Robert Speicher 已提交
90 91
      # Default branch in the repository
      def root_ref
92 93 94 95 96
        gitaly_ref_client.default_branch_name
      rescue GRPC::NotFound => e
        raise NoRepository.new(e.message)
      rescue GRPC::Unknown => e
        raise Gitlab::Git::CommandError.new(e.message)
R
Robert Speicher 已提交
97 98
      end

99
      def exists?
100
        gitaly_repository_client.exists?
101 102
      end

R
Robert Speicher 已提交
103 104 105
      # Returns an Array of branch names
      # sorted by name ASC
      def branch_names
106 107
        wrapped_gitaly_errors do
          gitaly_ref_client.branch_names
108
        end
R
Robert Speicher 已提交
109 110 111
      end

      # Returns an Array of Branches
112
      def branches
113 114
        wrapped_gitaly_errors do
          gitaly_ref_client.branches
115
        end
R
Robert Speicher 已提交
116 117 118 119
      end

      # Directly find a branch with a simple name (e.g. master)
      #
J
Jacob Vosmaer 已提交
120 121 122
      def find_branch(name)
        wrapped_gitaly_errors do
          gitaly_ref_client.find_branch(name)
J
Jacob Vosmaer 已提交
123
        end
R
Robert Speicher 已提交
124 125
      end

126
      def local_branches(sort_by: nil)
127 128
        wrapped_gitaly_errors do
          gitaly_ref_client.local_branches(sort_by: sort_by)
R
Robert Speicher 已提交
129 130 131 132 133
        end
      end

      # Returns the number of valid branches
      def branch_count
J
Jacob Vosmaer 已提交
134 135
        wrapped_gitaly_errors do
          gitaly_ref_client.count_branch_names
136 137
        end
      end
R
Robert Speicher 已提交
138

139 140 141 142
      def expire_has_local_branches_cache
        clear_memoization(:has_local_branches)
      end

143
      def has_local_branches?
144 145 146 147 148
        strong_memoize(:has_local_branches) do
          uncached_has_local_branches?
        end
      end

149 150 151 152 153 154 155
      # Git repository can contains some hidden refs like:
      #   /refs/notes/*
      #   /refs/git-as-svn/*
      #   /refs/pulls/*
      # This refs by default not visible in project page and not cloned to client side.
      alias_method :has_visible_content?, :has_local_branches?

156 157
      # Returns the number of valid tags
      def tag_count
J
Jacob Vosmaer 已提交
158 159
        wrapped_gitaly_errors do
          gitaly_ref_client.count_tag_names
R
Robert Speicher 已提交
160 161 162 163 164
        end
      end

      # Returns an Array of tag names
      def tag_names
165 166 167
        wrapped_gitaly_errors do
          gitaly_ref_client.tag_names
        end
R
Robert Speicher 已提交
168 169 170
      end

      # Returns an Array of Tags
J
Jacob Vosmaer 已提交
171
      #
R
Robert Speicher 已提交
172
      def tags
173 174
        wrapped_gitaly_errors do
          gitaly_ref_client.tags
A
Ahmad Sherif 已提交
175
        end
R
Robert Speicher 已提交
176 177
      end

178 179 180 181
      # Returns true if the given ref name exists
      #
      # Ref names must start with `refs/`.
      def ref_exists?(ref_name)
J
Jacob Vosmaer 已提交
182 183
        wrapped_gitaly_errors do
          gitaly_ref_exists?(ref_name)
184 185 186
        end
      end

R
Robert Speicher 已提交
187 188 189 190
      # Returns true if the given tag exists
      #
      # name - The name of the tag as a String.
      def tag_exists?(name)
J
Jacob Vosmaer 已提交
191 192
        wrapped_gitaly_errors do
          gitaly_ref_exists?("refs/tags/#{name}")
193
        end
R
Robert Speicher 已提交
194 195 196 197 198 199
      end

      # Returns true if the given branch exists
      #
      # name - The name of the branch as a String.
      def branch_exists?(name)
J
Jacob Vosmaer 已提交
200 201
        wrapped_gitaly_errors do
          gitaly_ref_exists?("refs/heads/#{name}")
202
        end
R
Robert Speicher 已提交
203 204 205 206 207 208 209
      end

      # Returns an Array of branch and tag names
      def ref_names
        branch_names + tag_names
      end

210
      def delete_all_refs_except(prefixes)
J
Jacob Vosmaer 已提交
211 212
        wrapped_gitaly_errors do
          gitaly_ref_client.delete_refs(except_with_prefixes: prefixes)
213
        end
214 215
      end

216
      def archive_metadata(ref, storage_path, project_path, format = "tar.gz", append_sha:)
R
Robert Speicher 已提交
217 218 219 220
        ref ||= root_ref
        commit = Gitlab::Git::Commit.find(self, ref)
        return {} if commit.nil?

221
        prefix = archive_prefix(ref, commit.id, project_path, append_sha: append_sha)
R
Robert Speicher 已提交
222 223 224

        {
          'ArchivePrefix' => prefix,
225
          'ArchivePath' => archive_file_path(storage_path, commit.id, prefix, format),
226 227
          'CommitId' => commit.id,
          'GitalyRepository' => gitaly_repository.to_h
R
Robert Speicher 已提交
228 229 230
        }
      end

231 232
      # This is both the filename of the archive (missing the extension) and the
      # name of the top-level member of the archive under which all files go
233
      def archive_prefix(ref, sha, project_path, append_sha:)
234 235 236 237
        append_sha = (ref != sha) if append_sha.nil?

        formatted_ref = ref.tr('/', '-')

238
        prefix_segments = [project_path, formatted_ref]
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
        prefix_segments << sha if append_sha

        prefix_segments.join('-')
      end
      private :archive_prefix

      # The full path on disk where the archive should be stored. This is used
      # to cache the archive between requests.
      #
      # The path is a global namespace, so needs to be globally unique. This is
      # achieved by including `gl_repository` in the path.
      #
      # Archives relating to a particular ref when the SHA is not present in the
      # filename must be invalidated when the ref is updated to point to a new
      # SHA. This is achieved by including the SHA in the path.
      #
      # As this is a full path on disk, it is not "cloud native". This should
      # be resolved by either removing the cache, or moving the implementation
      # into Gitaly and removing the ArchivePath parameter from the git-archive
      # senddata response.
      def archive_file_path(storage_path, sha, name, format = "tar.gz")
R
Robert Speicher 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        # Build file path
        return nil unless name

        extension =
          case format
          when "tar.bz2", "tbz", "tbz2", "tb2", "bz2"
            "tar.bz2"
          when "tar"
            "tar"
          when "zip"
            "zip"
          else
            # everything else should fall back to tar.gz
            "tar.gz"
          end

        file_name = "#{name}.#{extension}"
277
        File.join(storage_path, self.gl_repository, sha, file_name)
R
Robert Speicher 已提交
278
      end
279
      private :archive_file_path
R
Robert Speicher 已提交
280 281 282

      # Return repo size in megabytes
      def size
283
        size = gitaly_repository_client.repository_size
284

R
Robert Speicher 已提交
285 286 287
        (size.to_f / 1024).round(2)
      end

288
      # Build an array of commits.
R
Robert Speicher 已提交
289 290 291 292 293 294 295 296 297 298
      #
      # Usage.
      #   repo.log(
      #     ref: 'master',
      #     path: 'app/models',
      #     limit: 10,
      #     offset: 5,
      #     after: Time.new(2016, 4, 21, 14, 32, 10)
      #   )
      def log(options)
299 300 301 302 303 304 305
        default_options = {
          limit: 10,
          offset: 0,
          path: nil,
          follow: false,
          skip_merges: false,
          after: nil,
T
Tiago Botelho 已提交
306 307
          before: nil,
          all: false
308 309 310 311 312
        }

        options = default_options.merge(options)
        options[:offset] ||= 0

313 314 315 316 317
        limit = options[:limit]
        if limit == 0 || !limit.is_a?(Integer)
          raise ArgumentError.new("invalid Repository#log limit: #{limit.inspect}")
        end

318 319
        wrapped_gitaly_errors do
          gitaly_commit_client.find_commits(options)
320
        end
R
Robert Speicher 已提交
321 322
      end

323
      def new_commits(newrev)
324 325
        wrapped_gitaly_errors do
          gitaly_ref_client.list_new_commits(newrev)
326 327 328
        end
      end

329
      def new_blobs(newrev)
330
        return [] if newrev.blank? || newrev == ::Gitlab::Git::BLANK_SHA
331 332 333 334 335 336 337 338

        strong_memoize("new_blobs_#{newrev}") do
          wrapped_gitaly_errors do
            gitaly_ref_client.list_new_blobs(newrev, REV_LIST_COMMIT_LIMIT)
          end
        end
      end

339
      def count_commits(options)
340
        options = process_count_commits_options(options.dup)
341

342 343 344 345 346 347 348 349 350 351 352
        wrapped_gitaly_errors do
          if options[:left_right]
            from = options[:from]
            to = options[:to]

            right_count = gitaly_commit_client
              .commit_count("#{from}..#{to}", options)
            left_count = gitaly_commit_client
              .commit_count("#{to}..#{from}", options)

            [left_count, right_count]
353
          else
354
            gitaly_commit_client.commit_count(options[:ref], options)
355 356
          end
        end
357 358
      end

R
Robert Speicher 已提交
359
      # Counts the amount of commits between `from` and `to`.
360 361
      def count_commits_between(from, to, options = {})
        count_commits(from: from, to: to, **options)
R
Robert Speicher 已提交
362 363
      end

R
Rubén Dávila 已提交
364 365 366
      # old_rev and new_rev are commit ID's
      # the result of this method is an array of Gitlab::Git::RawDiffChange
      def raw_changes_between(old_rev, new_rev)
367 368
        @raw_changes_between ||= {}

369 370 371
        @raw_changes_between[[old_rev, new_rev]] ||=
          begin
            return [] if new_rev.blank? || new_rev == Gitlab::Git::BLANK_SHA
372

373
            wrapped_gitaly_errors do
374 375 376 377 378
              gitaly_repository_client.raw_changes_between(old_rev, new_rev)
                .each_with_object([]) do |msg, arr|
                msg.raw_changes.each { |change| arr << ::Gitlab::Git::RawDiffChange.new(change) }
              end
            end
R
Rubén Dávila 已提交
379
          end
380 381
      rescue ArgumentError => e
        raise Gitlab::Git::Repository::GitError.new(e)
R
Rubén Dávila 已提交
382 383
      end

R
Robert Speicher 已提交
384
      # Returns the SHA of the most recent common ancestor of +from+ and +to+
385
      def merge_base(from, to)
386 387
        wrapped_gitaly_errors do
          gitaly_repository_client.find_merge_base(from, to)
388
        end
R
Robert Speicher 已提交
389 390
      end

391
      # Returns true is +from+ is direct ancestor to +to+, otherwise false
392
      def ancestor?(from, to)
393
        gitaly_commit_client.ancestor?(from, to)
394 395
      end

396
      def merged_branch_names(branch_names = [])
397 398 399 400 401 402
        return [] unless root_ref

        root_sha = find_branch(root_ref)&.target

        return [] unless root_sha

403 404
        branches = wrapped_gitaly_errors do
          gitaly_merged_branch_names(branch_names, root_sha)
405 406 407
        end

        Set.new(branches)
408 409
      end

R
Robert Speicher 已提交
410 411 412 413 414
      # Return an array of Diff objects that represent the diff
      # between +from+ and +to+.  See Diff::filter_diff_options for the allowed
      # diff options.  The +options+ hash can also include :break_rewrites to
      # split larger rewrites into delete/add pairs.
      def diff(from, to, options = {}, *paths)
415
        iterator = gitaly_commit_client.diff(from, to, options.merge(paths: paths))
416 417

        Gitlab::Git::DiffCollection.new(iterator, options)
R
Robert Speicher 已提交
418 419
      end

420 421 422 423 424 425
      def diff_stats(left_id, right_id)
        stats = wrapped_gitaly_errors do
          gitaly_commit_client.diff_stats(left_id, right_id)
        end

        Gitlab::Git::DiffStatsCollection.new(stats)
426
      rescue CommandError, TypeError
427 428
        Gitlab::Git::DiffStatsCollection.new([])
      end
R
Robert Speicher 已提交
429

430 431
      # Returns a RefName for a given SHA
      def ref_name_for_sha(ref_path, sha)
432 433
        raise ArgumentError, "sha can't be empty" unless sha.present?

434
        gitaly_ref_client.find_ref_name(sha, ref_path)
435 436
      end

437 438 439
      # Get refs hash which key is is the commit id
      # and value is a Gitlab::Git::Tag or Gitlab::Git::Branch
      # Note that both inherit from Gitlab::Git::Ref
R
Robert Speicher 已提交
440
      def refs_hash
441 442 443 444 445 446 447 448
        return @refs_hash if @refs_hash

        @refs_hash = Hash.new { |h, k| h[k] = [] }

        (tags + branches).each do |ref|
          next unless ref.target && ref.name

          @refs_hash[ref.dereferenced_target.id] << ref.name
R
Robert Speicher 已提交
449
        end
450

R
Robert Speicher 已提交
451 452 453
        @refs_hash
      end

454
      # Returns url for submodule
R
Robert Speicher 已提交
455 456
      #
      # Ex.
457 458
      #   @repository.submodule_url_for('master', 'rack')
      #   # => git@localhost:rack.git
R
Robert Speicher 已提交
459
      #
460
      def submodule_url_for(ref, path)
J
Jacob Vosmaer 已提交
461 462
        wrapped_gitaly_errors do
          gitaly_submodule_url_for(ref, path)
R
Robert Speicher 已提交
463 464 465 466 467
        end
      end

      # Return total commits count accessible from passed ref
      def commit_count(ref)
468 469
        wrapped_gitaly_errors do
          gitaly_commit_client.commit_count(ref)
470
        end
R
Robert Speicher 已提交
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
      end

      # Mimic the `git clean` command and recursively delete untracked files.
      # Valid keys that can be passed in the +options+ hash are:
      #
      # :d - Remove untracked directories
      # :f - Remove untracked directories that are managed by a different
      #      repository
      # :x - Remove ignored files
      #
      # The value in +options+ must evaluate to true for an option to take
      # effect.
      #
      # Examples:
      #
      #   repo.clean(d: true, f: true) # Enable the -d and -f options
      #
      #   repo.clean(d: false, x: true) # -x is enabled, -d is not
      def clean(options = {})
        strategies = [:remove_untracked]
        strategies.push(:force) if options[:f]
        strategies.push(:remove_ignored) if options[:x]

        # TODO: implement this method
      end

497
      def add_branch(branch_name, user:, target:)
498 499 500
        wrapped_gitaly_errors do
          gitaly_operation_client.user_create_branch(branch_name, user, target)
        end
501 502
      end

503
      def add_tag(tag_name, user:, target:, message: nil)
504 505
        wrapped_gitaly_errors do
          gitaly_operation_client.add_tag(tag_name, user, target, message)
506 507 508
        end
      end

509
      def update_branch(branch_name, user:, newrev:, oldrev:)
510 511
        wrapped_gitaly_errors do
          gitaly_operation_client.user_update_branch(branch_name, user, newrev, oldrev)
512
        end
513 514
      end

515
      def rm_branch(branch_name, user:)
516 517
        wrapped_gitaly_errors do
          gitaly_operation_client.user_delete_branch(branch_name, user)
518
        end
519 520
      end

521
      def rm_tag(tag_name, user:)
522 523
        wrapped_gitaly_errors do
          gitaly_operation_client.rm_tag(tag_name, user)
524
        end
525 526 527 528 529 530
      end

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

J
Jacob Vosmaer 已提交
531
      def merge(user, source_sha, target_branch, message, &block)
532 533
        wrapped_gitaly_errors do
          gitaly_operation_client.user_merge_branch(user, source_sha, target_branch, message, &block)
534 535 536
        end
      end

537
      def ff_merge(user, source_sha, target_branch)
538 539
        wrapped_gitaly_errors do
          gitaly_operation_client.user_ff_branch(user, source_sha, target_branch)
540 541 542
        end
      end

543
      def revert(user:, commit:, branch_name:, message:, start_branch_name:, start_repository:)
544 545 546 547 548 549 550 551
        args = {
          user: user,
          commit: commit,
          branch_name: branch_name,
          message: message,
          start_branch_name: start_branch_name,
          start_repository: start_repository
        }
552

553 554
        wrapped_gitaly_errors do
          gitaly_operation_client.user_revert(args)
555 556 557 558
        end
      end

      def cherry_pick(user:, commit:, branch_name:, message:, start_branch_name:, start_repository:)
559 560 561 562 563 564 565 566
        args = {
          user: user,
          commit: commit,
          branch_name: branch_name,
          message: message,
          start_branch_name: start_branch_name,
          start_repository: start_repository
        }
567

568 569
        wrapped_gitaly_errors do
          gitaly_operation_client.user_cherry_pick(args)
570 571 572
        end
      end

R
Robert Speicher 已提交
573 574
      # Delete the specified branch from the repository
      def delete_branch(branch_name)
J
Jacob Vosmaer 已提交
575 576
        wrapped_gitaly_errors do
          gitaly_ref_client.delete_branch(branch_name)
577
        end
J
Jacob Vosmaer 已提交
578
      rescue CommandError => e
579
        raise DeleteBranchError, e
R
Robert Speicher 已提交
580
      end
L
Lin Jen-Shin 已提交
581

582
      def delete_refs(*ref_names)
J
Jacob Vosmaer 已提交
583 584
        wrapped_gitaly_errors do
          gitaly_delete_refs(*ref_names)
585
        end
L
Lin Jen-Shin 已提交
586
      end
R
Robert Speicher 已提交
587 588 589 590 591 592 593

      # Create a new branch named **ref+ based on **stat_point+, HEAD by default
      #
      # Examples:
      #   create_branch("feature")
      #   create_branch("other-feature", "master")
      def create_branch(ref, start_point = "HEAD")
J
Jacob Vosmaer 已提交
594 595
        wrapped_gitaly_errors do
          gitaly_ref_client.create_branch(ref, start_point)
596
        end
R
Robert Speicher 已提交
597 598
      end

599 600
      # If `mirror_refmap` is present the remote is set as mirror with that mapping
      def add_remote(remote_name, url, mirror_refmap: nil)
601 602
        wrapped_gitaly_errors do
          gitaly_remote_client.add_remote(remote_name, url, mirror_refmap)
603
        end
R
Robert Speicher 已提交
604 605
      end

606
      def remove_remote(remote_name)
607 608
        wrapped_gitaly_errors do
          gitaly_remote_client.remove_remote(remote_name)
609
        end
610 611
      end

612 613 614 615 616 617 618 619
      def find_remote_root_ref(remote_name)
        return unless remote_name.present?

        wrapped_gitaly_errors do
          gitaly_remote_client.find_remote_root_ref(remote_name)
        end
      end

R
Robert Speicher 已提交
620 621 622 623 624 625
      # Returns result like "git ls-files" , recursive and full file path
      #
      # Ex.
      #   repo.ls_files('master')
      #
      def ls_files(ref)
626
        gitaly_commit_client.ls_files(ref)
R
Robert Speicher 已提交
627 628 629
      end

      def copy_gitattributes(ref)
J
Jacob Vosmaer 已提交
630 631
        wrapped_gitaly_errors do
          gitaly_repository_client.apply_gitattributes(ref)
R
Robert Speicher 已提交
632 633 634
        end
      end

635 636 637
      def info_attributes
        return @info_attributes if @info_attributes

638
        content = gitaly_repository_client.info_attributes
639 640 641
        @info_attributes = AttributesParser.new(content)
      end

R
Robert Speicher 已提交
642 643 644 645
      # Returns the Git attributes for the given file path.
      #
      # See `Gitlab::Git::Attributes` for more information.
      def attributes(path)
646
        info_attributes.attributes(path)
R
Robert Speicher 已提交
647 648
      end

S
Sean McGivern 已提交
649 650 651 652
      def gitattribute(path, name)
        attributes(path)[name]
      end

653 654 655 656 657
      # Check .gitattributes for a given ref
      #
      # This only checks the root .gitattributes file,
      # it does not traverse subfolders to find additional .gitattributes files
      #
658 659 660
      # This method is around 30 times slower than `attributes`, which uses
      # `$GIT_DIR/info/attributes`. Consider caching AttributesAtRefParser
      # and reusing that for multiple calls instead of this method.
661 662 663 664 665
      def attributes_at(ref, file_path)
        parser = AttributesAtRefParser.new(self, ref)
        parser.attributes(file_path)
      end

666
      def languages(ref = nil)
Z
Zeger-Jan van de Weg 已提交
667 668
        wrapped_gitaly_errors do
          gitaly_commit_client.languages(ref)
669 670 671
        end
      end

672
      def license_short_name
673 674
        wrapped_gitaly_errors do
          gitaly_repository_client.license_short_name
675 676 677
        end
      end

678
      def fetch_source_branch!(source_repository, source_branch, local_ref)
679 680
        wrapped_gitaly_errors do
          gitaly_repository_client.fetch_source_branch(source_repository, source_branch, local_ref)
681 682 683 684
        end
      end

      def compare_source_branch(target_branch_name, source_repository, source_branch_name, straight:)
685 686 687 688 689 690 691 692 693 694 695 696
        tmp_ref = "refs/tmp/#{SecureRandom.hex}"

        return unless fetch_source_branch!(source_repository, source_branch_name, tmp_ref)

        Gitlab::Git::Compare.new(
          self,
          target_branch_name,
          tmp_ref,
          straight: straight
        )
      ensure
        delete_refs(tmp_ref)
697 698
      end

699
      def write_ref(ref_path, ref, old_ref: nil, shell: true)
700 701
        ref_path = "#{Gitlab::Git::BRANCH_REF_PREFIX}#{ref_path}" unless ref_path.start_with?("refs/") || ref_path == "HEAD"

702 703
        wrapped_gitaly_errors do
          gitaly_repository_client.write_ref(ref_path, ref, old_ref, shell)
704 705 706
        end
      end

707 708 709 710 711
      # Refactoring aid; allows us to copy code from app/models/repository.rb
      def commit(ref = 'HEAD')
        Gitlab::Git::Commit.find(self, ref)
      end

712 713
      def empty?
        !has_visible_content?
714 715
      end

716
      def fetch_repository_as_mirror(repository)
717 718
        wrapped_gitaly_errors do
          gitaly_remote_client.fetch_internal_remote(repository)
719
        end
720 721
      end

722 723 724 725
      def blob_at(sha, path)
        Gitlab::Git::Blob.find(self, sha, path) unless Gitlab::Git.blank_ref?(sha)
      end

726
      # Items should be of format [[commit_id, path], [commit_id1, path1]]
727
      def batch_blobs(items, blob_size_limit: Gitlab::Git::Blob::MAX_DATA_DISPLAY_SIZE)
728 729 730
        Gitlab::Git::Blob.batch(self, items, blob_size_limit: blob_size_limit)
      end

731
      def fsck
732
        msg, status = gitaly_repository_client.fsck
733

734
        raise GitError.new("Could not fsck repository: #{msg}") unless status.zero?
735 736
      end

737
      def create_from_bundle(bundle_path)
738
        gitaly_repository_client.create_from_bundle(bundle_path)
739 740
      end

741 742 743 744
      def create_from_snapshot(url, auth)
        gitaly_repository_client.create_from_snapshot(url, auth)
      end

745
      def rebase(user, rebase_id, branch:, branch_sha:, remote_repository:, remote_branch:)
746 747 748 749 750 751
        wrapped_gitaly_errors do
          gitaly_operation_client.user_rebase(user, rebase_id,
                                            branch: branch,
                                            branch_sha: branch_sha,
                                            remote_repository: remote_repository,
                                            remote_branch: remote_branch)
752 753 754 755
        end
      end

      def rebase_in_progress?(rebase_id)
756 757
        wrapped_gitaly_errors do
          gitaly_repository_client.rebase_in_progress?(rebase_id)
758
        end
759 760 761
      end

      def squash(user, squash_id, branch:, start_sha:, end_sha:, author:, message:)
762 763
        wrapped_gitaly_errors do
          gitaly_operation_client.user_squash(user, squash_id, branch,
764
              start_sha, end_sha, author, message)
765 766 767 768
        end
      end

      def squash_in_progress?(squash_id)
769 770
        wrapped_gitaly_errors do
          gitaly_repository_client.squash_in_progress?(squash_id)
771
        end
772 773
      end

774
      def bundle_to_disk(save_path)
775 776
        wrapped_gitaly_errors do
          gitaly_repository_client.create_bundle(save_path)
777 778 779 780 781
        end

        true
      end

782 783 784 785 786
      def multi_action(
        user, branch_name:, message:, actions:,
        author_email: nil, author_name: nil,
        start_branch_name: nil, start_repository: self)

787 788
        wrapped_gitaly_errors do
          gitaly_operation_client.user_commit_files(user, branch_name,
789 790
              message, actions, author_email, author_name,
              start_branch_name, start_repository)
791 792 793
        end
      end

794
      def write_config(full_path:)
795 796
        return unless full_path.present?

797
        # This guard avoids Gitaly log/error spam
Z
Zeger-Jan van de Weg 已提交
798
        raise NoRepository, 'repository does not exist' unless exists?
799

800 801 802 803 804 805 806 807 808 809
        set_config('gitlab.fullpath' => full_path)
      end

      def set_config(entries)
        wrapped_gitaly_errors do
          gitaly_repository_client.set_config(entries)
        end
      end

      def delete_config(*keys)
Z
Zeger-Jan van de Weg 已提交
810
        wrapped_gitaly_errors do
811
          gitaly_repository_client.delete_config(keys)
812
        end
813 814
      end

815
      def gitaly_repository
816
        Gitlab::GitalyClient::Util.repository(@storage, @relative_path, @gl_repository)
817 818
      end

819 820 821 822 823 824
      def gitaly_ref_client
        @gitaly_ref_client ||= Gitlab::GitalyClient::RefService.new(self)
      end

      def gitaly_commit_client
        @gitaly_commit_client ||= Gitlab::GitalyClient::CommitService.new(self)
825 826 827 828
      end

      def gitaly_repository_client
        @gitaly_repository_client ||= Gitlab::GitalyClient::RepositoryService.new(self)
829 830
      end

831 832 833 834
      def gitaly_operation_client
        @gitaly_operation_client ||= Gitlab::GitalyClient::OperationService.new(self)
      end

835 836 837 838
      def gitaly_remote_client
        @gitaly_remote_client ||= Gitlab::GitalyClient::RemoteService.new(self)
      end

839 840 841 842
      def gitaly_blob_client
        @gitaly_blob_client ||= Gitlab::GitalyClient::BlobService.new(self)
      end

843 844
      def gitaly_conflicts_client(our_commit_oid, their_commit_oid)
        Gitlab::GitalyClient::ConflictsService.new(self, our_commit_oid, their_commit_oid)
845 846
      end

847 848
      def gitaly_migrate(method, status: Gitlab::GitalyClient::MigrationStatus::OPT_IN, &block)
        Gitlab::GitalyClient.migrate(method, status: status, &block)
849 850
      rescue GRPC::NotFound => e
        raise NoRepository.new(e)
851 852
      rescue GRPC::InvalidArgument => e
        raise ArgumentError.new(e)
853 854
      rescue GRPC::BadStatus => e
        raise CommandError.new(e)
855 856 857 858 859 860 861 862 863 864
      end

      def wrapped_gitaly_errors(&block)
        yield block
      rescue GRPC::NotFound => e
        raise NoRepository.new(e)
      rescue GRPC::InvalidArgument => e
        raise ArgumentError.new(e)
      rescue GRPC::BadStatus => e
        raise CommandError.new(e)
865 866
      end

867
      def clean_stale_repository_files
868 869
        wrapped_gitaly_errors do
          gitaly_repository_client.cleanup if exists?
870 871
        end
      rescue Gitlab::Git::CommandError => e # Don't fail if we can't cleanup
872
        Rails.logger.error("Unable to clean repository on storage #{storage} with relative path #{relative_path}: #{e.message}")
873 874 875 876 877 878
        Gitlab::Metrics.counter(
          :failed_repository_cleanup_total,
          'Number of failed repository cleanup events'
        ).increment
      end

879
      def branch_names_contains_sha(sha)
880
        gitaly_ref_client.branch_names_contains_sha(sha)
881
      end
882

883
      def tag_names_contains_sha(sha)
884
        gitaly_ref_client.tag_names_contains_sha(sha)
885 886 887 888 889
      end

      def search_files_by_content(query, ref)
        return [] if empty? || query.blank?

890 891 892
        safe_query = Regexp.escape(query)
        ref ||= root_ref

893
        gitaly_repository_client.search_files_by_content(ref, safe_query)
894 895
      end

896
      def can_be_merged?(source_sha, target_branch)
J
Jacob Vosmaer 已提交
897
        if target_sha = find_branch(target_branch)&.target
M
Mark Chao 已提交
898 899 900 901
          !gitaly_conflicts_client(source_sha, target_sha).conflicts?
        else
          false
        end
902 903
      end

904
      def search_files_by_name(query, ref)
905
        safe_query = Regexp.escape(query.sub(%r{^/*}, ""))
906
        ref ||= root_ref
907 908 909

        return [] if empty? || safe_query.blank?

910
        gitaly_repository_client.search_files_by_name(ref, safe_query)
911 912 913
      end

      def find_commits_by_message(query, ref, path, limit, offset)
914 915 916 917
        wrapped_gitaly_errors do
          gitaly_commit_client
            .commits_by_message(query, revision: ref, path: path, limit: limit, offset: offset)
            .map { |c| commit(c) }
918 919 920
        end
      end

921 922 923 924 925 926
      def list_last_commits_for_tree(sha, path, offset: 0, limit: 25)
        wrapped_gitaly_errors do
          gitaly_commit_client.list_last_commits_for_tree(sha, path, offset: offset, limit: limit)
        end
      end

927
      def last_commit_for_path(sha, path)
928 929
        wrapped_gitaly_errors do
          gitaly_commit_client.last_commit_for_path(sha, path)
930 931 932
        end
      end

933
      def checksum
934 935 936 937 938 939
        # The exists? RPC is much cheaper, so we perform this request first
        raise NoRepository, "Repository does not exists" unless exists?

        gitaly_repository_client.calculate_checksum
      rescue GRPC::NotFound
        raise NoRepository # Guard against data races.
940 941
      end

R
Robert Speicher 已提交
942 943
      private

944
      def uncached_has_local_branches?
945 946
        wrapped_gitaly_errors do
          gitaly_repository_client.has_local_branches?
947 948 949
        end
      end

950 951 952 953 954 955 956 957
      def gitaly_merged_branch_names(branch_names, root_sha)
        qualified_branch_names = branch_names.map { |b| "refs/heads/#{b}" }

        gitaly_ref_client.merged_branches(qualified_branch_names)
          .reject { |b| b.target == root_sha }
          .map(&:name)
      end

958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
      def process_count_commits_options(options)
        if options[:from] || options[:to]
          ref =
            if options[:left_right] # Compare with merge-base for left-right
              "#{options[:from]}...#{options[:to]}"
            else
              "#{options[:from]}..#{options[:to]}"
            end

          options.merge(ref: ref)

        elsif options[:ref] && options[:left_right]
          from, to = options[:ref].match(/\A([^\.]*)\.{2,3}([^\.]*)\z/)[1..2]

          options.merge(from: from, to: to)
        else
          options
        end
      end

978 979 980 981 982 983
      def gitaly_submodule_url_for(ref, path)
        # We don't care about the contents so 1 byte is enough. Can't request 0 bytes, 0 means unlimited.
        commit_object = gitaly_commit_client.tree_entry(ref, path, 1)

        return unless commit_object && commit_object.type == :COMMIT

C
Clement Ho 已提交
984
        gitmodules = gitaly_commit_client.tree_entry(ref, '.gitmodules', Gitlab::Git::Blob::MAX_DATA_DISPLAY_SIZE)
985 986
        return unless gitmodules

987 988 989 990 991
        found_module = GitmodulesParser.new(gitmodules.data).parse[path]

        found_module && found_module['url']
      end

992 993 994
      # Returns true if the given ref name exists
      #
      # Ref names must start with `refs/`.
995 996 997 998
      def gitaly_ref_exists?(ref_name)
        gitaly_ref_client.ref_exists?(ref_name)
      end

999 1000 1001 1002
      def gitaly_copy_gitattributes(revision)
        gitaly_repository_client.apply_gitattributes(revision)
      end

1003
      def gitaly_delete_refs(*ref_names)
1004
        gitaly_ref_client.delete_refs(refs: ref_names) if ref_names.any?
1005
      end
R
Robert Speicher 已提交
1006 1007 1008
    end
  end
end