summaryrefslogtreecommitdiff
path: root/tools/find_deprecated_escaped_characters.py
blob: 6f90001ca6b12e0565c3e45364f57c44b03ffec6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#! /usr/bin/env python
r"""
Look for escape sequences deprecated in Python 3.6.

Python 3.6 deprecates a number of non-escape sequences starting with '\' that
were accepted before. For instance, '\(' was previously accepted but must now
be written as '\\(' or r'\('.

"""
from __future__ import division, absolute_import, print_function

import sys

def main(root):
    """Find deprecated escape sequences.

    Checks for deprecated escape sequences in ``*.py files``. If `root` is a
    file, that file is checked, if `root` is a directory all ``*.py`` files
    found in a recursive descent are checked.

    If a deprecated escape sequence is found, the file and line where found is
    printed. Note that for multiline strings the line where the string ends is
    printed and the error(s) are somewhere in the body of the string.

    Parameters
    ----------
    root : str
        File or directory to check.
    Returns
    -------
    None

    """
    import ast
    import tokenize
    import warnings
    from pathlib import Path

    count = 0
    base = Path(root)
    paths = base.rglob("*.py") if base.is_dir() else [base]
    for path in paths:
        # use tokenize to auto-detect encoding on systems where no
        # default encoding is defined (e.g. LANG='C')
        with tokenize.open(str(path)) as f:
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter('always')
                tree = ast.parse(f.read())
            if w:
                print("file: ", str(path))
                for e in w:
                    print('line: ', e.lineno, ': ', e.message)
                print()
                count += len(w)
    print("Errors Found", count)


if __name__ == "__main__":
    from argparse import ArgumentParser

    if sys.version_info[:2] < (3, 6):
        raise RuntimeError("Python version must be >= 3.6")

    parser = ArgumentParser(description="Find deprecated escaped characters")
    parser.add_argument('root', help='directory or file to be checked')
    args = parser.parse_args()
    main(args.root)