|
| 1 | +// Copyright 2026 Josh Waldrep |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +//go:build windows |
| 5 | + |
| 6 | +package cli |
| 7 | + |
| 8 | +import ( |
| 9 | + "fmt" |
| 10 | + "os" |
| 11 | + "path/filepath" |
| 12 | + "syscall" |
| 13 | +) |
| 14 | + |
| 15 | +const ( |
| 16 | + errSharingViolation = syscall.Errno(32) |
| 17 | + errLockViolation = syscall.Errno(33) |
| 18 | +) |
| 19 | + |
| 20 | +// acquireRulesLock acquires an exclusive lock file handle for mutating |
| 21 | +// operations. On Windows, opening a file with share mode 0 prevents other |
| 22 | +// processes from opening the same path until the handle is closed. |
| 23 | +func acquireRulesLock(rulesDir string) (func(), error) { |
| 24 | + lockPath := filepath.Join(rulesDir, ".rules.lock") |
| 25 | + |
| 26 | + pathp, err := syscall.UTF16PtrFromString(lockPath) |
| 27 | + if err != nil { |
| 28 | + return nil, fmt.Errorf("encoding lock file path: %w", err) |
| 29 | + } |
| 30 | + |
| 31 | + handle, err := syscall.CreateFile( |
| 32 | + pathp, |
| 33 | + syscall.GENERIC_READ|syscall.GENERIC_WRITE, |
| 34 | + 0, |
| 35 | + nil, |
| 36 | + syscall.OPEN_ALWAYS, |
| 37 | + syscall.FILE_ATTRIBUTE_NORMAL, |
| 38 | + 0, |
| 39 | + ) |
| 40 | + if err != nil { |
| 41 | + if err == errSharingViolation || err == errLockViolation { |
| 42 | + return nil, fmt.Errorf("another rules command is running (lock: %s)", lockPath) |
| 43 | + } |
| 44 | + return nil, fmt.Errorf("opening lock file: %w", err) |
| 45 | + } |
| 46 | + |
| 47 | + f := os.NewFile(uintptr(handle), lockPath) |
| 48 | + if f == nil { |
| 49 | + _ = syscall.CloseHandle(handle) |
| 50 | + return nil, fmt.Errorf("creating lock file handle: %s", lockPath) |
| 51 | + } |
| 52 | + |
| 53 | + return func() { |
| 54 | + _ = f.Close() |
| 55 | + }, nil |
| 56 | +} |
0 commit comments