Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 18 additions & 30 deletions src/configlock/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down Expand Up @@ -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:
Expand All @@ -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)
4 changes: 2 additions & 2 deletions src/configlock/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down
9 changes: 0 additions & 9 deletions src/configlock/test_config.json

This file was deleted.

Loading