git.rb 2.17 KB
Newer Older
1 2
module Gitlab
  module Git
3
    BLANK_SHA = ('0' * 40).freeze
4 5
    TAG_REF_PREFIX = "refs/tags/".freeze
    BRANCH_REF_PREFIX = "refs/heads/".freeze
6

7
    CommandError = Class.new(StandardError)
8
    CommitError = Class.new(StandardError)
9

10
    class << self
11 12
      include Gitlab::EncodingHelper

13
      def ref_name(ref)
14
        encode_utf8(ref).sub(/\Arefs\/(tags|heads|remotes)\//, '')
15 16
      end

17 18 19 20 21 22 23 24 25
      def branch_name(ref)
        ref = ref.to_s
        if self.branch_ref?(ref)
          self.ref_name(ref)
        else
          nil
        end
      end

26
      def committer_hash(email:, name:)
27 28
        return if email.nil? || name.nil?

29 30 31 32 33 34 35
        {
          email: email,
          name: name,
          time: Time.now
        }
      end

36 37 38 39 40 41 42 43 44
      def tag_name(ref)
        ref = ref.to_s
        if self.tag_ref?(ref)
          self.ref_name(ref)
        else
          nil
        end
      end

45 46 47 48 49 50 51 52 53 54 55
      def tag_ref?(ref)
        ref.start_with?(TAG_REF_PREFIX)
      end

      def branch_ref?(ref)
        ref.start_with?(BRANCH_REF_PREFIX)
      end

      def blank_ref?(ref)
        ref == BLANK_SHA
      end
56 57 58 59

      def version
        Gitlab::VersionInfo.parse(Gitlab::Popen.popen(%W(#{Gitlab.config.git.bin_path} --version)).first)
      end
60 61 62 63 64 65 66 67 68

      def check_namespace!(*objects)
        expected_namespace = self.name + '::'
        objects.each do |object|
          unless object.class.name.start_with?(expected_namespace)
            raise ArgumentError, "expected object in #{expected_namespace}, got #{object}"
          end
        end
      end
69 70 71 72

      def diff_line_code(file_path, new_line_position, old_line_position)
        "#{Digest::SHA1.hexdigest(file_path)}_#{old_line_position}_#{new_line_position}"
      end
73 74 75 76 77 78 79 80 81 82 83 84

      def shas_eql?(sha1, sha2)
        return false if sha1.nil? || sha2.nil?
        return false unless sha1.class == sha2.class

        # If either of the shas is below the minimum length, we cannot be sure
        # that they actually refer to the same commit because of hash collision.
        length = [sha1.length, sha2.length].min
        return false if length < Gitlab::Git::Commit::MIN_SHA_LENGTH

        sha1[0, length] == sha2[0, length]
      end
85
    end
86 87
  end
end