Cleanup PR #647, Resolves Issue #611

This commit is contained in:
BJ Dierkes 2023-12-26 19:41:38 -06:00
commit 2202fadd25
4 changed files with 20 additions and 2 deletions

View File

@ -10,7 +10,8 @@ Bugs:
Features:
- None
- `[utils.fs]` Add Timestamp Support to fs.backup
- [Issue #611](https://github.com/datafolklabs/cement/issues/611)
Refactoring:

View File

@ -19,4 +19,5 @@ documentation, or testing:
- Stelios Tymvios (namedLambda)
- Spyros Vlachos (devspyrosv)
- Joe Roberts (jjroberts)
- Mudassir Chapra(muddi900)
- sigma67

View File

@ -3,6 +3,7 @@
import os
import tempfile
import shutil
from datetime import datetime
class Tmp(object):
@ -170,7 +171,7 @@ def ensure_parent_dir_exists(path):
return ensure_dir_exists(parent_dir)
def backup(path, suffix='.bak'):
def backup(path, suffix='.bak', **kwargs):
"""
Rename a file or directory safely without overwriting an existing
backup of the same name.
@ -178,6 +179,9 @@ def backup(path, suffix='.bak'):
Args:
path (str): The path to the file or directory to make a backup of.
suffix (str): The suffix to rename files with.
timestamp(bool): whether to add a timestamp to the backup suffix
timestamp_format(str): Date-Time format in python datetime.datetime
notation. default '%Y-%m-%d-%H:%M:%S'
Returns:
str: The new path of backed up file/directory
@ -194,6 +198,12 @@ def backup(path, suffix='.bak'):
count = -1
new_path = None
path = abspath(path)
if kwargs.get('timestamp', False) is True:
timestamp_format = kwargs.get('timestamp_format', '%Y-%m-%d-%H:%M:%S')
timestamp = datetime.now().strftime(timestamp_format)
suffix = '-'.join((suffix, timestamp))
while True:
if os.path.exists(path):
if count == -1:

View File

@ -1,5 +1,6 @@
import os
import re
from pytest import raises
from cement.utils import fs
@ -73,3 +74,8 @@ def test_backup_dir_trailing_slash(tmp):
# https://github.com/datafolklabs/cement/issues/610
bkdir = fs.backup("%s/" % tmp.dir)
assert "%s.bak" % os.path.basename(tmp.dir) == os.path.basename(bkdir)
def test_backup_timestamp(tmp):
bkfile = fs.backup(tmp.file, timestamp=True)
assert re.match('(.*).bak-[\d]+-[\d]+-[\d]+(.*)', bkfile) # noqa: W605