Debian Codegraph @

example_test.go

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