Skip to content

Commit a46ff14

Browse files
committed
Add FilestatMatcher
Signed-off-by: Olivier Mehani <shtrom@ssji.net>
1 parent c3072d0 commit a46ff14

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

rotate_backups/__init__.py

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -353,8 +353,41 @@ def timestamp_pattern(self, value):
353353
set_property(self, 'timestamp_pattern', pattern)
354354

355355

356-
class RotateBackups(PropertyManager):
356+
class FilestatMatch(Match):
357+
"""A match based on a filename statistics."""
358+
359+
entry: str = None
360+
field: str = None
361+
362+
def __init__(self, entry: str, timestamp='mtime'):
363+
"""Make a Match from a field's stat attribute."""
364+
self.entry = entry
365+
self.field = f'st_{timestamp}'
366+
367+
def match_to_datetime(self) -> datetime.datetime:
368+
"""Return a datetime from the file's stat field."""
369+
return datetime.datetime.fromtimestamp(
370+
getattr(os.stat(self.entry), self.field)
371+
)
372+
373+
374+
class FilestatMatcher(Matcher):
375+
"""A date-matching scheme based on file statistics."""
357376

377+
timestamp: str = None
378+
379+
def __init__(self, timestamp: str = 'mtime'):
380+
"""Make a Matcher based on a file's stat attribute."""
381+
self.timestamp = timestamp
382+
383+
def search(self, location: str, entry: str) -> FilestatMatch:
384+
"""Return the file's stat attribute."""
385+
return FilestatMatch(
386+
os.path.join(location.directory, entry),
387+
self.timestamp)
388+
389+
390+
class RotateBackups(PropertyManager):
358391
"""Python API for the ``rotate-backups`` program."""
359392

360393
def __init__(self, rotation_scheme, **options):
@@ -371,6 +404,9 @@ def __init__(self, rotation_scheme, **options):
371404
"""
372405
options.update(rotation_scheme=rotation_scheme)
373406
super(RotateBackups, self).__init__(**options)
407+
if self.stat_timestamp:
408+
logger.info("Using file mtime to determine file date")
409+
self.matcher = FilestatMatcher()
374410

375411
@mutable_property
376412
def config_file(self):
@@ -511,6 +547,10 @@ def rotation_scheme(self):
511547
in the dictionary.
512548
"""
513549

550+
@mutable_property
551+
def stat_timestamp(self):
552+
"""Whether to use the files' mtime instead of parsing their name."""
553+
514554
@mutable_property
515555
def strict(self):
516556
"""

0 commit comments

Comments
 (0)