toolkit.py 13.9 KB
Newer Older
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
"""toolkit.py - utility functions for DHParser

Copyright 2016  by Eckhart Arnold (arnold@badw.de)
                Bavarian Academy of Sciences an Humanities (badw.de)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied.  See the License for the specific language governing
permissions and limitations under the License.


Module ``toolkit`` contains utility functions and cross-sectional
functionality like logging support that is needed across several 
of the the other DHParser-Modules.

For logging functionality, the global variable LOGGING is defined which
contains the name of a directory where log files shall be placed. By
setting its value to the empty string "" logging can be turned off.

To read the directory name function ``LOGS_DIR()`` should be called
rather than reading the variable LOGGING. ``LOGS_DIR()`` makes sure
the directory exists and raises an error if a file with the same name
already exists.
"""

33
import codecs
Eckhart Arnold's avatar
Eckhart Arnold committed
34
import contextlib
35
import hashlib
36
import io
37
import os
38
import parser
39

di68kap's avatar
di68kap committed
40
41
42
43
try:
    import regex as re
except ImportError:
    import re
44
import sys
45

46
try:
47
    import typing
48
except ImportError:
49
    import DHParser.foreign_typing as typing
di68kap's avatar
di68kap committed
50
    sys.modules['typing'] = typing  # make it possible to import from typing
51

52
from typing import Any, Iterable, Sequence, Set, Union, cast
53

54
__all__ = ('logging',
Eckhart Arnold's avatar
Eckhart Arnold committed
55
           'is_logging',
56
           'clear_logs',
Eckhart Arnold's avatar
Eckhart Arnold committed
57
           'log_dir',
58
           'logfile_basename',
59
           'escape_re',
60
           'escape_control_characters',
Eckhart Arnold's avatar
Eckhart Arnold committed
61
           'is_filename',
62
           'lstrip_docstring',
63
64
           'load_if_file',
           'is_python_code',
65
66
           'md5',
           'expand_table',
67
           'compile_python_object',
68
           'smart_list',
69
           'sane_parser_name')
70
71
72
73
74
75
76


#######################################################################
#
# logging
#
#######################################################################
77
78


Eckhart Arnold's avatar
Eckhart Arnold committed
79
80
81
def log_dir() -> str:
    """Creates a directory for log files (if it does not exist) and
    returns its path.
82

Eckhart Arnold's avatar
Eckhart Arnold committed
83
84
85
    WARNING: Any files in the log dir will eventually be overwritten.
    Don't use a directory name that could be the name of a directory
    for other purposes than logging.
86
87
88
89

    Returns:
        name of the logging directory
    """
Eckhart Arnold's avatar
Eckhart Arnold committed
90
    # the try-except clauses in the following are precautions for multiprocessing
91
    global LOGGING
Eckhart Arnold's avatar
Eckhart Arnold committed
92
    try:
93
        dirname = LOGGING  # raises a name error if LOGGING is not defined
Eckhart Arnold's avatar
Eckhart Arnold committed
94
95
96
        if not dirname:
            raise NameError  # raise a name error if LOGGING evaluates to False
    except NameError:
97
98
        raise NameError("No access to log directory before logging has been "
                        "turned on within the same thread/process.")
Eckhart Arnold's avatar
Eckhart Arnold committed
99
100
101
    if os.path.exists(dirname) and not os.path.isdir(dirname):
        raise IOError('"' + dirname + '" cannot be used as log directory, '
                                      'because it is not a directory!')
102
    else:
Eckhart Arnold's avatar
Eckhart Arnold committed
103
104
105
106
107
        try:
            os.mkdir(dirname)
        except FileExistsError:
            pass
    info_file_name = os.path.join(dirname, 'info.txt')
108
109
110
111
    if not os.path.exists(info_file_name):
        with open(info_file_name, 'w') as f:
            f.write("This directory has been created by DHParser to store log files from\n"
                    "parsing. ANY FILE IN THIS DIRECTORY CAN BE OVERWRITTEN! Therefore,\n"
112
113
                    "do not place any files here and do not bother editing files in this\n"
                    "directory as any changes will get lost.\n")
114
115
116
    return dirname


Eckhart Arnold's avatar
Eckhart Arnold committed
117
@contextlib.contextmanager
118
def logging(dirname="LOGS"):
Eckhart Arnold's avatar
Eckhart Arnold committed
119
120
    """Context manager. Log files within this context will be stored in
    directory ``dirname``. Logging is turned off if name is empty.
121

Eckhart Arnold's avatar
Eckhart Arnold committed
122
123
124
125
126
    Args:
        dirname: the name for the log directory or the empty string to
            turn logging of
    """
    global LOGGING
127
128
    if dirname and not isinstance(dirname, str): 
        dirname = "LOGS"  # be fail tolerant here...
Eckhart Arnold's avatar
Eckhart Arnold committed
129
130
131
132
133
134
135
136
137
    try:
        save = LOGGING
    except NameError:
        save = ""
    LOGGING = dirname
    yield
    LOGGING = save


138
def is_logging() -> bool:
Eckhart Arnold's avatar
Eckhart Arnold committed
139
140
141
142
143
144
145
146
    """-> True, if logging is turned on."""
    global LOGGING
    try:
        return bool(LOGGING)
    except NameError:
        return False


147
def clear_logs(logfile_types=frozenset(['.cst', '.ast', '.log'])):
Eckhart Arnold's avatar
Eckhart Arnold committed
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
    """Removes all logs from the log-directory and removes the
    log-directory if it is empty.
    """
    log_dirname = log_dir()
    files = os.listdir(log_dirname)
    only_log_files = True
    for file in files:
        path = os.path.join(log_dirname, file)
        if os.path.splitext(file)[1] in logfile_types or file == 'info.txt':
            os.remove(path)
        else:
            only_log_files = False
    if only_log_files:
        os.rmdir(log_dirname)


164
def escape_re(strg: str) -> str:
165
166
    """
    Returns the string with all regular expression special characters escaped.
167
    """
168
    # assert isinstance(strg, str)
169
170
    re_chars = r"\.^$*+?{}[]()#<>=|!"
    for esc_ch in re_chars:
171
172
        strg = strg.replace(esc_ch, '\\' + esc_ch)
    return strg
173
174


175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def escape_control_characters(strg: str) -> str:
    """Replace all control characters (e.g. \n \t) in a string by their
    backslashed representation."""
    return repr(strg).replace('\\\\', '\\')[1:-1]


def lstrip_docstring(docstring: str) -> str:
    """
    Strips leading whitespace from a docstring.
    """
    lines = docstring.replace('\t', '    ').split('\n')
    indent = 255  # highest integer value
    for line in lines[1:]:
        stripped = line.lstrip()
        if stripped:  # ignore empty lines
            indent = min(indent, len(line) - len(stripped))
    if indent >= 255:
        indent = 0
    return '\n'.join([lines[0]] + [line[indent:] for line in lines[1:]])


196
def is_filename(strg: str) -> bool:
Eckhart Arnold's avatar
Eckhart Arnold committed
197
    """Tries to guess whether string ``s`` is a file name."""
198
199
200
    return strg.find('\n') < 0 and strg[:1] != " " and strg[-1:] != " " \
           and all(strg.find(ch) < 0 for ch in '*?"<>|')
           # and strg.find('*') < 0 and strg.find('?') < 0
Eckhart Arnold's avatar
Eckhart Arnold committed
201
202


203
def logfile_basename(filename_or_text, function_or_class_or_instance) -> str:
Eckhart Arnold's avatar
Eckhart Arnold committed
204
205
206
207
208
209
210
    """Generates a reasonable logfile-name (without extension) based on
    the given information.
    """
    if is_filename(filename_or_text):
        return os.path.basename(os.path.splitext(filename_or_text)[0])
    else:
        try:
211
            name = function_or_class_or_instance.__qualname.__
Eckhart Arnold's avatar
Eckhart Arnold committed
212
        except AttributeError:
213
214
215
            name = function_or_class_or_instance.__class__.__name__
        i = name.find('.')
        return name[:i] + '_out' if i >= 0 else name
Eckhart Arnold's avatar
Eckhart Arnold committed
216
217


218
219
220
221
222
223
224
#######################################################################
#
# loading and compiling
#
#######################################################################


225
226
227
def load_if_file(text_or_file) -> str:
    """Reads and returns content of a text-file if parameter
    `text_or_file` is a file name (i.e. a single line string),
228
    otherwise (i.e. if `text_or_file` is a multi-line string)
229
    `text_or_file` is returned.
230
    """
Eckhart Arnold's avatar
Eckhart Arnold committed
231
    if is_filename(text_or_file):
232
233
234
235
        try:
            with open(text_or_file, encoding="utf-8") as f:
                content = f.read()
            return content
236
        except FileNotFoundError:
237
            if re.fullmatch(r'[\w/:. \\]+', text_or_file):
238
239
                raise FileNotFoundError('Not a valid file: ' + text_or_file + '!\n(Add "\\n" '
                                        'to distinguish source data from a file name.)')
240
241
            else:
                return text_or_file
242
243
244
245
    else:
        return text_or_file


246
def is_python_code(text_or_file: str) -> bool:
247
248
249
    """Checks whether 'text_or_file' is python code or the name of a file that
    contains python code.
    """
Eckhart Arnold's avatar
Eckhart Arnold committed
250
    if is_filename(text_or_file):
251
252
        return text_or_file[-3:].lower() == '.py'
    try:
253
254
        parser.suite(text_or_file)
        # compile(text_or_file, '<string>', 'exec')
255
256
257
258
259
260
        return True
    except (SyntaxError, ValueError, OverflowError):
        pass
    return False


261
def has_fenced_code(text_or_file: str, info_strings=('ebnf', 'test')) -> bool:
262
263
264
265
266
267
268
269
270
271
272
273
274
275
    """Checks whether `text_or_file` contains fenced code blocks, which are
    marked by one of the given info strings.
    See http://spec.commonmark.org/0.28/#fenced-code-blocks for more
    information on fenced code blocks in common mark documents.
    """
    if is_filename(text_or_file):
        with open(text_or_file, 'r', encoding='utf-8') as f:
            markdown = f.read()
    else:
        markdown = text_or_file

    if markdown.find('\n~~~') < 0 and markdown.find('\n```') < 0:
        return False

276
277
278
279
280
281
    if isinstance(info_strings, str):
        info_strings = (info_strings,)
    fence_tmpl = '\n(?:(?:``[`]*[ ]*(?:%s)(?=[ .\-:\n])[^`\n]*\n)' + \
                 '|(?:~~[~]*[ ]*(?:%s)(?=[ .\-:\n])[\n]*\n))'
    label_re = '|'.join('(?:%s)' % matched_string for matched_string in info_strings)
    rx_fence = re.compile(fence_tmpl % (label_re, label_re), flags=re.IGNORECASE)
282

283
284
285
    for match in rx_fence.finditer(markdown):
        matched_string = re.match('(?:\n`+)|(?:\n~+)', match.group(0)).group(0)
        if markdown.find(matched_string, match.end()) >= 0:
286
287
            return True
        else:
288
289
            break
    return False
290
291


292
293
294
295
296
297
298
299
300
301
def md5(*txt):
    """Returns the md5-checksum for `txt`. This can be used to test if
    some piece of text, for example a grammar source file, has changed.
    """
    md5_hash = hashlib.md5()
    for t in txt:
        md5_hash.update(t.encode('utf8'))
    return md5_hash.hexdigest()


302
303
304
305
306
307
308
309
310
311
312
def compile_python_object(python_src, catch_obj_regex=""):
    """Compiles the python source code and returns the (first) object
    the name of which is matched by ``catch_obj_regex``. If catch_obj
    is the empty string, the namespace dictionary will be returned.
    """
    if isinstance(catch_obj_regex, str):
        catch_obj_regex = re.compile(catch_obj_regex)
    code = compile(python_src, '<string>', 'exec')
    namespace = {}
    exec(code, namespace)  # safety risk?
    if catch_obj_regex:
313
314
        matches = [key for key in namespace if catch_obj_regex.match(key)]
        if len(matches) < 1:
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
            raise ValueError("No object matching /%s/ defined in source code." %
                             catch_obj_regex.pattern)
        elif len(matches) > 1:
            raise ValueError("Ambiguous matches for %s : %s" %
                             (str(catch_obj_regex), str(matches)))
        return namespace[matches[0]] if matches else None
    else:
        return namespace


#######################################################################
#
# smart lists and multi-keyword tables
#
#######################################################################


Eckhart Arnold's avatar
Eckhart Arnold committed
332
# def smart_list(arg: Union[str, Iterable[T]]) -> Union[Sequence[str], Sequence[T]]:
333
def smart_list(arg: Union[str, Iterable, Any]) -> Union[Sequence, Set]:
334
    """Returns the argument as list, depending on its type and content.
335

336
337
338
    If the argument is a string, it will be interpreted as a list of
    comma separated values, trying ';', ',', ' ' as possible delimiters
    in this order, e.g.
339
340
341
342
343
344
345
    >>> smart_list('1; 2, 3; 4')
    ['1', '2, 3', '4']
    >>> smart_list('2, 3')
    ['2', '3']
    >>> smart_list('a b cd')
    ['a', 'b', 'cd']

346
347
    If the argument is a collection other than a string, it will be
    returned as is, e.g.
348
349
350
351
352
    >>> smart_list((1, 2, 3))
    (1, 2, 3)
    >>> smart_list({1, 2, 3})
    {1, 2, 3}

353
354
    If the argument is another iterable than a collection, it will
    be converted into a list, e.g.
355
356
357
    >>> smart_list(i for i in {1,2,3})
    [1, 2, 3]

358
    Finally, if none of the above is true, the argument will be
359
    wrapped in a list and returned, e.g.
360
361
    >>> smart_list(125)
    [125]
362
363
364
365
366
    """
    if isinstance(arg, str):
        for delimiter in (';', ','):
            lst = arg.split(delimiter)
            if len(lst) > 1:
367
368
                return [s.strip() for s in lst]
        return [s.strip() for s in arg.strip().split(' ')]
369
    elif isinstance(arg, Sequence) or isinstance(arg, Set):
370
        return arg
Eckhart Arnold's avatar
Eckhart Arnold committed
371
    elif isinstance(arg, Iterable):
372
        return list(arg)
373
374
375
376
    else:
        return [arg]


377
378
379
380
381
def expand_table(compact_table):
    """Expands a table by separating keywords that are tuples or strings
    containing comma separated words into single keyword entries with
    the same values. Returns the expanded table.
    Example:
382
383
    >>> expand_table({"a, b": 1, ('d','e','f'):5, "c":3})
    {'a': 1, 'b': 1, 'd': 5, 'e': 5, 'f': 5, 'c': 3}
384
385
386
387
388
    """
    expanded_table = {}
    keys = list(compact_table.keys())
    for key in keys:
        value = compact_table[key]
389
        for k in smart_list(key):
390
            if k in expanded_table:
391
                raise KeyError('Key "%s" used more than once in compact table!' % key)
392
            expanded_table[k] = value
393
    return expanded_table
394
395


396
397
398
399
400
401
402
#######################################################################
#
# miscellaneous
#
#######################################################################


403
def sane_parser_name(name) -> bool:
404
    """Checks whether given name is an acceptable parser name. Parser names
405
    must not be preceded or succeeded by a double underscore '__'!
406
    """
di68kap's avatar
di68kap committed
407
408
409
    return name and name[:2] != '__' and name[-2:] != '__'


410
411
412
413
414
415
416
#######################################################################
#
# initialization
#
#######################################################################


417
418
try:
    if sys.stdout.encoding.upper() != "UTF-8":
419
        # make sure that `print()` does not raise an error on
420
        # non-ASCII characters:
421
422
        sys.stdout = cast(io.TextIOWrapper, codecs.getwriter("utf-8")(cast(
            io.BytesIO, cast(io.TextIOWrapper, sys.stdout).detach())))
423
424
425
except AttributeError:
    # somebody has already taken care of this !?
    pass