Skip to content

Commit

Permalink
#531 add API to get default branch
Browse files Browse the repository at this point in the history
Signed-off-by: Alexande B <abobrikovich@gmail.com>
  • Loading branch information
CAMOBAP committed Jan 31, 2022
1 parent 521b8e7 commit f243744
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/git.rb
Original file line number Diff line number Diff line change
Expand Up @@ -308,4 +308,12 @@ def self.ls_remote(location = nil, options = {})
def self.open(working_dir, options = {})
Base.open(working_dir, options)
end

# returns a String containing information about the default remote branch
# of the target repository
#
# @param [String|NilClass] location the target repository location or nil for '.'
def self.remote_default_branch(location = '.')
Base.open(location).remote.default_branch
end
end
14 changes: 14 additions & 0 deletions lib/git/lib.rb
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,20 @@ def branch_current
branches_all.select { |b| b[1] }.first[0] rescue nil
end

def branch_default
begin
full_name = command("symbolic-ref", "refs/remotes/origin/HEAD")
return full_name.gsub(%r{^refs/remotes/origin/}, "")
rescue Git::GitExecuteError
begin
full_name = command("symbolic-ref", "refs/origin/HEAD")
return full_name.gsub(%r{^refs/origin/}, "")
rescue Git::GitExecuteError
return command("symbolic-ref", "--short", "HEAD")
end
end
end

def branch_contains(commit, branch_name="")
command("branch", [branch_name, "--contains", commit])
end
Expand Down
5 changes: 5 additions & 0 deletions lib/git/remote.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ def branch(branch = 'master')
def remove
@base.lib.remote_remove(@name)
end

# @return [String] name of default branch
def default_branch
@base.lib.branch_default
end

def to_s
@name
Expand Down
3 changes: 3 additions & 0 deletions tests/units/test_git_path.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,7 @@ def test_readables_in_temp_dir
end
end

def test_default_branch
assert_equal(@git.remote.default_branch, "git_grep")
end
end
5 changes: 5 additions & 0 deletions tests/units/test_lib.rb
Original file line number Diff line number Diff line change
Expand Up @@ -291,4 +291,9 @@ def test_show
assert(@lib.show('gitsearch1', 'scott/text.txt') == "hello\nthis is\na file\nthat is\nput here\nto search one\nto search two\nnothing!\n")
end

def test_branch_default
assert_equal(@lib.branch_default, "git_grep")
@lib.change_head_branch("master")
assert_equal(@lib.branch_default, "master")
end
end

0 comments on commit f243744

Please sign in to comment.