Initial upload: API Mock CLI v0.1.0
Some checks failed
CI / test (3.10) (push) Has been cancelled
CI / test (3.11) (push) Has been cancelled
CI / test (3.12) (push) Has been cancelled
CI / test (3.9) (push) Has been cancelled
CI / lint (push) Has been cancelled
CI / type-check (push) Has been cancelled
CI / build (push) Has been cancelled
Some checks failed
CI / test (3.10) (push) Has been cancelled
CI / test (3.11) (push) Has been cancelled
CI / test (3.12) (push) Has been cancelled
CI / test (3.9) (push) Has been cancelled
CI / lint (push) Has been cancelled
CI / type-check (push) Has been cancelled
CI / build (push) Has been cancelled
This commit is contained in:
60
src/utils/file.py
Normal file
60
src/utils/file.py
Normal file
@@ -0,0 +1,60 @@
|
||||
import json
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List
|
||||
|
||||
|
||||
class FileUtils:
|
||||
@staticmethod
|
||||
def read_file(path: str) -> str:
|
||||
with open(path, "r") as f:
|
||||
return f.read()
|
||||
|
||||
@staticmethod
|
||||
def write_file(path: str, content: str) -> None:
|
||||
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(path, "w") as f:
|
||||
f.write(content)
|
||||
|
||||
@staticmethod
|
||||
def load_json(path: str) -> Dict[str, Any]:
|
||||
with open(path, "r") as f:
|
||||
return json.load(f)
|
||||
|
||||
@staticmethod
|
||||
def write_json(path: str, data: Any, indent: int = 2) -> None:
|
||||
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(path, "w") as f:
|
||||
json.dump(data, f, indent=indent)
|
||||
|
||||
@staticmethod
|
||||
def load_yaml(path: str) -> Dict[str, Any]:
|
||||
with open(path, "r") as f:
|
||||
return yaml.safe_load(f) or {}
|
||||
|
||||
@staticmethod
|
||||
def write_yaml(path: str, data: Any) -> None:
|
||||
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(path, "w") as f:
|
||||
yaml.dump(data, f, default_flow_style=False)
|
||||
|
||||
@staticmethod
|
||||
def ensure_dir(path: str) -> None:
|
||||
Path(path).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@staticmethod
|
||||
def file_exists(path: str) -> bool:
|
||||
return Path(path).exists()
|
||||
|
||||
@staticmethod
|
||||
def list_files(path: str, pattern: str = "*") -> List[str]:
|
||||
return [str(p) for p in Path(path).glob(pattern)]
|
||||
|
||||
@staticmethod
|
||||
def read_yaml_or_json(path: str) -> Dict[str, Any]:
|
||||
if path.endswith(".yaml") or path.endswith(".yml"):
|
||||
return FileUtils.load_yaml(path)
|
||||
elif path.endswith(".json"):
|
||||
return FileUtils.load_json(path)
|
||||
else:
|
||||
raise ValueError(f"Unsupported file format: {path}")
|
||||
Reference in New Issue
Block a user