Skip to content

Commit 536df08

Browse files
authored
Fix parsing when in detached HEAD state in Git::Lib#branches_all (#641)
Signed-off-by: James Couball <jcouball@yahoo.com>
1 parent 5c6833f commit 536df08

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

lib/git/lib.rb

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,11 @@ def change_head_branch(branch_name)
357357
)
358358
359359
# The branch's full refname
360-
(?<refname>[^[[:blank:]]]+)
360+
(?:
361+
(?<not_a_branch>\(not[[:blank:]]a[[:blank:]]branch\)) |
362+
(?:\(HEAD[[:blank:]]detached[[:blank:]]at[[:blank:]](?<detached_ref>[^\)]+)\)) |
363+
(?<refname>[^[[:blank:]]]+)
364+
)
361365
362366
# Optional symref
363367
# If this ref is a symbolic reference, this is the ref referenced
@@ -371,13 +375,14 @@ def branches_all
371375
command_lines('branch', '-a').map do |line|
372376
match_data = line.match(BRANCH_LINE_REGEXP)
373377
raise GitExecuteError, 'Unexpected branch line format' unless match_data
378+
next nil if match_data[:not_a_branch] || match_data[:detached_ref]
374379
[
375380
match_data[:refname],
376381
!match_data[:current].nil?,
377382
!match_data[:worktree].nil?,
378383
match_data[:symref]
379384
]
380-
end
385+
end.compact
381386
end
382387

383388
def worktrees_all

tests/units/test_branch.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,26 @@ def setup
5050
end
5151
end
5252

53+
test 'Git::Base#branchs with detached head' do
54+
in_temp_dir do
55+
git = Git.init('.', initial_branch: 'master')
56+
File.write('file1.txt', 'hello world')
57+
git.add('file1.txt')
58+
git.commit('Initial commit')
59+
git.add_tag('v1.0.0')
60+
File.write('file2.txt', 'hello world')
61+
git.add('file2.txt')
62+
git.commit('Second commit')
63+
64+
# This will put us in a detached head state
65+
git.checkout('v1.0.0')
66+
67+
branches = assert_nothing_raised { git.branches }
68+
assert_equal(1, branches.size)
69+
assert_equal('master', branches.first.name)
70+
end
71+
end
72+
5373
def test_branches_local
5474
bs = @git.branches.local
5575
assert(bs.size > 4)

0 commit comments

Comments
 (0)