Debian Codegraph @

_examples/checkout-branch/main.go

raw
1 package main
2
3 import (
4 "fmt"
5 "os"
6
7 "github.com/go-git/go-git/v5"
8 . "github.com/go-git/go-git/v5/_examples"
9 "github.com/go-git/go-git/v5/config"
10 "github.com/go-git/go-git/v5/plumbing"
11 )
12
13 // Checkout a branch
14 func main() {
15 CheckArgs("<url>", "<directory>", "<branch>")
16 url, directory, branch := os.Args[1], os.Args[2], os.Args[3]
17
18 // Clone the given repository to the given directory
19 Info("git clone %s %s", url, directory)
20 r, err := git.PlainClone(directory, false, &git.CloneOptions{
21 URL: url,
22 })
23 CheckIfError(err)
24
25 // ... retrieving the commit being pointed by HEAD
26 Info("git show-ref --head HEAD")
27 ref, err := r.Head()
28 CheckIfError(err)
29
30 fmt.Println(ref.Hash())
31
32 w, err := r.Worktree()
33 CheckIfError(err)
34
35 // ... checking out branch
36 Info("git checkout %s", branch)
37
38 branchRefName := plumbing.NewBranchReferenceName(branch)
39 branchCoOpts := git.CheckoutOptions{
40 Branch: plumbing.ReferenceName(branchRefName),
41 Force: true,
42 }
43 if err := w.Checkout(&branchCoOpts); err != nil {
44 Warning("local checkout of branch '%s' failed, will attempt to fetch remote branch of same name.", branch)
45 Warning("like `git checkout <branch>` defaulting to `git checkout -b <branch> --track <remote>/<branch>`")
46
47 mirrorRemoteBranchRefSpec := fmt.Sprintf("refs/heads/%s:refs/heads/%s", branch, branch)
48 err = fetchOrigin(r, mirrorRemoteBranchRefSpec)
49 CheckIfError(err)
50
51 err = w.Checkout(&branchCoOpts)
52 CheckIfError(err)
53 }
54 CheckIfError(err)
55
56 Info("checked out branch: %s", branch)
57
58 // ... retrieving the commit being pointed by HEAD (branch now)
59 Info("git show-ref --head HEAD")
60 ref, err = r.Head()
61 CheckIfError(err)
62 fmt.Println(ref.Hash())
63 }
64
65 func fetchOrigin(repo *git.Repository, refSpecStr string) error {
66 remote, err := repo.Remote("origin")
67 CheckIfError(err)
68
69 var refSpecs []config.RefSpec
70 if refSpecStr != "" {
71 refSpecs = []config.RefSpec{config.RefSpec(refSpecStr)}
72 }
73
74 if err = remote.Fetch(&git.FetchOptions{
75 RefSpecs: refSpecs,
76 }); err != nil {
77 if err == git.NoErrAlreadyUpToDate {
78 fmt.Print("refs already up to date")
79 } else {
80 return fmt.Errorf("fetch origin failed: %v", err)
81 }
82 }
83
84 return nil
85 }