import pathlib


def mockfs(monkeypatch, tmp_path):
    """Setup a fake fs root for pathlib objects at tmp_path/mockfs."""
    mockfs_dir = pathlib.PosixPath(tmp_path / "mockfs")
    mockfs_dir.mkdir()

    class FakePath(pathlib.Path):
        def __new__(cls, *args, **kwargs):
            parts = pathlib.PosixPath(*args).relative_to("/").parts
            # Make sure we don't double up our mocked directory.
            mock_dir_parts = mockfs_dir.relative_to("/").parts
            if parts[: len(mock_dir_parts)] == mock_dir_parts:
                return pathlib.PosixPath(*args)
            return pathlib.PosixPath("/", *mock_dir_parts, *parts)

    monkeypatch.setattr(pathlib, "Path", FakePath)
    return mockfs_dir