forked from rjeczalik/notify
-
Notifications
You must be signed in to change notification settings - Fork 14
/
example_inotify_test.go
84 lines (70 loc) · 2.59 KB
/
example_inotify_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
// 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.
// +build linux
package notify_test
import (
"log"
"golang.org/x/sys/unix"
"github.com/syncthing/notify"
)
// This example shows how to watch changes made on file-system by text editor
// when saving a file. Usually, either InCloseWrite or InMovedTo (when swapping
// with a temporary file) event is created.
func ExampleWatch_linux() {
// 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 inotify-specific events within a
// current working directory. Dispatch each InCloseWrite and InMovedTo
// events separately to c.
if err := notify.Watch(".", c, notify.InCloseWrite, notify.InMovedTo); err != nil {
log.Fatal(err)
}
defer notify.Stop(c)
// Block until an event is received.
switch ei := <-c; ei.Event() {
case notify.InCloseWrite:
log.Println("Editing of", ei.Path(), "file is done.")
case notify.InMovedTo:
log.Println("File", ei.Path(), "was swapped/moved into the watched directory.")
}
}
// This example shows how to use Sys() method from EventInfo interface to tie
// two separate events generated by rename(2) function.
func ExampleWatch_linuxMove() {
// 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, 2)
// Set up a watchpoint listening for inotify-specific events within a
// current working directory. Dispatch each InMovedFrom and InMovedTo
// events separately to c.
if err := notify.Watch(".", c, notify.InMovedFrom, notify.InMovedTo); err != nil {
log.Fatal(err)
}
defer notify.Stop(c)
// Inotify reports move filesystem action by sending two events tied with
// unique cookie value (uint32): one of the events is of InMovedFrom type
// carrying move source path, while the second one is of InMoveTo type
// carrying move destination path.
moves := make(map[uint32]struct {
From string
To string
})
// Wait for moves.
for ei := range c {
cookie := ei.Sys().(*unix.InotifyEvent).Cookie
info := moves[cookie]
switch ei.Event() {
case notify.InMovedFrom:
info.From = ei.Path()
case notify.InMovedTo:
info.To = ei.Path()
}
moves[cookie] = info
if cookie != 0 && info.From != "" && info.To != "" {
log.Println("File:", info.From, "was renamed to", info.To)
delete(moves, cookie)
}
}
}