utils: add git_repository

This commit is contained in:
Seeker 2021-01-06 21:25:57 -08:00
parent 4e79550b03
commit 41e0619de8
5 changed files with 58 additions and 3 deletions

View File

@ -20,6 +20,7 @@ Style/Documentation:
- 'utils.rb'
- 'utils/fork.rb'
- 'utils/gems.rb'
- 'utils/git_repository.rb'
- 'utils/popen.rb'
- 'utils/shell.rb'
- 'version.rb'

View File

@ -40,11 +40,12 @@ module GitRepositoryExtension
end
# Gets a short commit hash of the HEAD commit.
sig { returns(T.nilable(String)) }
def git_short_head
sig { params(length: T.nilable(Integer)).returns(T.nilable(String)) }
def git_short_head(length: 4)
return unless git? && Utils::Git.available?
Utils.popen_read("git", "rev-parse", "--short=4", "--verify", "-q", "HEAD", chdir: self).chomp.presence
Utils.popen_read("git", "rev-parse", "--short#{length&.to_s&.prepend("=")}",
"--verify", "-q", "HEAD", chdir: self).chomp.presence
end
# Gets the relative date of the last commit, e.g. "1 hour ago"

View File

@ -0,0 +1,32 @@
# typed: false
# frozen_string_literal: true
require "utils/git_repository"
describe Utils do
before do
HOMEBREW_CACHE.cd do
system "git", "init"
Pathname("README.md").write("README")
system "git", "add", "README.md"
system "git", "commit", "-m", "File added"
end
end
let(:head_revision) { HOMEBREW_CACHE.cd { `git rev-parse HEAD`.chomp } }
let(:short_head_revision) { HOMEBREW_CACHE.cd { `git rev-parse --short HEAD`.chomp } }
describe ".git_head" do
it "returns the revision at HEAD" do
expect(described_class.git_head(HOMEBREW_CACHE)).to eq(head_revision)
expect(described_class.git_head(HOMEBREW_CACHE, length: 5)).to eq(head_revision[0...5])
end
end
describe ".git_short_head" do
it "returns the short revision at HEAD" do
expect(described_class.git_short_head(HOMEBREW_CACHE)).to eq(short_head_revision)
expect(described_class.git_short_head(HOMEBREW_CACHE, length: 5)).to eq(head_revision[0...5])
end
end
end

View File

@ -7,6 +7,7 @@ require "utils/fork"
require "utils/formatter"
require "utils/gems"
require "utils/git"
require "utils/git_repository"
require "utils/github"
require "utils/inreplace"
require "utils/link"

View File

@ -0,0 +1,20 @@
# typed: strict
# frozen_string_literal: true
module Utils
extend T::Sig
sig { params(repo: T.any(String, Pathname), length: T.nilable(Integer)).returns(T.nilable(String)) }
def self.git_head(repo, length: nil)
return git_short_head(repo, length: length) if length.present?
repo = Pathname(repo).extend(GitRepositoryExtension)
repo.git_head
end
sig { params(repo: T.any(String, Pathname), length: T.nilable(Integer)).returns(T.nilable(String)) }
def self.git_short_head(repo, length: nil)
repo = Pathname(repo).extend(GitRepositoryExtension)
repo.git_short_head(length: length)
end
end