| 1 |
""" |
| 2 |
Utility functions for test scripts |
| 3 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. |
| 6 |
:license: BSD, see LICENSE for details. |
| 7 |
""" |
| 8 |
|
| 9 |
import os |
| 10 |
import os.path |
| 11 |
|
| 12 |
|
| 13 |
def unpack_output_file(path): |
| 14 |
""" |
| 15 |
Unpack an output file into objects contining the line number, the text, |
| 16 |
and the token name. The output file can be either a ``.output`` file |
| 17 |
containing a token stream, or a ``.txt`` with input and tokens. |
| 18 |
""" |
| 19 |
from collections import namedtuple |
| 20 |
entry = namedtuple('OutputEntry', ['text', 'token', 'linenumber']) |
| 21 |
|
| 22 |
skip_until_tokens = path.endswith('.txt') |
| 23 |
|
| 24 |
for linenumber, line in enumerate(open(path, encoding='utf-8').readlines()): |
| 25 |
line = line.strip() |
| 26 |
if not line: |
| 27 |
continue |
| 28 |
|
| 29 |
if skip_until_tokens: |
| 30 |
if line != '---tokens---': |
| 31 |
continue |
| 32 |
|
| 33 |
skip_until_tokens = False |
| 34 |
|
| 35 |
# Line can start with ' or ", so let's check which one it is |
| 36 |
# and find the matching one |
| 37 |
quotation_start = 0 |
| 38 |
quotation_end = line.rfind(line[0]) |
| 39 |
text = line[quotation_start+1:quotation_end] |
| 40 |
token = line.split()[-1] |
| 41 |
text = text.replace('\\n', '\n') |
| 42 |
text = text.replace('\\t', '\t') |
| 43 |
yield entry(text, token, linenumber + 1) |
| 44 |
|
| 45 |
|
| 46 |
def process_output_files(root_directory, callback): |
| 47 |
""" |
| 48 |
Process all output (i.e. .output and .txt files for snippets) files |
| 49 |
in a directory tree using the provided callback. |
| 50 |
The callback should return ``True`` in case of success, ``False`` |
| 51 |
otherwise. |
| 52 |
|
| 53 |
The function returns the number of files for which the callback returned |
| 54 |
``False``. |
| 55 |
""" |
| 56 |
errors = 0 |
| 57 |
for directory, _, files in os.walk(root_directory): |
| 58 |
for file in files: |
| 59 |
_, ext = os.path.splitext(file) |
| 60 |
|
| 61 |
if ext not in {'.txt', '.output'}: |
| 62 |
continue |
| 63 |
|
| 64 |
path = os.path.join(directory, file) |
| 65 |
if not callback(path): |
| 66 |
errors += 1 |
| 67 |
|
| 68 |
return errors |