From 81ea4f95a0a82506ccc350ead38ec7d290fad3cc Mon Sep 17 00:00:00 2001
From: Chongyi Zheng <harry@harryzheng.com>
Date: Wed, 2 Nov 2022 22:32:52 -0400
Subject: [PATCH] Handle branch name with prefix in GitHub migration (#20357)

GitHub allows releases with target commitish `refs/heads/BRANCH`, which
then causes issues in Gitea after migration. This fix handles cases that
a branch already has a prefix.

Fixes #20317

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
---
 services/migrations/github.go | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/services/migrations/github.go b/services/migrations/github.go
index 016d05886..e5683fb53 100644
--- a/services/migrations/github.go
+++ b/services/migrations/github.go
@@ -15,6 +15,7 @@ import (
 	"strings"
 	"time"
 
+	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/log"
 	base "code.gitea.io/gitea/modules/migration"
 	"code.gitea.io/gitea/modules/proxy"
@@ -307,10 +308,14 @@ func (g *GithubDownloaderV3) GetLabels() ([]*base.Label, error) {
 }
 
 func (g *GithubDownloaderV3) convertGithubRelease(rel *github.RepositoryRelease) *base.Release {
+	// GitHub allows commitish to be a reference.
+	// In this case, we need to remove the prefix, i.e. convert "refs/heads/main" to "main".
+	targetCommitish := strings.TrimPrefix(rel.GetTargetCommitish(), git.BranchPrefix)
+
 	r := &base.Release{
 		Name:            rel.GetName(),
 		TagName:         rel.GetTagName(),
-		TargetCommitish: rel.GetTargetCommitish(),
+		TargetCommitish: targetCommitish,
 		Draft:           rel.GetDraft(),
 		Prerelease:      rel.GetPrerelease(),
 		Created:         rel.GetCreatedAt().Time,