Files
proxy-scraper-checker/proxy_scraper_checker/fs.py
T

43 lines
1.2 KiB
Python
Raw Normal View History

2024-02-08 09:12:13 +03:00
from __future__ import annotations
2025-01-09 15:30:45 +03:00
import asyncio
2024-02-08 09:12:13 +03:00
import logging
2024-06-03 14:08:42 +05:00
from typing import TYPE_CHECKING
2024-02-08 09:12:13 +03:00
import platformdirs
2024-06-03 14:08:42 +05:00
if TYPE_CHECKING:
from pathlib import Path
2024-11-06 15:05:34 +03:00
_logger = logging.getLogger(__name__)
2024-02-08 09:12:13 +03:00
CACHE_PATH = platformdirs.user_cache_path("proxy_scraper_checker")
2025-01-09 15:30:45 +03:00
async def add_permission(
2024-02-08 09:42:30 +03:00
path: Path, permission: int, /, *, missing_ok: bool = False
) -> None:
2024-02-08 09:12:13 +03:00
try:
2025-01-09 15:30:45 +03:00
current_permissions = (await asyncio.to_thread(path.stat)).st_mode
2024-02-08 09:42:30 +03:00
new_permissions = current_permissions | permission
if current_permissions != new_permissions:
2025-01-09 15:30:45 +03:00
await asyncio.to_thread(path.chmod, new_permissions)
2024-11-06 15:05:34 +03:00
_logger.info(
2024-02-08 09:42:30 +03:00
"Changed permissions of %s from %o to %o",
path,
current_permissions,
new_permissions,
)
2024-02-08 09:12:13 +03:00
except FileNotFoundError:
2024-02-08 09:42:30 +03:00
if not missing_ok:
raise
2024-02-08 09:12:13 +03:00
2025-01-09 15:30:45 +03:00
async def create_or_fix_dir(path: Path, /, *, permission: int) -> None:
2024-02-08 09:12:13 +03:00
try:
2025-01-09 15:30:45 +03:00
await asyncio.to_thread(path.mkdir, parents=True)
2024-02-08 09:12:13 +03:00
except FileExistsError:
2025-01-09 15:30:45 +03:00
if not await asyncio.to_thread(path.is_dir):
2024-02-08 09:12:13 +03:00
msg = f"{path} is not a directory"
raise ValueError(msg) from None
2025-01-09 15:30:45 +03:00
await add_permission(path, permission)