Skip to content

Commit 2b06c10

Browse files
authored
Add support for HEAD ref in /src/branch and /src/commit routes (#27384)
Add support for HEAD in paths: ``` /src/branch/HEAD/README.md /src/commit/HEAD/README.md ``` Closes #26920
1 parent bc21723 commit 2b06c10

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

modules/context/repo.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -776,6 +776,8 @@ const (
776776
RepoRefBlob
777777
)
778778

779+
const headRefName = "HEAD"
780+
779781
// RepoRef handles repository reference names when the ref name is not
780782
// explicitly given
781783
func RepoRef() func(*Context) context.CancelFunc {
@@ -836,6 +838,14 @@ func getRefName(ctx *Base, repo *Repository, pathType RepoRefType) string {
836838
case RepoRefBranch:
837839
ref := getRefNameFromPath(ctx, repo, path, repo.GitRepo.IsBranchExist)
838840
if len(ref) == 0 {
841+
842+
// check if ref is HEAD
843+
parts := strings.Split(path, "/")
844+
if parts[0] == headRefName {
845+
repo.TreePath = strings.Join(parts[1:], "/")
846+
return repo.Repository.DefaultBranch
847+
}
848+
839849
// maybe it's a renamed branch
840850
return getRefNameFromPath(ctx, repo, path, func(s string) bool {
841851
b, exist, err := git_model.FindRenamedBranch(ctx, repo.Repository.ID, s)
@@ -864,6 +874,16 @@ func getRefName(ctx *Base, repo *Repository, pathType RepoRefType) string {
864874
repo.TreePath = strings.Join(parts[1:], "/")
865875
return parts[0]
866876
}
877+
878+
if len(parts) > 0 && parts[0] == headRefName {
879+
// HEAD ref points to last default branch commit
880+
commit, err := repo.GitRepo.GetBranchCommit(repo.Repository.DefaultBranch)
881+
if err != nil {
882+
return ""
883+
}
884+
repo.TreePath = strings.Join(parts[1:], "/")
885+
return commit.ID.String()
886+
}
867887
case RepoRefBlob:
868888
_, err := repo.GitRepo.GetBlob(path)
869889
if err != nil {

tests/integration/repo_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,10 @@ func TestViewRepoDirectoryReadme(t *testing.T) {
302302
check("plain", "/user2/readme-test/src/branch/plain/", "README", "plain-text", "Birken my stocks gee howdy")
303303
check("i18n", "/user2/readme-test/src/branch/i18n/", "README.zh.md", "markdown", "蛋糕是一个谎言")
304304

305+
// using HEAD ref
306+
check("branch-HEAD", "/user2/readme-test/src/branch/HEAD/", "README.md", "markdown", "The cake is a lie.")
307+
check("commit-HEAD", "/user2/readme-test/src/commit/HEAD/", "README.md", "markdown", "The cake is a lie.")
308+
305309
// viewing different subdirectories
306310
check("subdir", "/user2/readme-test/src/branch/subdir/libcake", "README.md", "markdown", "Four pints of sugar.")
307311
check("docs-direct", "/user2/readme-test/src/branch/special-subdir-docs/docs/", "README.md", "markdown", "This is in docs/")

0 commit comments

Comments
 (0)