Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

parse fails if path or base_path is not a str #40

Open
RhetTbull opened this issue Jul 30, 2023 · 1 comment
Open

parse fails if path or base_path is not a str #40

RhetTbull opened this issue Jul 30, 2023 · 1 comment

Comments

@RhetTbull
Copy link

If you use a non-str argument to parse() for either path or base_path, parse fails. There are many valid reasons for using parse this way, notably using a pathlib.Path instead of a str. I think it would be better if both arguments accepted str | os.PathLike (or str | os.PathLike | None in the case of base_path) though one could make an argument that bytes should be valid as well. See os.PathLike.

If base_path is non-str, the error is:

AttributeError: 'PosixPath' object has no attribute '_Path__parts

And if path is non-str, the error is:

'PosixPath' object has no attribute 'relpath'

The errors occur here:

def match(self, path, is_dir=None):
if isinstance(path, str):
path = _Path(path)
rel_path = path.relpath(self.__base_path)

which calls:

def relpath(self, base_path):
if self.__parts[: len(base_path.__parts)] == base_path.__parts:
return "/".join(self.__parts[len(base_path.__parts) :])

I've fixed these in my vendored copy of this library and happy to push a PR. The issue happens because of these lines where isinstance checks whether the argument is a str:

class _IgnoreRules:
def __init__(self, rules, base_path):
self.__rules = rules
self.__can_return_immediately = not any((r.negation for r in rules))
self.__base_path = _Path(base_path) if isinstance(base_path, str) else base_path
def match(self, path, is_dir=None):
if isinstance(path, str):
path = _Path(path)

and

def __init__(self, path):
if isinstance(path, str):
abs_path = os.path.abspath(path)
self.__parts = tuple(_path_split(abs_path))
self.__joined = abs_path
self.__is_dir = None
else:
self.__parts = path
self.__joined = None
self.__is_dir = None

Where the code assumes the argument is either a str or a _Path.

The following test code demonstrates the error:

""" Test match with non-string arguments. """
import io
import pathlib
import unittest
import unittest.mock

import gitignorefile


class TestMatchNonStr(unittest.TestCase):
    """Test match with non-string arguments."""
    def test_simple_base_path(self):
        """Test non-str pathlike arguments for base_path"""
        matches = self.__parse_gitignore_string(["__pycache__/", "*.py[cod]"], mock_base_path=pathlib.Path("/home/michael"))
        for is_dir in (False, True):
            with self.subTest(i=is_dir):
                self.assertFalse(matches("/home/michael/main.py", is_dir=is_dir))
                self.assertTrue(matches("/home/michael/main.pyc", is_dir=is_dir))
                self.assertTrue(matches("/home/michael/dir/main.pyc", is_dir=is_dir))
        self.assertFalse(matches("/home/michael/__pycache__", is_dir=False))
        self.assertTrue(matches("/home/michael/__pycache__", is_dir=True))

    def test_simple_matches(self):
        """Test non-str pathlike arguments for match"""
        matches = self.__parse_gitignore_string(["__pycache__/", "*.py[cod]"], mock_base_path=pathlib.Path("/home/michael"))
        for is_dir in (False, True):
            with self.subTest(i=is_dir):
                self.assertFalse(matches(pathlib.Path("/home/michael/main.py"), is_dir=is_dir))
                self.assertTrue(matches(pathlib.Path("/home/michael/main.pyc"), is_dir=is_dir))
                self.assertTrue(matches(pathlib.Path("/home/michael/dir/main.pyc"), is_dir=is_dir))
        self.assertFalse(matches(pathlib.Path("/home/michael/__pycache__"), is_dir=False))
        self.assertTrue(matches(pathlib.Path("/home/michael/__pycache__"), is_dir=True))

    def __parse_gitignore_string(self, data, mock_base_path):
        with unittest.mock.patch("builtins.open", lambda _: io.StringIO("\n".join(data))):
            return gitignorefile.parse(f"{mock_base_path}/.gitignore", base_path=mock_base_path)
RhetTbull added a commit to RhetTbull/gitignorefile that referenced this issue Jul 30, 2023
@RhetTbull
Copy link
Author

You can see my relatively simple changes here. I also suggest adding type hints and am happy to include a PR for those if you'd like. It was not obvious to me without type hints that a non-str object (which contains a __str__() method) like pathlib.Path would fail.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant