VOIDER commited on
Commit
3c5f9e7
·
verified ·
1 Parent(s): 29606bb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +327 -350
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 = ".git/, __pycache__/, *.pyc, *.pyo, *.o, *.so, *.a, *.dll, *.dylib, node_modules/, dist/, build/, .env, .venv/, venv/, *.log, *tmp*, *temp*"
14
-
15
- # --- Вспомогательные функции ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- def get_repo_name_from_url(url):
18
- """Извлекает имя репозитория из URL."""
19
  try:
20
- return url.split('/')[-1].replace('.git', '')
21
- except Exception:
22
- return "repository"
 
 
 
 
 
23
 
24
- def is_binary(filepath):
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
- def generate_markdown_from_path(
53
- repo_path,
54
- include_content,
55
- max_content_kb,
56
- ignore_patterns_str,
57
- progress=gr.Progress(track_ τότε=True)
 
 
 
 
 
 
 
 
 
 
 
58
  ):
59
- """
60
- Генерирует Markdown-представление структуры и содержимого каталога.
61
- """
62
- repo_path_obj = Path(repo_path).resolve()
63
  markdown_lines = []
64
- max_content_bytes = max_content_kb * 1024 if include_content and max_content_kb > 0 else 0
65
-
66
- progress(0, desc="Parsing ignore patterns...")
67
- spec = create_gitignore_spec(ignore_patterns_str, repo_path_obj)
68
-
69
- # Используем Path() для упрощения работы с путями
70
- root_path = Path(repo_path).resolve()
71
- num_files_processed = 0
72
- total_items = sum(1 for _ in root_path.rglob('*')) # Приблизительная оценка для прогресс-бара
73
-
74
- markdown_lines.append(f"# Repository Structure: {root_path.name}\n")
75
-
76
- progress(0.1, desc="Walking directory tree...")
77
-
78
- items_to_process = sorted(list(root_path.rglob('*')), key=lambda p: str(p))
79
- processed_count = 0
80
-
81
- # Рекурсивная функция для обхода и генерации Markdown
82
- def process_directory(current_path, level=0):
83
- nonlocal processed_count
84
- indent = ' ' * level
85
- # Сначала обрабатываем каталоги, затем файлы
86
- entries = sorted(list(current_path.iterdir()), key=lambda p: (p.is_file(), p.name))
87
-
88
- for entry in entries:
89
- processed_count += 1
90
- relative_path_for_match = entry.relative_to(root_path)
91
-
92
- # --- Игнорирование ---
93
- # pathspec ожидает строки, добавляем '/' для каталогов для правильного соответствия
94
- match_path_str = str(relative_path_for_match)
95
- if entry.is_dir():
96
- match_path_str += '/'
97
-
98
- is_ignored = spec.match_file(match_path_str)
99
- # print(f"Checking '{match_path_str}': ignored={is_ignored}") # Для отладки
100
-
101
- if is_ignored:
102
- # print(f"Ignoring: {entry}")
103
- # Если директория игнорируется, пропускаем всё её содержимое
104
- if entry.is_dir():
105
- # Нужно посчитать все элементы внутри для прогресса
106
- try:
107
- ignored_subtree_count = sum(1 for _ in entry.rglob('*'))
108
- processed_count += ignored_subtree_count
109
- except Exception:
110
- pass # Игнорируем ошибки доступа и т.д.
111
- continue # Пропускаем этот элемент
112
-
113
- # Обновляем прогресс
114
- progress(min(0.1 + 0.8 * (processed_count / total_items), 0.9) if total_items > 0 else 0.5,
115
- desc=f"Processing: {relative_path_for_match}")
116
-
117
- # --- Генерация Markdown ---
118
- if entry.is_dir():
119
- markdown_lines.append(f"{indent}- **{entry.name}/**")
120
- process_directory(entry, level + 1) # Рекурсивный вызов
121
- elif entry.is_file():
122
- markdown_lines.append(f"{indent}- {entry.name}")
123
- if include_content:
124
- try:
125
- file_size = entry.stat().st_size
126
- if max_content_bytes == 0: # 0 означает без контента
127
- continue
128
- if max_content_bytes > 0 and file_size > max_content_bytes:
129
- markdown_lines.append(f"{indent} `[Content omitted: File size ({file_size / 1024:.2f} KB) > limit ({max_content_kb} KB)]`")
130
- elif file_size == 0:
131
- markdown_lines.append(f"{indent} `[File is empty]`")
132
- elif is_binary(entry):
133
- markdown_lines.append(f"{indent} `[Content omitted: Binary file detected]`")
134
- else:
135
- try:
136
- # Пытаемся читать как UTF-8, затем как Latin-1 если не вышло
137
- file_content = entry.read_text(encoding='utf-8')
138
- except UnicodeDecodeError:
139
- try:
140
- file_content = entry.read_text(encoding='latin-1')
141
- except Exception as read_err:
142
- markdown_lines.append(f"{indent} `[Error reading file: {read_err}]`")
143
- continue # Пропускаем добавление блока кода при ошибке
144
-
145
- # Определяем язык для подсветки синтаксиса (опционально)
146
- lang = entry.suffix.lstrip('.')
147
- markdown_lines.append(f"{indent} ```{lang}\n{file_content}\n{indent} ```")
148
-
149
- except OSError as e:
150
- markdown_lines.append(f"{indent} `[Error accessing file: {e}]`")
151
- except Exception as e:
152
- markdown_lines.append(f"{indent} `[Unexpected error processing file: {e}]`")
153
-
154
- # Запускаем обработку с корневого каталога
155
- process_directory(root_path)
156
-
157
- progress(1, desc="Markdown generated!")
158
- return "\n".join(markdown_lines)
159
-
160
-
161
- # --- Основная функция Gradio ---
162
-
163
- def process_repository(
164
- input_type,
165
- repo_url,
166
- branch_tag,
167
- zip_upload,
168
- include_content,
169
- max_content_kb,
170
- ignore_patterns,
171
- progress=gr.Progress(track_progress=True)
 
 
 
 
 
 
 
172
  ):
173
- """
174
- Главная функция, вызываемая Gradio. Обрабатывает URL или ZIP.
175
- """
176
- status_updates = []
177
- output_md = ""
178
- download_file = None
179
-
180
- temp_dir = tempfile.mkdtemp()
181
- repo_path = ""
182
- repo_name = "repository"
183
 
184
  try:
185
- if input_type == "URL":
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
- if result.returncode != 0:
206
- raise subprocess.CalledProcessError(result.returncode, git_command, output=result.stdout, stderr=result.stderr)
207
-
208
- status_updates.append("Cloning successful.")
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
- status_updates.append("Markdown generation complete.")
 
 
 
 
258
 
259
- # --- Подготовка файла для скачивания ---
260
- output_filename = f"{repo_name}_structure.md"
261
- output_filepath = os.path.join(temp_dir, output_filename)
262
- with open(output_filepath, "w", encoding="utf-8") as f:
263
- f.write(output_md)
264
- download_file = output_filepath # Gradio поймет это как путь к файлу для скачивания
 
 
265
 
266
- yield "\n".join(status_updates), output_md, download_file, progress
267
 
268
  except ValueError as ve:
269
- status_updates.append(f"Input Error: {ve}")
270
- yield "\n".join(status_updates), "", None, gr.Progress(visible=False) # Скрыть прогресс при ошибке
271
  except subprocess.CalledProcessError as cpe:
272
- status_updates.append(f"Git Error: Failed to clone repository.")
273
- status_updates.append(f"Command: {' '.join(cpe.cmd)}")
274
- status_updates.append(f"Stderr: {cpe.stderr}")
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
- status_updates.append(f"An unexpected error occurred: {type(e).__name__}: {e}")
282
  import traceback
283
- status_updates.append(f"Traceback:\n{traceback.format_exc()}") # Добавим traceback для отладки
284
- yield "\n".join(status_updates), "", None, gr.Progress(visible=False) # Скрыть прогресс при ошибке
285
-
286
  finally:
287
- # --- Очистка ---
288
- # Не удаляем temp_dir сразу, если download_file указывает на файл внутри него.
289
- # Gradio сам управляет временными файлами, которые он возвращает.
290
- # Но если мы создали временный каталог для клонирования/извлечения,
291
- # который *не* содержит возвращаемый файл напрямую, его нужно удалить.
292
- # В данном случае download_file *внутри* temp_dir, Gradio должен справиться.
293
- # Для надежности можно скопировать файл в другое временное место,
294
- # а потом удалить temp_dir. Но пока оставим так, Gradio обычно чистит за собой.
295
- # print(f"Temp directory {temp_dir} contents:")
296
- # for item in Path(temp_dir).rglob('*'): print(f"- {item}")
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 (via URL or ZIP) into a single Markdown file representing its structure and optionally content.")
306
 
307
  with gr.Row():
308
  with gr.Column(scale=1):
309
- input_type = gr.Radio(
310
- ["URL", "Upload ZIP"], label="Input Source", value="URL"
 
311
  )
312
 
313
- # --- URL Inputs ---
314
- with gr.Group(visible=True) as url_inputs:
315
- repo_url = gr.Textbox(
316
- label="Git Repository URL",
317
- placeholder="https://github.com/username/repository.git",
318
- lines=1,
319
- )
320
- branch_tag = gr.Textbox(
321
- label="Branch / Tag (Optional)",
322
- placeholder="main (or specific branch/tag)",
323
- lines=1,
324
- )
325
-
326
- # --- ZIP Upload Input ---
327
- with gr.Group(visible=False) as zip_inputs:
328
- zip_upload = gr.File(label="Upload ZIP File", file_types=[".zip"])
329
-
330
-
331
- # --- Options ---
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("### Status & Output")
371
- status_box = gr.Textbox(label="Current Status", lines=5, interactive=False)
372
- output_markdown = gr.Textbox(
373
- label="Generated Markdown",
374
- lines=20,
375
- interactive=True, # Позволяет копировать текст
376
- show_copy_button=True
377
- )
378
- download_button = gr.File(label="Download Markdown File", interactive=False)
379
-
 
 
 
 
 
 
 
 
 
 
380
 
381
- # --- Привязка кнопки к функции ---
382
  generate_button.click(
383
- process_repository,
384
  inputs=[
385
- input_type,
386
- repo_url,
387
- branch_tag,
388
- zip_upload,
389
- include_content,
390
- max_content_kb,
391
- ignore_patterns,
392
  ],
393
- outputs=[status_box, output_markdown, download_button],
 
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