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

Add an OSAgnosticPath type #217

Open
Callum027 opened this issue May 4, 2024 · 0 comments
Open

Add an OSAgnosticPath type #217

Callum027 opened this issue May 4, 2024 · 0 comments
Assignees
Labels
enhancement New feature or request plugins Vendored plugin or plugin API-related issue or pull request
Milestone

Comments

@Callum027
Copy link
Member

Callum027 commented May 4, 2024

Allows for a single type to handle path comparisons for remote instances.

Original implementation from the Sonarr plugin:

from __future__ import annotations

import re

from pathlib import PurePosixPath, PureWindowsPath
from typing import Any, Type

from pydantic import GetCoreSchemaHandler
from pydantic_core import core_schema
from typing_extensions import Self


class OSAgnosticPath(str):
    def is_windows(self) -> bool:
        return bool(re.match(r"^[A-Za-z]:", self) or self.startswith("\\\\"))

    def is_posix(self) -> bool:
        return not self.is_windows()

    def __add__(self, other: Any) -> OSAgnosticPath:
        return OSAgnosticPath(super().__add__(other))

    def __eq__(self, other: Any) -> bool:
        try:
            if self.is_windows():
                return PureWindowsPath(self) == PureWindowsPath(other)
            else:
                return PurePosixPath(self) == PurePosixPath(other)
        except TypeError:
            return False

    def __hash__(self) -> int:
        if self.is_windows():
            return hash(PureWindowsPath(self))
        else:
            return hash(PurePosixPath(self))

    @classmethod
    def __get_pydantic_core_schema__(
        cls,
        source: Type[Any],
        handler: GetCoreSchemaHandler,
    ) -> core_schema.CoreSchema:
        return core_schema.no_info_plain_validator_function(cls.validate)

    @classmethod
    def validate(cls, value: Any) -> Self:
        return cls(value)
@Callum027 Callum027 added enhancement New feature or request plugins Vendored plugin or plugin API-related issue or pull request labels May 4, 2024
@Callum027 Callum027 added this to the v1.0.0 milestone May 4, 2024
@Callum027 Callum027 self-assigned this May 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request plugins Vendored plugin or plugin API-related issue or pull request
Projects
None yet
Development

No branches or pull requests

1 participant