gpkgstatus.utils.config

A Config module that creates, reads and checks ~/.gpkgconfig JSON config file.

  1"""A Config module that creates, reads and checks ~/.gpkgconfig JSON \
  2    config file.
  3"""
  4
  5import json
  6import logging
  7import os
  8import sys
  9
 10from pathlib import Path
 11from random import randint
 12
 13from termcolor import colored
 14
 15
 16class Config:
 17    """A Config class that contains fields or keys of the \
 18        config file.
 19    """
 20
 21    cache_time: int
 22    verbose: bool
 23    __path: Path
 24
 25    def __init__(self):
 26        self.cache_time = randint(52, 65) * 60
 27        self.verbose = False
 28
 29        logging.info("Set Cache Time: %d min", self.cache_time // 60)
 30        logging.info("Set Verbose to %s", self.verbose)
 31
 32        # Set Path
 33        if "XDG_CONFIG_HOME" in os.environ:
 34            self.__path = Path(os.environ["XDG_CONFIG_HOME"]).joinpath(".gpkgconfig")
 35        else:
 36            self.__path = Path.expanduser(Path("~/.config/.gpkgconfig"))
 37
 38        logging.info("Set path to %s", self.__path)
 39
 40    def check(self) -> bool:
 41        """Checks whether config file exists, and also checks if \
 42            it is a valid JSON file.
 43
 44        Returns:
 45            bool: Whether config file exists and is a valid JSON file
 46        """
 47        path = self.__path
 48        if not (path.exists() and path.is_file()):
 49            logging.info("Config file not found")
 50            return False
 51
 52        try:
 53            with open(path, encoding="utf-8") as file:
 54                json.load(file)
 55        except json.JSONDecodeError:
 56            logging.info("Config file is not a valid JSON file")
 57            return False
 58
 59        logging.info("Config file is valid")
 60        return True
 61
 62    def create(self):
 63        """Creates config file in corresponding path.
 64
 65        If script doesn't have permissions to write to config dir,
 66        it will tell the user to check config dir permissions.
 67        """
 68
 69        config = {"cache_time": self.cache_time, "verbose": self.verbose}
 70        try:
 71            with open(self.__path, "w", encoding="utf-8") as file:
 72                json.dump(config, file, skipkeys=True, indent=4)
 73
 74            logging.info("Config file written to %s", self.__path)
 75
 76        except PermissionError:
 77            print(
 78                colored(
 79                    "Error: Permission denied. Please check home directory permissions.",
 80                    "red",
 81                )
 82            )
 83            sys.exit(1)
 84
 85    def read(self):
 86        """If config file exists, this method reads the JSON config file.
 87
 88        It also checks if ("cache_time", "verbose") are keys in JSON file.
 89        In case if one of them doesn't exist, it states that file is not
 90        a valid config file.
 91        """
 92        with open(self.__path, encoding="utf-8") as file:
 93            data = json.load(file)
 94
 95        if all(key not in data.keys() for key in ("cache_time", "verbose")):
 96            print(colored("File is not a valid Config file.", "light_red"))
 97            sys.exit(1)
 98
 99        self.cache_time = data["cache_time"]
100        self.verbose = data["verbose"]
101
102    def main(self):
103        """Main Method
104
105        The method checks if file exists and reads the file. If file
106        is not generated, then it calls the `create()` function.
107        """
108        if not self.check():
109            self.create()
110
111        self.read()
class Config:
 17class Config:
 18    """A Config class that contains fields or keys of the \
 19        config file.
 20    """
 21
 22    cache_time: int
 23    verbose: bool
 24    __path: Path
 25
 26    def __init__(self):
 27        self.cache_time = randint(52, 65) * 60
 28        self.verbose = False
 29
 30        logging.info("Set Cache Time: %d min", self.cache_time // 60)
 31        logging.info("Set Verbose to %s", self.verbose)
 32
 33        # Set Path
 34        if "XDG_CONFIG_HOME" in os.environ:
 35            self.__path = Path(os.environ["XDG_CONFIG_HOME"]).joinpath(".gpkgconfig")
 36        else:
 37            self.__path = Path.expanduser(Path("~/.config/.gpkgconfig"))
 38
 39        logging.info("Set path to %s", self.__path)
 40
 41    def check(self) -> bool:
 42        """Checks whether config file exists, and also checks if \
 43            it is a valid JSON file.
 44
 45        Returns:
 46            bool: Whether config file exists and is a valid JSON file
 47        """
 48        path = self.__path
 49        if not (path.exists() and path.is_file()):
 50            logging.info("Config file not found")
 51            return False
 52
 53        try:
 54            with open(path, encoding="utf-8") as file:
 55                json.load(file)
 56        except json.JSONDecodeError:
 57            logging.info("Config file is not a valid JSON file")
 58            return False
 59
 60        logging.info("Config file is valid")
 61        return True
 62
 63    def create(self):
 64        """Creates config file in corresponding path.
 65
 66        If script doesn't have permissions to write to config dir,
 67        it will tell the user to check config dir permissions.
 68        """
 69
 70        config = {"cache_time": self.cache_time, "verbose": self.verbose}
 71        try:
 72            with open(self.__path, "w", encoding="utf-8") as file:
 73                json.dump(config, file, skipkeys=True, indent=4)
 74
 75            logging.info("Config file written to %s", self.__path)
 76
 77        except PermissionError:
 78            print(
 79                colored(
 80                    "Error: Permission denied. Please check home directory permissions.",
 81                    "red",
 82                )
 83            )
 84            sys.exit(1)
 85
 86    def read(self):
 87        """If config file exists, this method reads the JSON config file.
 88
 89        It also checks if ("cache_time", "verbose") are keys in JSON file.
 90        In case if one of them doesn't exist, it states that file is not
 91        a valid config file.
 92        """
 93        with open(self.__path, encoding="utf-8") as file:
 94            data = json.load(file)
 95
 96        if all(key not in data.keys() for key in ("cache_time", "verbose")):
 97            print(colored("File is not a valid Config file.", "light_red"))
 98            sys.exit(1)
 99
100        self.cache_time = data["cache_time"]
101        self.verbose = data["verbose"]
102
103    def main(self):
104        """Main Method
105
106        The method checks if file exists and reads the file. If file
107        is not generated, then it calls the `create()` function.
108        """
109        if not self.check():
110            self.create()
111
112        self.read()

A Config class that contains fields or keys of the config file.

Config()
26    def __init__(self):
27        self.cache_time = randint(52, 65) * 60
28        self.verbose = False
29
30        logging.info("Set Cache Time: %d min", self.cache_time // 60)
31        logging.info("Set Verbose to %s", self.verbose)
32
33        # Set Path
34        if "XDG_CONFIG_HOME" in os.environ:
35            self.__path = Path(os.environ["XDG_CONFIG_HOME"]).joinpath(".gpkgconfig")
36        else:
37            self.__path = Path.expanduser(Path("~/.config/.gpkgconfig"))
38
39        logging.info("Set path to %s", self.__path)
def check(self) -> bool:
41    def check(self) -> bool:
42        """Checks whether config file exists, and also checks if \
43            it is a valid JSON file.
44
45        Returns:
46            bool: Whether config file exists and is a valid JSON file
47        """
48        path = self.__path
49        if not (path.exists() and path.is_file()):
50            logging.info("Config file not found")
51            return False
52
53        try:
54            with open(path, encoding="utf-8") as file:
55                json.load(file)
56        except json.JSONDecodeError:
57            logging.info("Config file is not a valid JSON file")
58            return False
59
60        logging.info("Config file is valid")
61        return True

Checks whether config file exists, and also checks if it is a valid JSON file.

Returns:

bool: Whether config file exists and is a valid JSON file

def create(self):
63    def create(self):
64        """Creates config file in corresponding path.
65
66        If script doesn't have permissions to write to config dir,
67        it will tell the user to check config dir permissions.
68        """
69
70        config = {"cache_time": self.cache_time, "verbose": self.verbose}
71        try:
72            with open(self.__path, "w", encoding="utf-8") as file:
73                json.dump(config, file, skipkeys=True, indent=4)
74
75            logging.info("Config file written to %s", self.__path)
76
77        except PermissionError:
78            print(
79                colored(
80                    "Error: Permission denied. Please check home directory permissions.",
81                    "red",
82                )
83            )
84            sys.exit(1)

Creates config file in corresponding path.

If script doesn't have permissions to write to config dir, it will tell the user to check config dir permissions.

def read(self):
 86    def read(self):
 87        """If config file exists, this method reads the JSON config file.
 88
 89        It also checks if ("cache_time", "verbose") are keys in JSON file.
 90        In case if one of them doesn't exist, it states that file is not
 91        a valid config file.
 92        """
 93        with open(self.__path, encoding="utf-8") as file:
 94            data = json.load(file)
 95
 96        if all(key not in data.keys() for key in ("cache_time", "verbose")):
 97            print(colored("File is not a valid Config file.", "light_red"))
 98            sys.exit(1)
 99
100        self.cache_time = data["cache_time"]
101        self.verbose = data["verbose"]

If config file exists, this method reads the JSON config file.

It also checks if ("cache_time", "verbose") are keys in JSON file. In case if one of them doesn't exist, it states that file is not a valid config file.

def main(self):
103    def main(self):
104        """Main Method
105
106        The method checks if file exists and reads the file. If file
107        is not generated, then it calls the `create()` function.
108        """
109        if not self.check():
110            self.create()
111
112        self.read()

Main Method

The method checks if file exists and reads the file. If file is not generated, then it calls the create() function.