@@ -3,48 +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"
7
6
"github.com/go-git/go-git/v5/plumbing"
8
7
"github.com/neel1996/gitconvex-server/global"
9
8
"strings"
10
9
)
11
10
11
+ // intermediateFetch performs a remote fetch if the selected checkout branch is a remote branch
12
+ func intermediateFetch (repo * git.Repository , branchName string ) {
13
+ logger .Log ("Fetching from remote for remote branch -> " + branchName , global .StatusInfo )
14
+ remoteChan := make (chan RemoteDataModel )
15
+ go RemoteData (repo , remoteChan )
16
+ remoteData := <- remoteChan
17
+ remoteURL := remoteData .RemoteURL
18
+ FetchFromRemote (repo , * remoteURL [0 ], branchName )
19
+ }
20
+
12
21
// CheckoutBranch checks out the branchName received as argument
13
22
func CheckoutBranch (repo * git.Repository , branchName string ) string {
14
23
var isRemoteBranch bool
24
+ var referenceBranchName string
25
+
15
26
logger := global.Logger {}
16
27
w , _ := repo .Worktree ()
17
28
18
29
if strings .Contains (branchName , "remotes/" ) {
19
30
splitRef := strings .Split (branchName , "/" )
20
- branchName = "refs/heads/" + splitRef [len (splitRef )- 1 ]
31
+ branchName = splitRef [len (splitRef )- 1 ]
32
+ referenceBranchName = "refs/heads/" + branchName
21
33
isRemoteBranch = true
22
34
} else {
23
- branchName = "refs/heads/" + branchName
35
+ referenceBranchName = "refs/heads/" + branchName
24
36
}
25
37
26
38
// If the branch is a remote branch then a remote fetch will be performed and then the branch checkout will be initiated
27
39
if isRemoteBranch {
28
40
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
- }
41
+ intermediateFetch (repo , branchName )
35
42
36
43
checkoutErr := w .Checkout (& git.CheckoutOptions {
37
- Branch : plumbing .ReferenceName (branchName ),
44
+ Branch : plumbing .ReferenceName (referenceBranchName ),
38
45
Force : true ,
39
46
})
40
47
if checkoutErr != nil {
41
- logger .Log (checkoutErr .Error (), global .StatusError )
48
+ logger .Log ("Checkout failed - " + checkoutErr .Error (), global .StatusError )
42
49
return global .BranchCheckoutError
43
50
}
44
51
}
45
52
46
53
checkoutErr := w .Checkout (& git.CheckoutOptions {
47
- Branch : plumbing .ReferenceName (branchName ),
54
+ Branch : plumbing .ReferenceName (referenceBranchName ),
48
55
Keep : true ,
49
56
})
50
57
if checkoutErr != nil {
0 commit comments