Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add {Event,Op}.Has() #477

Merged
merged 1 commit into from Jul 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -49,7 +49,7 @@ func main() {
return
}
log.Println("event:", event)
if event.Op&fsnotify.Write == fsnotify.Write {
if event.Has(fsnotify.Write) {
log.Println("modified file:", event.Name)
}
case err, ok := <-watcher.Errors:
Expand Down
2 changes: 1 addition & 1 deletion cmd/fsnotify/main.go
Expand Up @@ -42,7 +42,7 @@ func main() {

i++
m := ""
if e.Op&fsnotify.Write == fsnotify.Write {
if e.Has(fsnotify.Write) {
m = "(modified)"
}
line("%3d %-10s %-10s %q", i, e.Op, m, e.Name)
Expand Down
40 changes: 24 additions & 16 deletions fsnotify.go
Expand Up @@ -5,7 +5,8 @@
//go:build !plan9
// +build !plan9

// Package fsnotify provides a platform-independent interface for file system notifications.
// Package fsnotify provides a cross-platform interface for file system
// notifications.
package fsnotify

import (
Expand All @@ -24,6 +25,9 @@ type Event struct {
Name string

// File operation that triggered the event.
//
// This is a bitmask as some systems may send multiple operations at once.
// Use the Op.Has() or Event.Has() method instead of comparing with ==.
Op Op
}

Expand All @@ -40,30 +44,34 @@ const (
)

func (op Op) String() string {
// Use a builder for efficient string concatenation
var builder strings.Builder

if op&Create == Create {
builder.WriteString("|CREATE")
var b strings.Builder
if op.Has(Create) {
b.WriteString("|CREATE")
}
if op&Remove == Remove {
builder.WriteString("|REMOVE")
if op.Has(Remove) {
b.WriteString("|REMOVE")
}
if op&Write == Write {
builder.WriteString("|WRITE")
if op.Has(Write) {
b.WriteString("|WRITE")
}
if op&Rename == Rename {
builder.WriteString("|RENAME")
if op.Has(Rename) {
b.WriteString("|RENAME")
}
if op&Chmod == Chmod {
builder.WriteString("|CHMOD")
if op.Has(Chmod) {
b.WriteString("|CHMOD")
}
if builder.Len() == 0 {
if b.Len() == 0 {
return ""
}
return builder.String()[1:] // Strip leading pipe
return b.String()[1:]
}

// Has reports if this operation has the given operation.
func (o Op) Has(h Op) bool { return o&h == h }

// Has reports if this event has the given operation.
func (e Event) Has(op Op) bool { return e.Op.Has(op) }

// String returns a string representation of the event in the form
// "file: REMOVE|WRITE|..."
func (e Event) String() string {
Expand Down