Skip to content

Commit

Permalink
fix: issue where home dir was not hidden in stacktraces (#2189)
Browse files Browse the repository at this point in the history
  • Loading branch information
antazoey authored Jul 25, 2024
1 parent bcfadd3 commit abc8a25
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 10 deletions.
25 changes: 16 additions & 9 deletions src/ape/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ def __init__(
super().__init__(message)


def handle_ape_exception(err: ApeException, base_paths: Iterable[Path]) -> bool:
def handle_ape_exception(err: ApeException, base_paths: Iterable[Union[Path, str]]) -> bool:
"""
Handle a transaction error by showing relevant stack frames,
including custom contract frames added to the exception.
Expand All @@ -708,26 +708,33 @@ def handle_ape_exception(err: ApeException, base_paths: Iterable[Path]) -> bool:
Args:
err (:class:`~ape.exceptions.TransactionError`): The transaction error
being handled.
base_paths (Optional[Iterable[Path]]): Optionally include additional
base_paths (Optional[Iterable[Union[Path, str]]]): Optionally include additional
source-path prefixes to use when finding relevant frames.
Returns:
bool: ``True`` if outputted something.
"""

tb = traceback.extract_tb(sys.exc_info()[2])
if not (relevant_tb := [f for f in tb if any(str(p) in f.filename for p in base_paths)]):
home_str = str(Path.home())
if not (relevant_frames := _get_relevant_frames(base_paths)):
return False

click.echo()
formatted_tb = traceback.format_list(relevant_tb)
rich_print("".join(formatted_tb))
formatted_tb = [x.replace(home_str, "$HOME") for x in relevant_frames]
rich_print(f"\n{''.join(formatted_tb)}")

# Prevent double logging traceback.
# Prevent double logging of a traceback by using `show_traceback=False`.
logger.error(Abort.from_ape_exception(err, show_traceback=False))
return True


def _get_relevant_frames(base_paths: Iterable[Union[Path, str]]):
# Abstracted for testing easement.
tb = traceback.extract_tb(sys.exc_info()[2])
if relevant_tb := [f for f in tb if any(str(p) in f.filename for p in base_paths)]:
return [x for x in traceback.format_list(relevant_tb)]

return []


class Abort(click.ClickException):
"""
A wrapper around a CLI exception. When you raise this error,
Expand Down
27 changes: 26 additions & 1 deletion tests/functional/test_exceptions.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import re
from pathlib import Path

from ape.api import ReceiptAPI
from ape.exceptions import Abort, NetworkNotFoundError, TransactionError
from ape.exceptions import (
Abort,
ContractLogicError,
NetworkNotFoundError,
TransactionError,
handle_ape_exception,
)
from ape_ethereum.transactions import DynamicFeeTransaction, Receipt


Expand Down Expand Up @@ -104,3 +111,21 @@ def test_no_options(self):
actual = str(error)
expected = "No networks found."
assert actual == expected


def test_handle_ape_exception_hides_home_dir(mocker):
base_paths = ["this/is/base/path"]
mock_tb_get = mocker.patch("ape.exceptions._get_relevant_frames")
tb_str = f"""
File "{Path.home()}/this/is/base/path/myfile.vy", line 18, in setNumber2
setNumber(5)
""".lstrip()
mock_tb_get.return_value = [tb_str]
print_watcher = mocker.patch("ape.exceptions.rich_print")
ape_exception = ContractLogicError()
assert handle_ape_exception(ape_exception, base_paths) is True
actual = print_watcher.call_args[0][0]

# We expect the same only the home dir has been hidden.
expected = "\n" + tb_str.replace(str(Path.home()), "$HOME")
assert actual == expected

0 comments on commit abc8a25

Please sign in to comment.