Skip to content

Commit f243744

Browse files
committed
#531 add API to get default branch
Signed-off-by: Alexande B <abobrikovich@gmail.com>
1 parent 521b8e7 commit f243744

File tree

5 files changed

+35
-0
lines changed

5 files changed

+35
-0
lines changed

lib/git.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,4 +308,12 @@ def self.ls_remote(location = nil, options = {})
308308
def self.open(working_dir, options = {})
309309
Base.open(working_dir, options)
310310
end
311+
312+
# returns a String containing information about the default remote branch
313+
# of the target repository
314+
#
315+
# @param [String|NilClass] location the target repository location or nil for '.'
316+
def self.remote_default_branch(location = '.')
317+
Base.open(location).remote.default_branch
318+
end
311319
end

lib/git/lib.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,20 @@ def branch_current
399399
branches_all.select { |b| b[1] }.first[0] rescue nil
400400
end
401401

402+
def branch_default
403+
begin
404+
full_name = command("symbolic-ref", "refs/remotes/origin/HEAD")
405+
return full_name.gsub(%r{^refs/remotes/origin/}, "")
406+
rescue Git::GitExecuteError
407+
begin
408+
full_name = command("symbolic-ref", "refs/origin/HEAD")
409+
return full_name.gsub(%r{^refs/origin/}, "")
410+
rescue Git::GitExecuteError
411+
return command("symbolic-ref", "--short", "HEAD")
412+
end
413+
end
414+
end
415+
402416
def branch_contains(commit, branch_name="")
403417
command("branch", [branch_name, "--contains", commit])
404418
end

lib/git/remote.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ def branch(branch = 'master')
2727
def remove
2828
@base.lib.remote_remove(@name)
2929
end
30+
31+
# @return [String] name of default branch
32+
def default_branch
33+
@base.lib.branch_default
34+
end
3035

3136
def to_s
3237
@name

tests/units/test_git_path.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,7 @@ def test_readables_in_temp_dir
4444
end
4545
end
4646

47+
def test_default_branch
48+
assert_equal(@git.remote.default_branch, "git_grep")
49+
end
4750
end

tests/units/test_lib.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,4 +291,9 @@ def test_show
291291
assert(@lib.show('gitsearch1', 'scott/text.txt') == "hello\nthis is\na file\nthat is\nput here\nto search one\nto search two\nnothing!\n")
292292
end
293293

294+
def test_branch_default
295+
assert_equal(@lib.branch_default, "git_grep")
296+
@lib.change_head_branch("master")
297+
assert_equal(@lib.branch_default, "master")
298+
end
294299
end

0 commit comments

Comments
 (0)