From 01527284efee68ebd242bdce490d1bcc851c558a Mon Sep 17 00:00:00 2001 From: Mariusz Strzelecki Date: Thu, 24 Nov 2022 14:17:02 +0100 Subject: [PATCH] Ensure that Path() type is supported in matches() --- gitignore_parser.py | 5 +++-- tests.py | 5 +++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/gitignore_parser.py b/gitignore_parser.py index f78d86f..0c79c46 100644 --- a/gitignore_parser.py +++ b/gitignore_parser.py @@ -4,6 +4,7 @@ from os.path import dirname from pathlib import Path +from typing import Union def handle_negation(file_path, rules): matched = False @@ -132,7 +133,7 @@ def __str__(self): def __repr__(self): return ''.join(['IgnoreRule(\'', self.pattern, '\')']) - def match(self, abs_path): + def match(self, abs_path: Union[str, Path]): matched = False if self.base_path: rel_path = str(Path(abs_path).resolve().relative_to(self.base_path)) @@ -140,7 +141,7 @@ def match(self, abs_path): rel_path = str(Path(abs_path)) # Path() strips the trailing slash, so we need to preserve it # in case of directory-only negation - if self.negation and abs_path[-1] == '/': + if self.negation and type(abs_path) == str and abs_path[-1] == '/': rel_path += '/' if rel_path.startswith('./'): rel_path = rel_path[2:] diff --git a/tests.py b/tests.py index 1340401..2934841 100644 --- a/tests.py +++ b/tests.py @@ -1,4 +1,5 @@ from unittest.mock import patch, mock_open +from pathlib import Path from gitignore_parser import parse_gitignore @@ -127,6 +128,10 @@ def test_single_asterisk(self): self.assertTrue(matches('/home/michael/directory')) self.assertTrue(matches('/home/michael/directory-trailing/')) + def test_supports_path_type_argument(self): + matches = _parse_gitignore_string('file1\n!file2', fake_base_dir='/home/michael') + self.assertTrue(matches(Path('/home/michael/file1'))) + self.assertFalse(matches(Path('/home/michael/file2'))) def _parse_gitignore_string(data: str, fake_base_dir: str = None): with patch('builtins.open', mock_open(read_data=data)):