Skip to content

Commit 6f46f8c

Browse files
authored
Merge pull request #446 from dlambda/co-br
checkout-branch example
2 parents 0dfff25 + cc10b2a commit 6f46f8c

File tree

3 files changed

+124
-35
lines changed

3 files changed

+124
-35
lines changed

Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ build-git:
2828
test:
2929
@echo "running against `git version`"; \
3030
$(GOTEST) -race ./...
31+
$(GOTEST) -v _examples/common_test.go _examples/common.go --examples
3132

3233
TEMP_REPO := $(shell mktemp)
3334
test-sha256:

_examples/checkout-branch/main.go

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
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+
}

_examples/common_test.go

Lines changed: 38 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ package examples
22

33
import (
44
"flag"
5-
"go/build"
65
"os"
76
"os/exec"
87
"path/filepath"
8+
"runtime"
99
"testing"
1010
)
1111

@@ -14,26 +14,43 @@ var examplesTest = flag.Bool("examples", false, "run the examples tests")
1414
var defaultURL = "https://github.com/git-fixtures/basic.git"
1515

1616
var args = map[string][]string{
17-
"branch": {defaultURL, tempFolder()},
18-
"checkout": {defaultURL, tempFolder(), "35e85108805c84807bc66a02d91535e1e24b38b9"},
19-
"clone": {defaultURL, tempFolder()},
20-
"context": {defaultURL, tempFolder()},
21-
"commit": {cloneRepository(defaultURL, tempFolder())},
22-
"custom_http": {defaultURL},
23-
"open": {cloneRepository(defaultURL, tempFolder())},
24-
"progress": {defaultURL, tempFolder()},
25-
"push": {setEmptyRemote(cloneRepository(defaultURL, tempFolder()))},
26-
"revision": {cloneRepository(defaultURL, tempFolder()), "master~2^"},
27-
"showcase": {defaultURL, tempFolder()},
28-
"tag": {cloneRepository(defaultURL, tempFolder())},
29-
"pull": {createRepositoryWithRemote(tempFolder(), defaultURL)},
30-
"ls": {cloneRepository(defaultURL, tempFolder()), "HEAD", "vendor"},
31-
"merge_base": {cloneRepository(defaultURL, tempFolder()), "--is-ancestor", "HEAD~3", "HEAD^"},
17+
"blame": {defaultURL, "CHANGELOG"},
18+
"branch": {defaultURL, tempFolder()},
19+
"checkout": {defaultURL, tempFolder(), "35e85108805c84807bc66a02d91535e1e24b38b9"},
20+
"checkout-branch": {defaultURL, tempFolder(), "branch"},
21+
"clone": {defaultURL, tempFolder()},
22+
"commit": {cloneRepository(defaultURL, tempFolder())},
23+
"context": {defaultURL, tempFolder()},
24+
"custom_http": {defaultURL},
25+
"find-if-any-tag-point-head": {cloneRepository(defaultURL, tempFolder())},
26+
"ls": {cloneRepository(defaultURL, tempFolder()), "HEAD", "vendor"},
27+
"ls-remote": {defaultURL},
28+
"merge_base": {cloneRepository(defaultURL, tempFolder()), "--is-ancestor", "HEAD~3", "HEAD^"},
29+
"open": {cloneRepository(defaultURL, tempFolder())},
30+
"progress": {defaultURL, tempFolder()},
31+
"pull": {createRepositoryWithRemote(tempFolder(), defaultURL)},
32+
"push": {setEmptyRemote(cloneRepository(defaultURL, tempFolder()))},
33+
"revision": {cloneRepository(defaultURL, tempFolder()), "master~2^"},
34+
"sha256": {tempFolder()},
35+
"showcase": {defaultURL, tempFolder()},
36+
"tag": {cloneRepository(defaultURL, tempFolder())},
3237
}
3338

34-
var ignored = map[string]bool{}
39+
// tests not working / set-up
40+
var ignored = map[string]bool{
41+
"azure_devops": true,
42+
"ls": true,
43+
"sha256": true,
44+
"submodule": true,
45+
"tag-create-push": true,
46+
}
47+
48+
var (
49+
tempFolders = []string{}
3550

36-
var tempFolders = []string{}
51+
_, callingFile, _, _ = runtime.Caller(0)
52+
basepath = filepath.Dir(callingFile)
53+
)
3754

3855
func TestExamples(t *testing.T) {
3956
flag.Parse()
@@ -44,13 +61,13 @@ func TestExamples(t *testing.T) {
4461

4562
defer deleteTempFolders()
4663

47-
examples, err := filepath.Glob(examplesFolder())
64+
exampleMains, err := filepath.Glob(filepath.Join(basepath, "*", "main.go"))
4865
if err != nil {
4966
t.Errorf("error finding tests: %s", err)
5067
}
5168

52-
for _, example := range examples {
53-
dir := filepath.Dir(example)
69+
for _, main := range exampleMains {
70+
dir := filepath.Dir(main)
5471
_, name := filepath.Split(dir)
5572

5673
if ignored[name] {
@@ -71,20 +88,6 @@ func tempFolder() string {
7188
return path
7289
}
7390

74-
func packageFolder() string {
75-
return filepath.Join(
76-
build.Default.GOPATH,
77-
"src", "github.com/go-git/go-git/v5",
78-
)
79-
}
80-
81-
func examplesFolder() string {
82-
return filepath.Join(
83-
packageFolder(),
84-
"_examples", "*", "main.go",
85-
)
86-
}
87-
8891
func cloneRepository(url, folder string) string {
8992
cmd := exec.Command("git", "clone", url, folder)
9093
err := cmd.Run()

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy