From f1399b1b4b449484c5254206c77638fdc03341ad Mon Sep 17 00:00:00 2001 From: Nicholas Hollander <31573882+nhhollander@users.noreply.github.com> Date: Sat, 7 Nov 2020 14:26:59 -0500 Subject: [PATCH] Add support for combining pathspec objects via addition operator (#43) --- pathspec/pathspec.py | 21 ++++++++++++++ pathspec/tests/test_pathspec.py | 51 +++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/pathspec/pathspec.py b/pathspec/pathspec.py index be058ff..73250ef 100644 --- a/pathspec/pathspec.py +++ b/pathspec/pathspec.py @@ -46,6 +46,27 @@ def __len__(self): """ return len(self.patterns) + def __add__(self, other): + """ + Combines the :attr:`Pathspec.patterns` patterns from two + :class:`PathSpec` instances. + """ + if isinstance(other, PathSpec): + return PathSpec(self.patterns + other.patterns) + else: + return NotImplemented + + def __iadd__(self, other): + """ + Adds the :attr:`Pathspec.patterns` patterns from one :class:`PathSpec` + instance to this instance. + """ + if isinstance(other, PathSpec): + self.patterns += other.patterns + return self + else: + return NotImplemented + @classmethod def from_lines(cls, pattern_factory, lines): """ diff --git a/pathspec/tests/test_pathspec.py b/pathspec/tests/test_pathspec.py index 1f5bb8b..e9435f6 100644 --- a/pathspec/tests/test_pathspec.py +++ b/pathspec/tests/test_pathspec.py @@ -127,3 +127,54 @@ def test_02_ne(self): '!*.txt', ]) self.assertNotEqual(first_spec, second_spec) + + def test_01_addition(self): + """ + Test pattern addition using + operator + """ + first_spec = pathspec.PathSpec.from_lines('gitwildmatch', [ + 'test.txt', + 'test.png' + ]) + second_spec = pathspec.PathSpec.from_lines('gitwildmatch', [ + 'test.html', + 'test.jpg' + ]) + combined_spec = first_spec + second_spec + results = set(combined_spec.match_files([ + 'test.txt', + 'test.png', + 'test.html', + 'test.jpg' + ], separators=('\\',))) + self.assertEqual(results, { + 'test.txt', + 'test.png', + 'test.html', + 'test.jpg' + }) + + def test_02_addition(self): + """ + Test pattern addition using += operator + """ + spec = pathspec.PathSpec.from_lines('gitwildmatch', [ + 'test.txt', + 'test.png' + ]) + spec += pathspec.PathSpec.from_lines('gitwildmatch', [ + 'test.html', + 'test.jpg' + ]) + results = set(spec.match_files([ + 'test.txt', + 'test.png', + 'test.html', + 'test.jpg' + ], separators=('\\',))) + self.assertEqual(results, { + 'test.txt', + 'test.png', + 'test.html', + 'test.jpg' + })