From f243744afbdb8eb86d7833bc37bac325cb4d4f18 Mon Sep 17 00:00:00 2001 From: Alexande B Date: Thu, 15 Jul 2021 14:28:02 +0200 Subject: [PATCH] #531 add API to get default branch Signed-off-by: Alexande B --- lib/git.rb | 8 ++++++++ lib/git/lib.rb | 14 ++++++++++++++ lib/git/remote.rb | 5 +++++ tests/units/test_git_path.rb | 3 +++ tests/units/test_lib.rb | 5 +++++ 5 files changed, 35 insertions(+) diff --git a/lib/git.rb b/lib/git.rb index 4ad1bd97..9d460f7b 100644 --- a/lib/git.rb +++ b/lib/git.rb @@ -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 diff --git a/lib/git/lib.rb b/lib/git/lib.rb index 2d6c129d..e5008b7e 100644 --- a/lib/git/lib.rb +++ b/lib/git/lib.rb @@ -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 diff --git a/lib/git/remote.rb b/lib/git/remote.rb index 73556a7c..91016c2a 100644 --- a/lib/git/remote.rb +++ b/lib/git/remote.rb @@ -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 diff --git a/tests/units/test_git_path.rb b/tests/units/test_git_path.rb index 6d4700ca..966368b3 100644 --- a/tests/units/test_git_path.rb +++ b/tests/units/test_git_path.rb @@ -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 diff --git a/tests/units/test_lib.rb b/tests/units/test_lib.rb index 8c8c420d..6bac55ba 100644 --- a/tests/units/test_lib.rb +++ b/tests/units/test_lib.rb @@ -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