gunk-dev/the-valley

lock.go

sourceccb7354855a5main's published tip history
1.0 KiB
1package review
2
3import (
4 "errors"
5 "fmt"
6 "os"
7 "path/filepath"
8 "strings"
9 "syscall"
10)
11
12// ErrLocked: another klaus review --post holds this PR's lock.
13var ErrLocked = errors.New("another klaus review --post is running for this PR")
14
15// lockPR takes a non-blocking exclusive flock on dir/review-<owner>-<repo>-<n>.lock; the returned func releases it.
16func lockPR(dir, repo, prNumber string) (func(), error) {
17 if err := os.MkdirAll(dir, 0o755); err != nil {
18 return nil, err
19 }
20 name := strings.NewReplacer("/", "-", string(filepath.Separator), "-").Replace("review-" + repo + "-" + prNumber + ".lock")
21 path := filepath.Join(dir, name)
22 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644)
23 if err != nil {
24 return nil, err
25 }
26 if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
27 f.Close()
28 if errors.Is(err, syscall.EWOULDBLOCK) {
29 return nil, fmt.Errorf("%w (lock %s)", ErrLocked, path)
30 }
31 return nil, fmt.Errorf("locking %s: %w", path, err)
32 }
33 return func() { f.Close() }, nil // close drops the flock
34}