51 lines
1.3 KiB
Python
51 lines
1.3 KiB
Python
"""General utility helpers for file operations and logging."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from pathlib import Path
|
|
|
|
from .constants import APP_NAME, LOG_FILE_NAME
|
|
|
|
|
|
def setup_logger(gradle_home: Path) -> logging.Logger:
|
|
"""Configure and return the application logger.
|
|
|
|
Logs are written to ``<gradle_home>/gradle-mirror.log`` and include timestamps.
|
|
"""
|
|
|
|
gradle_home.mkdir(parents=True, exist_ok=True)
|
|
log_path = gradle_home / LOG_FILE_NAME
|
|
|
|
logger = logging.getLogger(APP_NAME)
|
|
if logger.handlers:
|
|
return logger
|
|
|
|
logger.setLevel(logging.INFO)
|
|
formatter = logging.Formatter(
|
|
fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
|
|
datefmt="%Y-%m-%d %H:%M:%S",
|
|
)
|
|
|
|
file_handler = logging.FileHandler(log_path, encoding="utf-8")
|
|
file_handler.setFormatter(formatter)
|
|
|
|
logger.addHandler(file_handler)
|
|
logger.propagate = False
|
|
return logger
|
|
|
|
|
|
def read_text_if_exists(path: Path) -> str:
|
|
"""Read UTF-8 text if file exists; otherwise return empty string."""
|
|
|
|
if not path.exists():
|
|
return ""
|
|
return path.read_text(encoding="utf-8")
|
|
|
|
|
|
def write_text(path: Path, content: str) -> None:
|
|
"""Write UTF-8 text content, creating parent folders if needed."""
|
|
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(content, encoding="utf-8")
|