| 1 |
#!/usr/bin/env python3 |
| 2 |
# |
| 3 |
# byteify-strings.py - transform string literals to be Python 3 safe |
| 4 |
# |
| 5 |
# Copyright 2015 Gregory Szorc <[email protected]> |
| 6 |
# |
| 7 |
# This software may be used and distributed according to the terms of the |
| 8 |
# GNU General Public License version 2 or any later version. |
| 9 |
|
| 10 |
|
| 11 |
import argparse |
| 12 |
import contextlib |
| 13 |
import errno |
| 14 |
import os |
| 15 |
import sys |
| 16 |
import tempfile |
| 17 |
import token |
| 18 |
import tokenize |
| 19 |
|
| 20 |
|
| 21 |
def adjusttokenpos(t, ofs): |
| 22 |
"""Adjust start/end column of the given token""" |
| 23 |
return t._replace( |
| 24 |
start=(t.start[0], t.start[1] + ofs), end=(t.end[0], t.end[1] + ofs) |
| 25 |
) |
| 26 |
|
| 27 |
|
| 28 |
def replacetokens(tokens, opts): |
| 29 |
"""Transform a stream of tokens from raw to Python 3. |
| 30 |
|
| 31 |
Returns a generator of possibly rewritten tokens. |
| 32 |
|
| 33 |
The input token list may be mutated as part of processing. However, |
| 34 |
its changes do not necessarily match the output token stream. |
| 35 |
""" |
| 36 |
sysstrtokens = set() |
| 37 |
|
| 38 |
# The following utility functions access the tokens list and i index of |
| 39 |
# the for i, t enumerate(tokens) loop below |
| 40 |
def _isop(j, *o): |
| 41 |
"""Assert that tokens[j] is an OP with one of the given values""" |
| 42 |
try: |
| 43 |
return tokens[j].type == token.OP and tokens[j].string in o |
| 44 |
except IndexError: |
| 45 |
return False |
| 46 |
|
| 47 |
def _findargnofcall(n): |
| 48 |
"""Find arg n of a call expression (start at 0) |
| 49 |
|
| 50 |
Returns index of the first token of that argument, or None if |
| 51 |
there is not that many arguments. |
| 52 |
|
| 53 |
Assumes that token[i + 1] is '('. |
| 54 |
|
| 55 |
""" |
| 56 |
nested = 0 |
| 57 |
for j in range(i + 2, len(tokens)): |
| 58 |
if _isop(j, ')', ']', '}'): |
| 59 |
# end of call, tuple, subscription or dict / set |
| 60 |
nested -= 1 |
| 61 |
if nested < 0: |
| 62 |
return None |
| 63 |
elif n == 0: |
| 64 |
# this is the starting position of arg |
| 65 |
return j |
| 66 |
elif _isop(j, '(', '[', '{'): |
| 67 |
nested += 1 |
| 68 |
elif _isop(j, ',') and nested == 0: |
| 69 |
n -= 1 |
| 70 |
|
| 71 |
return None |
| 72 |
|
| 73 |
def _ensuresysstr(j): |
| 74 |
"""Make sure the token at j is a system string |
| 75 |
|
| 76 |
Remember the given token so the string transformer won't add |
| 77 |
the byte prefix. |
| 78 |
|
| 79 |
Ignores tokens that are not strings. Assumes bounds checking has |
| 80 |
already been done. |
| 81 |
|
| 82 |
""" |
| 83 |
k = j |
| 84 |
currtoken = tokens[k] |
| 85 |
while currtoken.type in (token.STRING, token.NEWLINE, tokenize.NL): |
| 86 |
k += 1 |
| 87 |
if currtoken.type == token.STRING and currtoken.string.startswith( |
| 88 |
("'", '"') |
| 89 |
): |
| 90 |
sysstrtokens.add(currtoken) |
| 91 |
try: |
| 92 |
currtoken = tokens[k] |
| 93 |
except IndexError: |
| 94 |
break |
| 95 |
|
| 96 |
def _isitemaccess(j): |
| 97 |
"""Assert the next tokens form an item access on `tokens[j]` and that |
| 98 |
`tokens[j]` is a name. |
| 99 |
""" |
| 100 |
try: |
| 101 |
return ( |
| 102 |
tokens[j].type == token.NAME |
| 103 |
and _isop(j + 1, '[') |
| 104 |
and tokens[j + 2].type == token.STRING |
| 105 |
and _isop(j + 3, ']') |
| 106 |
) |
| 107 |
except IndexError: |
| 108 |
return False |
| 109 |
|
| 110 |
def _ismethodcall(j, *methodnames): |
| 111 |
"""Assert the next tokens form a call to `methodname` with a string |
| 112 |
as first argument on `tokens[j]` and that `tokens[j]` is a name. |
| 113 |
""" |
| 114 |
try: |
| 115 |
return ( |
| 116 |
tokens[j].type == token.NAME |
| 117 |
and _isop(j + 1, '.') |
| 118 |
and tokens[j + 2].type == token.NAME |
| 119 |
and tokens[j + 2].string in methodnames |
| 120 |
and _isop(j + 3, '(') |
| 121 |
and tokens[j + 4].type == token.STRING |
| 122 |
) |
| 123 |
except IndexError: |
| 124 |
return False |
| 125 |
|
| 126 |
coldelta = 0 # column increment for new opening parens |
| 127 |
coloffset = -1 # column offset for the current line (-1: TBD) |
| 128 |
parens = [(0, 0, 0, -1)] # stack of (line, end-column, column-offset, type) |
| 129 |
ignorenextline = False # don't transform the next line |
| 130 |
insideignoreblock = False # don't transform until turned off |
| 131 |
for i, t in enumerate(tokens): |
| 132 |
# Compute the column offset for the current line, such that |
| 133 |
# the current line will be aligned to the last opening paren |
| 134 |
# as before. |
| 135 |
if coloffset < 0: |
| 136 |
lastparen = parens[-1] |
| 137 |
if t.start[1] == lastparen[1]: |
| 138 |
coloffset = lastparen[2] |
| 139 |
elif t.start[1] + 1 == lastparen[1] and lastparen[3] not in ( |
| 140 |
token.NEWLINE, |
| 141 |
tokenize.NL, |
| 142 |
): |
| 143 |
# fix misaligned indent of s/util.Abort/error.Abort/ |
| 144 |
coloffset = lastparen[2] + (lastparen[1] - t.start[1]) |
| 145 |
else: |
| 146 |
coloffset = 0 |
| 147 |
|
| 148 |
# Reset per-line attributes at EOL. |
| 149 |
if t.type in (token.NEWLINE, tokenize.NL): |
| 150 |
yield adjusttokenpos(t, coloffset) |
| 151 |
coldelta = 0 |
| 152 |
coloffset = -1 |
| 153 |
if not insideignoreblock: |
| 154 |
ignorenextline = ( |
| 155 |
tokens[i - 1].type == token.COMMENT |
| 156 |
and tokens[i - 1].string == "# no-py3-transform" |
| 157 |
) |
| 158 |
continue |
| 159 |
|
| 160 |
if t.type == token.COMMENT: |
| 161 |
if t.string == "# py3-transform: off": |
| 162 |
insideignoreblock = True |
| 163 |
if t.string == "# py3-transform: on": |
| 164 |
insideignoreblock = False |
| 165 |
|
| 166 |
if ignorenextline or insideignoreblock: |
| 167 |
yield adjusttokenpos(t, coloffset) |
| 168 |
continue |
| 169 |
|
| 170 |
# Remember the last paren position. |
| 171 |
if _isop(i, '(', '[', '{'): |
| 172 |
parens.append(t.end + (coloffset + coldelta, tokens[i + 1].type)) |
| 173 |
elif _isop(i, ')', ']', '}'): |
| 174 |
parens.pop() |
| 175 |
|
| 176 |
# Convert most string literals to byte literals. String literals |
| 177 |
# in Python 2 are bytes. String literals in Python 3 are unicode. |
| 178 |
# Most strings in Mercurial are bytes and unicode strings are rare. |
| 179 |
# Rather than rewrite all string literals to use ``b''`` to indicate |
| 180 |
# byte strings, we apply this token transformer to insert the ``b`` |
| 181 |
# prefix nearly everywhere. |
| 182 |
if t.type == token.STRING and t not in sysstrtokens: |
| 183 |
s = t.string |
| 184 |
|
| 185 |
# Preserve docstrings as string literals. This is inconsistent |
| 186 |
# with regular unprefixed strings. However, the |
| 187 |
# "from __future__" parsing (which allows a module docstring to |
| 188 |
# exist before it) doesn't properly handle the docstring if it |
| 189 |
# is b''' prefixed, leading to a SyntaxError. We leave all |
| 190 |
# docstrings as unprefixed to avoid this. This means Mercurial |
| 191 |
# components touching docstrings need to handle unicode, |
| 192 |
# unfortunately. |
| 193 |
if s[0:3] in ("'''", '"""'): |
| 194 |
# If it's assigned to something, it's not a docstring |
| 195 |
if not _isop(i - 1, '='): |
| 196 |
yield adjusttokenpos(t, coloffset) |
| 197 |
continue |
| 198 |
|
| 199 |
# If the first character isn't a quote, it is likely a string |
| 200 |
# prefixing character (such as 'b', 'u', or 'r'. Ignore. |
| 201 |
if s[0] not in ("'", '"'): |
| 202 |
yield adjusttokenpos(t, coloffset) |
| 203 |
continue |
| 204 |
|
| 205 |
# String literal. Prefix to make a b'' string. |
| 206 |
yield adjusttokenpos(t._replace(string='b%s' % t.string), coloffset) |
| 207 |
coldelta += 1 |
| 208 |
continue |
| 209 |
|
| 210 |
# This looks like a function call. |
| 211 |
if t.type == token.NAME and _isop(i + 1, '('): |
| 212 |
fn = t.string |
| 213 |
|
| 214 |
# *attr() builtins don't accept byte strings to 2nd argument. |
| 215 |
if fn in ( |
| 216 |
'getattr', |
| 217 |
'setattr', |
| 218 |
'hasattr', |
| 219 |
'safehasattr', |
| 220 |
'wrapfunction', |
| 221 |
'wrapclass', |
| 222 |
'addattr', |
| 223 |
): |
| 224 |
arg1idx = _findargnofcall(1) |
| 225 |
if arg1idx is not None: |
| 226 |
_ensuresysstr(arg1idx) |
| 227 |
|
| 228 |
# .encode() and .decode() on str/bytes/unicode don't accept |
| 229 |
# byte strings on Python 3. |
| 230 |
elif fn in ('encode', 'decode') and _isop(i - 1, '.'): |
| 231 |
for argn in range(2): |
| 232 |
argidx = _findargnofcall(argn) |
| 233 |
if argidx is not None: |
| 234 |
_ensuresysstr(argidx) |
| 235 |
|
| 236 |
# It changes iteritems/values to items/values as they are not |
| 237 |
# present in Python 3 world. |
| 238 |
elif opts['dictiter'] and fn in ('iteritems', 'itervalues'): |
| 239 |
yield adjusttokenpos(t._replace(string=fn[4:]), coloffset) |
| 240 |
continue |
| 241 |
|
| 242 |
if t.type == token.NAME and t.string in opts['treat-as-kwargs']: |
| 243 |
if _isitemaccess(i): |
| 244 |
_ensuresysstr(i + 2) |
| 245 |
if _ismethodcall(i, 'get', 'pop', 'setdefault', 'popitem'): |
| 246 |
_ensuresysstr(i + 4) |
| 247 |
|
| 248 |
# Looks like "if __name__ == '__main__'". |
| 249 |
if ( |
| 250 |
t.type == token.NAME |
| 251 |
and t.string == '__name__' |
| 252 |
and _isop(i + 1, '==') |
| 253 |
): |
| 254 |
_ensuresysstr(i + 2) |
| 255 |
|
| 256 |
# Emit unmodified token. |
| 257 |
yield adjusttokenpos(t, coloffset) |
| 258 |
|
| 259 |
|
| 260 |
def process(fin, fout, opts): |
| 261 |
tokens = tokenize.tokenize(fin.readline) |
| 262 |
tokens = replacetokens(list(tokens), opts) |
| 263 |
fout.write(tokenize.untokenize(tokens)) |
| 264 |
|
| 265 |
|
| 266 |
def tryunlink(fname): |
| 267 |
try: |
| 268 |
os.unlink(fname) |
| 269 |
except OSError as err: |
| 270 |
if err.errno != errno.ENOENT: |
| 271 |
raise |
| 272 |
|
| 273 |
|
| 274 |
@contextlib.contextmanager |
| 275 |
def editinplace(fname): |
| 276 |
n = os.path.basename(fname) |
| 277 |
d = os.path.dirname(fname) |
| 278 |
fp = tempfile.NamedTemporaryFile( |
| 279 |
prefix='.%s-' % n, suffix='~', dir=d, delete=False |
| 280 |
) |
| 281 |
try: |
| 282 |
yield fp |
| 283 |
fp.close() |
| 284 |
if os.name == 'nt': |
| 285 |
tryunlink(fname) |
| 286 |
os.rename(fp.name, fname) |
| 287 |
finally: |
| 288 |
fp.close() |
| 289 |
tryunlink(fp.name) |
| 290 |
|
| 291 |
|
| 292 |
def main(): |
| 293 |
ap = argparse.ArgumentParser() |
| 294 |
ap.add_argument( |
| 295 |
'--version', action='version', version='Byteify strings 1.0' |
| 296 |
) |
| 297 |
ap.add_argument( |
| 298 |
'-i', |
| 299 |
'--inplace', |
| 300 |
action='store_true', |
| 301 |
default=False, |
| 302 |
help='edit files in place', |
| 303 |
) |
| 304 |
ap.add_argument( |
| 305 |
'--dictiter', |
| 306 |
action='store_true', |
| 307 |
default=False, |
| 308 |
help='rewrite iteritems() and itervalues()', |
| 309 |
), |
| 310 |
ap.add_argument( |
| 311 |
'--treat-as-kwargs', |
| 312 |
nargs="+", |
| 313 |
default=[], |
| 314 |
help="ignore kwargs-like objects", |
| 315 |
), |
| 316 |
ap.add_argument('files', metavar='FILE', nargs='+', help='source file') |
| 317 |
args = ap.parse_args() |
| 318 |
opts = { |
| 319 |
'dictiter': args.dictiter, |
| 320 |
'treat-as-kwargs': set(args.treat_as_kwargs), |
| 321 |
} |
| 322 |
for fname in args.files: |
| 323 |
fname = os.path.realpath(fname) |
| 324 |
if args.inplace: |
| 325 |
with editinplace(fname) as fout: |
| 326 |
with open(fname, 'rb') as fin: |
| 327 |
process(fin, fout, opts) |
| 328 |
else: |
| 329 |
with open(fname, 'rb') as fin: |
| 330 |
fout = sys.stdout.buffer |
| 331 |
process(fin, fout, opts) |
| 332 |
|
| 333 |
|
| 334 |
if __name__ == '__main__': |
| 335 |
if sys.version_info[0:2] < (3, 7): |
| 336 |
print('This script must be run under Python 3.7+') |
| 337 |
sys.exit(3) |
| 338 |
main() |