@@ -6,6 +6,7 @@ package git
66import (
77 "context"
88 "regexp"
9+ "strconv"
910 "strings"
1011
1112 "gitea.dev/modules/git/gitcmd"
@@ -18,6 +19,7 @@ const (
1819 RemotePrefix = "refs/remotes/"
1920 // PullPrefix is the base directory of the pull information of git.
2021 PullPrefix = "refs/pull/"
22+ pullSuffix = "/head"
2123)
2224
2325// refNamePatternInvalid is regular expression with unallowed characters in git reference name
@@ -93,6 +95,10 @@ func RefNameFromCommit(shortName string) RefName {
9395 return RefName (shortName )
9496}
9597
98+ func RefNameFromPullIndex (prIndex int64 ) RefName {
99+ return RefName (PullPrefix + strconv .FormatInt (prIndex , 10 ) + pullSuffix )
100+ }
101+
96102func (ref RefName ) String () string {
97103 return string (ref )
98104}
@@ -134,14 +140,21 @@ func (ref RefName) BranchName() string {
134140 return ref .nameWithoutPrefix (BranchPrefix )
135141}
136142
137- // PullName returns the pull request name part of refs like refs/pull/<pull_name>/head
138- func (ref RefName ) PullName () string {
143+ func (ref RefName ) PullIndex () (int64 , bool ) {
139144 refName := string (ref )
140- lastIdx := strings .LastIndexByte (refName [ len ( PullPrefix ):], '/' )
141- if strings . HasPrefix ( refName , PullPrefix ) && lastIdx > - 1 {
142- return refName [ len ( PullPrefix ) : lastIdx + len ( PullPrefix )]
145+ s , ok := strings .CutPrefix (refName , PullPrefix )
146+ if ! ok {
147+ return 0 , false
143148 }
144- return ""
149+ pullStr , last , ok := strings .CutLast (s , "/" )
150+ if ! ok || last != "head" {
151+ return 0 , false
152+ }
153+ pullIndex , err := strconv .ParseInt (pullStr , 10 , 64 )
154+ if err != nil {
155+ return 0 , false
156+ }
157+ return pullIndex , true
145158}
146159
147160// ForBranchName returns the branch name part of refs like refs/for/<branch_name>
@@ -165,7 +178,7 @@ func (ref RefName) ShortName() string {
165178 return ref .RemoteName ()
166179 }
167180 if ref .IsPull () {
168- return ref .PullName ( )
181+ return strings . TrimSuffix ( ref .nameWithoutPrefix ( PullPrefix ), pullSuffix )
169182 }
170183 if ref .IsFor () {
171184 return ref .ForBranchName ()
0 commit comments