/
bilalovmc
/
fast_api_templ
Обзор
Документация
Войти
/
bilalovmc
/
fast_api_templ
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
project_parser.py
113 строк
5 KB
Марсель
init
10 июл 2025, 15:02
10 июл 2025, 15:02
f55c6b9
Код
Авторство
О чём код?
import os from pathlib import Path def get_project_structure(root_dir, indent="", structure=None): if structure is None: structure = [] root_dir = Path(root_dir) items = sorted(os.listdir(root_dir)) for i, item in enumerate(items): path = root_dir / item is_last = i == len(items) - 1 if path.name.startswith("."): continue if path.is_dir(): line = f"{indent}{'└── ' if is_last else '├── '}{path.name}" # Добавляем комментарий только для папок верхнего уровня if indent == "": line += get_folder_comment(path.name) structure.append(line) new_indent = indent + (" " if is_last else "│ ") get_project_structure(path, new_indent, structure) else: line = f"{indent}{'└── ' if is_last else '├── '}{path.name}" # Добавляем комментарий только для файлов верхнего уровня if indent == "": line += get_file_comment(path.name) structure.append(line) return structure def get_folder_comment(folder_name): # Здесь можно добавить описание для конкретных папок comments = { "db": " # module contains db configurations", "dao": " # Data Access Objects. Contains different classes to interact with database.", "models": " # Package contains different models for ORMs.", "services": " # Package for different external services such as rabbit or redis etc.", "static": " # Static content.", "tests": " # Tests for project.", "web": " # Package contains web server. Handlers, startup config.", "api": " # Package with all handlers.", } return comments.get(folder_name, "") def get_file_comment(file_name): # Здесь можно добавить описание для конкретных файлов comments = { "__main__.py": " # Startup script. Starts uvicorn.", "settings.py": " # Main configuration settings for project.", "router.py": " # Main router.", "application.py": " # FastAPI application configuration.", "lifespan.py": " # Contains actions to perform on startup and shutdown.", "conftest.py": " # Fixtures for all tests.", } return comments.get(file_name, "") def process_project_directory(project_path, output_file): project_path = Path(project_path) if not project_path.exists() or not project_path.is_dir(): print(f"Ошибка: {project_path} не является папкой или не существует") return with open(output_file, "w", encoding="utf-8") as f: # Сначала собираем все файлы с кодом for file_path in project_path.rglob("*"): if file_path.is_file() and not file_path.name.startswith("."): try: relative_path = file_path.relative_to(project_path) # Пропускаем бинарные и другие не текстовые файлы if file_path.suffix in ( ".py", ".txt", ".md", ".yaml", ".yml", ".json", ".html", ".css", ".js", ): f.write(f"Файл: {relative_path}\n") f.write("Код:\n") with open(file_path, "r", encoding="utf-8") as code_file: f.write(code_file.read()) f.write("\n\n") except UnicodeDecodeError: f.write(f"Файл: {relative_path}\n") f.write("(бинарный файл, содержимое не отображается)\n\n") except Exception as e: f.write(f"Файл: {relative_path}\n") f.write(f"(ошибка при чтении файла: {str(e)})\n\n") # Затем добавляем структуру проекта f.write("\nСтруктура проекта:\n") structure = get_project_structure(project_path) f.write("\n".join(structure)) if __name__ == "__main__": project_path = "C:/Dev/kontur/fast_balancer_2/fast_balancer_2" output_file = "project_context.txt" print(f"Обработка проекта: {project_path}") process_project_directory(project_path, output_file) print(f"Результат сохранен в файл: {output_file}")