From 3837b26ee097fb461a76d6d17e050df35c0bff2a Mon Sep 17 00:00:00 2001 From: Valentin Lab Date: Wed, 4 Feb 2015 19:07:55 +0700 Subject: [PATCH] new: added ``udiff`` to get unified diffs of strings. --- README.rst | 17 +++++++++++++++++ src/kids/txt/__init__.py | 1 + src/kids/txt/diff.py | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 src/kids/txt/diff.py diff --git a/README.rst b/README.rst index 0d95121..f7022cb 100644 --- a/README.rst +++ b/README.rst @@ -33,6 +33,7 @@ using ``kids.txt``: - You'll have a ``indent`` / ``dedent`` / ``shorten`` command also in python 2. - You'll be able to ``wrap`` text keeping the paragraph separated. - minor helper like ``ucfirst`` function. +- produce unified diffs between 2 strings easily with ``udiff``. Installation @@ -134,6 +135,22 @@ replace the last 2 characters by a '..' to indicate truncation:: 'sup..' +udiff +----- + +Shows the unified diff between to text:: + + >>> print(txt.udiff('a\n\nc', 'b\n\nc')) + --- None + +++ None + @@ -1,3 +1,3 @@ + -a + +b + + c + + + Contributing ============ diff --git a/src/kids/txt/__init__.py b/src/kids/txt/__init__.py index adeb8a2..85661db 100644 --- a/src/kids/txt/__init__.py +++ b/src/kids/txt/__init__.py @@ -1,3 +1,4 @@ # Package placeholder from .txt import indent, dedent, paragraph_wrap, ucfirst, shorten +from .diff import udiff diff --git a/src/kids/txt/diff.py b/src/kids/txt/diff.py new file mode 100644 index 0000000..86490f5 --- /dev/null +++ b/src/kids/txt/diff.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +import difflib + + +def udiff(a, b, fa=None, fb=None): + r"""Returns a classical unified diff between two given strings. + + Straightforward to use:: + + >>> print(udiff('a\n\nc', 'b\n\nc')) + --- None + +++ None + @@ -1,3 +1,3 @@ + -a + +b + + c + + + Note that if the input texts do not ends with a new line, it'll be + added automatically, so:: + + >>> udiff('a', 'b') == udiff('a\n', 'b') == udiff('a', 'b\n') + True + + + """ + if not a.endswith("\n"): + a += "\n" + if not b.endswith("\n"): + b += "\n" + return "".join( + difflib.unified_diff( + a.splitlines(1), b.splitlines(1), + fa, fb))