text.py 17.2 KB
Newer Older
kk's avatar
kk committed
1
2
3
4
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Various text-processing utilities
# ---------------------------------------------------------------------
5
# Copyright (C) 2007-2020 The NOC Project
kk's avatar
kk committed
6
7
8
9
10
# See LICENSE for details
# ---------------------------------------------------------------------

# Python modules
import re
Dmitry Volodin's avatar
Dmitry Volodin committed
11
from itertools import zip_longest
kk's avatar
kk committed
12
13
14

# Third-party modules
from numpy import array
15
from typing import List, Union, Iterable
kk's avatar
kk committed
16

Dmitry Volodin's avatar
Dmitry Volodin committed
17
18
19
# NOC modules
from noc.core.comp import bord

kk's avatar
kk committed
20
21
22
23
rx_header_start = re.compile(r"^\s*[-=]+[\s\+]+[-=]+")
rx_col = re.compile(r"^([\s\+]*)([\-]+|[=]+)")


24
25
26
27
def default_line_wrapper(p_line):
    return p_line.expandtabs()


kk's avatar
kk committed
28
29
30
31
32
33
34
35
def parse_table(
    s,
    allow_wrap=False,
    allow_extend=False,
    expand_columns=False,
    max_width=0,
    footer=None,
    n_row_delim="",
36
37
    line_wrapper=default_line_wrapper,
    row_wrapper=None,
kk's avatar
kk committed
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
):
    """
    Parse string containing table an return a list of table rows.
    Each row is a list of cells.
    Columns are determined by a sequences of ---- or ==== which are
    determines rows bounds.
    Examples:
    First Second Third
    ----- ------ -----
    a     b       c
    ddd   eee     fff
    Will be parsed down to the [["a","b","c"],["ddd","eee","fff"]]

    :param s: Table for parsing
    :type s: str
    :param allow_wrap: Union if cell contins multiple line
    :type allow_wrap: bool
    :param allow_extend: Check if column on row longest then column width, enlarge it and shift rest of columns
    :type allow_extend: bool
    :param expand_columns: Expand columns covering all available width
    :type expand_columns: bool
    :param max_width: Max table width, if table width < max_width extend length, else - nothing
    :type max_width: int
    :param footer: stop iteration if match expression footer
    :type footer: string
    :param n_row_delim: Append delimiter to next cell line
    :type n_row_delim: string
65
66
67
68
    :param line_wrapper: Call line_wrapper with line argument
    :type line_wrapper: callable
    :param row_wrapper: Call row_wrapper with row argument
    :type row_wrapper: callable
kk's avatar
kk committed
69
70
71
72
73
    """
    r = []
    columns = []
    if footer is not None:
        rx_footer = re.compile(footer)
74
75
    if line_wrapper and not callable(line_wrapper):
        line_wrapper = None
76
    if row_wrapper and not callable(row_wrapper):
77
        row_wrapper = None
kk's avatar
kk committed
78
    for line in s.splitlines():
79
        if line_wrapper:
kk's avatar
kk committed
80
            # Replace tabs with spaces with step 8
81
            line = line_wrapper(line)
kk's avatar
kk committed
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
        if not line.strip() and footer is None:
            columns = []
            continue
        if footer is not None and rx_footer.search(line):
            break  # Footer reached, stop
        if not columns and rx_header_start.match(line):
            # Column delimiters found. try to determine column's width
            columns = []
            x = 0
            while line:
                match = rx_col.match(line)
                if not match:
                    break
                spaces = len(match.group(1))
                dashes = len(match.group(2))
                columns += [(x + spaces, x + spaces + dashes)]
                x += match.end()
                line = line[match.end() :]
            if max_width and columns[-1][-1] < max_width:
                columns[-1] = (columns[-1][0], max_width)
            if expand_columns:
                columns = [(cc[0], nc[0] - 1) for cc, nc in zip(columns, columns[1:])] + [
                    columns[-1]
                ]
        elif columns:  # Fetch cells
            if allow_extend:
                # Find which spaces between column not empty
                ll = len(line)
                for i, (f, t) in enumerate(columns):
                    if t < ll and line[t].strip():
                        # If spaces not empty - shift column width equal size row
                        shift = len(line[f:].split()[0]) - (t - f)
                        # Enlarge column
                        columns[i] = (f, t + shift)
                        # Shift rest
                        columns[i + 1 :] = [(v[0] + shift, v[1] + shift) for v in columns[i + 1 :]]
                        break
            if allow_wrap:
                row = [line[f:t] for f, t in columns]
                if r and not row[0].strip():
                    # first column is empty
                    for i, x in enumerate(row):
                        if (
                            x.strip()
                            and not r[-1][i].endswith(n_row_delim)
                            and not x.startswith(n_row_delim)
                        ):
129
                            r[-1][i] += "%s%s" % (n_row_delim, row_wrapper(x) if row_wrapper else x)
kk's avatar
kk committed
130
                        else:
131
                            r[-1][i] += row_wrapper(x) if row_wrapper else x
kk's avatar
kk committed
132
133
134
                else:
                    r += [row]
            else:
135
136
137
138
139
140
                r += [
                    [
                        row_wrapper(line[f:t]).strip() if row_wrapper else line[f:t].strip()
                        for f, t in columns
                    ]
                ]
kk's avatar
kk committed
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
    if allow_wrap:
        return [[x.strip() for x in rr] for rr in r]
    else:
        return r


#
# Convert HTML to plain text
#
rx_html_tags = re.compile("</?[^>+]+>", re.MULTILINE | re.DOTALL)


def strip_html_tags(s):
    t = rx_html_tags.sub("", s)
    for k, v in [("&nbsp;", " "), ("&lt;", "<"), ("&gt;", ">"), ("&amp;", "&")]:
        t = t.replace(k, v)
    return t


#
# Convert XML to list of elements
#
def xml_to_table(s, root, row):
    # pylint: disable=line-too-long
    """
    >>> xml_to_table('<?xml version="1.0" encoding="UTF-8" ?><response><action><row><a>1</a><b>2</b></row><row><a>3</a><b>4</b></row></action></response>','action','row') # noqa
    [{'a': '1', 'b': '2'}, {'a': '3', 'b': '4'}]
    """
    # Detect root element
    match = re.search(r"<%s>(.*)</%s>" % (root, root), s, re.DOTALL | re.IGNORECASE)
    if not match:
        return []
    s = match.group(1)
    row_re = re.compile(r"<%s>(.*?)</%s>" % (row, row), re.DOTALL | re.IGNORECASE)
    item_re = re.compile(r"<([^\]+])>(.*?)</\1>", re.DOTALL | re.IGNORECASE)
    r = []
    for m in [x for x in row_re.split(s) if x]:
        data = item_re.findall(m)
        if data:
            r += [dict(data)]
    return r


#
# Convert list of values to string of ranges
#
def list_to_ranges(s):
    """
    >>> list_to_ranges([])
    ''
    >>> list_to_ranges([1])
    '1'
    >>> list_to_ranges([1,2])
    '1-2'
    >>> list_to_ranges([1,2,3])
    '1-3'
    >>> list_to_ranges([1,2,3,5])
    '1-3,5'
    >>> list_to_ranges([1,2,3,5,6,7])
    '1-3,5-7'
    >>> list_to_ranges(range(1,4001))
    '1-4000'
    """

    def f():
        if last_start == last_end:
            return str(last_start)
        else:
            return "%d-%d" % (last_start, last_end)

    last_start = None
    last_end = None
    r = []
    for i in sorted(s):
        if last_end is not None and i == last_end + 1:
            last_end += 1
        else:
            if last_start is not None:
                r += [f()]
            last_start = i
            last_end = i
    if last_start is not None:
        r += [f()]
    return ",".join(r)


#
# Convert range string to a list of integers
#
rx_range = re.compile(r"^(\d+)\s*-\s*(\d+)$")


def ranges_to_list(s, splitter=","):
    """
    >>> ranges_to_list("1")
    [1]
    >>> ranges_to_list("1, 2")
    [1, 2]
    >>> ranges_to_list("1, 10-12")
    [1, 10, 11, 12]
    >>> ranges_to_list("1, 10-12, 15, 17-19")
    [1, 10, 11, 12, 15, 17, 18, 19]
    """
    r = []
    if "to" in s:
        s = s.replace(" to ", "-")
    for p in s.split(splitter):
        p = p.strip()
        try:
            r += [int(p)]
            continue
        except ValueError:
            pass
        match = rx_range.match(p)
        if not match:
            raise SyntaxError
        f, t = [int(x) for x in match.groups()]
        if f >= t:
            raise SyntaxError
        for i in range(f, t + 1):
            r += [i]
    return sorted(r)


def replace_re_group(expr, group, pattern):
266
    if isinstance(expr, bytes):
Dmitry Volodin's avatar
Dmitry Volodin committed
267
268
269
270
        return _replace_re_group_binary(expr, group, pattern)
    return _replace_re_group_text(expr, group, pattern)


271
def _replace_re_group_text(expr: str, group: str, pattern: str) -> str:
kk's avatar
kk committed
272
    """
Dmitry Volodin's avatar
Dmitry Volodin committed
273
274
    Replace regular expression group with pattern

kk's avatar
kk committed
275
276
277
278
279
280
281
    >>> replace_re_group("nothing","(?P<groupname>","groupvalue")
    'nothing'
    >>> replace_re_group("the (?P<groupname>simple) test","(?P<groupname>","groupvalue")
    'the groupvalue test'
    >>> replace_re_group("the (?P<groupname> nested (test)>)","(?P<groupname>","groupvalue")
    'the groupvalue'
    """
Dmitry Volodin's avatar
Dmitry Volodin committed
282
    r = []
kk's avatar
kk committed
283
284
285
286
    lg = len(group)
    while expr:
        idx = expr.find(group)
        if idx == -1:
Dmitry Volodin's avatar
Dmitry Volodin committed
287
288
            break
        r += [expr[:idx]]
kk's avatar
kk committed
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
        expr = expr[idx + lg :]
        level = 1  # Level of parenthesis nesting
        while expr:
            c = expr[0]
            expr = expr[1:]
            if c == "\\":
                # Skip quoted character
                expr = expr[1:]
                continue
            elif c == "(":
                # Increase nesting level
                level += 1
                continue
            elif c == ")":
                # Decrease nesting level
                level -= 1
                if level == 0:
                    # Replace with pattern and search for next
Dmitry Volodin's avatar
Dmitry Volodin committed
307
308
309
310
311
312
                    r += [pattern]
                    break
    r += [expr]
    return "".join(r)


313
def _replace_re_group_binary(expr: bytes, group: bytes, pattern: bytes) -> bytes:
Dmitry Volodin's avatar
Dmitry Volodin committed
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
    """
    Replace regular expression group with pattern

    >>> replace_re_group("nothing","(?P<groupname>","groupvalue")
    'nothing'
    >>> replace_re_group("the (?P<groupname>simple) test","(?P<groupname>","groupvalue")
    'the groupvalue test'
    >>> replace_re_group("the (?P<groupname> nested (test)>)","(?P<groupname>","groupvalue")
    'the groupvalue'
    """
    r = []
    lg = len(group)
    while expr:
        idx = expr.find(group)
        if idx == -1:
            break
        r += [expr[:idx]]
        expr = expr[idx + lg :]
        level = 1  # Level of parenthesis nesting
        while expr:
            c = bord(expr[0])
            expr = expr[1:]
            if c == 0x5C:  # "\\"
                # Skip quoted character
                expr = expr[1:]
                continue
            elif c == 0x28:  # "("
                # Increase nesting level
                level += 1
                continue
            elif c == 0x29:  # ")"
                # Decrease nesting level
                level -= 1
                if level == 0:
                    # Replace with pattern and search for next
                    r += [pattern]
kk's avatar
kk committed
350
                    break
Dmitry Volodin's avatar
Dmitry Volodin committed
351
352
    r += [expr]
    return b"".join(r)
kk's avatar
kk committed
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372


def indent(text, n=4):
    """
    Indent each line of text with spaces

    :param text: text
    :param n: amount of spaces to ident

    >>> indent("")
    ''
    >>> indent("the quick brown fox\\njumped over an lazy dog\\nend")
    '    the quick brown fox\\n    jumped over an lazy dog\\n    end'
    """
    if not text:
        return ""
    i = " " * n
    return i + text.replace("\n", "\n" + i)


373
374
375
rx_split_alnum = re.compile(r"(\d+|[^0-9]+)")


376
def _iter_split_alnum(s: str) -> Iterable[str]:
377
378
379
380
381
382
383
384
385
386
    """
    Iterator yielding alphabetic and numeric sections if string

    :param s:
    :return:
    """
    for match in rx_split_alnum.finditer(s):
        yield match.group(0)


387
def split_alnum(s: str) -> List[Union[str, int]]:
kk's avatar
kk committed
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
    """
    Split line to a sequence of iterating alpha and digit strings

    :param s:
    :type s: str
    :return: list
    :rtype: list

    >>> split_alnum("Fa 0/1")
    ['Fa ', 0, '/', 1]
    >>> split_alnum("Fa 0/1.15")
    ['Fa ', 0, '/', 1, '.', 15]
    >>> split_alnum("ge-1/0/1")
    ['ge-', 1, '/', 0, '/', 1]
    >>> split_alnum("ge-1/0/1.15")
    ['ge-', 1, '/', 0, '/', 1, '.', 15]
    """

406
    def maybe_int(v: str) -> Union[str, int]:
kk's avatar
kk committed
407
        try:
408
            return int(v)
kk's avatar
kk committed
409
        except ValueError:
410
            return v
kk's avatar
kk committed
411

412
413
414
    return [maybe_int(x) for x in _iter_split_alnum(s)]


415
def alnum_key(s: str) -> str:
416
417
418
419
420
421
    """
    Comparable alpha-numeric key
    :param s:
    :return:
    """

422
    def maybe_formatted_int(v: str) -> str:
423
424
425
426
427
428
        try:
            return "%012d" % int(v)
        except ValueError:
            return v

    return "".join(maybe_formatted_int(x) for x in _iter_split_alnum(s))
kk's avatar
kk committed
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581


rx_notspace = re.compile(r"^\S+")


def find_indented(s):
    """
    Parses following text structure:

    section 1 header
        line 1
        line 2
    section 2 header
        line 1
        line 2

    >>> find_idented("section0\\nsection 1\\n  line 1-1\\n  line 1-2\\n\\n"\
                     "section 2\\n  line 2-1\\n  line 2-2")
    ['section 1\n  line 1-1\n  line 1-2', 'section 2\n  line 2-1\n  line 2-2']
    :param s:
    :return:
    """
    r = []
    cr = []
    for l in s.splitlines():
        if rx_notspace.match(l):
            if len(cr) > 1:
                r += ["\n".join(cr)]
            cr = [l]
            continue
        elif l:
            cr += [l]
    if len(cr) > 1:
        r += ["\n".join(cr)]
    return r


def parse_kv(kmap, data, sep=":"):
    """
    :param kmap: text -> dict mapping
    :param data:
    :return: dict
    """
    r = {}
    for line in data.splitlines():
        if sep not in line:
            continue
        k, v = line.strip().split(sep, 1)
        k = k.strip().lower()
        if k in kmap:
            r[kmap[k]] = v.strip()
    return r


def str_dict(d):
    """
    Convert dict to key=value, key=value, .... string
    :type d: dict
    :rtype: str
    """
    return ", ".join("%s=%s" % (k, d[k]) for k in d)


rx_safe_path = re.compile(r"[^a-z0-9\-\+]+", re.IGNORECASE)


def quote_safe_path(d):
    return rx_safe_path.sub("_", d)


def to_seconds(v):
    """
    Convert string value to seconds.
    Available acronyms are h, d, w, m, y
    """
    m = 1
    if v.endswith("h"):
        v = v[:-1]
        m = 3600
    elif v.endswith("d"):
        v = v[:-1]
        m = 24 * 3600
    elif v.endswith("w"):
        v = v[:-1]
        m = 7 * 24 * 3600
    elif v.endswith("m"):
        v = v[:-1]
        m = 30 * 24 * 3600
    elif v.endswith("y"):
        v = v[:-1]
        m = 365 * 24 * 3600
    try:
        v = int(v)
    except ValueError:
        raise "Invalid time: %s" % v
    return v * m


def format_table(widths, data, sep=" ", hsep=" "):
    """
    Print formatted table.
    :param widths: list of minimal column widths
    :param data: list of rows, first row is the header
    :param sep: column separator
    :param hsep: header line separator
    """
    # Calculate column widths
    widths = list(widths)
    for row in data:
        widths = [max(x, len(y)) for x, y in zip(widths, row)]
    # Build print mask
    mask = sep.join("%%-%ds" % w for w in widths)
    out = [
        # Header line
        mask % tuple(data[0]),
        # Header separator
        hsep.join("-" * w for w in widths),
    ]
    out += [mask % tuple(row) for row in data[1:]]
    return "\n".join(out)


rx_non_numbers = re.compile("[^0-9]+")


def clean_number(n):
    """
    Remove all non-number occurences
    :param n:
    :return:
    """
    return rx_non_numbers.sub("", n)


def safe_shadow(text):
    """
    Shadow string to first and last char
    :param text:
    :return:

    >>> safe_shadow(None)
    'None'
    >>>safe_shadow("s")
    '******'
    >>>safe_shadow("sssssss")
    's******s'
    >>> safe_shadow(1)
    '******'
    >>> safe_shadow([1, 2])
    '******'
     """
    if not text:
        return "None"
582
    elif not isinstance(text, str):
kk's avatar
kk committed
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
        return "******"
    elif len(text) > 2:
        return "%s******%s" % (text[0], text[-1])
    else:
        return "******"


def ch_escape(s):
    return s.replace("\n", "\\n").replace("\t", "\\t").replace("\\", "\\\\")


ESC_REPLACEMENTS = {re.escape("\n"): " ", re.escape("\t"): "        "}

rx_escape = re.compile("|".join(ESC_REPLACEMENTS))


def tsv_escape(text):
    return rx_escape.sub(lambda match: ESC_REPLACEMENTS[re.escape(match.group(0))], text)


def parse_table_header(v):
    """
    Parse header structured multiline format:
    Config    Current Agg     Min    Ld Share  Flags Ld Share  Agg Link  Link Up
    Master    Master  Control Active Algorithm       Group     Mbr State Transitions
    :param v:
    :return: Dictionary {start column position: header}
    {10: 'Config Master', 18: 'Current Master', 26: 'Agg Control', 33: 'Min Active',
     43: 'Ld Share Algorithm', 49: 'Flags ', 59: 'Ld Share Group', 63: 'Agg Mbr', 69: 'Link State'}
    """
    head = []
    empty_header = None
    header = {}
    for num, lines in enumerate(zip_longest(*v, fillvalue="-")):
        #
        if empty_header is None:
            empty_header = (" ",) * len(lines)
            head += [lines]
            continue
        if set(head[-1]) == {" "} and lines != empty_header:
            head = array(head)
            # Transpone list header string
            header[num] = " ".join(["".join(s).strip() for s in head.transpose().tolist()])
            header[num] = header[num].strip()
            head = []
        head += [lines]
    else:
        # last column
        head = array(head)
        header[num] = " ".join(["".join(s).strip(" -") for s in head.transpose().tolist()])
        header[num] = header[num].strip()
    return header