- в 0.16 расширился набор правил по умолчанию: 29 срабатываний там, где 0.15 давал "All checks passed" - subprocess.run без явного check (PLW1510) — проставлен check=False там, где код и так разбирает returncode сам - слепые except Exception в оркестраторе бэкапов и скриптах помечены noqa: BLE001 с объяснением, почему перехват намеренно широкий - EXE001 и TRY004 отключены в pyproject: бит исполняемости в репозитории ничего не решает, а ValueError при разборе config.toml — про содержимое конфига, а не про тип аргумента - ruff format в 0.16 форматирует python внутри markdown, из-за чего переформатирован пример в docs/drafts/gitea-runner-on-demand.md
51 lines
1.4 KiB
Python
51 lines
1.4 KiB
Python
#!/usr/bin/env python3
|
|
|
|
import argparse
|
|
import os
|
|
from pathlib import Path
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(
|
|
description="Retain specified number of files in a directory sorted by name, delete others."
|
|
)
|
|
parser.add_argument("directory", type=str, help="Path to target directory")
|
|
parser.add_argument(
|
|
"--keep", type=int, default=2, help="Number of files to retain (default: 2)"
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
# Validate arguments
|
|
if args.keep < 0:
|
|
parser.error("--keep value cannot be negative")
|
|
|
|
directory = Path(args.directory)
|
|
if not directory.is_dir():
|
|
parser.error(f"Directory not found: {args.directory}")
|
|
|
|
# Get list of files (exclude subdirectories)
|
|
files = []
|
|
with os.scandir(directory) as entries:
|
|
for entry in entries:
|
|
if entry.is_file():
|
|
files.append(entry.name)
|
|
|
|
# Sort files alphabetically
|
|
sorted_files = sorted(files)
|
|
|
|
# Identify files to delete
|
|
to_delete = sorted_files[: -args.keep] if args.keep > 0 else sorted_files.copy()
|
|
|
|
# Delete files and print results
|
|
for filename in to_delete:
|
|
filepath = directory / filename
|
|
try:
|
|
filepath.unlink()
|
|
print(f"Deleted: {filename}")
|
|
except Exception as e: # noqa: BLE001
|
|
print(f"Error deleting {filename}: {e!s}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|