/
checkout.go
76 lines (68 loc) · 2.12 KB
/
checkout.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package daemon
import (
"errors"
"github.com/libgit2/git2go"
"log"
)
func CheckoutBranch(repo *git.Repository, branchName string) error {
checkoutOpts := &git.CheckoutOpts{
Strategy: git.CheckoutSafe | git.CheckoutRecreateMissing | git.CheckoutAllowConflicts | git.CheckoutUseTheirs,
}
//Getting the reference for the remote branch
// remoteBranch, err := repo.References.Lookup("refs/remotes/origin/" + branchName)
remoteBranch, err := repo.LookupBranch("origin/"+branchName, git.BranchRemote)
if err != nil {
log.Print("Failed to find remote branch: " + branchName)
return err
}
defer remoteBranch.Free()
// Lookup for commit from remote branch
commit, err := repo.LookupCommit(remoteBranch.Target())
if err != nil {
log.Print("Failed to find remote branch commit: " + branchName)
return err
}
defer commit.Free()
localBranch, err := repo.LookupBranch(branchName, git.BranchLocal)
// No local branch, lets create one
if localBranch == nil || err != nil {
// Creating local branch
localBranch, err = repo.CreateBranch(branchName, commit, false)
if err != nil {
log.Printf("Failed to create local branch: %s\n", branchName)
return err
}
// // Setting upstream to origin branch
// err = localBranch.SetUpstream("origin/" + branchName)
// if err != nil {
// log.Print("Failed to create upstream to origin/" + branchName)
// return err
// }
}
if localBranch == nil {
return errors.New("Error while locating/creating local branch")
}
defer localBranch.Free()
// Getting the tree for the branch
localCommit, err := repo.LookupCommit(localBranch.Target())
if err != nil {
log.Print("Failed to lookup for commit in local branch " + branchName)
return err
}
defer localCommit.Free()
tree, err := repo.LookupTree(localCommit.TreeId())
if err != nil {
log.Print("Failed to lookup for tree " + branchName)
return err
}
defer tree.Free()
// Checkout the tree
err = repo.CheckoutTree(tree, checkoutOpts)
if err != nil {
log.Print("Failed to checkout tree " + branchName)
return err
}
// Setting the Head to point to our branch
repo.SetHead("refs/heads/" + branchName)
return nil
}