diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c9162b9 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +root = true + +[*] +charset = utf-8 +indent_style = tab +indent_size = 4 +insert_final_newline = true +end_of_line = lf + +[*.{yml,yaml}] +indent_style = space +indent_size = 2 diff --git a/.github/.templateMarker b/.github/.templateMarker new file mode 100644 index 0000000..5e3a3e0 --- /dev/null +++ b/.github/.templateMarker @@ -0,0 +1 @@ +KOLANICH/python_project_boilerplate.py diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..89ff339 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,8 @@ +version: 2 +updates: + - package-ecosystem: "pip" + directory: "/" + schedule: + interval: "daily" + allow: + - dependency-type: "all" diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml new file mode 100644 index 0000000..7fe33b3 --- /dev/null +++ b/.github/workflows/CI.yml @@ -0,0 +1,15 @@ +name: CI +on: + push: + branches: [master] + pull_request: + branches: [master] + +jobs: + build: + runs-on: ubuntu-22.04 + steps: + - name: typical python workflow + uses: KOLANICH-GHActions/typical-python-workflow@master + with: + github_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6f96863 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +__pycache__ +*.pyc +*.pyo +./slicerangetools.egg-info +./build +./dist +./.eggs + diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..ad79d60 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,49 @@ +image: registry.gitlab.com/kolanich-subgroups/docker-images/fixed_python:latest +stages: + - build + - test + +variables: + DOCKER_DRIVER: overlay2 + SAST_ANALYZER_IMAGE_TAG: latest + SAST_DISABLE_DIND: "true" + +include: + - template: SAST.gitlab-ci.yml + #- template: DAST.gitlab-ci.yml + #- template: License-Management.gitlab-ci.yml + #- template: Container-Scanning.gitlab-ci.yml + #- template: Dependency-Scanning.gitlab-ci.yml + - template: Code-Quality.gitlab-ci.yml + + +build: + tags: + - shared + stage: build + variables: + GIT_DEPTH: "1" + PYTHONUSERBASE: ${CI_PROJECT_DIR}/python_user_packages + + before_script: + - export PATH="$PATH:$PYTHONUSERBASE/bin" # don't move into `variables` + + cache: + paths: + - $PYTHONUSERBASE + + script: + - python3 setup.py bdist_wheel + - mkdir wheels + - mv ./dist/*.whl ./wheels/sideBySideDiff-0.CI-py3-none-any.whl + - pip3 install --user --upgrade ./wheels/sideBySideDiff-0.CI-py3-none-any.whl + #- coverage run --source=sideBySideDiff -m pytest --junitxml=./rspec.xml ./tests/tests.py + #- coverage report -m || true + #- coveralls || true + #- codecov || true + + artifacts: + paths: + - wheels + #reports: + # junit: rspec.xml diff --git a/Code_Of_Conduct.md b/Code_Of_Conduct.md new file mode 100644 index 0000000..2b781c7 --- /dev/null +++ b/Code_Of_Conduct.md @@ -0,0 +1 @@ +No codes of conduct! diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..20f0fa8 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,4 @@ +include UNLICENSE +include *.md +include tests +include .editorconfig diff --git a/ReadMe.md b/ReadMe.md new file mode 100644 index 0000000..73c670c --- /dev/null +++ b/ReadMe.md @@ -0,0 +1,9 @@ +sideBySideDiff.py [![Unlicensed work](https://raw.githubusercontent.com/unlicense/unlicense.org/master/static/favicon.png)](https://unlicense.org/) +================== +~~[![GitLab Build Status](https://gitlab.com/KOLANICH/sideBySideDiff.py/badges/master/pipeline.svg)](https://gitlab.com/KOLANICH/sideBySideDiff.py/pipelines/master/latest)~~ +~~![GitLab Coverage](https://gitlab.com/KOLANICH/sideBySideDiff.py/badges/master/coverage.svg)~~ +[![Libraries.io Status](https://img.shields.io/librariesio/github/KOLANICH/sideBySideDiff.py.svg)](https://libraries.io/github/KOLANICH/sideBySideDiff.py) +[![Code style: antiflash](https://img.shields.io/badge/code%20style-antiflash-FFF.svg)](https://codeberg.org/KOLANICH-tools/antiflash.py) + +This is a library to create 2-way side-by-side diffs and show them in CLI using ANSI color codes. + diff --git a/UNLICENSE b/UNLICENSE new file mode 100644 index 0000000..efb9808 --- /dev/null +++ b/UNLICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..937bf2d --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,35 @@ +[build-system] +requires = ["setuptools>=61.2.0", "wheel", "setuptools_scm[toml]>=3.4.3"] +build-backend = "setuptools.build_meta" + +[project] +name = "sideBySideDiff" +authors = [{name = "KOLANICH"}] +description = "A library to create 2-way side-by-side diffs for showing them in console" +readme = "ReadMe.md" +keywords = ["diff", "2-way-diff", "compare", "ANSI color codes", "ECMA-45"] +license = {text = "Unlicense"} +classifiers = [ + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Development Status :: 4 - Beta", + "Environment :: Other Environment", + "Intended Audience :: Developers", + "License :: Public Domain", + "Operating System :: OS Independent", + "Topic :: Software Development :: Libraries :: Python Modules", +] +requires-python = ">=3.4" +dependencies = [ + "RichConsole", # @ git+https://codeberg.org/KOLANICH-libs/RichConsole.py.git" +] +dynamic = ["version"] + +[project.urls] +Homepage = "https://codeberg.org/KOLANICH-libs/sideBySideDiff.py" + +[tool.setuptools] +zip-safe = true +py-modules = ["sideBySideDiff"] + +[tool.setuptools_scm] diff --git a/sideBySideDiff.py b/sideBySideDiff.py new file mode 100644 index 0000000..9a54570 --- /dev/null +++ b/sideBySideDiff.py @@ -0,0 +1,138 @@ +import typing +from math import log10, ceil +import difflib +from RichConsole import RichStr, groups, rsjoin + + +def getMaxWidth(column: typing.List[str]) -> int: + return max(len(str(e)) for e in column) + + +def deletedStyle(l: str) -> RichStr: + return groups.CrossedOut.crossedOut(groups.Fore.green(l)) + + +StyleT = typing.Callable[[str], typing.Union[str, RichStr]] +StylePairT = typing.Tuple[StyleT, StyleT] + +StringConverterT = typing.Callable[[typing.Any], str] + +def dummy(x): + return x + +StyleDictT = typing.Dict[str, typing.Union[StyleT, StylePairT]] +defaultStyle = { + "equal": (dummy, dummy), + "replace": (groups.Fore.lightblueEx, groups.Fore.lightblueEx), + "insert": (groups.Back.lightyellowEx, groups.Fore.lightgreenEx), + "delete": (deletedStyle, groups.Back.lightredEx), + "lineNo": groups.Fore.lightcyanEx +} + +rangeOrSlice = typing.Union[slice, range] + + +def azip(a: typing.Any, ar: rangeOrSlice, b: typing.Any, br: rangeOrSlice, substitute: typing.Any = None) -> typing.Iterator[typing.Any]: + #ar.stop = typing.cast(int, ar.stop) + #ar.start = typing.cast(int, ar.start) + #br.stop = typing.cast(int, br.stop) + #br.start = typing.cast(int, br.start) + + al = ar.stop - ar.start + bl = br.stop - br.start + + d = al - bl + comm = min(al, bl) + yield from zip(a[ar.start : ar.start + comm], range(ar.start, ar.start + comm), b[br.start : br.start + comm], range(br.start, br.start + comm)) + + if d > 0: + yield from zip(a[ar.start + comm : ar.stop], range(ar.start + comm, ar.stop), [substitute] * d, [None] * d) + elif d < 0: + yield from zip([substitute] * (-d), [None] * (-d), b[br.start + comm : br.stop], range(br.start + comm, br.stop)) + + +def genPadding(l: int, padder: str = " ") -> str: + return padder * l + + +LineNumberT = typing.Union[str, int] + + +def genNum(n: LineNumberT, numWidth: int) -> str: + r = str(n) + return genPadding(numWidth - len(r), "0") + r + + +def generateRichStrLineDiff(al: str, aln: LineNumberT, bl: str, bln: LineNumberT, opStyle: StylePairT, lineNoStyle: StyleT, maxW: typing.Tuple[int, int], numWidth: int, strConverter: StringConverterT) -> RichStr: + if al is None: + al = "" + if bl is None: + bl = "" + al = strConverter(al) + bl = strConverter(bl) + + if aln is None: + aln = genPadding(numWidth) + + if bln is None: + bln = genPadding(numWidth) + + return rsjoin(" ", ( + lineNoStyle(genNum(aln, numWidth)), + opStyle[0](al), + genPadding(maxW[0] - len(al)), + lineNoStyle(genNum(bln, numWidth)), + opStyle[1](bl) + )) + + +OpcodeT = typing.Tuple[str, int, int, int, int] + +def sideBySideDiff(a: typing.List[str], b: typing.List[str], *, style: typing.Optional[StyleDictT] = None, strConverter: typing.Optional[StringConverterT] = None, names: typing.Optional[typing.Tuple[str, str]] = None, matcherClass: typing.Optional[typing.Type[difflib.SequenceMatcher]]=None, opcodes: typing.Optional[typing.Iterable[OpcodeT]]=None) -> typing.Iterator[RichStr]: + style_ = type(defaultStyle)(defaultStyle) + if style is not None: + style_.update(style) + if strConverter is None: + strConverter = str + + lns = style_["lineNo"] + + + if opcodes is None: + if matcherClass is None: + matcherClass = difflib.SequenceMatcher + m = matcherClass(None, a, b) + opcodes = m.get_opcodes() + + maxW = (getMaxWidth(a), getMaxWidth(b)) + numMaxWidth = ceil(log10(max(len(a), len(b)))) + + if names is not None: + maxW = typing.cast(typing.Tuple[int, int], tuple(max(szs) for szs in zip(maxW, (len(n) for n in names)))) + secondHeaderPadding = 1 + numMaxWidth + maxW[0] # space between first line and its number # padding + yield " ".join((genPadding(numMaxWidth), names[0], genPadding(secondHeaderPadding - len(names[0])), names[1])) + + for oc, aS, aE, bS, bE in opcodes: + opStyle = style_[oc] + if oc == "equal": + for al, aln, bl, bln in zip(a[aS:aE], range(aS, aE), b[bS:bE], range(bS, bE)): + yield generateRichStrLineDiff(al, aln, bl, bln, opStyle, lns, maxW, numMaxWidth, strConverter) + + elif oc == "replace": + for al, aln, bl, bln in azip(a, range(aS, aE), b, range(bS, bE), None): + yield generateRichStrLineDiff(al, aln, bl, bln, opStyle, lns, maxW, numMaxWidth, strConverter) + elif oc == "insert": + for bl, bln in zip(b[bS:bE], range(bS, bE)): + yield generateRichStrLineDiff(genPadding(maxW[0]), genPadding(numMaxWidth), bl, bln, opStyle, lns, maxW, numMaxWidth, strConverter) + elif oc == "delete": + for al, aln in zip(a[aS:aE], range(aS, aE)): + yield generateRichStrLineDiff(al, aln, genPadding(maxW[1]), genPadding(numMaxWidth), opStyle, lns, maxW, numMaxWidth, strConverter) + + +if __name__ == "__main__": + from pathlib import Path + import sys + with Path(sys.argv[1]).open("rt", encoding="utf-8") as f0: + with Path(sys.argv[2]).open("rt", encoding="utf-8") as f1: + for l in sideBySideDiff(f0.read().splitlines(), f1.read().splitlines()): + print(l)