aboutsummaryrefslogtreecommitdiffstats
path: root/config_file/config_file_path.py
blob: 439aceecb49cba556ce064ca4a846c11c311a6d0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
from __future__ import annotations

import os
import pathlib
from typing import Type

from config_file.parsers.abstract_parser import AbstractParser
from config_file.parsers.ini_parser import IniParser
from config_file.parsers.json_parser import JsonParser
from config_file.parsers.toml_parser import TomlParser
from config_file.parsers.yaml_parser import YamlParser

from .utils import split_on_dot

# NOTE: Python 3.12+ supports subclassing pathlib.Path directly.
# See https://discuss.python.org/t/support-subclassing-pathlib-path/29095
_BasePath: Type[pathlib.Path]
if os.name == "nt":
    _BasePath = pathlib.WindowsPath
else:
    _BasePath = pathlib.PosixPath


class ConfigFilePath(_BasePath):  # type: ignore[valid-type, misc]
    """A ConfigFilePath object, which subclasses Path.

    It provides us easy ways to grab the original config file
    path, file extension, validate the path, or determine the parser
    that should be use for the given file type.
    """

    @property
    def original_path(self) -> ConfigFilePath:
        """Computes the original configuration file path.

        e.g. ConfigFilePath("./config.ini").original_path -> "./config.original.ini"

        Returns:
            The path to the original configuration file, which
            may or may not exist.
        """
        file_parts = split_on_dot(self, only_last_dot=True)
        file_parts.insert(-1, "original")
        return ConfigFilePath(".".join(file_parts))

    @property
    def extension(self) -> str:
        """Retrieves the extension of the file
        path we passed in, without the '.'.

        e.g. ConfigFilePath("./pyproject.toml").extension -> "toml"

        Returns:
            The extension of the current file path.
        """
        _, extension = os.path.splitext(str(self))
        return extension[1:]

    @property
    def file_parser(self) -> AbstractParser:
        """Determine what parser should be used for this file.

        Raises:
            ValueError: If the extension of the file is not recognized.
            ParsingError: If the contents could not be parsed.

        Returns:
            The instantiated parser that should be used for this file.
        """
        if self.extension == "":
            raise ValueError(
                "Tried to determine a parser to use, but the file at "
                f"{self} does not have an extension."
            )

        if self.extension == "ini":
            return IniParser(self.contents)
        elif self.extension == "json":
            return JsonParser(self.contents)
        elif self.extension == "yaml" or self.extension == "yml":
            return YamlParser(self.contents)
        elif self.extension == "toml":
            return TomlParser(self.contents)
        else:
            raise ValueError(
                f"File path at `{self}` contains an unrecognized file type."
            )

    @property
    def contents(self) -> str:
        """Retrieve the contents of the file.

        Returns:
            The contents of the file at this path.
        """
        with open(self, "r") as file:
            return file.read()

    def validate(self) -> ConfigFilePath:
        """Validates that the current path exists, is a directory,
        and expands any home tidles.

        Raises:
            FileNotFoundError: If the path does not exist.
            ValueError: If the path leads to a directory.

        Returns:
            A ConfigFilePath object with any ~'s expanded.
        """
        if len(self.parts) >= 1 and self.parts[0] == "~":
            self = ConfigFilePath(self.expanduser())

        if not self.exists():
            raise FileNotFoundError(
                f"The specified config file ({self}) does not exist."
            )

        if self.is_dir():
            raise ValueError(f"The specified config file ({self}) is a directory")

        return self