Files
Reims-Go/internal/filelock/filelock.go
T

49 lines
1.3 KiB
Go

// Package filelock takes exclusive, cross-process locks on files. The lock is
// LockFileEx over the whole file on Windows and flock elsewhere, which is
// what Rust's File::try_lock uses, so it also excludes reims-ctl and
// reims-util where they lock the same file.
package filelock
import (
"context"
"fmt"
"os"
"time"
)
// TryLock takes an exclusive lock on f without waiting. It reports false when
// another process holds it.
func TryLock(f *os.File) (bool, error) { return tryLock(f) }
// Unlock releases a lock taken with TryLock.
func Unlock(f *os.File) { unlock(f) }
// Acquire creates path if needed and waits until it holds an exclusive lock
// on it, checking every poll, until ctx ends. The returned function releases
// the lock and closes the file.
func Acquire(ctx context.Context, path string, poll time.Duration) (func(), error) {
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644)
if err != nil {
return nil, err
}
if poll <= 0 {
poll = 100 * time.Millisecond
}
for {
ok, err := tryLock(f)
if err != nil {
f.Close()
return nil, fmt.Errorf("lock %s: %w", path, err)
}
if ok {
return func() { unlock(f); f.Close() }, nil
}
select {
case <-ctx.Done():
f.Close()
return nil, fmt.Errorf("lock %s: %w", path, ctx.Err())
case <-time.After(poll):
}
}
}