@@ -3,38 +3,55 @@ package git
3
3
import (
4
4
"fmt"
5
5
"github.com/go-git/go-git/v5"
6
+ "github.com/go-git/go-git/v5/config"
6
7
"github.com/go-git/go-git/v5/plumbing"
7
8
"github.com/neel1996/gitconvex-server/global"
8
9
"strings"
9
10
)
10
11
11
12
// CheckoutBranch checks out the branchName received as argument
12
13
func CheckoutBranch (repo * git.Repository , branchName string ) string {
14
+ var isRemoteBranch bool
13
15
logger := global.Logger {}
16
+ w , _ := repo .Worktree ()
14
17
15
18
if strings .Contains (branchName , "remotes/" ) {
16
19
splitRef := strings .Split (branchName , "/" )
17
20
branchName = "refs/heads/" + splitRef [len (splitRef )- 1 ]
21
+ isRemoteBranch = true
18
22
} else {
19
23
branchName = "refs/heads/" + branchName
20
24
}
21
25
22
- w , _ := repo .Worktree ()
26
+ // If the branch is a remote branch then a remote fetch will be performed and then the branch checkout will be initiated
27
+ if isRemoteBranch {
28
+ logger .Log (fmt .Sprintf ("Branch - %s is a remote branch\n Trying with intermediate remote fetch!" , branchName ), global .StatusWarning )
29
+ fetchErr := repo .Fetch (& git.FetchOptions {
30
+ RefSpecs : []config.RefSpec {config .RefSpec (branchName + ":" + branchName )},
31
+ })
32
+ if fetchErr != nil {
33
+ logger .Log ("Remote fetch failed -> " + fetchErr .Error (), global .StatusWarning )
34
+ }
35
+
36
+ checkoutErr := w .Checkout (& git.CheckoutOptions {
37
+ Branch : plumbing .ReferenceName (branchName ),
38
+ Force : true ,
39
+ })
40
+ if checkoutErr != nil {
41
+ logger .Log (checkoutErr .Error (), global .StatusError )
42
+ return "CHECKOUT_FAILED"
43
+ }
44
+ }
45
+
23
46
checkoutErr := w .Checkout (& git.CheckoutOptions {
24
47
Branch : plumbing .ReferenceName (branchName ),
25
48
Keep : true ,
26
49
})
27
50
if checkoutErr != nil {
28
- logger .Log (fmt .Sprintf ("Failed to checkout branch - %s --> %v\n Retrying with new branch creation!" , branchName , checkoutErr .Error ()), global .StatusWarning )
29
- err := w .Checkout (& git.CheckoutOptions {
30
- Branch : plumbing .ReferenceName (branchName ),
31
- Create : true ,
32
- Keep : true ,
33
- })
34
- if err != nil {
35
- return "CHECKOUT_FAILED"
36
- }
51
+ logger .Log (checkoutErr .Error (), global .StatusError )
52
+ return "CHECKOUT_FAILED"
37
53
}
54
+
38
55
logger .Log (fmt .Sprintf ("Current branch checked out to -> %s" , branchName ), global .StatusInfo )
39
56
return fmt .Sprintf ("Head checked out to branch - %v" , branchName )
40
57
}
0 commit comments