Skip to content

Commit

Permalink
feat: add rename_file and remove_file to TradeEnv
Browse files Browse the repository at this point in the history
This adds normalizing methods for removing and renaming files that will log the operation at DEBUG1,
and in the case of rename will ensure a .old backup of the existing file.

Committing separately of other work that leverages it.
  • Loading branch information
kfsone authored and eyeonus committed May 5, 2024
1 parent a6ca423 commit 778278d
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions tradedangerous/tradeenv.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# into a single object, the TradeEnv. See TradeEnv docstring for more.
from __future__ import annotations

from pathlib import Path
import os
import sys
import traceback
Expand Down Expand Up @@ -270,3 +271,36 @@ def _WARN_DISABLED(*args, **kwargs):
return noteFn

return None

def remove_file(self, *args) -> bool:
""" Unlinks a file, as long as it exists, and logs the action at level 1. """
path = Path(*args)
if not path.exists():
return False
path.unlink()
self.DEBUG1(":cross_mark: deleted {}", path)
return True

def rename_file(self, *, old: os.PathLike, new: os.PathLike) -> bool:
"""
If 'new' exists, deletes it, and then attempts to rename old -> new. If new is not specified,
then '.old' is appended to the end of the old filename while retaining the original suffix.
:param old: The current path/name of the file.
:param new: The path/name to rename the file to and remove before attempting.
:returns: True if the file existed and was renamed.
"""
# Promote new to a guaranteed Path and remove it if it's present.
new = Path(new)
self.remove_file(new)

# Promote new to a guaranteed Path and confirm it exists.
old = Path(old)
if not old.exists():
return False

# Perform the rename and log it at level 1.
old.rename(new)
self.DEBUG1(":recycle: moved {} to {}", old, new)

return True

0 comments on commit 778278d

Please sign in to comment.