forked from syncthing/notify
-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_test.go
87 lines (72 loc) · 2.42 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright (c) 2014-2015 The Notify Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
package notify_test
import (
"log"
"path/filepath"
"time"
"github.com/syncthing/notify"
)
// This is a basic example showing how to work with notify.Watch function.
func ExampleWatch() {
// Make the channel buffered to ensure no event is dropped. Notify will drop
// an event if the receiver is not able to keep up the sending pace.
c := make(chan notify.EventInfo, 1)
// Set up a watchpoint listening on events within current working directory.
// Dispatch each create and remove events separately to c.
if err := notify.Watch(".", c, notify.Create, notify.Remove); err != nil {
log.Fatal(err)
}
defer notify.Stop(c)
// Block until an event is received.
ei := <-c
log.Println("Got event:", ei)
}
// This example shows how to set up a recursive watchpoint.
func ExampleWatch_recursive() {
// Make the channel buffered to ensure no event is dropped. Notify will drop
// an event if the receiver is not able to keep up the sending pace.
c := make(chan notify.EventInfo, 1)
// Set up a watchpoint listening for events within a directory tree rooted
// at current working directory. Dispatch remove events to c.
if err := notify.Watch("./...", c, notify.Remove); err != nil {
log.Fatal(err)
}
defer notify.Stop(c)
// Block until an event is received.
ei := <-c
log.Println("Got event:", ei)
}
// This example shows why it is important to not create leaks by stoping
// a channel when it's no longer being used.
func ExampleStop() {
waitfor := func(path string, e notify.Event, timeout time.Duration) bool {
dir, file := filepath.Split(path)
c := make(chan notify.EventInfo, 1)
if err := notify.Watch(dir, c, e); err != nil {
log.Fatal(err)
}
// Clean up watchpoint associated with c. If Stop was not called upon
// return the channel would be leaked as notify holds the only reference
// to it and does not release it on its own.
defer notify.Stop(c)
t := time.After(timeout)
for {
select {
case ei := <-c:
if filepath.Base(ei.Path()) == file {
return true
}
case <-t:
return false
}
}
}
if waitfor("index.lock", notify.Create, 5*time.Second) {
log.Println("The git repository was locked")
}
if waitfor("index.lock", notify.Remove, 5*time.Second) {
log.Println("The git repository was unlocked")
}
}