Skip to content

Commit

Permalink
feat: use options on retry (unix) (#78)
Browse files Browse the repository at this point in the history
  • Loading branch information
ldez committed Jun 30, 2024
1 parent 41cd564 commit b659e1e
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 13 deletions.
5 changes: 4 additions & 1 deletion flock.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -175,6 +177,7 @@ func (f *Flock) ensureFhState() {
return
}

f.fh.Close()
_ = f.fh.Close()

f.fh = nil
}
17 changes: 9 additions & 8 deletions flock_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ func (f *Flock) lock(locked *bool, flag int) error {
}

*locked = true

return nil
}

Expand Down Expand Up @@ -100,7 +101,7 @@ func (f *Flock) Unlock() error {
return err
}

f.fh.Close()
_ = f.fh.Close()

f.l = false
f.r = false
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down
7 changes: 4 additions & 3 deletions flock_unix_variants.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion flock_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func (f *Flock) Unlock() error {
return errNo
}

f.fh.Close()
_ = f.fh.Close()

f.l = false
f.r = false
Expand Down

0 comments on commit b659e1e

Please sign in to comment.