~homeworkprod/byceps

ref: 4237b3ec9496efe95dcce82bea3207ab9de4d520 byceps/byceps/services/text_diff/service.py -rw-r--r-- 1.0 KiB
4237b3ec — Jochen Kupperschmidt Move ticketing blueprint into `site` subpackage 1 year, 11 months ago
                                                                                
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
"""
byceps.services.text_diff.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from difflib import HtmlDiff
from typing import Optional


def create_html_diff(
    from_text: str,
    to_text: str,
    from_description: str,
    to_description: str,
    *,
    numlines: int = 3,
) -> Optional[str]:
    """Calculate the difference between the two texts and render it as HTML.

    If the texts to compare are equal, `None` is returned.
    """
    from_text = _fallback_if_none(from_text)
    to_text = _fallback_if_none(to_text)

    if from_text == to_text:
        return None

    from_lines = from_text.split('\n')
    to_lines = to_text.split('\n')

    return HtmlDiff().make_table(
        from_lines,
        to_lines,
        from_description,
        to_description,
        context=True,
        numlines=numlines,
    )


def _fallback_if_none(value: Optional[str], *, fallback: str = '') -> str:
    return value if (value is not None) else fallback