aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMáximo Cuadros <mcuadros@gmail.com>2016-12-12 15:50:03 +0100
committerGitHub <noreply@github.com>2016-12-12 15:50:03 +0100
commit3967812bd0de40330dfbb9e1a7d14d4073cc1b10 (patch)
treedbd5df2a66bdd50df40fd773e1d1ec284483ecfe
parent6f701ecc18909959364b708b8efddd03cf4e809c (diff)
downloadgo-git-3967812bd0de40330dfbb9e1a7d14d4073cc1b10.tar.gz
examples: review, testing and documentation (#176)
* examples reviews, testing and documentation * including the execution on travis, and fix readme * fix example link * including the execution on travis
-rw-r--r--examples/README.md13
-rw-r--r--examples/clone/main.go73
-rw-r--r--examples/common.go32
-rw-r--r--examples/common_test.go105
-rw-r--r--examples/custom_http/main.go55
-rw-r--r--examples/fs_implementation/main.go118
-rw-r--r--examples/fs_implementation/main_test.go197
-rw-r--r--examples/latest/latest.go31
-rw-r--r--examples/open/main.go39
-rw-r--r--examples/remotes/main.go44
-rw-r--r--examples/showcase/main.go (renamed from examples/basic/main.go)42
-rw-r--r--examples/storage/main.go41
-rw-r--r--remote_test.go46
13 files changed, 293 insertions, 543 deletions
diff --git a/examples/README.md b/examples/README.md
new file mode 100644
index 0000000..8762b4a
--- /dev/null
+++ b/examples/README.md
@@ -0,0 +1,13 @@
+# go-git: examples
+
+Here you can find a list of annotated _go-git_ examples:
+
+### Basic
+- [showcase](showcase/main.go) - A small showcase of the capabilities of _go-git_
+- [open](open/main.go) - Opening a existing repository cloned by _git_
+- [clone](clone/main.go) - Cloning a repository
+- [remotes](remotes/main.go) - Working with remotes: adding, removing, etc
+
+### Advanced
+- [custom_http](custom_http/main.go) - Replacing the HTTP client using a custom one
+- [storage](storage/main.go) - Implementing a custom storage system
diff --git a/examples/clone/main.go b/examples/clone/main.go
index 0fa5fe6..13257ca 100644
--- a/examples/clone/main.go
+++ b/examples/clone/main.go
@@ -2,87 +2,36 @@ package main
import (
"fmt"
- "io"
"os"
- "path/filepath"
-
- "github.com/fatih/color"
"gopkg.in/src-d/go-git.v4"
+ . "gopkg.in/src-d/go-git.v4/examples"
)
func main() {
- checkArgs()
+ CheckArgs("<url>", "<directory>")
url := os.Args[1]
directory := os.Args[2]
r, err := git.NewFilesystemRepository(directory)
- checkIfError(err)
+ CheckIfError(err)
- // Clone the given repository, using depth we create a shallow clone :
- // > git clone <url> --depth 1
- color.Blue("git clone %s --depth 1 %s", url, directory)
+ // Clone the given repository to the given directory
+ Info("git clone %s %s", url, directory)
err = r.Clone(&git.CloneOptions{
- URL: url,
+ URL: url,
+ Depth: 1,
})
- checkIfError(err)
+
+ CheckIfError(err)
// ... retrieving the branch being pointed by HEAD
ref, err := r.Head()
- checkIfError(err)
+ CheckIfError(err)
// ... retrieving the commit object
commit, err := r.Commit(ref.Hash())
- checkIfError(err)
+ CheckIfError(err)
fmt.Println(commit)
- os.Exit(0)
-
- // ... we get all the files from the commit
- files, err := commit.Files()
- checkIfError(err)
-
- // ... now we iterate the files to save to disk
- err = files.ForEach(func(f *git.File) error {
- abs := filepath.Join(directory, f.Name)
- dir := filepath.Dir(abs)
-
- os.MkdirAll(dir, 0777)
- file, err := os.Create(abs)
- if err != nil {
- return err
- }
-
- defer file.Close()
- r, err := f.Reader()
- if err != nil {
- return err
- }
-
- defer r.Close()
-
- if err := file.Chmod(f.Mode); err != nil {
- return err
- }
-
- _, err = io.Copy(file, r)
- return err
- })
- checkIfError(err)
-}
-
-func checkIfError(err error) {
- if err == nil {
- return
- }
-
- color.Red("error: %s", err)
- os.Exit(1)
-}
-
-func checkArgs() {
- if len(os.Args) < 3 {
- color.Cyan("Usage: %s <url> <directory>", os.Args[0])
- os.Exit(1)
- }
}
diff --git a/examples/common.go b/examples/common.go
new file mode 100644
index 0000000..971b0f6
--- /dev/null
+++ b/examples/common.go
@@ -0,0 +1,32 @@
+package examples
+
+import (
+ "os"
+ "strings"
+
+ "github.com/fatih/color"
+)
+
+func CheckArgs(arg ...string) {
+ if len(os.Args) < len(arg)+1 {
+ Warning("Usage: %s %s", os.Args[0], strings.Join(arg, " "))
+ os.Exit(1)
+ }
+}
+
+func CheckIfError(err error) {
+ if err == nil {
+ return
+ }
+
+ color.Red("error: %s", err)
+ os.Exit(1)
+}
+
+func Info(format string, args ...interface{}) {
+ color.Blue(format, args...)
+}
+
+func Warning(format string, args ...interface{}) {
+ color.Cyan(format, args...)
+}
diff --git a/examples/common_test.go b/examples/common_test.go
new file mode 100644
index 0000000..1059f4b
--- /dev/null
+++ b/examples/common_test.go
@@ -0,0 +1,105 @@
+package examples
+
+import (
+ "flag"
+ "go/build"
+ "io/ioutil"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+)
+
+var examplesTest = flag.Bool("examples", false, "run the examples tests")
+
+var defaultURL = "https://github.com/mcuadros/basic.git"
+
+var args = map[string][]string{
+ "showcase": []string{defaultURL},
+ "custom_http": []string{defaultURL},
+ "clone": []string{defaultURL, tempFolder()},
+ "open": []string{filepath.Join(cloneRepository(defaultURL, tempFolder()), ".git")},
+}
+
+var ignored = map[string]bool{
+ "storage": true,
+}
+
+var tempFolders = []string{}
+
+func TestExamples(t *testing.T) {
+ flag.Parse()
+ if !*examplesTest && os.Getenv("CI") == "" {
+ t.Skip("skipping examples tests, pass --examples to execute it")
+ return
+ }
+
+ defer deleteTempFolders()
+
+ examples, err := filepath.Glob(examplesFolder())
+ if err != nil {
+ t.Errorf("error finding tests: %s", err)
+ }
+
+ for _, example := range examples {
+ _, name := filepath.Split(filepath.Dir(example))
+
+ if ignored[name] {
+ continue
+ }
+
+ t.Run(name, func(t *testing.T) {
+ testExample(t, name, example)
+ })
+ }
+}
+
+func tempFolder() string {
+ path, err := ioutil.TempDir("", "")
+ CheckIfError(err)
+
+ tempFolders = append(tempFolders, path)
+ return path
+}
+
+func packageFolder() string {
+ return filepath.Join(
+ build.Default.GOPATH,
+ "src", "gopkg.in/src-d/go-git.v4",
+ )
+}
+
+func examplesFolder() string {
+ return filepath.Join(
+ packageFolder(),
+ "examples", "*", "main.go",
+ )
+}
+
+func cloneRepository(url, folder string) string {
+ cmd := exec.Command("git", "clone", url, folder)
+ err := cmd.Run()
+ CheckIfError(err)
+
+ return folder
+}
+
+func testExample(t *testing.T, name, example string) {
+ cmd := exec.Command("go", append([]string{
+ "run", filepath.Join(example),
+ }, args[name]...)...)
+
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+
+ if err := cmd.Run(); err != nil {
+ t.Errorf("error running cmd %q", err)
+ }
+}
+
+func deleteTempFolders() {
+ for _, folder := range tempFolders {
+ err := os.RemoveAll(folder)
+ CheckIfError(err)
+ }
+}
diff --git a/examples/custom_http/main.go b/examples/custom_http/main.go
new file mode 100644
index 0000000..0853569
--- /dev/null
+++ b/examples/custom_http/main.go
@@ -0,0 +1,55 @@
+package main
+
+import (
+ "crypto/tls"
+ "fmt"
+ "net/http"
+ "os"
+ "time"
+
+ "gopkg.in/src-d/go-git.v4"
+ . "gopkg.in/src-d/go-git.v4/examples"
+ "gopkg.in/src-d/go-git.v4/plumbing/transport/client"
+ githttp "gopkg.in/src-d/go-git.v4/plumbing/transport/http"
+)
+
+// Here is an example to configure http client according to our own needs.
+func main() {
+ CheckArgs("<url>")
+ url := os.Args[1]
+
+ // Create a custom http(s) client with your config
+ customClient := &http.Client{
+ // accept any certificate (might be useful for testing)
+ Transport: &http.Transport{
+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+ },
+
+ // 15 second timeout
+ Timeout: 15 * time.Second,
+
+ // don't follow redirect
+ CheckRedirect: func(req *http.Request, via []*http.Request) error {
+ return http.ErrUseLastResponse
+ },
+ }
+
+ // Override http(s) default protocol to use our custom client
+ client.InstallProtocol("https", githttp.NewClient(customClient))
+
+ // Create an in-memory repository
+ r := git.NewMemoryRepository()
+
+ // Clone repository using the new client if the protocol is https://
+ Info("git clone %s", url)
+
+ err := r.Clone(&git.CloneOptions{URL: url})
+ CheckIfError(err)
+
+ // Retrieve the branch pointed by HEAD
+ Info("git rev-parse HEAD")
+
+ head, err := r.Head()
+ CheckIfError(err)
+ fmt.Println(head.Hash())
+}
diff --git a/examples/fs_implementation/main.go b/examples/fs_implementation/main.go
deleted file mode 100644
index e5d2851..0000000
--- a/examples/fs_implementation/main.go
+++ /dev/null
@@ -1,118 +0,0 @@
-package main
-
-import "fmt"
-
-func main() {
- fmt.Println("example to be fixed")
-}
-
-/*
-import (
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "path/filepath"
- "strings"
-
- "gopkg.in/src-d/go-git.v4"
- "gopkg.in/src-d/go-git.v4/storage/filesystem"
- "gopkg.in/src-d/go-git.v4/utils/fs"
-)
-
-func main() {
- if len(os.Args) != 2 {
- usage()
- os.Exit(1)
- }
-
- fs := NewCustomFS(os.Args[1])
-
- s, err := filesystem.NewStorage(fs, ".git")
- if err != nil {
- fmt.Fprint(os.Stderr, err)
- os.Exit(1)
- }
-
- repo, err := git.NewRepository(s)
- if err != nil {
- fmt.Fprint(os.Stderr, err)
- os.Exit(1)
- }
-
- iter, err := repo.Commits()
- if err != nil {
- fmt.Fprint(os.Stderr, err)
- os.Exit(1)
- }
- defer iter.Close()
-
- for {
- commit, err := iter.Next()
- if err != nil {
- if err == io.EOF {
- break
- }
-
- fmt.Fprint(os.Stderr, err)
- os.Exit(1)
- }
-
- fmt.Println(commit)
- }
-}
-
-func usage() {
- fmt.Fprintf(os.Stderr, "%s <path to .git dir>", os.Args[0])
-}
-
-// A simple proxy filesystem example: It mimics local filesystems, using
-// 'base' as its root and a funny path separator ("--").
-//
-// Example: when constructed with 'newFS("tmp")', a path like 'foo--bar'
-// will represent the local path "/tmp/foo/bar".
-type CustomFS struct {
- base string
-}
-
-const separator = "--"
-
-func NewCustomFS(path string) *CustomFS {
- return &CustomFS{
- base: path,
- }
-}
-
-func (fs *CustomFS) Stat(path string) (info os.FileInfo, err error) {
- f, err := os.Open(fs.ToReal(path))
- if err != nil {
- return nil, err
- }
-
- defer func() {
- errClose := f.Close()
- if err == nil {
- err = errClose
- }
- }()
-
- return f.Stat()
-}
-
-func (fs *CustomFS) ToReal(path string) string {
- parts := strings.Split(path, separator)
- return filepath.Join(fs.base, filepath.Join(parts...))
-}
-
-func (fs *CustomFS) Open(path string) (fs.ReadSeekCloser, error) {
- return os.Open(fs.ToReal(path))
-}
-
-func (fs *CustomFS) ReadDir(path string) ([]os.FileInfo, error) {
- return ioutil.ReadDir(fs.ToReal(path))
-}
-
-func (fs *CustomFS) Join(elem ...string) string {
- return strings.Join(elem, separator)
-}
-*/
diff --git a/examples/fs_implementation/main_test.go b/examples/fs_implementation/main_test.go
deleted file mode 100644
index 7a7607a..0000000
--- a/examples/fs_implementation/main_test.go
+++ /dev/null
@@ -1,197 +0,0 @@
-package main
-
-/*
-import (
- "io/ioutil"
- "os"
- "path/filepath"
- "reflect"
- "regexp"
- "testing"
-
- "github.com/alcortesm/tgz"
-)
-
-func TestMain(m *testing.M) {
- setUp()
- rval := m.Run()
- tearDown()
- os.Exit(rval)
-}
-
-func setUp() {
- var err error
- repo, err = tgz.Extract("../../storage/filesystem/internal/dotgit/fixtures/spinnaker-gc.tgz")
- if err != nil {
- panic(err)
- }
-}
-
-var repo string
-
-func tearDown() {
- err := os.RemoveAll(repo)
- if err != nil {
- panic(err)
- }
-}
-
-func TestJoin(t *testing.T) {
- fs := NewCustomFS("")
- for i, test := range [...]struct {
- input []string
- expected string
- }{
- {
- input: []string{},
- expected: "",
- }, {
- input: []string{"a"},
- expected: "a",
- }, {
- input: []string{"a", "b"},
- expected: "a--b",
- }, {
- input: []string{"a", "b", "c"},
- expected: "a--b--c",
- },
- } {
- obtained := fs.Join(test.input...)
- if obtained != test.expected {
- t.Fatalf("test %d:\n\tinput = %v\n\tobtained = %v\n\texpected = %v\n",
- i, test.input, obtained, test.expected)
- }
- }
-}
-
-func TestStat(t *testing.T) {
- fs := NewCustomFS(filepath.Join(repo, ".git/"))
- for i, path := range [...]string{
- "index",
- "info--refs",
- "objects--pack--pack-584416f86235cac0d54bfabbdc399fb2b09a5269.pack",
- } {
- real, err := os.Open(fs.ToReal(path))
- if err != nil {
- t.Fatalf("test %d: openning real: %s", err)
- }
-
- expected, err := real.Stat()
- if err != nil {
- t.Fatalf("test %d: stat on real: %s", err)
- }
-
- obtained, err := fs.Stat(path)
- if err != nil {
- t.Fatalf("test %d: fs.Stat unexpected error: %s", i, err)
- }
-
- if !reflect.DeepEqual(obtained, expected) {
- t.Fatalf("test %d:\n\tinput = %s\n\tobtained = %v\n\texpected = %v\n",
- i, path, obtained, expected)
- }
-
- err = real.Close()
- if err != nil {
- t.Fatalf("test %d: closing real: %s", i, err)
- }
- }
-}
-
-func TestStatErrors(t *testing.T) {
- fs := NewCustomFS(filepath.Join(repo, ".git/"))
- for i, test := range [...]struct {
- input string
- errRegExp string
- }{
- {
- input: "bla",
- errRegExp: ".*bla: no such file or directory",
- }, {
- input: "bla--foo",
- errRegExp: ".*bla/foo: no such file or directory",
- },
- } {
- expected := regexp.MustCompile(test.errRegExp)
-
- _, err := fs.Stat(test.input)
- if err == nil {
- t.Fatalf("test %d: no error returned", i)
- }
- if !expected.MatchString(err.Error()) {
- t.Fatalf("test %d: error missmatch\n\tobtained = %q\n\texpected regexp = %q\n",
- i, err.Error(), test.errRegExp)
- }
- }
-}
-
-func TestOpen(t *testing.T) {
- fs := NewCustomFS(filepath.Join(repo, ".git/"))
- for i, path := range [...]string{
- "index",
- "info--refs",
- "objects--pack--pack-584416f86235cac0d54bfabbdc399fb2b09a5269.pack",
- } {
- real, err := os.Open(fs.ToReal(path))
- if err != nil {
- t.Fatalf("test %d: openning real: %s", err)
- }
-
- realData, err := ioutil.ReadAll(real)
- if err != nil {
- t.Fatal("test %d: ioutil.ReadAll on real: %s", err)
- }
-
- err = real.Close()
- if err != nil {
- t.Fatal("test %d: closing real: %s", err)
- }
-
- obtained, err := fs.Open(path)
- if err != nil {
- t.Fatalf("test %d: fs.Open unexpected error: %s", i, err)
- }
-
- obtainedData, err := ioutil.ReadAll(obtained)
- if err != nil {
- t.Fatal("test %d: ioutil.ReadAll on obtained: %s", err)
- }
-
- err = obtained.Close()
- if err != nil {
- t.Fatal("test %d: closing obtained: %s", err)
- }
-
- if !reflect.DeepEqual(obtainedData, realData) {
- t.Fatalf("test %d:\n\tinput = %s\n\tobtained = %v\n\texpected = %v\n",
- i, path, obtainedData, realData)
- }
- }
-}
-
-func TestReadDir(t *testing.T) {
- fs := NewCustomFS(filepath.Join(repo, ".git/"))
- for i, path := range [...]string{
- "info",
- ".",
- "",
- "objects",
- "objects--pack",
- } {
- expected, err := ioutil.ReadDir(fs.ToReal(path))
- if err != nil {
- t.Fatalf("test %d: real ReadDir: %s", err)
- }
-
- obtained, err := fs.ReadDir(path)
- if err != nil {
- t.Fatalf("test %d: fs.ReadDir unexpected error: %s", i, err)
- }
-
- if !reflect.DeepEqual(obtained, expected) {
- t.Fatalf("test %d:\n\tinput = %s\n\tobtained = %v\n\texpected = %v\n",
- i, path, obtained, expected)
- }
- }
-}
-*/
diff --git a/examples/latest/latest.go b/examples/latest/latest.go
deleted file mode 100644
index 05f583a..0000000
--- a/examples/latest/latest.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package main
-
-import (
- "fmt"
- "os"
-
- "gopkg.in/src-d/go-git.v4"
-)
-
-func main() {
- url := os.Args[1]
-
- fmt.Printf("Retrieving latest commit from: %q ...\n", url)
- r := git.NewMemoryRepository()
-
- if err := r.Clone(&git.CloneOptions{URL: url}); err != nil {
- panic(err)
- }
-
- head, err := r.Head()
- if err != nil {
- panic(err)
- }
-
- commit, err := r.Commit(head.Hash())
- if err != nil {
- panic(err)
- }
-
- fmt.Println(commit)
-}
diff --git a/examples/open/main.go b/examples/open/main.go
index fa11844..90fd406 100644
--- a/examples/open/main.go
+++ b/examples/open/main.go
@@ -3,38 +3,33 @@ package main
import (
"fmt"
"os"
- "path/filepath"
"gopkg.in/src-d/go-git.v4"
+ . "gopkg.in/src-d/go-git.v4/examples"
)
func main() {
- path, _ := filepath.Abs(os.Args[1])
- fmt.Printf("Opening repository %q ...\n", path)
+ CheckArgs("<path>")
+ path := os.Args[1]
+ // We instance a new repository targeting the given path (the .git folder)
r, err := git.NewFilesystemRepository(path)
- if err != nil {
- panic(err)
- }
+ CheckIfError(err)
- iter, err := r.Commits()
- if err != nil {
- panic(err)
- }
+ // Length of the HEAD history
+ Info("git rev-list HEAD --count")
- defer iter.Close()
+ // ... retrieving the HEAD reference
+ ref, err := r.Head()
+ CheckIfError(err)
- var count = 0
- err = iter.ForEach(func(commit *git.Commit) error {
- count++
- fmt.Println(commit)
+ // ... retrieving the commit object
+ commit, err := r.Commit(ref.Hash())
+ CheckIfError(err)
- return nil
- })
+ // ... calculating the commit history
+ commits, err := commit.History()
+ CheckIfError(err)
- if err != nil {
- panic(err)
- }
-
- fmt.Println("total commits:", count)
+ fmt.Println(len(commits))
}
diff --git a/examples/remotes/main.go b/examples/remotes/main.go
index 43b127f..c0d71f5 100644
--- a/examples/remotes/main.go
+++ b/examples/remotes/main.go
@@ -3,50 +3,53 @@ package main
import (
"fmt"
- "github.com/fatih/color"
-
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/config"
+ . "gopkg.in/src-d/go-git.v4/examples"
"gopkg.in/src-d/go-git.v4/plumbing"
)
func main() {
// Create a new repository
- color.Blue("git init")
+ Info("git init")
r := git.NewMemoryRepository()
// Add a new remote, with the default fetch refspec
- // > git remote add example https://github.com/git-fixtures/basic.git
- color.Blue("git remote add example https://github.com/git-fixtures/basic.git")
+ Info("git remote add example https://github.com/git-fixtures/basic.git")
- r.CreateRemote(&config.RemoteConfig{
+ _, err := r.CreateRemote(&config.RemoteConfig{
Name: "example",
URL: "https://github.com/git-fixtures/basic.git",
})
+ CheckIfError(err)
+
// List remotes from a repository
- // > git remotes -v
- color.Blue("git remotes -v")
+ Info("git remotes -v")
+
+ list, err := r.Remotes()
+ CheckIfError(err)
- list, _ := r.Remotes()
for _, r := range list {
fmt.Println(r)
}
// Pull using the create repository
- // > git pull example
- color.Blue("git pull example")
-
- r.Pull(&git.PullOptions{
+ Info("git pull example")
+ err = r.Pull(&git.PullOptions{
RemoteName: "example",
})
+ CheckIfError(err)
+
// List the branches
// > git show-ref
- color.Blue("git show-ref")
+ Info("git show-ref")
+
+ refs, err := r.References()
+ CheckIfError(err)
- refs, _ := r.References()
- refs.ForEach(func(ref *plumbing.Reference) error {
+ err = refs.ForEach(func(ref *plumbing.Reference) error {
// The HEAD is omitted in a `git show-ref` so we ignore the symbolic
// references, the HEAD
if ref.Type() == plumbing.SymbolicReference {
@@ -57,8 +60,11 @@ func main() {
return nil
})
+ CheckIfError(err)
+
// Delete the example remote
- // > git remote rm example
- color.Blue("git remote rm example")
- r.DeleteRemote("example")
+ Info("git remote rm example")
+
+ err = r.DeleteRemote("example")
+ CheckIfError(err)
}
diff --git a/examples/basic/main.go b/examples/showcase/main.go
index d92002a..ff5c7d3 100644
--- a/examples/basic/main.go
+++ b/examples/showcase/main.go
@@ -2,41 +2,45 @@ package main
import (
"fmt"
+ "os"
"strings"
- "github.com/fatih/color"
-
"gopkg.in/src-d/go-git.v4"
+ . "gopkg.in/src-d/go-git.v4/examples"
)
func main() {
- r, _ := git.NewFilesystemRepository(".git")
+ CheckArgs("<url>")
+ url := os.Args[1]
+
+ r := git.NewMemoryRepository()
// Clone the given repository, creating the remote, the local branches
// and fetching the objects, exactly as:
- // > git clone https://github.com/git-fixtures/basic.git
- color.Blue("git clone https://github.com/git-fixtures/basic.git")
+ Info("git clone %s", url)
- r.Clone(&git.CloneOptions{
- URL: "https://github.com/git-fixtures/basic.git",
- })
+ err := r.Clone(&git.CloneOptions{URL: url})
+ CheckIfError(err)
// Getting the latest commit on the current branch
- // > git log -1
- color.Blue("git log -1")
+ Info("git log -1")
// ... retrieving the branch being pointed by HEAD
- ref, _ := r.Head()
+ ref, err := r.Head()
+ CheckIfError(err)
+
// ... retrieving the commit object
commit, err := r.Commit(ref.Hash())
- fmt.Println(commit, err)
+ CheckIfError(err)
+ fmt.Println(commit)
// List the tree from HEAD
- // > git ls-tree -r HEAD
- color.Blue("git ls-tree -r HEAD")
+ Info("git ls-tree -r HEAD")
// ... retrieve the tree from the commit
- tree, _ := commit.Tree()
+ tree, err := commit.Tree()
+ CheckIfError(err)
+
// ... get the files iterator and print the file
tree.Files().ForEach(func(f *git.File) error {
fmt.Printf("100644 blob %s %s\n", f.Hash, f.Name)
@@ -44,14 +48,14 @@ func main() {
})
// List the history of the repository
- // > git log --oneline
- color.Blue("git log --oneline")
+ Info("git log --oneline")
+
+ commits, err := commit.History()
+ CheckIfError(err)
- commits, _ := commit.History()
for _, c := range commits {
hash := c.Hash.String()
line := strings.Split(c.Message, "\n")
fmt.Println(hash[:7], line[0])
}
-
}
diff --git a/examples/storage/main.go b/examples/storage/main.go
index d85f8e9..b047e43 100644
--- a/examples/storage/main.go
+++ b/examples/storage/main.go
@@ -6,29 +6,29 @@ import (
"strings"
"gopkg.in/src-d/go-git.v4"
+ . "gopkg.in/src-d/go-git.v4/examples"
"gopkg.in/src-d/go-git.v4/examples/storage/aerospike"
driver "github.com/aerospike/aerospike-client-go"
- "github.com/fatih/color"
)
func main() {
- checkArgs()
+ CheckArgs("<clone|log>", "<url>")
action := os.Args[1]
url := os.Args[2]
// Aerospike client to be used by the custom storage
client, err := driver.NewClient("127.0.0.1", 3000)
- checkIfError(err)
+ CheckIfError(err)
// New instance of the custom aerospike storage, all the objects,
// references and configuration is saved to aerospike
s, err := aerospike.NewStorage(client, "test", url)
- checkIfError(err)
+ CheckIfError(err)
// A new repository instance using as storage the custom implementation
r, err := git.NewRepository(s)
- checkIfError(err)
+ CheckIfError(err)
switch action {
case "clone":
@@ -43,24 +43,23 @@ func main() {
func clone(r *git.Repository, url string) {
// Clone the given repository, all the objects, references and
// configuration sush as remotes, are save into the Aerospike database.
- // > git clone <url>
- color.Blue("git clone %s", url)
+ Info("git clone %s", url)
+
err := r.Clone(&git.CloneOptions{URL: url})
- checkIfError(err)
+ CheckIfError(err)
}
func log(r *git.Repository) {
// Prints the history of the repository starting in the current HEAD, the
// objects are retrieved from Aerospike database.
- // > git log --oneline
- color.Blue("git log --oneline")
+ Info("git log --oneline")
ref, err := r.Head()
- checkIfError(err)
+ CheckIfError(err)
commit, err := r.Commit(ref.Hash())
- checkIfError(err)
+ CheckIfError(err)
commits, err := commit.History()
- checkIfError(err)
+ CheckIfError(err)
for _, c := range commits {
hash := c.Hash.String()
@@ -68,19 +67,3 @@ func log(r *git.Repository) {
fmt.Println(hash[:7], line[0])
}
}
-
-func checkIfError(err error) {
- if err == nil {
- return
- }
-
- color.Red("error: %s", err)
- os.Exit(1)
-}
-
-func checkArgs() {
- if len(os.Args) < 3 {
- color.Cyan("Usage: %s <clone|log> <url>", os.Args[0])
- os.Exit(1)
- }
-}
diff --git a/remote_test.go b/remote_test.go
index c3e86df..a4e8e35 100644
--- a/remote_test.go
+++ b/remote_test.go
@@ -2,20 +2,14 @@ package git
import (
"bytes"
- "crypto/tls"
- "fmt"
"io"
"io/ioutil"
- "net/http"
"os"
- "time"
"gopkg.in/src-d/go-git.v4/config"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/protocol/packp/capability"
"gopkg.in/src-d/go-git.v4/plumbing/storer"
- "gopkg.in/src-d/go-git.v4/plumbing/transport/client"
- githttp "gopkg.in/src-d/go-git.v4/plumbing/transport/http"
"gopkg.in/src-d/go-git.v4/storage/filesystem"
"gopkg.in/src-d/go-git.v4/storage/memory"
osfs "gopkg.in/src-d/go-git.v4/utils/fs/os"
@@ -259,43 +253,3 @@ func (s *RemoteSuite) TestString(c *C) {
"foo\thttps://github.com/git-fixtures/basic.git (push)",
)
}
-
-// Here is an example to configure http client according to our own needs.
-func Example_customHTTPClient() {
- const url = "https://github.com/git-fixtures/basic.git"
-
- // Create a custom http(s) client with your config
- customClient := &http.Client{
- Transport: &http.Transport{
- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
- }, // accept any certificate (might be useful for testing)
- Timeout: 15 * time.Second, // 15 second timeout
- CheckRedirect: func(req *http.Request, via []*http.Request) error { // don't follow redirect
- return http.ErrUseLastResponse
- },
- }
-
- // Override http(s) default protocol to use our custom client
- client.InstallProtocol(
- "https",
- githttp.NewClient(customClient))
-
- // Create an in-memory repository
- r := NewMemoryRepository()
-
- // Clone repo
- if err := r.Clone(&CloneOptions{URL: url}); err != nil {
- panic(err)
- }
-
- // Retrieve the branch pointed by HEAD
- head, err := r.Head()
- if err != nil {
- panic(err)
- }
-
- // Print latest commit hash
- fmt.Println(head.Hash())
- // Output:
- // 6ecf0ef2c2dffb796033e5a02219af86ec6584e5
-}