-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatcher.go
114 lines (94 loc) · 2.37 KB
/
watcher.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
108
109
110
111
112
113
114
package LinuxApps
import (
"github.com/fsnotify/fsnotify"
"os"
"path"
"strings"
)
func NewAppWatcher(onChange func(*AppInfo) error, onRemove func() error) *AppWatcher {
return &AppWatcher{
OnChange: onChange,
OnRemove: onRemove,
}
}
type AppWatcher struct {
OnChange func(*AppInfo) error
OnRemove func() error
}
func (aw *AppWatcher) Start() error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
defer watcher.Close()
// Watch app path
err = watcher.Add(DesktopFilesPath)
if err != nil {
panic(err)
}
// Watch override file, only if it exists
if _, err := os.Stat(DesktopFilesOverridePath); !os.IsNotExist(err) {
err = watcher.Add(DesktopFilesOverridePath)
if err != nil {
panic(err)
}
}
done := make(chan bool)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
continue
}
if event.Op&fsnotify.Remove == fsnotify.Remove {
if !strings.HasSuffix(event.Name, ".desktop") {
continue
}
filePathComponents := strings.Split(event.Name, "/")
fileName := filePathComponents[len(filePathComponents) - 1]
if strings.Contains(event.Name, DesktopFilesOverridePath) {
// Check that the file is not overriding any other
if _, err := os.Stat(DesktopFilesPath + fileName); os.IsNotExist(err) {
aw.OnRemove()
continue
}
}
// Check for original (non-overridden) file
app, err := decodeDesktopFile(DesktopFilesPath + fileName)
if err != nil {
panic(err)
}
err = aw.OnChange(app)
if err != nil {
panic(err)
}
} else if event.Op&fsnotify.Write == fsnotify.Write {
if !strings.HasSuffix(event.Name, ".desktop") {
continue
}
app, err := decodeDesktopFile(event.Name)
if err != nil {
continue
}
// Ignore if being overridden
if !strings.HasPrefix(event.Name, DesktopFilesOverridePath) {
// Check if it's been overridden
filePathComponents := strings.Split(event.Name, string(os.PathSeparator))
fileName := filePathComponents[len(filePathComponents) - 1]
if _, err = os.Stat(path.Join(DesktopFilesOverridePath, fileName)); !os.IsNotExist(err) {
// File exists in override folder
continue
}
}
err = aw.OnChange(app)
if err != nil {
panic(err)
}
}
}
}
}()
<-done
return nil
}