@@ -196,13 +196,13 @@ def future_import(feature, node):
196196 if does_tree_import (u"__future__" , feature , node ):
197197 return
198198
199- # Look for a shebang line
200- shebang_idx = None
199+ # Look for a shebang or encoding line
200+ shebang_encoding_idx = None
201201
202202 for idx , node in enumerate (root .children ):
203- # If it's a shebang line, attach the prefix to
204- if is_shebang_comment (node ):
205- shebang_idx = idx
203+ # If it's a shebang or encoding line, attach the prefix to
204+ if is_shebang_comment (node ) or is_encoding_comment ( node ) :
205+ shebang_encoding_idx = idx
206206 if node .type == syms .simple_stmt and \
207207 len (node .children ) > 0 and node .children [0 ].type == token .STRING :
208208 # skip over docstring
@@ -216,9 +216,9 @@ def future_import(feature, node):
216216 return
217217
218218 import_ = FromImport (u'__future__' , [Leaf (token .NAME , feature , prefix = " " )])
219- if shebang_idx == 0 and idx == 0 :
219+ if shebang_encoding_idx == 0 and idx == 0 :
220220 # If this __future__ import would go on the first line,
221- # detach the shebang prefix from the current first line
221+ # detach the shebang / encoding prefix from the current first line
222222 # and attach it to our new __future__ import node.
223223 import_ .prefix = root .children [0 ].prefix
224224 root .children [0 ].prefix = u''
@@ -424,16 +424,34 @@ def check_future_import(node):
424424 assert False , "strange import: %s" % savenode
425425
426426
427- SHEBANG_REGEX = r'^#!\s*.*python'
427+ SHEBANG_REGEX = r'^#!.*python'
428+ ENCODING_REGEX = r"^#.*coding[:=]\s*([-\w.]+)"
429+
428430
429431def is_shebang_comment (node ):
430432 """
431433 Comments are prefixes for Leaf nodes. Returns whether the given node has a
432- prefix that looks like a shebang line.
434+ prefix that looks like a shebang line or an encoding line:
435+
436+ #!/usr/bin/env python
437+ #!/usr/bin/python3
433438 """
434439 return bool (re .match (SHEBANG_REGEX , node .prefix ))
435440
436441
442+ def is_encoding_comment (node ):
443+ """
444+ Comments are prefixes for Leaf nodes. Returns whether the given node has a
445+ prefix that looks like an encoding line:
446+
447+ # coding: utf-8
448+ # encoding: utf-8
449+ # -*- coding: <encoding name> -*-
450+ # vim: set fileencoding=<encoding name> :
451+ """
452+ return bool (re .match (ENCODING_REGEX , node .prefix ))
453+
454+
437455def wrap_in_fn_call (fn_name , args , prefix = None ):
438456 """
439457 Example:
0 commit comments