From b659e1e00ac3f430ee58fbfc49f69a9a3b45178c Mon Sep 17 00:00:00 2001 From: Ludovic Fernandez Date: Sun, 30 Jun 2024 19:43:00 +0200 Subject: [PATCH] feat: use options on retry (unix) (#78) --- flock.go | 5 ++++- flock_unix.go | 17 +++++++++-------- flock_unix_variants.go | 7 ++++--- flock_windows.go | 2 +- 4 files changed, 18 insertions(+), 13 deletions(-) diff --git a/flock.go b/flock.go index 1ab65d8..987a59f 100644 --- a/flock.go +++ b/flock.go @@ -143,10 +143,12 @@ func tryCtx(ctx context.Context, fn func() (bool, error), retryDelay time.Durati if ctx.Err() != nil { return false, ctx.Err() } + for { if ok, err := fn(); ok || err != nil { return ok, err } + select { case <-ctx.Done(): return false, ctx.Err() @@ -175,6 +177,7 @@ func (f *Flock) ensureFhState() { return } - f.fh.Close() + _ = f.fh.Close() + f.fh = nil } diff --git a/flock_unix.go b/flock_unix.go index 4fde9f0..f1d4e87 100644 --- a/flock_unix.go +++ b/flock_unix.go @@ -72,6 +72,7 @@ func (f *Flock) lock(locked *bool, flag int) error { } *locked = true + return nil } @@ -100,7 +101,7 @@ func (f *Flock) Unlock() error { return err } - f.fh.Close() + _ = f.fh.Close() f.l = false f.r = false @@ -152,10 +153,10 @@ func (f *Flock) try(locked *bool, flag int) (bool, error) { retry: err := syscall.Flock(int(f.fh.Fd()), flag|syscall.LOCK_NB) - switch err { - case syscall.EWOULDBLOCK: + switch { + case errors.Is(err, syscall.EWOULDBLOCK): return false, nil - case nil: + case err == nil: *locked = true return true, nil } @@ -183,12 +184,12 @@ func (f *Flock) reopenFDOnError(err error) (bool, error) { } if st, err := f.fh.Stat(); err == nil { // if the file is able to be read and written - if st.Mode()&0o600 == 0o600 { - f.fh.Close() + if st.Mode()&f.perm == f.perm { + _ = f.fh.Close() f.fh = nil - // reopen in read-write mode and set the filehandle - fh, err := os.OpenFile(f.path, os.O_CREATE|os.O_RDWR, os.FileMode(0o600)) + // reopen in read-write mode and set the file handle + fh, err := os.OpenFile(f.path, f.flag, f.perm) if err != nil { return false, err } diff --git a/flock_unix_variants.go b/flock_unix_variants.go index e485e16..4a439f4 100644 --- a/flock_unix_variants.go +++ b/flock_unix_variants.go @@ -257,13 +257,14 @@ func (f *Flock) try(locked *bool, flag lockType) (bool, error) { defer f.ensureFhState() } - haslock, err := f.doLock(tryLock, flag, false) + hasLock, err := f.doLock(tryLock, flag, false) if err != nil { return false, err } - *locked = haslock - return haslock, nil + *locked = hasLock + + return hasLock, nil } // setlkw calls FcntlFlock with cmd for the entire file indicated by fd. diff --git a/flock_windows.go b/flock_windows.go index ab8294d..82a24a2 100644 --- a/flock_windows.go +++ b/flock_windows.go @@ -81,7 +81,7 @@ func (f *Flock) Unlock() error { return errNo } - f.fh.Close() + _ = f.fh.Close() f.l = false f.r = false