-
Notifications
You must be signed in to change notification settings - Fork 1
/
os.go
107 lines (93 loc) · 1.91 KB
/
os.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// Copyright 2023 The Yock Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package process
import (
"path/filepath"
"sync"
"time"
"github.com/ansurfen/yock/ycho"
"github.com/fsnotify/fsnotify"
)
type OSNotify struct {
fsn *fsnotify.Watcher
fsCallback map[string][]int
fsCbLock *sync.Mutex
handles []*OSHandle
handleLock *sync.Mutex
}
func NewOSNotify() *OSNotify {
watch, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
return &OSNotify{
fsn: watch,
fsCallback: make(map[string][]int),
fsCbLock: &sync.Mutex{},
handleLock: &sync.Mutex{},
}
}
func (n *OSNotify) Remove(id int) {
n.handleLock.Lock()
defer n.handleLock.Unlock()
if id >= 0 && id < len(n.handles) {
n.handles[id].enable = false
}
}
type OSHandle struct {
handle func()
enable bool
}
func (n *OSNotify) AddFunc(paths []string, cmd func()) int {
n.handleLock.Lock()
n.handles = append(n.handles, &OSHandle{
enable: true,
handle: cmd,
})
id := len(n.handles) - 1
n.handleLock.Unlock()
n.fsCbLock.Lock()
defer n.fsCbLock.Unlock()
for _, path := range paths {
n.fsn.Add(path)
n.fsCallback[path] = append(n.fsCallback[path], id)
}
return id
}
func (n *OSNotify) Listen() {
for {
select {
// file system
case event, ok := <-n.fsn.Events:
if !ok {
continue
}
cur := event.Name
prev := filepath.Join(cur, "..")
for cur != prev {
if cb, ok := n.fsCallback[cur]; ok {
for _, c := range cb {
handle := n.handles[c]
if handle.enable {
n.handles[c].handle()
}
}
}
cur = filepath.Join(cur, "..")
prev = filepath.Join(prev, "..")
}
case err, ok := <-n.fsn.Errors:
if !ok {
// ycho.Error()
continue
}
ycho.Error(err)
default:
// port listen
// hardware listen
// script
time.Sleep(500 * time.Microsecond)
}
}
}