From 7ff173f5ee6fe37d5a8bae5c250f0e8c17022ab4 Mon Sep 17 00:00:00 2001 From: Ludovic Fernandez Date: Sat, 6 Jul 2024 23:24:19 +0200 Subject: [PATCH] chore: factorize (#91) --- flock.go | 21 +++++++++++++++------ flock_unix.go | 10 +++------- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/flock.go b/flock.go index 4c99551..73a2579 100644 --- a/flock.go +++ b/flock.go @@ -176,9 +176,11 @@ func (f *Flock) setFh() error { return nil } -// ensure the file handle is closed if no lock is held. -func (f *Flock) ensureFhState() { - if f.l || f.r || f.fh == nil { +// resetFh resets file handle: +// - tries to close the file (ignore errors) +// - sets fh to nil. +func (f *Flock) resetFh() { + if f.fh == nil { return } @@ -187,11 +189,18 @@ func (f *Flock) ensureFhState() { f.fh = nil } +// ensure the file handle is closed if no lock is held. +func (f *Flock) ensureFhState() { + if f.l || f.r || f.fh == nil { + return + } + + f.resetFh() +} + func (f *Flock) reset() { f.l = false f.r = false - _ = f.fh.Close() - - f.fh = nil + f.resetFh() } diff --git a/flock_unix.go b/flock_unix.go index 1c9d079..b27089a 100644 --- a/flock_unix.go +++ b/flock_unix.go @@ -9,7 +9,6 @@ package flock import ( "errors" - "os" "golang.org/x/sys/unix" ) @@ -197,16 +196,13 @@ func (f *Flock) reopenFDOnError(err error) (bool, error) { return false, nil } - _ = f.fh.Close() - f.fh = nil + f.resetFh() - // reopen in read-write mode and set the file handle - fh, err := os.OpenFile(f.path, f.flag, f.perm) + // reopen the file handle + err = f.setFh() if err != nil { return false, err } - f.fh = fh - return true, nil }