diff options
author | Máximo Cuadros <mcuadros@gmail.com> | 2017-08-22 16:49:38 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-08-22 16:49:38 +0200 |
commit | 6f3b2d878d2f84f513c9dc08b000f653ea83f690 (patch) | |
tree | 4e2b9171b64cae785a58c3f71a2f4b00d65c3b7a /_examples/context | |
parent | bd81c1f3b5ba3ea22243b8e49ab56dd07a6484d6 (diff) | |
parent | fc560b8c758d064b9f189cfd89b5f6aa3f82872d (diff) | |
download | go-git-6f3b2d878d2f84f513c9dc08b000f653ea83f690.tar.gz |
Merge pull request #555 from mcuadros/ctx-example
_examples: context
Diffstat (limited to '_examples/context')
-rw-r--r-- | _examples/context/main.go | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/_examples/context/main.go b/_examples/context/main.go new file mode 100644 index 0000000..72885ff --- /dev/null +++ b/_examples/context/main.go @@ -0,0 +1,46 @@ +package main + +import ( + "context" + "os" + "os/signal" + + "gopkg.in/src-d/go-git.v4" + . "gopkg.in/src-d/go-git.v4/_examples" +) + +// Gracefull cancellation example of a basic git operation such as Clone. +func main() { + CheckArgs("<url>", "<directory>") + url := os.Args[1] + directory := os.Args[2] + + // Clone the given repository to the given directory + Info("git clone %s %s", url, directory) + + stop := make(chan os.Signal, 1) + signal.Notify(stop, os.Interrupt) + + // The context is the mechanism used by go-git, to support deadlines and + // cancellation signals. + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() // cancel when we are finished consuming integers + + go func() { + <-stop + Warning("\nSignal detected, canceling operation...") + cancel() + }() + + Warning("To gracefully stop the clone operation, push Crtl-C.") + + // Using PlainCloneContext we can provide to a context, if the context + // is cancelled, the clone operation stops gracefully. + _, err := git.PlainCloneContext(ctx, directory, false, &git.CloneOptions{ + URL: url, + Progress: os.Stdout, + }) + + // If the context was cancelled, an error is returned. + CheckIfError(err) +} |