| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"os" |
| 6 |
"os/signal" |
| 7 |
|
| 8 |
"gopkg.in/src-d/go-git.v4" |
| 9 |
. "gopkg.in/src-d/go-git.v4/_examples" |
| 10 |
) |
| 11 |
|
| 12 |
// Graceful cancellation example of a basic git operation such as Clone. |
| 13 |
func main() { |
| 14 |
CheckArgs("<url>", "<directory>") |
| 15 |
url := os.Args[1] |
| 16 |
directory := os.Args[2] |
| 17 |
|
| 18 |
// Clone the given repository to the given directory |
| 19 |
Info("git clone %s %s", url, directory) |
| 20 |
|
| 21 |
stop := make(chan os.Signal, 1) |
| 22 |
signal.Notify(stop, os.Interrupt) |
| 23 |
|
| 24 |
// The context is the mechanism used by go-git, to support deadlines and |
| 25 |
// cancellation signals. |
| 26 |
ctx, cancel := context.WithCancel(context.Background()) |
| 27 |
defer cancel() // cancel when we are finished consuming integers |
| 28 |
|
| 29 |
go func() { |
| 30 |
<-stop |
| 31 |
Warning("\nSignal detected, canceling operation...") |
| 32 |
cancel() |
| 33 |
}() |
| 34 |
|
| 35 |
Warning("To gracefully stop the clone operation, push Crtl-C.") |
| 36 |
|
| 37 |
// Using PlainCloneContext we can provide to a context, if the context |
| 38 |
// is cancelled, the clone operation stops gracefully. |
| 39 |
_, err := git.PlainCloneContext(ctx, directory, false, &git.CloneOptions{ |
| 40 |
URL: url, |
| 41 |
Progress: os.Stdout, |
| 42 |
}) |
| 43 |
|
| 44 |
// If the context was cancelled, an error is returned. |
| 45 |
CheckIfError(err) |
| 46 |
} |