diff options
author | Máximo Cuadros <mcuadros@gmail.com> | 2016-09-01 00:42:41 +0200 |
---|---|---|
committer | Máximo Cuadros <mcuadros@gmail.com> | 2016-09-01 00:42:41 +0200 |
commit | 2ca4ab90ec5d4c430ac891a4edd5014d7043d539 (patch) | |
tree | 9741b5d6e28b79b0ec70160afdcf7babd58fe56b /examples | |
parent | 5bed3e8fab965738f3f55bb01d15cd4748c26066 (diff) | |
download | go-git-2ca4ab90ec5d4c430ac891a4edd5014d7043d539.tar.gz |
examples: new clone example
Diffstat (limited to 'examples')
-rw-r--r-- | examples/clone/main.go | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/examples/clone/main.go b/examples/clone/main.go new file mode 100644 index 0000000..f95dc8f --- /dev/null +++ b/examples/clone/main.go @@ -0,0 +1,84 @@ +package main + +import ( + "io" + "os" + "path/filepath" + + "github.com/fatih/color" + + "gopkg.in/src-d/go-git.v4" +) + +func main() { + checkArgs() + url := os.Args[1] + directory := os.Args[2] + + r := git.NewMemoryRepository() + + // 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) + + err := r.Clone(&git.CloneOptions{ + URL: url, + Depth: 1, + }) + checkIfError(err) + + // ... retrieving the branch being pointed by HEAD + ref, err := r.Head() + checkIfError(err) + // ... retrieving the commit object + commit, err := r.Commit(ref.Hash()) + checkIfError(err) + + // ... 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) + } +} |