Skip to content

Commit 8111aec

Browse files
authored
feat: add Stat method (#127)
1 parent 6f0f0ed commit 8111aec

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

flock.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,22 @@ func (f *Flock) RLocked() bool {
125125
return f.r
126126
}
127127

128+
// Stat returns the FileInfo structure describing the lock file.
129+
// If the lock file does not exist or cannot be accessed, an error is returned.
130+
//
131+
// This can be used to check the modification time of the lock file,
132+
// which is useful for detecting stale locks.
133+
func (f *Flock) Stat() (fs.FileInfo, error) {
134+
f.m.RLock()
135+
defer f.m.RUnlock()
136+
137+
if f.fh != nil {
138+
return f.fh.Stat()
139+
}
140+
141+
return os.Stat(f.path)
142+
}
143+
128144
func (f *Flock) String() string {
129145
return f.path
130146
}

flock_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,3 +313,36 @@ func (s *TestSuite) TestFlock_RLock() {
313313
s.False(gf.Locked())
314314
s.True(gf.RLocked())
315315
}
316+
317+
func (s *TestSuite) TestFlock_Stat() {
318+
// Test Stat when file doesn't exist yet (for non-directory case)
319+
if !s.dir {
320+
_, err := s.flock.Stat()
321+
s.True(os.IsNotExist(err))
322+
}
323+
324+
// Create the lock file
325+
locked, err := s.flock.TryLock()
326+
s.Require().NoError(err)
327+
s.True(locked)
328+
329+
// Test Stat after lock is acquired
330+
info, err := s.flock.Stat()
331+
s.Require().NoError(err)
332+
s.NotNil(info)
333+
334+
// Check modification time is recent
335+
modTime := info.ModTime()
336+
s.WithinDuration(time.Now(), modTime, 1*time.Second)
337+
338+
// Unlock and verify Stat still works (file persists)
339+
err = s.flock.Unlock()
340+
s.Require().NoError(err)
341+
342+
info, err = s.flock.Stat()
343+
s.Require().NoError(err)
344+
s.NotNil(info)
345+
346+
// The modification time should be approximately the same as before
347+
s.WithinDuration(modTime, info.ModTime(), 100*time.Millisecond)
348+
}

0 commit comments

Comments
 (0)