summaryrefslogtreecommitdiffstats
path: root/Lib/lib2to3
diff options
context:
space:
mode:
authorSerhiy Storchaka <storchaka@gmail.com>2013-09-16 20:57:00 (GMT)
committerSerhiy Storchaka <storchaka@gmail.com>2013-09-16 20:57:00 (GMT)
commit935349406aeb9d43fecea447f0309ce63ed3a406 (patch)
tree0c0cbc4c991840c4cb1e0cf835069fe571be7c03 /Lib/lib2to3
parent3c41154331ed281514943a1d2c61fca0d89dc63c (diff)
parentdafea851901fc1de278ad79727d3b44f46ba5a31 (diff)
downloadcpython-935349406aeb9d43fecea447f0309ce63ed3a406.zip
cpython-935349406aeb9d43fecea447f0309ce63ed3a406.tar.gz
cpython-935349406aeb9d43fecea447f0309ce63ed3a406.tar.bz2
Issue #18873: The tokenize module, IDLE, 2to3, and the findnocoding.py script
now detect Python source code encoding only in comment lines.
Diffstat (limited to 'Lib/lib2to3')
-rw-r--r--Lib/lib2to3/pgen2/tokenize.py9
-rw-r--r--Lib/lib2to3/tests/data/false_encoding.py2
-rw-r--r--Lib/lib2to3/tests/test_refactor.py4
3 files changed, 10 insertions, 5 deletions
diff --git a/Lib/lib2to3/pgen2/tokenize.py b/Lib/lib2to3/pgen2/tokenize.py
index 31e2969..83656fc 100644
--- a/Lib/lib2to3/pgen2/tokenize.py
+++ b/Lib/lib2to3/pgen2/tokenize.py
@@ -236,7 +236,7 @@ class Untokenizer:
startline = False
toks_append(tokval)
-cookie_re = re.compile("coding[:=]\s*([-\w.]+)")
+cookie_re = re.compile(r'^[ \t\f]*#.*coding[:=][ \t]*([-\w.]+)', re.ASCII)
def _get_normal_name(orig_enc):
"""Imitates get_normal_name in tokenizer.c."""
@@ -281,11 +281,10 @@ def detect_encoding(readline):
line_string = line.decode('ascii')
except UnicodeDecodeError:
return None
-
- matches = cookie_re.findall(line_string)
- if not matches:
+ match = cookie_re.match(line_string)
+ if not match:
return None
- encoding = _get_normal_name(matches[0])
+ encoding = _get_normal_name(match.group(1))
try:
codec = lookup(encoding)
except LookupError:
diff --git a/Lib/lib2to3/tests/data/false_encoding.py b/Lib/lib2to3/tests/data/false_encoding.py
new file mode 100644
index 0000000..f4e59e7
--- /dev/null
+++ b/Lib/lib2to3/tests/data/false_encoding.py
@@ -0,0 +1,2 @@
+#!/usr/bin/env python
+print '#coding=0'
diff --git a/Lib/lib2to3/tests/test_refactor.py b/Lib/lib2to3/tests/test_refactor.py
index 8bdebc1..5ecd9b1 100644
--- a/Lib/lib2to3/tests/test_refactor.py
+++ b/Lib/lib2to3/tests/test_refactor.py
@@ -271,6 +271,10 @@ from __future__ import print_function"""
fn = os.path.join(TEST_DATA_DIR, "different_encoding.py")
self.check_file_refactoring(fn)
+ def test_false_file_encoding(self):
+ fn = os.path.join(TEST_DATA_DIR, "false_encoding.py")
+ data = self.check_file_refactoring(fn)
+
def test_bom(self):
fn = os.path.join(TEST_DATA_DIR, "bom.py")
data = self.check_file_refactoring(fn)