diff --git a/src/configlock/helper.py b/src/configlock/helper.py index 3379948..b027703 100644 --- a/src/configlock/helper.py +++ b/src/configlock/helper.py @@ -6,6 +6,8 @@ from dotenv import load_dotenv import os +from configlock.exceptions import ConfigLockError + load_dotenv() CONFIG_LOG_FILE_PATH = os.getenv('CONFIG_LOG_FILE_PATH', 'config.lock.json') @@ -36,18 +38,6 @@ def check_file_exists(file_path: str | None = CONFIG_LOG_FILE_PATH) -> bool: return exists - -def read_yaml(file_path: str) -> dict: - try: - with open(file_path, "r") as f: - data = yaml.safe_load(f) - except FileNotFoundError: - raise - else: - typer.echo(f"Sucessfully read file") - return data - - def read_json(file_path: str) -> dict: try: with open(file_path, "r") as f: @@ -71,26 +61,24 @@ def write_json(data: dict, file_path: str | None = CONFIG_LOG_FILE_PATH) -> None typer.echo(f"Sucessfully wrote file") -def check_file_and_read_file(file_path: str) -> dict: - typer.echo(f"Reading {file_path}...") +def check_file_and_read_file(file: dict) -> dict: - path = Path(file_path) - suffix = path.suffix.lower() + data = detect_and_load(file) - reader_by_suffix = { - ".yaml": read_yaml, - ".yml": read_yaml, - ".json": read_json, - } + return data - reader = reader_by_suffix.get(suffix) - if reader is None: - typer.echo( - f"File not suppported: {suffix}. Use .yaml, .yml, or .json.", - err=True, - ) - raise ValueError("Error not able to read the file") - data = reader(file_path) - return data + +def detect_and_load(data): + + try: + data = json.loads(data) + return data + except ValueError: + pass # Content is not valid JSON + try: + data = yaml.safe_load(data) + return data + except yaml.YAMLError: + raise ConfigLockError("File is not of a supported file", error_code=1) diff --git a/src/configlock/main.py b/src/configlock/main.py index 61827b2..2c66d38 100644 --- a/src/configlock/main.py +++ b/src/configlock/main.py @@ -14,14 +14,14 @@ def main() -> None: @app.command() -def init(file_path: Annotated[str, typer.Argument(help="the path for the newly proposed file")]) -> None: +def init(file: Annotated[dict, typer.Argument(help="the path for the newly proposed file")]) -> None: """ Reads a YAML config and generates a lockfile. """ if check_file_exists(): typer.echo("File already exists!") else: - data = check_file_and_read_file(file_path) + data = check_file_and_read_file(file) write_json(data) diff --git a/src/configlock/test_config.json b/src/configlock/test_config.json deleted file mode 100644 index 1ab5e09..0000000 --- a/src/configlock/test_config.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "project_name": "ConfigLock", - "status": "Alpha", - "version": 1, - "team": { - "lead": "Philipp Stahlberg", - "contributors": [] - } -} \ No newline at end of file