1package git_test
2
3import (
4 "fmt"
5 "io"
6 "io/ioutil"
7 "log"
8 "os"
9 "path/filepath"
10
11 "gopkg.in/src-d/go-git.v4"
12 "gopkg.in/src-d/go-git.v4/config"
13 "gopkg.in/src-d/go-git.v4/plumbing"
14 "gopkg.in/src-d/go-git.v4/storage/memory"
15
16 "gopkg.in/src-d/go-billy.v4/memfs"
17)
18
19func ExampleClone() {
20 // Filesystem abstraction based on memory
21 fs := memfs.New()
22 // Git objects storer based on memory
23 storer := memory.NewStorage()
24
25 // Clones the repository into the worktree (fs) and storer all the .git
26 // content into the storer
27 _, _ = git.Clone(storer, fs, &git.CloneOptions{
28 URL: "https://github.com/git-fixtures/basic.git",
29 })
30
31 // Prints the content of the CHANGELOG file from the cloned repository
32 changelog, _ := fs.Open("CHANGELOG")
33
34 io.Copy(os.Stdout, changelog)
35 // Output: Initial changelog
36}
37
38func ExamplePlainClone() {
39 // Tempdir to clone the repository
40 dir, err := ioutil.TempDir("", "clone-example")
41 if err != nil {
42 log.Fatal(err)
43 }
44
45 defer os.RemoveAll(dir) // clean up
46
47 // Clones the repository into the given dir, just as a normal git clone does
48 _, err = git.PlainClone(dir, false, &git.CloneOptions{
49 URL: "https://github.com/git-fixtures/basic.git",
50 })
51
52 if err != nil {
53 log.Fatal(err)
54 }
55
56 // Prints the content of the CHANGELOG file from the cloned repository
57 changelog, err := os.Open(filepath.Join(dir, "CHANGELOG"))
58 if err != nil {
59 log.Fatal(err)
60 }
61
62 io.Copy(os.Stdout, changelog)
63 // Output: Initial changelog
64}
65
66func ExampleRepository_References() {
67 r, _ := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
68 URL: "https://github.com/git-fixtures/basic.git",
69 })
70
71 // simulating a git show-ref
72 refs, _ := r.References()
73 refs.ForEach(func(ref *plumbing.Reference) error {
74 if ref.Type() == plumbing.HashReference {
75 fmt.Println(ref)
76 }
77
78 return nil
79 })
80
81 // Example Output:
82 // 6ecf0ef2c2dffb796033e5a02219af86ec6584e5 refs/remotes/origin/master
83 // e8d3ffab552895c19b9fcf7aa264d277cde33881 refs/remotes/origin/branch
84 // 6ecf0ef2c2dffb796033e5a02219af86ec6584e5 refs/heads/master
85
86}
87
88func ExampleRepository_CreateRemote() {
89 r, _ := git.Init(memory.NewStorage(), nil)
90
91 // Add a new remote, with the default fetch refspec
92 _, err := r.CreateRemote(&config.RemoteConfig{
93 Name: "example",
94 URLs: []string{"https://github.com/git-fixtures/basic.git"},
95 })
96
97 if err != nil {
98 log.Fatal(err)
99 }
100
101 list, err := r.Remotes()
102 if err != nil {
103 log.Fatal(err)
104 }
105
106 for _, r := range list {
107 fmt.Println(r)
108 }
109
110 // Example Output:
111 // example https://github.com/git-fixtures/basic.git (fetch)
112 // example https://github.com/git-fixtures/basic.git (push)
113}