aboutsummaryrefslogtreecommitdiffhomepage
path: root/vendor/github.com/tdewolff/minify/cmd/minify/watch.go
blob: d97cbc85e1fd279fca4e0bfc414c62c84ec6df7f (plain)
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
package main

import (
	"os"
	"path/filepath"

	"github.com/fsnotify/fsnotify"
)

type RecursiveWatcher struct {
	watcher   *fsnotify.Watcher
	paths     map[string]bool
	recursive bool
}

func NewRecursiveWatcher(recursive bool) (*RecursiveWatcher, error) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return nil, err
	}
	return &RecursiveWatcher{watcher, make(map[string]bool), recursive}, nil
}

func (rw *RecursiveWatcher) Close() error {
	return rw.watcher.Close()
}

func (rw *RecursiveWatcher) AddPath(root string) error {
	info, err := os.Stat(root)
	if err != nil {
		return err
	}

	if info.Mode().IsRegular() {
		root = filepath.Dir(root)
		if rw.paths[root] {
			return nil
		}
		if err := rw.watcher.Add(root); err != nil {
			return err
		}
		rw.paths[root] = true
		return nil
	} else if !rw.recursive {
		if rw.paths[root] {
			return nil
		}
		if err := rw.watcher.Add(root); err != nil {
			return err
		}
		rw.paths[root] = true
		return nil
	} else {
		return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}
			if info.Mode().IsDir() {
				if !validDir(info) || rw.paths[path] {
					return filepath.SkipDir
				}
				if err := rw.watcher.Add(path); err != nil {
					return err
				}
				rw.paths[path] = true
			}
			return nil
		})
	}
}

func (rw *RecursiveWatcher) Run() chan string {
	files := make(chan string, 10)
	go func() {
		for rw.watcher.Events != nil && rw.watcher.Errors != nil {
			select {
			case event, ok := <-rw.watcher.Events:
				if !ok {
					rw.watcher.Events = nil
					break
				}
				if info, err := os.Stat(event.Name); err == nil {
					if validDir(info) {
						if event.Op&fsnotify.Create == fsnotify.Create {
							if err := rw.AddPath(event.Name); err != nil {
								Error.Println(err)
							}
						}
					} else if validFile(info) {
						if event.Op&fsnotify.Write == fsnotify.Write {
							files <- event.Name
						}
					}
				}
			case err, ok := <-rw.watcher.Errors:
				if !ok {
					rw.watcher.Errors = nil
					break
				}
				Error.Println(err)
			}
		}
		close(files)
	}()
	return files
}