You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
140 lines
5.9 KiB
140 lines
5.9 KiB
#!/usr/bin/env python3 |
|
|
|
import os |
|
import sys |
|
import magic # Убедитесь, что библиотека установлена (pip install python-magic) |
|
from datetime import datetime |
|
from glob import glob |
|
import pyperclip # Убедитесь, что библиотека установлена (pip install pyperclip) |
|
|
|
|
|
def get_file_info(filepath): |
|
"""Получение информации о файле""" |
|
stats = os.stat(filepath) |
|
size = stats.st_size |
|
created = datetime.fromtimestamp(stats.st_ctime).strftime("%Y-%m-%d %H:%M:%S") |
|
modified = datetime.fromtimestamp(stats.st_mtime).strftime("%Y-%m-%d %H:%M:%S") |
|
return size, created, modified |
|
|
|
|
|
def generate_tree(directory): |
|
tree_output = [] |
|
for root, dirs, files in os.walk(directory): |
|
if "/." in root: |
|
continue |
|
files = [f for f in files if not "/." in f and "secret" not in f.lower()] |
|
|
|
level = root.replace(directory, "").count(os.sep) |
|
indent = " " * 4 * level |
|
tree_output.append(f"{indent}{os.path.basename(root)}/") |
|
sub_indent = " " * 4 * (level + 1) |
|
for file in files: |
|
tree_output.append(f"{sub_indent}{file}") |
|
return "\n".join(tree_output) |
|
|
|
|
|
def process_directory(directory): |
|
"""Обработка указанной папки""" |
|
output = [] |
|
mime = magic.Magic(mime=True) # Инициализация magic для определения типа файла |
|
|
|
# Добавляем дерево файлов в начало отчёта |
|
output.append("Дерево файлов и папок:") |
|
output.append(generate_tree(directory)) |
|
output.append("=" * 50) |
|
|
|
for root, dirs, files in os.walk(directory): |
|
if "/." in root: |
|
continue |
|
# Фильтруем скрытые файлы и файлы, содержащие "secret" в имени |
|
files = [f for f in files if not "/." in f and "secret" not in f.lower()] |
|
|
|
for file in files: |
|
file_path = os.path.join(root, file) |
|
file_type = mime.from_file(file_path) # Определяем тип файла |
|
size, created, modified = get_file_info(file_path) |
|
|
|
# Добавляем информацию о файле в поток |
|
output.append(f"==== начало ({file}) ====") |
|
output.append( |
|
f"Файл: {file}\nРазмер: {size} байт\nСоздан: {created}\nИзменён: {modified}\nТип: {file_type}" |
|
) |
|
|
|
# Обработка текстовых файлов и программного кода |
|
if "text" in file_type or "script" in file_type or "json" in file_type: |
|
try: |
|
with open(file_path, "r", encoding="utf-8") as f: |
|
content = f.read() |
|
except Exception as e: |
|
content = f"Ошибка при чтении файла: {e}" |
|
output.append(f"Содержимое:\n{content}\n") |
|
|
|
# Обработка изображений |
|
elif "image" in file_type: |
|
output.append( |
|
"Содержимое: [Изображение: метаинформация недоступна в этом примере]\n" |
|
) |
|
|
|
# Обработка файлов форматов docx, odt (через pandoc) и pdf (через pdftotext) |
|
elif file.endswith((".docx", ".odt")): |
|
try: |
|
import subprocess |
|
|
|
result = subprocess.run( |
|
["pandoc", "-f", "docx", "-t", "plain", file_path], |
|
capture_output=True, |
|
text=True, |
|
) |
|
if result.returncode == 0: |
|
content = result.stdout |
|
else: |
|
content = f"Ошибка при конвертации pandoc: {result.stderr}" |
|
except Exception as e: |
|
content = f"Ошибка при обработке файла: {e}" |
|
output.append(f"Содержимое:\n{content}\n") |
|
|
|
elif file.endswith(".pdf"): |
|
try: |
|
import subprocess |
|
|
|
result = subprocess.run( |
|
["pdftotext", file_path, "-"], capture_output=True, text=True |
|
) |
|
if result.returncode == 0: |
|
content = result.stdout |
|
else: |
|
content = f"Ошибка при конвертации pdftotext: {result.stderr}" |
|
except Exception as e: |
|
content = f"Ошибка при обработке файла: {e}" |
|
output.append(f"Содержимое:\n{content}\n") |
|
|
|
# Другие файлы |
|
else: |
|
output.append("Содержимое: [Невозможно отобразить содержимое файла]\n") |
|
|
|
output.append(f"==== конец ({file}) ====") |
|
|
|
return "\n".join(output) |
|
|
|
|
|
def main(): |
|
if len(sys.argv) != 2: |
|
print("Использование: python script.py <путь_к_рабочей_папке>") |
|
sys.exit(1) |
|
|
|
working_directory = sys.argv[1] |
|
|
|
if not os.path.isdir(working_directory): |
|
print(f"Ошибка: Папка '{working_directory}' не существует.") |
|
sys.exit(1) |
|
|
|
result = process_directory(working_directory) |
|
|
|
result += f"""\nЭто было системное сообщение с описанием структуры каталогов, файлов и описанием файлов с их содержимым в рабочей папке. Не отвечай на это сообщение и жди дальнейших указаний.""" |
|
|
|
# Копируем результат в буфер обмена |
|
pyperclip.copy(result) |
|
|
|
|
|
if __name__ == "__main__": |
|
main()
|
|
|