File: watch_item.go

package info (click to toggle)
golang-github-gokyle-fswatch 0.0~git20121217.1dbdf83-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 84 kB
  • sloc: makefile: 3
file content (87 lines) | stat: -rw-r--r-- 1,776 bytes parent folder | download
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
package fswatch

import "os"

type watchItem struct {
	Path      string
	StatInfo  os.FileInfo
	LastEvent int
}

func watchPath(path string) (wi *watchItem) {
	wi = new(watchItem)
	wi.Path = path
	wi.LastEvent = NONE

	fi, err := os.Stat(path)
	if err == nil {
		wi.StatInfo = fi
	} else if os.IsNotExist(err) {
		wi.LastEvent = NOEXIST
	} else if os.IsPermission(err) {
		wi.LastEvent = NOPERM
	} else {
		wi.LastEvent = INVALID
	}
	return
}

func (wi *watchItem) Update() bool {
	fi, err := os.Stat(wi.Path)
	if err != nil {
		if os.IsNotExist(err) {
			if wi.LastEvent == NOEXIST {
				return false
			} else if wi.LastEvent == DELETED {
				wi.LastEvent = NOEXIST
				return false
			} else {
				wi.LastEvent = DELETED
				return true
			}
		} else if os.IsPermission(err) {
			if wi.LastEvent == NOPERM {
				return false
			} else {
				wi.LastEvent = NOPERM
				return true
			}
		} else {
			wi.LastEvent = INVALID
			return false
		}
	}

	if wi.LastEvent == NOEXIST {
		wi.LastEvent = CREATED
		wi.StatInfo = fi
		return true
	} else if fi.ModTime().After(wi.StatInfo.ModTime()) {
		wi.StatInfo = fi
		switch wi.LastEvent {
		case NONE, CREATED, NOPERM, INVALID:
			wi.LastEvent = MODIFIED
		case DELETED, NOEXIST:
			wi.LastEvent = CREATED
		}
		return true
	} else if fi.Mode() != wi.StatInfo.Mode() {
		wi.LastEvent = PERM
		wi.StatInfo = fi
		return true
	}
	return false
}

// Type Notification represents a file state change. The Path field indicates
// the file that was changed, while last event corresponds to one of the
// event type constants.
type Notification struct {
	Path  string
	Event int
}

// Notification returns a notification from a watchItem.
func (wi *watchItem) Notification() *Notification {
	return &Notification{wi.Path, wi.LastEvent}
}