generate_identifier_pattern.py
This file
Path
scripts/generate_identifier_pattern.py
78 lines · 2.2 KiB · Python
Last changed by
Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
History of this fileTake it
1#!/usr/bin/env python32import itertools3import os4import re5import sys67if sys.version_info[0] < 3:8 raise RuntimeError("This needs to run on Python 3.")91011def get_characters():12 """Find every Unicode character that is valid in a Python `identifier`_ but13 is not matched by the regex ``\\w`` group.1415 ``\\w`` matches some characters that aren't valid in identifiers, but16 :meth:`str.isidentifier` will catch that later in lexing.1718 All start characters are valid continue characters, so we only test for19 continue characters.2021 _identifier: https://docs.python.org/3/reference/lexical_analysis.html#identifiers22 """23 for cp in range(sys.maxunicode + 1):24 s = chr(cp)2526 if ("a" + s).isidentifier() and not re.match(r"\w", s):27 yield s282930def collapse_ranges(data):31 """Given a sorted list of unique characters, generate ranges representing32 sequential code points.3334 Source: https://stackoverflow.com/a/4629241/40061735 """36 for _, b in itertools.groupby(enumerate(data), lambda x: ord(x[1]) - x[0]):37 b = list(b)38 yield b[0][1], b[-1][1]394041def build_pattern(ranges):42 """Output the regex pattern for ranges of characters.4344 One and two character ranges output the individual characters.45 """46 out = []4748 for a, b in ranges:49 if a == b: # single char50 out.append(a)51 elif ord(b) - ord(a) == 1: # two chars, range is redundant52 out.append(a)53 out.append(b)54 else:55 out.append("{}-{}".format(a, b))5657 return "".join(out)585960def main():61 """Build the regex pattern and write it to62 ``jinja2/_identifier.py``.63 """64 pattern = build_pattern(collapse_ranges(get_characters()))65 filename = os.path.abspath(66 os.path.join(os.path.dirname(__file__), "..", "src", "jinja2", "_identifier.py")67 )6869 with open(filename, "w", encoding="utf8") as f:70 f.write("import re\n\n")71 f.write("# generated by scripts/generate_identifier_pattern.py\n")72 f.write("pattern = re.compile(\n")73 f.write(' r"[\\w{}]+" # noqa: B950\n'.format(pattern))74 f.write(")\n")757677if __name__ == "__main__":78 main()