Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add rename_file and remove_file to TradeEnv #161

Merged
merged 1 commit into from
May 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading