Skip to content

Commit abb1df6

Browse files
authored
Display git status of detached HEAD correctly (#209)
* Display `git status` of detached HEAD correctly * Fix wasm test
1 parent 7fb54e1 commit abb1df6

4 files changed

Lines changed: 222 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: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ def test_status_untracked_directory(repo_init_with_commit, git2cpp_path, tmp_pat
253253
p = subprocess.run(cmd_status, capture_output=True, cwd=tmp_path, text=True)
254254

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

0 commit comments

Comments
 (0)