Commits

Naoki INADA  committed ef1e88b Merge

merge upstream

  • Participants
  • Parent commits dbbd85b, d51934e

Comments (0)

Files changed (4)

File bpython/repl.py

 import inspect
 import os
 import pydoc
+import re
 import subprocess
 import sys
 import textwrap
                 line = self.current_line()
                 if inspection.is_eval_safe_name(line):
                     obj = self.get_object(line)
-            source = inspect.getsource(obj)
-        except (AttributeError, IOError, NameError, TypeError):
+            return get_source(obj)
+        except (AttributeError, IOError, NameError, TypeError, UnicodeError):
             return None
-        else:
-            return source
 
     def complete(self, tab=False):
         """Construct a full list of possible completions and construct and
 
     return token_is_any_of
 
+
 def extract_exit_value(args):
     """Given the arguments passed to `SystemExit`, return the value that
     should be passed to `sys.exit`.
         return args[0]
     else:
         return args
+
+
+if py3:
+    get_source = inspect.get_source
+else:
+    def get_source(obj):
+        lines, lnum = inspect.findsource(obj)
+
+        # PEP 0263: Encoding declarations.
+        m = re.search(r"coding[:=]\s*([-\w.]+)", ''.join(lines[:2]))
+        if m:
+            encoding = m.group(1)
+        else:
+            encoding = 'ascii'
+
+        if not inspect.ismodule(object):
+            lines = inspect.getblock(lines[lnum:])
+
+        return ''.join(lines).decode(encoding)

File bpython/test/_pep263_1.py

+# -*- coding: utf-8 -*-
+def spam(self):
+    # テスト
+    pass

File bpython/test/_pep263_2.py

+#XYZZY
+# -*- coding: utf-8 -*-
+def spam(self):
+    # テスト
+    pass

File bpython/test/test_repl.py

         pass
 
 
+class TestGetSource(unittest.TestCase):
+
+    def test_simple(self):
+        source = repl.get_source(TestGetSource)
+        self.assertTrue(source.startswith("class TestGetSource"))
+
+    def test_pep263_1(self):
+        from bpython.test import _pep263_1 as mod
+        source = repl.get_source(mod.spam)
+        self.assertTrue(source.startswith("def spam(self):\n"))
+        self.assertTrue(b"\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88"
+                        in source.encode('utf-8'))
+
+    def test_pep263_2(self):
+        from bpython.test import _pep263_2 as mod
+        source = repl.get_source(mod.spam)
+        self.assertTrue(source.startswith("def spam(self):\n"))
+        self.assertTrue(b"\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88"
+                        in source.encode('utf-8'))
+
+    def test_get_source_of_current_name(self):
+        r = FakeRepl()
+        r.current_func = setup_config
+        source = r.get_source_of_current_name()
+        self.assertTrue(source.startswith("def setup_config"))
 
 if __name__ == '__main__':
     unittest.main()