diff --git a/CHANGELOG.md b/CHANGELOG.md index e80bc5f0..04c27a0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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: diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index c1491541..a4e5e3bc 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -19,4 +19,5 @@ documentation, or testing: - Stelios Tymvios (namedLambda) - Spyros Vlachos (devspyrosv) - Joe Roberts (jjroberts) +- Mudassir Chapra(muddi900) - sigma67 diff --git a/cement/utils/fs.py b/cement/utils/fs.py index d4829cc3..fa0644d9 100644 --- a/cement/utils/fs.py +++ b/cement/utils/fs.py @@ -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: diff --git a/tests/utils/test_fs.py b/tests/utils/test_fs.py index 13d9b909..c856a234 100644 --- a/tests/utils/test_fs.py +++ b/tests/utils/test_fs.py @@ -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