Skip to content

Commit ab6ef94

Browse files
committed
Display git status of detached HEAD correctly
1 parent dc98333 commit ab6ef94

4 files changed

Lines changed: 221 additions & 5 deletions

File tree

‎src/subcommand/status_subcommand.cpp‎

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ namespace
259259
std::sort(untracked_items.begin(), untracked_items.end());
260260
for (const auto& it : untracked_items)
261261
{
262-
std::cout << colour << "?? " << termcolor::reset << it << std::endl;
262+
std::cout << colour << "??" << termcolor::reset << " " << it << std::endl;
263263
}
264264

265265
std::sort(ignored_items.begin(), ignored_items.end());
@@ -425,8 +425,8 @@ void print_tracking_info(repository_wrapper& repo, status_list_wrapper& sl, bool
425425
}
426426
std::cout << "]";
427427
}
428-
std::cout << std::endl;
429428
}
429+
std::cout << std::endl;
430430
}
431431
}
432432

@@ -618,18 +618,41 @@ void status_run(status_subcommand_options options)
618618
bool is_long;
619619
is_long = ((of == output_format::DEFAULT) || (of == output_format::LONG));
620620

621-
auto branch_name = repo.head_short_name();
621+
bool is_detached = repo.is_head_detached();
622+
std::string branch_name = is_detached ? "HEAD (no branch)" : repo.head_short_name();
622623
bool is_coloured = true;
623624
bool branch_flag = options.m_branch_flag;
624625
if (is_long)
625626
{
626-
std::cout << "On branch " << branch_name << std::endl;
627+
if (is_detached)
628+
{
629+
if (auto info = repo.get_detached_head_info())
630+
{
631+
std::cout << termcolor::red << "HEAD detached " << (info->is_at ? "at " : "from ")
632+
<< termcolor::reset << info->name << std::endl;
633+
}
634+
else
635+
{
636+
std::cout << termcolor::red << "Not currently on any branch." << termcolor::reset << std::endl;
637+
}
638+
}
639+
else
640+
{
641+
std::cout << "On branch " << branch_name << std::endl;
642+
}
627643
}
628644
else if (branch_flag)
629645
{
630646
if (is_coloured)
631647
{
632-
std::cout << "## " << termcolor::green << branch_name << termcolor::reset;
648+
if (is_detached)
649+
{
650+
std::cout << "## " << termcolor::red << branch_name << termcolor::reset;
651+
}
652+
else
653+
{
654+
std::cout << "## " << termcolor::green << branch_name << termcolor::reset;
655+
}
633656
}
634657
else
635658
{

‎src/wrapper/repository_wrapper.cpp‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,78 @@ bool repository_wrapper::is_head_unborn() const
9898
return git_repository_head_unborn(*this) == 1;
9999
}
100100

101+
bool repository_wrapper::is_head_detached() const
102+
{
103+
return git_repository_head_detached(*this) == 1;
104+
}
105+
106+
std::optional<repository_wrapper::detached_head_info> repository_wrapper::get_detached_head_info() const
107+
{
108+
git_reflog* reflog = nullptr;
109+
throw_if_error(git_reflog_read(&reflog, *this, "HEAD"));
110+
111+
std::optional<detached_head_info> result;
112+
constexpr std::string_view prefix = "checkout: moving from ";
113+
const size_t count = git_reflog_entrycount(reflog);
114+
for (size_t i = 0; i < count; ++i) // index 0 is the most recent entry
115+
{
116+
const git_reflog_entry* entry = git_reflog_entry_byindex(reflog, i);
117+
const char* msg = git_reflog_entry_message(entry);
118+
if (msg == nullptr)
119+
{
120+
continue;
121+
}
122+
std::string_view message(msg);
123+
if (!message.starts_with(prefix))
124+
{
125+
continue;
126+
}
127+
auto to_pos = message.find(" to ", prefix.size());
128+
if (to_pos == std::string_view::npos)
129+
{
130+
continue;
131+
}
132+
std::string target(message.substr(to_pos + 4));
133+
if (auto nl = target.find('\n'); nl != std::string::npos)
134+
{
135+
target.erase(nl);
136+
}
137+
138+
const git_oid new_oid = *git_reflog_entry_id_new(entry);
139+
auto checked_out = this->find_commit(new_oid);
140+
141+
detached_head_info info;
142+
// As in git, a checkout to "HEAD" is relative, so use the abbreviated SHA instead
143+
auto ref = (target == "HEAD") ? std::nullopt : this->find_reference_dwim(target);
144+
if (ref && git_oid_equal(&ref->peel<commit_wrapper>().oid(), &new_oid))
145+
{
146+
std::string_view name = git_reference_name(*ref);
147+
for (std::string_view p : {"refs/tags/", "refs/remotes/"})
148+
{
149+
if (name.starts_with(p))
150+
{
151+
name.remove_prefix(p.size());
152+
break;
153+
}
154+
}
155+
info.name = name;
156+
}
157+
else
158+
{
159+
git_buf abbrev = GIT_BUF_INIT;
160+
throw_if_error(git_object_short_id(&abbrev, checked_out));
161+
info.name = abbrev.ptr;
162+
git_buf_dispose(&abbrev);
163+
}
164+
info.is_at = git_oid_equal(&new_oid, &this->find_commit("HEAD").oid());
165+
result = info;
166+
break;
167+
}
168+
169+
git_reflog_free(reflog);
170+
return result;
171+
}
172+
101173
reference_wrapper repository_wrapper::head() const
102174
{
103175
git_reference* ref;

‎src/wrapper/repository_wrapper.hpp‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,15 @@ class repository_wrapper : public wrapper_base<git_repository>
5858

5959
// Head
6060
bool is_head_unborn() const;
61+
bool is_head_detached() const;
62+
63+
struct detached_head_info
64+
{
65+
std::string name; // e.g. "v1.0", "origin/main", or an abbreviated SHA
66+
bool is_at; // true: "detached at", false: "detached from"
67+
};
68+
69+
std::optional<detached_head_info> get_detached_head_info() const;
6170
reference_wrapper head() const;
6271
std::string head_short_name() const;
6372

‎test/test_status.py‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,3 +427,115 @@ def test_status_modified_staged_then_modified(repo_init_with_commit, git2cpp_pat
427427
assert "Changes not staged for commit" in out
428428
# Ensure the filename appears (it should appear in one or both sections)
429429
assert "initial.txt" in out
430+
431+
432+
def test_status_detached_at_tag(repo_init_with_commit, git2cpp_path, tmp_path):
433+
subprocess.run([git2cpp_path, "tag", "v1.0"], cwd=tmp_path, check=True)
434+
subprocess.run([git2cpp_path, "checkout", "v1.0"], cwd=tmp_path, check=True)
435+
436+
p = subprocess.run(
437+
[git2cpp_path, "status"], capture_output=True, cwd=tmp_path, text=True, check=True
438+
)
439+
out = strip_ansi_colours(p.stdout)
440+
assert out.splitlines()[0] == "HEAD detached at v1.0"
441+
assert "On branch" not in out
442+
443+
444+
def test_status_detached_at_sha(repo_init_with_commit, git2cpp_path, tmp_path):
445+
p_sha = subprocess.run(
446+
[git2cpp_path, "rev-parse", "HEAD"],
447+
capture_output=True,
448+
cwd=tmp_path,
449+
text=True,
450+
check=True,
451+
)
452+
sha = p_sha.stdout.strip()
453+
subprocess.run([git2cpp_path, "checkout", sha], cwd=tmp_path, check=True)
454+
455+
p = subprocess.run(
456+
[git2cpp_path, "status"], capture_output=True, cwd=tmp_path, text=True, check=True
457+
)
458+
out = strip_ansi_colours(p.stdout)
459+
assert out.splitlines()[0] == f"HEAD detached at {sha[:7]}"
460+
assert "On branch" not in out
461+
462+
463+
def test_status_detached_from(repo_init_with_commit, git2cpp_path, tmp_path):
464+
subprocess.run([git2cpp_path, "tag", "v1.0"], cwd=tmp_path, check=True)
465+
subprocess.run([git2cpp_path, "checkout", "v1.0"], cwd=tmp_path, check=True)
466+
467+
second = tmp_path / "second.txt"
468+
second.write_text("second")
469+
subprocess.run([git2cpp_path, "add", "second.txt"], cwd=tmp_path, check=True)
470+
subprocess.run([git2cpp_path, "commit", "-m", "Second commit"], cwd=tmp_path, check=True)
471+
472+
p = subprocess.run(
473+
[git2cpp_path, "status"], capture_output=True, cwd=tmp_path, text=True, check=True
474+
)
475+
out = strip_ansi_colours(p.stdout)
476+
assert out.splitlines()[0] == "HEAD detached from v1.0"
477+
assert "On branch" not in out
478+
479+
480+
def test_status_detached_at_remote_branch(commit_env_config, git2cpp_path, tmp_path):
481+
repo_path = tmp_path / "repo"
482+
repo_path.mkdir()
483+
subprocess.run([git2cpp_path, "init", "-b", "main"], cwd=repo_path, check=True)
484+
(repo_path / "file.txt").write_text("initial")
485+
subprocess.run([git2cpp_path, "add", "file.txt"], cwd=repo_path, check=True)
486+
subprocess.run([git2cpp_path, "commit", "-m", "initial"], cwd=repo_path, check=True)
487+
488+
clone_path = tmp_path / "clone"
489+
subprocess.run([git2cpp_path, "clone", str(repo_path), str(clone_path)], check=True)
490+
subprocess.run([git2cpp_path, "checkout", "origin/main"], cwd=clone_path, check=True)
491+
492+
p = subprocess.run(
493+
[git2cpp_path, "status"], capture_output=True, cwd=clone_path, text=True, check=True
494+
)
495+
out = strip_ansi_colours(p.stdout)
496+
assert out.splitlines()[0] == "HEAD detached at origin/main"
497+
assert "On branch" not in out
498+
499+
500+
def test_status_detached_no_reflog(repo_init_with_commit, git2cpp_path, tmp_path):
501+
p_sha = subprocess.run(
502+
[git2cpp_path, "rev-parse", "HEAD"],
503+
capture_output=True,
504+
cwd=tmp_path,
505+
text=True,
506+
check=True,
507+
)
508+
sha = p_sha.stdout.strip()
509+
subprocess.run([git2cpp_path, "checkout", sha], cwd=tmp_path, check=True)
510+
os.remove(tmp_path / ".git" / "logs" / "HEAD")
511+
512+
p = subprocess.run(
513+
[git2cpp_path, "status"], capture_output=True, cwd=tmp_path, text=True, check=True
514+
)
515+
out = strip_ansi_colours(p.stdout)
516+
assert out.splitlines()[0] == "Not currently on any branch."
517+
assert "On branch" not in out
518+
519+
520+
def test_status_short_branch_detached(repo_init_with_commit, git2cpp_path, tmp_path):
521+
subprocess.run([git2cpp_path, "tag", "v1.0"], cwd=tmp_path, check=True)
522+
subprocess.run([git2cpp_path, "checkout", "v1.0"], cwd=tmp_path, check=True)
523+
524+
p = subprocess.run(
525+
[git2cpp_path, "status", "-sb"], capture_output=True, cwd=tmp_path, text=True, check=True
526+
)
527+
assert strip_ansi_colours(p.stdout) == "## HEAD (no branch)\n"
528+
529+
530+
@pytest.mark.parametrize("dirty", [False, True])
531+
def test_status_short_branch_newline(repo_init_with_commit, git2cpp_path, tmp_path, dirty):
532+
if dirty:
533+
(tmp_path / "new.txt").write_text("new")
534+
expected = "## main\n?? new.txt\n"
535+
else:
536+
expected = "## main\n"
537+
538+
p = subprocess.run(
539+
[git2cpp_path, "status", "-sb"], capture_output=True, cwd=tmp_path, text=True, check=True
540+
)
541+
assert strip_ansi_colours(p.stdout) == expected

0 commit comments

Comments
 (0)