ceg.misc

Misc stuff dat i couldn't figure out where to put

  1# ╔═══╗
  2# ║╔═╗║
  3# ║║ ╚╝╔══╗╔══╗
  4# ║║ ╔╗║╔╗║║╔╗║
  5# ║╚═╝║║║═╣║╚╝║
  6# ╚═══╝╚══╝╚═╗║
  7#          ╔═╝║
  8#          ╚══╝
  9# ©Justaus3r 2022
 10# This file is part of "Ceg",a gist crud utility.
 11# Distributed under GPLV3
 12#    This program is free software: you can redistribute it and/or modify
 13#    it under the terms of the GNU General Public License as published by
 14#    the Free Software Foundation, either version 3 of the License, or
 15#    (at your option) any later version.
 16#    This program is distributed in the hope that it will be useful,
 17#    but WITHOUT ANY WARRANTY; without even the implied warranty of
 18#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 19#    GNU General Public License for more details.
 20#
 21#    You should have received a copy of the GNU General Public License
 22#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 23""" Misc stuff dat i couldn't figure out where to put """
 24
 25import os
 26import platform
 27import subprocess
 28from .exceptions import CegExceptions
 29from typing import List, Dict, Callable, Union, Optional, Type, TypeAlias
 30
 31__all__ = ("UtilInfo", "Misc")
 32
 33
 34class UtilInfo:
 35    """Metainfo about utility.
 36
 37    Class containing all the meta info about
 38    the utility.
 39
 40    Attributes:
 41        UTIL_NAME: The utility name.
 42        DESCRIPTION: Short description of the utility.
 43        VERSION: Semantic verson of the utility.
 44    """
 45
 46    UTIL_NAME: str = "ceg"
 47    UTIL_USAGE: str = f"{UTIL_NAME} [options] [sub-arguments]"
 48    EPILOG: str = """
 49sub-arguments:
 50  --post/-po
 51      --no-public/-np        switch gist visibility to private
 52
 53      --description/-desc    description for the gist
 54    
 55  --patch/-pa
 56      --gist-id/-gi          gist-id for the gist
 57
 58For more usage help, check out https://www.github.com/justaus3r/ceg/#examples"""
 59    DESCRIPTION: str = "An all in one github's gist manager."
 60    # Caution(message to myself): Be careful when updating the version because
 61    # wrong updates can be a mess.
 62    VERSION: str = "0.5.0"
 63
 64
 65def exception_executioner(exception_obj) -> None:
 66    """Raises exception taken as am argument.
 67
 68    Args:
 69        exception_obj: THe Exception object.
 70
 71    """
 72    if exception_obj:
 73        raise exception_obj
 74
 75
 76class Misc:
 77    """Misc stuff.
 78
 79    Contains all the miscellaneous vars.
 80
 81    Attributes:
 82    http_intrinsics: List containing names of all http methods.
 83    secret_key: Gitub Secret key extracted from env variable.
 84    """
 85
 86    http_intrinsics: List[str] = ["get", "post", "patch", "delete"]
 87    OptionalException: TypeAlias = Optional[
 88        Union[
 89            Type[CegExceptions.BadCredentials],
 90            Type[CegExceptions.ForbiddenResource],
 91            Type[CegExceptions.ResourceNotFound],
 92            Type[CegExceptions.UnprocessableRequest],
 93        ]
 94    ]
 95    HttpResponseCodes: TypeAlias = Dict[
 96        Union[int, str],
 97        Union[
 98            Dict[str, Dict[str, OptionalException]], Callable[[OptionalException], None]
 99        ],
100    ]
101    http_response_codes: HttpResponseCodes = {
102        200: {"OK!": {"exception_obj": None}},
103        201: {"Gist Created Sucessfully!": {"exception_obj": None}},
104        204: {"OK!.No Response Recieved.": {"exception_obj": None}},
105        401: {"Bad Credentials!": {"exception_obj": CegExceptions.BadCredentials}},
106        403: {
107            "Forbidden Resource!": {"exception_obj": CegExceptions.ForbiddenResource}
108        },
109        404: {"Resource not found!": {"exception_obj": CegExceptions.ResourceNotFound}},
110        422: {
111            "Request Unprocessable!": {
112                "exception_obj": CegExceptions.UnprocessableRequest
113            }
114        },
115        "exception_action": exception_executioner,
116    }
117    secret_key: Optional[str] = os.getenv("GITHUB_SECRET_KEY")
118
119
120class FileHandler:
121    """File & Directory Handler.
122
123    Responsible for creating gist directories,
124    files,writing content to them and removing
125    gist directories if found empty due to some
126    error.
127
128    Attributes:
129        return_code: return code which determines whether to keep a directory or not.
130    """
131
132    def __init__(self, dir_name: str) -> None:
133        "Inits FileHandler with some directory name"
134        self.__dir_name: str = dir_name
135        self.__return_code: int = 0
136        os.mkdir(self.__dir_name)
137
138    @property
139    def return_code(self) -> int:
140        return self.__return_code
141
142    @return_code.setter
143    def return_code(self, return_code) -> None:
144        self.__return_code = return_code
145        if self.__return_code == 1:
146            if len(os.listdir(self.__dir_name)) == 0:
147                os.rmdir(self.__dir_name)
148
149    def write(self, file_name: str, content: str) -> None:
150        with open(os.path.join(self.__dir_name, file_name), "w") as wr:
151            wr.write(content)
152
153
154def open_file(file_name: str) -> int:
155    """Opens an already existing or
156    a new file in default text editor for
157    one of the three major os's.
158
159    Args:
160        file_name: file to open.
161
162    Returns:
163        Returns an integer return code indicating
164        if the operation was successfull or not
165    """
166    try:
167        file_obj = open(file_name, "w")
168    except PermissionError:
169        return 1
170    util: str = ""
171    cmd: List[str] = [""]
172    if platform.system() == "Windows":
173        util = "start"
174    elif platform.system() == "Linux":
175        util = "xdg-open"
176        file_obj.write("# Placeholder text.")
177    elif platform.system() == "Darwin":
178        util = "open"
179        cmd.append("-t")
180    file_obj.close()
181    cmd[0] = util
182    cmd.append(file_name)
183    ret_code: int = subprocess.run(cmd, stdout=subprocess.DEVNULL).returncode
184
185    return ret_code
186
187
188def gist_filename_validated(file_name: str) -> bool:
189    """Validates the filename.
190
191    Validates and checks if the filename has filename
192    pattern prohibited by github and depending so,returns
193    a boolean to represent the respective state.
194
195    Args:
196        file_name: filename to validate.
197    Returns:
198        boolean representing the validated state of filename.
199
200    """
201    striped_filename: str = file_name.replace("gistfile", "")
202    # so the logic here is that if the filename contains 'gistfile'
203    # in it then that will be replaced with emtpy string and the filename
204    # will change,otherwise it won't change which will help us decide
205    # if it does contain that string and if it does then the remaining
206    # string will be validated for numerical digits
207    if striped_filename != file_name and striped_filename.isdigit():
208        return False
209    return True
class UtilInfo:
35class UtilInfo:
36    """Metainfo about utility.
37
38    Class containing all the meta info about
39    the utility.
40
41    Attributes:
42        UTIL_NAME: The utility name.
43        DESCRIPTION: Short description of the utility.
44        VERSION: Semantic verson of the utility.
45    """
46
47    UTIL_NAME: str = "ceg"
48    UTIL_USAGE: str = f"{UTIL_NAME} [options] [sub-arguments]"
49    EPILOG: str = """
50sub-arguments:
51  --post/-po
52      --no-public/-np        switch gist visibility to private
53
54      --description/-desc    description for the gist
55    
56  --patch/-pa
57      --gist-id/-gi          gist-id for the gist
58
59For more usage help, check out https://www.github.com/justaus3r/ceg/#examples"""
60    DESCRIPTION: str = "An all in one github's gist manager."
61    # Caution(message to myself): Be careful when updating the version because
62    # wrong updates can be a mess.
63    VERSION: str = "0.5.0"

Metainfo about utility.

Class containing all the meta info about the utility.

Attributes:
  • UTIL_NAME: The utility name.
  • DESCRIPTION: Short description of the utility.
  • VERSION: Semantic verson of the utility.
class Misc:
 77class Misc:
 78    """Misc stuff.
 79
 80    Contains all the miscellaneous vars.
 81
 82    Attributes:
 83    http_intrinsics: List containing names of all http methods.
 84    secret_key: Gitub Secret key extracted from env variable.
 85    """
 86
 87    http_intrinsics: List[str] = ["get", "post", "patch", "delete"]
 88    OptionalException: TypeAlias = Optional[
 89        Union[
 90            Type[CegExceptions.BadCredentials],
 91            Type[CegExceptions.ForbiddenResource],
 92            Type[CegExceptions.ResourceNotFound],
 93            Type[CegExceptions.UnprocessableRequest],
 94        ]
 95    ]
 96    HttpResponseCodes: TypeAlias = Dict[
 97        Union[int, str],
 98        Union[
 99            Dict[str, Dict[str, OptionalException]], Callable[[OptionalException], None]
100        ],
101    ]
102    http_response_codes: HttpResponseCodes = {
103        200: {"OK!": {"exception_obj": None}},
104        201: {"Gist Created Sucessfully!": {"exception_obj": None}},
105        204: {"OK!.No Response Recieved.": {"exception_obj": None}},
106        401: {"Bad Credentials!": {"exception_obj": CegExceptions.BadCredentials}},
107        403: {
108            "Forbidden Resource!": {"exception_obj": CegExceptions.ForbiddenResource}
109        },
110        404: {"Resource not found!": {"exception_obj": CegExceptions.ResourceNotFound}},
111        422: {
112            "Request Unprocessable!": {
113                "exception_obj": CegExceptions.UnprocessableRequest
114            }
115        },
116        "exception_action": exception_executioner,
117    }
118    secret_key: Optional[str] = os.getenv("GITHUB_SECRET_KEY")

Misc stuff.

Contains all the miscellaneous vars.

Attributes: http_intrinsics: List containing names of all http methods. secret_key: Gitub Secret key extracted from env variable.