常量
三个 error
var (
// ErrDurationTooShort occurs when calling the watcher's Start
// method with a duration that's less than 1 nanosecond.
ErrDurationTooShort = errors.New("error: duration is less than 1ns")
// ErrWatcherRunning occurs when trying to call the watcher's
// Start method and the polling cycle is still already running
// from previously calling Start and not yet calling Close.
ErrWatcherRunning = errors.New("error: watcher is already running")
// ErrWatchedFileDeleted is an error that occurs when a file or folder that was
// being watched has been deleted.
ErrWatchedFileDeleted = errors.New("error: watched file or folder deleted")
)
六个可以检测的操作
// An Op is a type that is used to describe what type
// of event has occurred during the watching process.
type Op uint32
// Ops
const (
Create Op = iota
Write
Remove
Rename
Chmod
Move
)
var ops = map[Op]string{
Create: "CREATE",
Write: "WRITE",
Remove: "REMOVE",
Rename: "RENAME",
Chmod: "CHMOD",
Move: "MOVE",
}
// String prints the string version of the Op consts
func (e Op) String() string {
if op, found := ops[e]; found {
return op
}
return "???"
}
结构
Event
// An Event describes an event that is received when files or directory
// changes occur. It includes the os.FileInfo of the changed file or
// directory and the type of event that's occurred and the full path of the file.
type Event struct {
Op
Path string
os.FileInfo
}
// String returns a string depending on what type of event occurred and the
// file name associated with the event.
func (e Event) String() string {
if e.FileInfo != nil {
pathType := "FILE"
if e.IsDir() {
pathType = "DIRECTORY"
}
return fmt.Sprintf("%s %q %s [%s]", pathType, e.Name(), e.Op, e.Path)
}
return "???"
}
Watcher
// Watcher describes a process that watches files for changes.
type Watcher struct {
Event chan Event
Error chan error
Closed chan struct{}
close chan struct{}
wg *sync.WaitGroup
// mu protects the following.
mu *sync.Mutex
running bool
names map[string]bool // bool for recursive or not.
files map[string]os.FileInfo // map of files.
ignored map[string]struct{} // ignored files or directories.
ops map[Op]struct{} // Op filtering.
ignoreHidden bool // ignore hidden files or not.
maxEvents int // max sent events per cycle
}
fileInfo
// fileInfo is an implementation of os.FileInfo that can be used
// as a mocked os.FileInfo when triggering an event when the specified
// os.FileInfo is nil.
type fileInfo struct {
name string
size int64
mode os.FileMode
modTime time.Time
sys interface{}
dir bool
}
func (fs *fileInfo) IsDir() bool {
return fs.dir
}
func (fs *fileInfo) ModTime() time.Time {
return fs.modTime
}
func (fs *fileInfo) Mode() os.FileMode {
return fs.mode
}
func (fs *fileInfo) Name() string {
return fs.name
}
func (fs *fileInfo) Size() int64 {
return fs.size
}
func (fs *fileInfo) Sys() interface{} {
return fs.sys
}