Skip to content

Fix parsing when in detached HEAD state in Git::Lib#branches_all #641

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions lib/git/lib.rb
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,11 @@ def change_head_branch(branch_name)
)

# The branch's full refname
(?<refname>[^[[:blank:]]]+)
(?:
(?<not_a_branch>\(not[[:blank:]]a[[:blank:]]branch\)) |
(?:\(HEAD[[:blank:]]detached[[:blank:]]at[[:blank:]](?<detached_ref>[^\)]+)\)) |
(?<refname>[^[[:blank:]]]+)
)

# Optional symref
# If this ref is a symbolic reference, this is the ref referenced
Expand All @@ -371,13 +375,14 @@ def branches_all
command_lines('branch', '-a').map do |line|
match_data = line.match(BRANCH_LINE_REGEXP)
raise GitExecuteError, 'Unexpected branch line format' unless match_data
next nil if match_data[:not_a_branch] || match_data[:detached_ref]
[
match_data[:refname],
!match_data[:current].nil?,
!match_data[:worktree].nil?,
match_data[:symref]
]
end
end.compact
end

def worktrees_all
Expand Down
20 changes: 20 additions & 0 deletions tests/units/test_branch.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,26 @@ def setup
end
end

test 'Git::Base#branchs with detached head' do
in_temp_dir do
git = Git.init('.', initial_branch: 'master')
File.write('file1.txt', 'hello world')
git.add('file1.txt')
git.commit('Initial commit')
git.add_tag('v1.0.0')
File.write('file2.txt', 'hello world')
git.add('file2.txt')
git.commit('Second commit')

# This will put us in a detached head state
git.checkout('v1.0.0')

branches = assert_nothing_raised { git.branches }
assert_equal(1, branches.size)
assert_equal('master', branches.first.name)
end
end

def test_branches_local
bs = @git.branches.local
assert(bs.size > 4)
Expand Down