Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,396 +3,373 @@ import os
|
|
| 3 |
import subprocess
|
| 4 |
import tempfile
|
| 5 |
import zipfile
|
|
|
|
| 6 |
import shutil
|
| 7 |
-
from pathlib import Path
|
| 8 |
-
import fnmatch # Для базового gitignore-подобного сопоставления (альтернатива pathspec)
|
| 9 |
from pathspec import PathSpec
|
| 10 |
from pathspec.patterns import GitWildMatchPattern
|
| 11 |
|
| 12 |
-
# ---
|
| 13 |
-
DEFAULT_IGNORE_PATTERNS = "
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
def get_repo_name_from_url(url):
|
| 18 |
-
"""Извлекает имя репозитория из URL."""
|
| 19 |
try:
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
try:
|
| 27 |
-
with open(filepath, 'rb') as f:
|
| 28 |
-
chunk = f.read(1024)
|
| 29 |
-
return b'\0' in chunk
|
| 30 |
-
except Exception:
|
| 31 |
-
return True # Считаем бинарным при ошибке чтения
|
| 32 |
-
|
| 33 |
-
def create_gitignore_spec(ignore_patterns_str, repo_root):
|
| 34 |
-
"""Создает объект PathSpec из строки паттернов."""
|
| 35 |
-
patterns = [p.strip() for p in ignore_patterns_str.split(',') if p.strip()]
|
| 36 |
-
# Добавляем .git/ всегда, если его нет
|
| 37 |
-
if ".git/" not in patterns and ".git" not in patterns:
|
| 38 |
-
patterns.append(".git/")
|
| 39 |
-
# print(f"Using patterns: {patterns}") # Для отладки
|
| 40 |
-
# Используем GitWildMatchPattern для поддержки синтаксиса .gitignore
|
| 41 |
-
try:
|
| 42 |
-
# pathspec ожидает паттерны относительно корня, где находится .gitignore
|
| 43 |
-
# Если мы находимся в корне репозитория, то пути файлов тоже должны быть относительными к этому корню
|
| 44 |
-
spec = PathSpec.from_lines(GitWildMatchPattern, patterns)
|
| 45 |
-
return spec
|
| 46 |
-
except Exception as e:
|
| 47 |
-
print(f"Error creating PathSpec: {e}")
|
| 48 |
-
# Возвращаем пустой spec в случае ошибки парсинга паттернов
|
| 49 |
-
return PathSpec.from_lines(GitWildMatchPattern, [])
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
):
|
| 59 |
-
"""
|
| 60 |
-
|
| 61 |
-
"""
|
| 62 |
-
repo_path_obj = Path(repo_path).resolve()
|
| 63 |
markdown_lines = []
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
#
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
):
|
| 173 |
-
"""
|
| 174 |
-
|
| 175 |
-
""
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
temp_dir = tempfile.mkdtemp()
|
| 181 |
-
repo_path = ""
|
| 182 |
-
repo_name = "repository"
|
| 183 |
|
| 184 |
try:
|
| 185 |
-
|
| 186 |
-
if not repo_url or not repo_url.startswith(('http://', 'https://')):
|
| 187 |
-
raise ValueError("Please provide a valid HTTP/HTTPS Git repository URL.")
|
| 188 |
-
|
| 189 |
-
repo_name = get_repo_name_from_url(repo_url)
|
| 190 |
-
repo_path = os.path.join(temp_dir, repo_name)
|
| 191 |
-
status_updates.append(f"Cloning repository: {repo_url}...")
|
| 192 |
-
yield "\n".join(status_updates), "", None, progress # Обновляем статус
|
| 193 |
-
|
| 194 |
-
git_command = ["git", "clone", "--depth", "1"] # Экономим трафик/время
|
| 195 |
-
if branch_tag:
|
| 196 |
-
git_command.extend(["--branch", branch_tag])
|
| 197 |
-
status_updates.append(f"Using branch/tag: {branch_tag}")
|
| 198 |
-
yield "\n".join(status_updates), "", None, progress
|
| 199 |
-
git_command.extend([repo_url, repo_path])
|
| 200 |
-
|
| 201 |
-
# progress(0.1, desc="Cloning...") # Начало клонирования
|
| 202 |
-
# Используем subprocess.run для выполнения команды git
|
| 203 |
-
result = subprocess.run(git_command, capture_output=True, text=True, check=False) # check=False для ручной проверки
|
| 204 |
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
yield "\n".join(status_updates), "", None, progress
|
| 210 |
-
|
| 211 |
-
elif input_type == "Upload ZIP":
|
| 212 |
-
if zip_upload is None:
|
| 213 |
-
raise ValueError("Please upload a ZIP file.")
|
| 214 |
-
|
| 215 |
-
status_updates.append(f"Processing uploaded ZIP file: {os.path.basename(zip_upload.name)}...")
|
| 216 |
-
yield "\n".join(status_updates), "", None, progress # Обновляем статус
|
| 217 |
-
|
| 218 |
-
repo_name = os.path.splitext(os.path.basename(zip_upload.name))[0]
|
| 219 |
-
repo_path = os.path.join(temp_dir, repo_name)
|
| 220 |
-
os.makedirs(repo_path, exist_ok=True)
|
| 221 |
-
|
| 222 |
-
# progress(0.1, desc="Extracting ZIP...") # Начало извлечения
|
| 223 |
-
try:
|
| 224 |
-
with zipfile.ZipFile(zip_upload.name, 'r') as zip_ref:
|
| 225 |
-
# Проверка на "Zip Slip" уязвимость (пути вне целевого каталога)
|
| 226 |
-
for member in zip_ref.namelist():
|
| 227 |
-
member_path = os.path.abspath(os.path.join(repo_path, member))
|
| 228 |
-
if not member_path.startswith(os.path.abspath(repo_path)):
|
| 229 |
-
raise SecurityException(f"Attempted Path Traversal in ZIP: {member}")
|
| 230 |
-
# Извлечение
|
| 231 |
-
zip_ref.extractall(repo_path)
|
| 232 |
-
status_updates.append("ZIP extraction successful.")
|
| 233 |
-
yield "\n".join(status_updates), "", None, progress
|
| 234 |
-
except zipfile.BadZipFile:
|
| 235 |
-
raise ValueError("Uploaded file is not a valid ZIP archive.")
|
| 236 |
-
except Exception as e:
|
| 237 |
-
raise RuntimeError(f"Error extracting ZIP file: {e}")
|
| 238 |
-
|
| 239 |
-
else:
|
| 240 |
-
raise ValueError("Invalid input type selected.")
|
| 241 |
-
|
| 242 |
-
# --- Генерация Markdown ---
|
| 243 |
-
status_updates.append("Generating Markdown structure...")
|
| 244 |
-
if include_content:
|
| 245 |
-
status_updates.append(f"Including file content (Max size: {max_content_kb} KB)...")
|
| 246 |
-
yield "\n".join(status_updates), "", None, progress # Обновляем статус
|
| 247 |
-
|
| 248 |
-
# Передаем объект progress в функцию генерации
|
| 249 |
-
output_md = generate_markdown_from_path(
|
| 250 |
-
repo_path,
|
| 251 |
-
include_content,
|
| 252 |
-
max_content_kb,
|
| 253 |
-
ignore_patterns if ignore_patterns else DEFAULT_IGNORE_PATTERNS,
|
| 254 |
-
progress=progress # Передаем объект progress
|
| 255 |
)
|
|
|
|
| 256 |
|
| 257 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
|
| 259 |
-
#
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
|
|
|
|
|
|
| 265 |
|
| 266 |
-
yield "\n"
|
| 267 |
|
| 268 |
except ValueError as ve:
|
| 269 |
-
|
| 270 |
-
yield "
|
| 271 |
except subprocess.CalledProcessError as cpe:
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
status_updates.append(f"Stdout: {cpe.stdout}")
|
| 276 |
-
yield "\n".join(status_updates), "", None, gr.Progress(visible=False)
|
| 277 |
-
except SecurityException as se: # Обработка Zip Slip
|
| 278 |
-
status_updates.append(f"Security Error: {se}")
|
| 279 |
-
yield "\n".join(status_updates), "", None, gr.Progress(visible=False)
|
| 280 |
except Exception as e:
|
| 281 |
-
|
| 282 |
import traceback
|
| 283 |
-
|
| 284 |
-
yield "
|
| 285 |
-
|
| 286 |
finally:
|
| 287 |
-
#
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
# print(f"Cleanup: {temp_dir} - Download file: {download_file}")
|
| 298 |
-
pass # Оставляем очистку Gradio для возвращенного файла
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
# --- Интерфейс Gradio ---
|
| 302 |
-
|
| 303 |
-
with gr.Blocks(title="GitHub Repo to Markdown") as demo:
|
| 304 |
gr.Markdown("# GitHub Repository to Markdown Converter")
|
| 305 |
-
gr.Markdown("Convert a GitHub repository (
|
| 306 |
|
| 307 |
with gr.Row():
|
| 308 |
with gr.Column(scale=1):
|
| 309 |
-
|
| 310 |
-
|
|
|
|
| 311 |
)
|
| 312 |
|
| 313 |
-
#
|
| 314 |
-
with
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
gr.Markdown("### Options")
|
| 333 |
-
include_content = gr.Checkbox(label="Include File Content in Output", value=False)
|
| 334 |
-
max_content_kb = gr.Number(
|
| 335 |
-
label="Max File Size for Content (KB)",
|
| 336 |
-
value=100,
|
| 337 |
-
minimum=0,
|
| 338 |
-
step=10,
|
| 339 |
-
info="Files larger than this won't have content included. 0 disables all content.",
|
| 340 |
-
interactive=True # По умолчанию будет активен
|
| 341 |
-
)
|
| 342 |
-
ignore_patterns = gr.Textbox(
|
| 343 |
-
label="Ignore Patterns (comma-separated, gitignore style)",
|
| 344 |
-
placeholder=".git/, node_modules/, *.log",
|
| 345 |
-
value=DEFAULT_IGNORE_PATTERNS,
|
| 346 |
-
lines=2,
|
| 347 |
-
info="Uses gitignore syntax. Add / for directories. Defaults provided."
|
| 348 |
)
|
| 349 |
|
| 350 |
-
# --- Кнопка запуска ---
|
| 351 |
generate_button = gr.Button("Generate Markdown", variant="primary")
|
| 352 |
|
| 353 |
-
# --- Логика видимости инпутов ---
|
| 354 |
-
def switch_input_type(choice):
|
| 355 |
-
return {
|
| 356 |
-
url_inputs: gr.update(visible=choice == "URL"),
|
| 357 |
-
zip_inputs: gr.update(visible=choice == "Upload ZIP"),
|
| 358 |
-
}
|
| 359 |
-
input_type.change(switch_input_type, inputs=input_type, outputs=[url_inputs, zip_inputs])
|
| 360 |
-
|
| 361 |
-
# --- Логика активности поля Max Size ---
|
| 362 |
-
def toggle_max_size(include):
|
| 363 |
-
return gr.update(interactive=include) # Поле активно, только если контент включен
|
| 364 |
-
# include_content.change(toggle_max_size, inputs=include_content, outputs=max_content_kb)
|
| 365 |
-
# Заметка: Убрал авто-деактивацию, т.к. 0 КБ - валидный способ отключить контент.
|
| 366 |
-
# Пусть пользователь сам решает, даже если галка снята.
|
| 367 |
-
|
| 368 |
-
|
| 369 |
with gr.Column(scale=2):
|
| 370 |
-
gr.Markdown("
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
|
| 381 |
-
# --- Привязка кнопки к функции ---
|
| 382 |
generate_button.click(
|
| 383 |
-
|
| 384 |
inputs=[
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
branch_tag,
|
| 388 |
-
zip_upload,
|
| 389 |
-
include_content,
|
| 390 |
-
max_content_kb,
|
| 391 |
-
ignore_patterns,
|
| 392 |
],
|
| 393 |
-
outputs=[
|
|
|
|
| 394 |
)
|
| 395 |
|
| 396 |
-
#
|
| 397 |
if __name__ == "__main__":
|
| 398 |
-
demo.launch()
|
|
|
|
| 3 |
import subprocess
|
| 4 |
import tempfile
|
| 5 |
import zipfile
|
| 6 |
+
import pathlib
|
| 7 |
import shutil
|
|
|
|
|
|
|
| 8 |
from pathspec import PathSpec
|
| 9 |
from pathspec.patterns import GitWildMatchPattern
|
| 10 |
|
| 11 |
+
# --- Configuration ---
|
| 12 |
+
DEFAULT_IGNORE_PATTERNS = """
|
| 13 |
+
# Default Ignore Patterns (Gitignore Syntax)
|
| 14 |
+
/.git/
|
| 15 |
+
/.hg/
|
| 16 |
+
/.svn/
|
| 17 |
+
/.vscode/
|
| 18 |
+
/.idea/
|
| 19 |
+
/node_modules/
|
| 20 |
+
/vendor/
|
| 21 |
+
/build/
|
| 22 |
+
/dist/
|
| 23 |
+
/target/
|
| 24 |
+
*.pyc
|
| 25 |
+
*.log
|
| 26 |
+
*.swp
|
| 27 |
+
*~
|
| 28 |
+
__pycache__/
|
| 29 |
+
.DS_Store
|
| 30 |
+
"""
|
| 31 |
+
MAX_OUTPUT_LINES = 10000 # Limit potential output size in display
|
| 32 |
+
INDENT_CHAR = " " # 4 spaces for indentation
|
| 33 |
+
FOLDER_ICON = "📁"
|
| 34 |
+
FILE_ICON = "📄"
|
| 35 |
+
|
| 36 |
+
# --- Core Logic ---
|
| 37 |
+
|
| 38 |
+
def get_repo_path(source_type, repo_url, branch_tag, zip_file_obj, progress=gr.Progress()):
|
| 39 |
+
"""Clones or extracts the repository, returning the local path."""
|
| 40 |
+
temp_dir = tempfile.mkdtemp()
|
| 41 |
+
repo_path = None
|
| 42 |
|
|
|
|
|
|
|
| 43 |
try:
|
| 44 |
+
if source_type == "URL":
|
| 45 |
+
if not repo_url:
|
| 46 |
+
raise ValueError("GitHub Repository URL is required.")
|
| 47 |
+
progress(0.1, desc="Cloning repository...")
|
| 48 |
+
git_command = ["git", "clone", "--depth", "1"] # Shallow clone for speed
|
| 49 |
+
if branch_tag:
|
| 50 |
+
git_command.extend(["--branch", branch_tag])
|
| 51 |
+
git_command.extend([repo_url, temp_dir])
|
| 52 |
|
| 53 |
+
print(f"Running command: {' '.join(git_command)}") # For debugging
|
| 54 |
+
result = subprocess.run(git_command, capture_output=True, text=True, check=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
if result.returncode != 0:
|
| 57 |
+
# Attempt clone without branch if specific one failed (might be default branch)
|
| 58 |
+
if branch_tag:
|
| 59 |
+
progress(0.2, desc=f"Branch '{branch_tag}' not found or clone failed, trying default branch...")
|
| 60 |
+
git_command = ["git", "clone", "--depth", "1", repo_url, temp_dir]
|
| 61 |
+
print(f"Running command: {' '.join(git_command)}") # For debugging
|
| 62 |
+
result = subprocess.run(git_command, capture_output=True, text=True, check=False)
|
| 63 |
+
|
| 64 |
+
if result.returncode != 0:
|
| 65 |
+
error_message = f"Git clone failed:\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}"
|
| 66 |
+
print(error_message) # Log detailed error
|
| 67 |
+
# Try to extract a user-friendly message
|
| 68 |
+
if "Authentication failed" in result.stderr:
|
| 69 |
+
raise ValueError("Authentication failed. Private repositories require different handling (e.g., tokens) which is not supported here.")
|
| 70 |
+
elif "not found" in result.stderr:
|
| 71 |
+
raise ValueError(f"Repository or branch '{branch_tag or 'default'}' not found at URL: {repo_url}")
|
| 72 |
+
else:
|
| 73 |
+
raise ValueError(f"Git clone failed. Check URL and branch/tag. Error: {result.stderr.splitlines()[-1] if result.stderr else 'Unknown error'}")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
repo_path = pathlib.Path(temp_dir)
|
| 77 |
+
progress(0.5, desc="Repository cloned.")
|
| 78 |
+
print(f"Cloned repo to: {repo_path}") # Debugging
|
| 79 |
+
|
| 80 |
+
elif source_type == "Upload ZIP":
|
| 81 |
+
if zip_file_obj is None:
|
| 82 |
+
raise ValueError("ZIP file upload is required.")
|
| 83 |
+
progress(0.1, desc="Extracting ZIP file...")
|
| 84 |
+
zip_path = zip_file_obj.name # Gradio provides a temp file path
|
| 85 |
+
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
| 86 |
+
# Check for common zip structure (single top-level dir)
|
| 87 |
+
top_level_dirs = list(set(p.split('/')[0] for p in zip_ref.namelist() if '/' in p))
|
| 88 |
+
extract_target = temp_dir
|
| 89 |
+
potential_repo_root = temp_dir
|
| 90 |
+
if len(top_level_dirs) == 1:
|
| 91 |
+
# If zip contains repo-main/file structure, extract *into* temp_dir
|
| 92 |
+
# The actual repo content will be inside temp_dir/repo-main/
|
| 93 |
+
zip_ref.extractall(extract_target)
|
| 94 |
+
potential_repo_root = os.path.join(temp_dir, top_level_dirs[0])
|
| 95 |
+
print(f"ZIP has single top-level dir: {top_level_dirs[0]}. Potential root: {potential_repo_root}")
|
| 96 |
+
else:
|
| 97 |
+
# Otherwise, extract directly into temp_dir
|
| 98 |
+
zip_ref.extractall(extract_target)
|
| 99 |
+
print(f"ZIP structure seems flat or multi-root. Using extract target as root: {extract_target}")
|
| 100 |
+
|
| 101 |
+
# Basic check if potential_repo_root looks like a valid directory
|
| 102 |
+
if os.path.isdir(potential_repo_root):
|
| 103 |
+
repo_path = pathlib.Path(potential_repo_root)
|
| 104 |
+
else:
|
| 105 |
+
# Fallback if single dir logic failed or wasn't applicable
|
| 106 |
+
repo_path = pathlib.Path(extract_target)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
progress(0.5, desc="ZIP extracted.")
|
| 110 |
+
print(f"Extracted ZIP to: {repo_path}") # Debugging
|
| 111 |
+
else:
|
| 112 |
+
raise ValueError("Invalid source type selected.")
|
| 113 |
|
| 114 |
+
if not repo_path or not repo_path.is_dir():
|
| 115 |
+
raise ValueError(f"Could not determine repository root directory within: {temp_dir}")
|
| 116 |
+
|
| 117 |
+
return repo_path, temp_dir # Return both the repo content path and the parent temp dir for cleanup
|
| 118 |
+
|
| 119 |
+
except Exception as e:
|
| 120 |
+
# Clean up the temporary directory on error before re-raising
|
| 121 |
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 122 |
+
print(f"Error in get_repo_path: {e}") # Log error
|
| 123 |
+
raise e # Re-raise the exception to be caught by the main function
|
| 124 |
+
|
| 125 |
+
def generate_markdown_structure(
|
| 126 |
+
repo_root_path: pathlib.Path,
|
| 127 |
+
include_content: bool,
|
| 128 |
+
max_size_kb: int,
|
| 129 |
+
ignore_patterns_str: str,
|
| 130 |
+
progress=gr.Progress()
|
| 131 |
):
|
| 132 |
+
"""Generates the Markdown string from the repository structure."""
|
| 133 |
+
repo_root_path = pathlib.Path(repo_root_path) # Ensure it's a Path object
|
|
|
|
|
|
|
| 134 |
markdown_lines = []
|
| 135 |
+
max_file_size_bytes = max_size_kb * 1024 if max_size_kb > 0 else 0
|
| 136 |
+
|
| 137 |
+
# --- Prepare ignore patterns ---
|
| 138 |
+
# Combine default and user patterns
|
| 139 |
+
full_ignore_patterns = DEFAULT_IGNORE_PATTERNS.strip() + "\n" + ignore_patterns_str.strip()
|
| 140 |
+
# Filter out empty lines
|
| 141 |
+
patterns = [line for line in full_ignore_patterns.splitlines() if line.strip() and not line.strip().startswith('#')]
|
| 142 |
+
spec = PathSpec.from_lines(GitWildMatchPattern, patterns)
|
| 143 |
+
print(f"Using ignore patterns: {patterns}") # Debugging
|
| 144 |
+
|
| 145 |
+
# --- Add header ---
|
| 146 |
+
repo_name = repo_root_path.name
|
| 147 |
+
markdown_lines.append(f"# {FOLDER_ICON} {repo_name}")
|
| 148 |
+
markdown_lines.append("")
|
| 149 |
+
|
| 150 |
+
# --- Walk through the directory ---
|
| 151 |
+
progress(0.6, desc="Scanning repository structure...")
|
| 152 |
+
files_processed = 0
|
| 153 |
+
total_items_estimate = sum(1 for _ in repo_root_path.rglob('*')) # Rough estimate for progress
|
| 154 |
+
|
| 155 |
+
items_scanned = 0
|
| 156 |
+
for item_path in sorted(repo_root_path.rglob('*')):
|
| 157 |
+
items_scanned += 1
|
| 158 |
+
if items_scanned % 50 == 0: # Update progress periodically
|
| 159 |
+
progress(0.6 + (0.3 * (items_scanned / max(1, total_items_estimate))), desc=f"Scanning: {item_path.name}")
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
relative_path = item_path.relative_to(repo_root_path)
|
| 163 |
+
|
| 164 |
+
# Check if the path itself or any of its parent directories should be ignored
|
| 165 |
+
# Need to check components because pathspec matches relative paths
|
| 166 |
+
components = relative_path.parts
|
| 167 |
+
ignored = False
|
| 168 |
+
# Check root path first for patterns like '/node_modules/'
|
| 169 |
+
if spec.match_file(str(relative_path)):
|
| 170 |
+
ignored = True
|
| 171 |
+
# Check parent directories if a pattern like 'node_modules/' should match anywhere
|
| 172 |
+
current_check_path = ""
|
| 173 |
+
for part in components:
|
| 174 |
+
current_check_path = os.path.join(current_check_path, part)
|
| 175 |
+
if spec.match_file(current_check_path):
|
| 176 |
+
ignored = True
|
| 177 |
+
break
|
| 178 |
+
|
| 179 |
+
if ignored:
|
| 180 |
+
# If it's a directory, prevent os.walk from descending further if we were using it
|
| 181 |
+
# With rglob, we just skip the current item
|
| 182 |
+
print(f"Ignoring: {relative_path}") # Debugging
|
| 183 |
+
continue
|
| 184 |
+
|
| 185 |
+
# Calculate depth and indentation
|
| 186 |
+
depth = len(relative_path.parts) -1 # 0-based depth relative to root content
|
| 187 |
+
indent = INDENT_CHAR * depth
|
| 188 |
+
|
| 189 |
+
# Add entry to Markdown
|
| 190 |
+
if item_path.is_dir():
|
| 191 |
+
markdown_lines.append(f"{indent}{FOLDER_ICON} **{item_path.name}/**")
|
| 192 |
+
elif item_path.is_file():
|
| 193 |
+
markdown_lines.append(f"{indent}{FILE_ICON} {item_path.name}")
|
| 194 |
+
files_processed += 1
|
| 195 |
+
|
| 196 |
+
# Include file content if requested and within limits
|
| 197 |
+
if include_content and max_file_size_bytes > 0:
|
| 198 |
+
try:
|
| 199 |
+
file_size = item_path.stat().st_size
|
| 200 |
+
if file_size == 0:
|
| 201 |
+
markdown_lines.append(f"{indent}{INDENT_CHAR}```")
|
| 202 |
+
markdown_lines.append(f"{indent}{INDENT_CHAR}[Empty File]")
|
| 203 |
+
markdown_lines.append(f"{indent}{INDENT_CHAR}```")
|
| 204 |
+
elif file_size <= max_file_size_bytes:
|
| 205 |
+
try:
|
| 206 |
+
content = item_path.read_text(encoding='utf-8')
|
| 207 |
+
lang = item_path.suffix.lstrip('.')
|
| 208 |
+
# Simple lang detection, can be expanded
|
| 209 |
+
if not lang: lang = "text"
|
| 210 |
+
|
| 211 |
+
markdown_lines.append(f"{indent}{INDENT_CHAR}```{lang}")
|
| 212 |
+
# Indent content lines
|
| 213 |
+
content_lines = content.splitlines()
|
| 214 |
+
# Limit output lines displayed in Markdown preview if necessary
|
| 215 |
+
# Note: The downloaded file will have full content
|
| 216 |
+
display_lines = content_lines[:MAX_OUTPUT_LINES]
|
| 217 |
+
for line in display_lines:
|
| 218 |
+
markdown_lines.append(f"{indent}{INDENT_CHAR}{line}")
|
| 219 |
+
if len(content_lines) > MAX_OUTPUT_LINES:
|
| 220 |
+
markdown_lines.append(f"{indent}{INDENT_CHAR}[... content truncated in preview ...]")
|
| 221 |
+
markdown_lines.append(f"{indent}{INDENT_CHAR}```")
|
| 222 |
+
except UnicodeDecodeError:
|
| 223 |
+
markdown_lines.append(f"{indent}{INDENT_CHAR}[Content omitted: Not a UTF-8 text file (Size: {file_size} bytes)]")
|
| 224 |
+
except Exception as read_err:
|
| 225 |
+
markdown_lines.append(f"{indent}{INDENT_CHAR}[Content omitted: Error reading file - {read_err}]")
|
| 226 |
+
else:
|
| 227 |
+
markdown_lines.append(f"{indent}{INDENT_CHAR}[Content omitted: File size ({file_size} bytes) exceeds limit ({max_file_size_bytes} bytes)]")
|
| 228 |
+
except OSError as stat_err:
|
| 229 |
+
markdown_lines.append(f"{indent}{INDENT_CHAR}[Content omitted: Error accessing file - {stat_err}]")
|
| 230 |
+
|
| 231 |
+
elif include_content and max_file_size_bytes == 0: # Content included, but 0 size limit means no content shown
|
| 232 |
+
markdown_lines.append(f"{indent}{INDENT_CHAR}[Content omitted: Max file size set to 0 KB]")
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
# Add a newline for separation, helps readability
|
| 236 |
+
markdown_lines.append("")
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
progress(0.95, desc="Formatting output...")
|
| 240 |
+
final_markdown = "\n".join(markdown_lines)
|
| 241 |
+
print(f"Processed {files_processed} files.") # Debugging
|
| 242 |
+
return final_markdown
|
| 243 |
+
|
| 244 |
+
# --- Gradio Interface ---
|
| 245 |
+
|
| 246 |
+
def process_repo(
|
| 247 |
+
source_type, repo_url, branch_tag, zip_file_obj,
|
| 248 |
+
include_content, max_size_kb, ignore_patterns,
|
| 249 |
+
progress=gr.Progress(track_tqdm=True)
|
| 250 |
):
|
| 251 |
+
"""Main function called by Gradio button."""
|
| 252 |
+
status = ""
|
| 253 |
+
output_markdown = ""
|
| 254 |
+
output_file_path = None
|
| 255 |
+
repo_root_path = None
|
| 256 |
+
temp_dir_to_clean = None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
try:
|
| 259 |
+
progress(0, desc="Starting...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
+
# 1. Get Repository Path
|
| 262 |
+
yield "Fetching repository...", "", None # Update status, clear outputs
|
| 263 |
+
repo_root_path, temp_dir_to_clean = get_repo_path(
|
| 264 |
+
source_type, repo_url, branch_tag, zip_file_obj, progress=progress
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
)
|
| 266 |
+
yield f"Repository ready at: {repo_root_path}", "", None
|
| 267 |
|
| 268 |
+
# 2. Generate Markdown
|
| 269 |
+
yield "Generating Markdown structure...", "", None
|
| 270 |
+
markdown_content = generate_markdown_structure(
|
| 271 |
+
repo_root_path, include_content, int(max_size_kb), ignore_patterns, progress=progress
|
| 272 |
+
)
|
| 273 |
|
| 274 |
+
# 3. Prepare Output File
|
| 275 |
+
yield "Saving Markdown to file...", markdown_content[:3000] + ("\n\n[... Output truncated in preview ...]" if len(markdown_content)>3000 else ""), None # Show preview
|
| 276 |
+
output_filename = f"{repo_root_path.name}_structure.md"
|
| 277 |
+
# Save the file in a place Gradio can access (it manages temp files)
|
| 278 |
+
# Create a temporary file for Gradio output
|
| 279 |
+
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".md", encoding='utf-8') as temp_file:
|
| 280 |
+
temp_file.write(markdown_content)
|
| 281 |
+
output_file_path = temp_file.name # Gradio needs the path to this file
|
| 282 |
|
| 283 |
+
yield f"Done. Output file '{output_filename}' ready for download.", markdown_content[:3000] + ("\n\n[... Output truncated in preview ...]" if len(markdown_content)>3000 else ""), gr.File.update(value=output_file_path, visible=True, label=f"Download {output_filename}") # Make file downloadable
|
| 284 |
|
| 285 |
except ValueError as ve:
|
| 286 |
+
print(f"Value Error: {ve}") # Log error
|
| 287 |
+
yield f"Error: {ve}", "", gr.File.update(value=None, visible=False)
|
| 288 |
except subprocess.CalledProcessError as cpe:
|
| 289 |
+
error_detail = cpe.stderr or cpe.stdout or "Unknown git error"
|
| 290 |
+
print(f"Git Error: {error_detail}") # Log error
|
| 291 |
+
yield f"Git command failed: {error_detail}", "", gr.File.update(value=None, visible=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
except Exception as e:
|
| 293 |
+
print(f"Unexpected Error: {e}") # Log error
|
| 294 |
import traceback
|
| 295 |
+
traceback.print_exc() # Print full traceback to logs
|
| 296 |
+
yield f"An unexpected error occurred: {e}", "", gr.File.update(value=None, visible=False)
|
|
|
|
| 297 |
finally:
|
| 298 |
+
# 4. Cleanup
|
| 299 |
+
if temp_dir_to_clean:
|
| 300 |
+
print(f"Cleaning up temporary directory: {temp_dir_to_clean}")
|
| 301 |
+
shutil.rmtree(temp_dir_to_clean, ignore_errors=True)
|
| 302 |
+
print("Cleanup complete.")
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
# --- Build Gradio UI ---
|
| 306 |
+
|
| 307 |
+
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="cyan")) as demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
gr.Markdown("# GitHub Repository to Markdown Converter")
|
| 309 |
+
gr.Markdown("Convert a GitHub repository's structure (and optionally content) into a single Markdown file.")
|
| 310 |
|
| 311 |
with gr.Row():
|
| 312 |
with gr.Column(scale=1):
|
| 313 |
+
gr.Markdown("## Input Source")
|
| 314 |
+
input_source = gr.Radio(
|
| 315 |
+
["URL", "Upload ZIP"], label="Select Source Type", value="URL"
|
| 316 |
)
|
| 317 |
|
| 318 |
+
url_input_group = gr.Group(visible=True) # Show URL by default
|
| 319 |
+
with url_input_group:
|
| 320 |
+
repo_url_input = gr.Textbox(label="Git Repository URL", placeholder="https://github.com/user/repo.git")
|
| 321 |
+
branch_tag_input = gr.Textbox(label="Branch / Tag (Optional)", placeholder="main")
|
| 322 |
+
|
| 323 |
+
zip_input_group = gr.Group(visible=False) # Hide ZIP by default
|
| 324 |
+
with zip_input_group:
|
| 325 |
+
zip_file_input = gr.File(label="Upload Repository ZIP", file_types=[".zip"])
|
| 326 |
+
|
| 327 |
+
# --- Configuration Options ---
|
| 328 |
+
gr.Markdown("## Configuration")
|
| 329 |
+
include_content_checkbox = gr.Checkbox(label="Include File Content in Output", value=False)
|
| 330 |
+
max_size_input = gr.Number(label="Max File Size for Content (KB)", value=100, minimum=0, step=10,
|
| 331 |
+
info="Files larger than this won't have content included. Set to 0 to disable content inclusion entirely, even if checked above.")
|
| 332 |
+
ignore_patterns_input = gr.Textbox(
|
| 333 |
+
label="Ignore Patterns (comma-separated or newline, gitignore style)",
|
| 334 |
+
info="Uses .gitignore syntax. Add / for directories. Default patterns provided.",
|
| 335 |
+
lines=5,
|
| 336 |
+
value=DEFAULT_IGNORE_PATTERNS.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
)
|
| 338 |
|
|
|
|
| 339 |
generate_button = gr.Button("Generate Markdown", variant="primary")
|
| 340 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
with gr.Column(scale=2):
|
| 342 |
+
gr.Markdown("## Status & Output")
|
| 343 |
+
status_output = gr.Textbox(label="Current Status", interactive=False, lines=2)
|
| 344 |
+
# Use a Textbox for preview initially, as Markdown rendering can be slow/heavy
|
| 345 |
+
markdown_preview_output = gr.Textbox(label="Markdown Preview (Truncated)", interactive=False, lines=20)
|
| 346 |
+
# Use gr.File for the final download link
|
| 347 |
+
download_output = gr.File(label="Download Markdown File", visible=False, interactive=False)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
# --- Event Handlers ---
|
| 351 |
+
def toggle_input_visibility(choice):
|
| 352 |
+
if choice == "URL":
|
| 353 |
+
return gr.update(visible=True), gr.update(visible=False)
|
| 354 |
+
else: # ZIP
|
| 355 |
+
return gr.update(visible=False), gr.update(visible=True)
|
| 356 |
+
|
| 357 |
+
input_source.change(
|
| 358 |
+
fn=toggle_input_visibility,
|
| 359 |
+
inputs=input_source,
|
| 360 |
+
outputs=[url_input_group, zip_input_group],
|
| 361 |
+
)
|
| 362 |
|
|
|
|
| 363 |
generate_button.click(
|
| 364 |
+
fn=process_repo,
|
| 365 |
inputs=[
|
| 366 |
+
input_source, repo_url_input, branch_tag_input, zip_file_input,
|
| 367 |
+
include_content_checkbox, max_size_input, ignore_patterns_input
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
],
|
| 369 |
+
outputs=[status_output, markdown_preview_output, download_output],
|
| 370 |
+
# api_name="generate_markdown" # Optional: for API access
|
| 371 |
)
|
| 372 |
|
| 373 |
+
# --- Launch the App ---
|
| 374 |
if __name__ == "__main__":
|
| 375 |
+
demo.queue().launch(debug=True) # Enable queue for handling multiple users, debug=True for local testing
|