Skip to content

Commit

Permalink
Fix reading egg file (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
gaogaotiantian authored Feb 28, 2021
1 parent c01b803 commit 8e42103
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 4 deletions.
26 changes: 22 additions & 4 deletions src/watchpoints/watch_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import sys
import pprint
import threading
import os.path
import zipfile


class WatchPrint:
Expand Down Expand Up @@ -50,10 +52,26 @@ def _frame_string(self, frame):

def getsourceline(self, exec_info):
try:
with open(exec_info[1], encoding="utf-8") as f:
lines = f.readlines()
return f"> {lines[exec_info[2] - 1].strip()}"
except (FileNotFoundError, PermissionError):
filename = exec_info[1]
if os.path.exists(filename):
with open(exec_info[1], encoding="utf-8") as f:
lines = f.readlines()
return f"> {lines[exec_info[2] - 1].strip()}"
else:
# We may have an egg file, we try to figure out if we have a zipfile
# in the path and unzip that
potential_egg = filename
f_paths = []
while os.path.dirname(potential_egg) != potential_egg:
potential_egg, f_path = os.path.split(potential_egg)
f_paths.append(f_path)
if zipfile.is_zipfile(potential_egg):
with zipfile.ZipFile(potential_egg) as zf:
with zf.open("/".join(reversed(f_paths))) as f:
lines = f.readlines()
return f"> {lines[exec_info[2] - 1].decode('utf-8').strip()}"
return "unable to locate the source"
except (FileNotFoundError, PermissionError): # pragma: no cover
return "unable to locate the source"

def printer(self, obj):
Expand Down
Binary file added tests/data/watchpoints-0.1.5-py3.8.egg
Binary file not shown.
13 changes: 13 additions & 0 deletions tests/test_watch_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import io
import inspect
import unittest
import os.path
import sys
from watchpoints.watch_print import WatchPrint

Expand All @@ -31,3 +32,15 @@ def __init__(self):
elem.alias = "james"
wp(inspect.currentframe(), elem, ("a", "b", "c"))
self.assertIn("james", s.getvalue())

def test_getsourceline(self):
wp = WatchPrint()
line = wp.getsourceline((
None,
os.path.join(os.path.dirname(__file__), "data", "watchpoints-0.1.5-py3.8.egg", "watchpoints", "watch_print.py"),
12
))
self.assertEqual(line, "> class WatchPrint:")

line = wp.getsourceline((None, "file/not/exist", 100))
self.assertEqual(line, "unable to locate the source")

0 comments on commit 8e42103

Please sign in to comment.