Files
lazygit/pkg/config/file_lock.go
T
Stefan HallerandClaude Opus 5.5 ce77cfaf92 Lock state.yml while reading or updating it
Two lazygit instances can update state.yml at the same moment. Both
read the same contents, and the second write discards the change of the
first. Also, os.WriteFile empties the file before it writes the new
contents. An instance that reads the file at that moment gets an empty
file, which reads as the default state, or a partial one, which doesn't
parse. This can already happen when several instances start at once,
for example when a tmux session is restored, because each of them
updates state.yml at startup.

Take an exclusive lock on a separate lock file while updating, and a
shared one while reading. Each lock call opens the lock file anew, so
the lock also keeps goroutines of the same instance apart; the test
relies on this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 08:10:59 +01:00

34 lines
696 B
Go

//go:build !windows
package config
import (
"errors"
"os"
"golang.org/x/sys/unix"
)
// lockFile blocks until it has locked file. The lock is released by unlockFile,
// or when the file is closed or the process exits.
func lockFile(file *os.File, kind lockKind) error {
how := unix.LOCK_SH
if kind == exclusiveLock {
how = unix.LOCK_EX
}
for {
err := unix.Flock(int(file.Fd()), how)
if !errors.Is(err, unix.EINTR) {
return err
}
}
}
func unlockFile(file *os.File) error {
return unix.Flock(int(file.Fd()), unix.LOCK_UN)
}
func isLockingUnsupported(err error) bool {
return errors.Is(err, unix.ENOTSUP) || errors.Is(err, unix.EOPNOTSUPP) || errors.Is(err, unix.ENOLCK)
}