- набор правил ruff расширен по канону rp-local-env (ANN, PTH, C90, G и др.), в lefthook добавлен job ruff check --fix - код приведён под новые правила: логирование через %s вместо f-строк, os.path заменён на pathlib, run_backup_process и initialize разбиты на функции по порогу цикломатической сложности
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:
|
|
print(f"Error deleting {filename}: {str(e)}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|