fix: parse HEAD ref (#38119)

backport #38088
This commit is contained in:
Lunny Xiao
2026-06-14 12:52:44 -07:00
committed by GitHub
parent 98cc15b307
commit bb4cccc6e9
4 changed files with 30 additions and 3 deletions

View File

@@ -161,7 +161,7 @@ func (ref RefName) ShortName() string {
if ref.IsFor() {
return ref.ForBranchName()
}
return string(ref) // usually it is a commit ID
return string(ref) // usually it is a commit ID, or "HEAD"
}
// RefGroup returns the group type of the reference

View File

@@ -8,6 +8,7 @@ import (
"strings"
"code.gitea.io/gitea/modules/git/gitcmd"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
)
@@ -86,8 +87,11 @@ func (repo *Repository) UnstableGuessRefByShortName(shortName string) RefName {
commit, err := repo.GetCommit(shortName)
if err == nil {
commitIDString := commit.ID.String()
if strings.HasPrefix(commitIDString, shortName) {
// Make sure the short name is either a partial commit ID, or the symbolic HEAD ref.
if strings.HasPrefix(commitIDString, shortName) || shortName == "HEAD" {
return RefName(commitIDString)
} else {
setting.PanicInDevOrTesting("abuse of UnstableGuessRefByShortName, queried %s, got %s", shortName, commitIDString)
}
}
return ""

View File

@@ -53,3 +53,18 @@ func TestRepository_GetRefsFiltered(t *testing.T) {
assert.Equal(t, "3ad28a9149a2864384548f3d17ed7f38014c9e8a", refs[1].Object.String())
}
}
func TestRepository_UnstableGuessRefByShortName(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer bareRepo1.Close()
headCommit, err := bareRepo1.GetCommit("HEAD")
assert.NoError(t, err)
assert.Equal(t, RefName(headCommit.ID.String()), bareRepo1.UnstableGuessRefByShortName("HEAD"))
assert.Equal(t, RefName(headCommit.ID.String()), bareRepo1.UnstableGuessRefByShortName(headCommit.ID.String()[:8]))
assert.Equal(t, RefNameFromBranch("master"), bareRepo1.UnstableGuessRefByShortName("master"))
assert.Empty(t, bareRepo1.UnstableGuessRefByShortName("NotExisting"))
}

View File

@@ -36,9 +36,17 @@ func TestCompareTag(t *testing.T) {
// A dropdown for both base and head.
assert.Lenf(t, selection.Nodes, 2, "The template has changed")
req = NewRequest(t, "GET", "/user2/repo1/compare/v1.1...HEAD")
resp = session.MakeRequest(t, req, http.StatusOK)
assert.True(t, test.IsNormalPageCompleted(resp.Body.String()))
req = NewRequest(t, "GET", "/user2/repo1/compare/v1.1...NotExisting").SetHeader("Accept", "text/html")
resp = session.MakeRequest(t, req, http.StatusNotFound)
assert.True(t, test.IsNormalPageCompleted(resp.Body.String()))
req = NewRequest(t, "GET", "/user2/repo1/compare/invalid").SetHeader("Accept", "text/html")
resp = session.MakeRequest(t, req, http.StatusNotFound)
assert.True(t, test.IsNormalPageCompleted(resp.Body.String()), "expect 404 page not 500")
assert.True(t, test.IsNormalPageCompleted(resp.Body.String()))
}
// Compare with inferred default branch (master)