/
fsnotify.go
105 lines (93 loc) · 2.48 KB
/
fsnotify.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
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !plan9
// +build !plan9
// Package fsnotify provides a platform-independent interface for file system notifications.
package fsnotify
import (
"errors"
"fmt"
"io/fs"
"path/filepath"
"strings"
)
// These are the generalized file operations that can trigger a notification.
const (
Create Op = 1 << iota
Write
Remove
Rename
Chmod
)
// Common errors that can be reported by a watcher
var (
ErrNonExistentWatch = errors.New("can't remove non-existent watcher")
ErrEventOverflow = errors.New("fsnotify queue overflow")
ErrNotDirectory = errors.New("not a directory")
ErrRecursionUnsupported = errors.New("recursion not supported")
)
// Event represents a single file system notification.
type Event struct {
Name string // Relative path to the file or directory.
Op Op // File operation that triggered the event.
}
// Op describes a set of file operations.
type Op uint32
func (op Op) String() string {
// Use a builder for efficient string concatenation
var builder strings.Builder
if op&Create == Create {
builder.WriteString("|CREATE")
}
if op&Remove == Remove {
builder.WriteString("|REMOVE")
}
if op&Write == Write {
builder.WriteString("|WRITE")
}
if op&Rename == Rename {
builder.WriteString("|RENAME")
}
if op&Chmod == Chmod {
builder.WriteString("|CHMOD")
}
if builder.Len() == 0 {
return ""
}
return builder.String()[1:] // Strip leading pipe
}
// String returns a string representation of the event in the form
// "file: REMOVE|WRITE|..."
func (e Event) String() string {
return fmt.Sprintf("%q: %s", e.Name, e.Op.String())
}
// findDirs finds all directories under path (return value *includes* path as
// the first entry).
func findDirs(path string) ([]string, error) {
dirs := make([]string, 0, 8)
err := filepath.WalkDir(path, func(root string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if root == path && !d.IsDir() {
return fmt.Errorf("%q: %w", path, ErrNotDirectory)
}
if d.IsDir() {
dirs = append(dirs, root)
}
return nil
})
if err != nil {
return nil, err
}
return dirs, nil
}
// Check if this path is recursive (ends with "/..."), and return the path with
// the /... stripped.
func recursivePath(path string) (string, bool) {
if filepath.Base(path) == "..." {
return filepath.Dir(path), true
}
return path, false
}