Skip to content

Instantly share code, notes, and snippets.

@jacking75
Created March 3, 2025 04:53
Show Gist options
  • Save jacking75/9adc1883a5ddaf1c17bee4d4f1492d20 to your computer and use it in GitHub Desktop.
Save jacking75/9adc1883a5ddaf1c17bee4d4f1492d20 to your computer and use it in GitHub Desktop.
디렉토리에 있는 파일들을 마크다운 파일로 정리해주는 파이썬 스크립트
import os
def write_code_to_markdown_split(repo_path, output_dir, max_size_mb=10):
"""
저장소 내의 소스 코드를 재귀적으로 읽고,
Markdown 형식으로 10MB 미만의 파일로 분할해서 출력하는 스크립트
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
current_file_size = 0
file_counter = 1
current_md_file = None
def open_new_md_file():
"""
새로운 Markdown 파일을 열고, 그 핸들과 패스를 반환한다.
"""
nonlocal file_counter, current_file_size
file_path = os.path.join(output_dir, f"repository_code_part_{file_counter}.md")
md_file = open(file_path, "w", encoding="utf-8")
md_file.write("# Repository Code Overview\n\n")
md_file.write(f"Source: `{repo_path}`\n\n")
current_file_size = 0
file_counter += 1
return md_file, file_path
# 최초의 Markdown 파일을 연다
current_md_file, current_file_path = open_new_md_file()
def write_file_content(file_path, relative_path):
"""
파일 내용을 Markdown 형식으로 현재의 Markdown 파일에 쓴다
"""
nonlocal current_file_size, current_md_file
header = f"## {relative_path}\n\n"
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
except Exception as e:
content = f"Unable to read file: {e}"
code_block = f"```{os.path.splitext(file_path)[-1][1:]}\n{content}\n```\n\n"
entry_size = len(header.encode("utf-8")) + len(code_block.encode("utf-8"))
# 현재의 Markdown 파일에 추가할 수 없는 경우 새로운 파일을 연다
if current_file_size + entry_size > max_size_mb * 1024 * 1024:
current_md_file.close()
current_md_file, current_file_path = open_new_md_file()
# 현재의 Markdown 파일에 쓴다
current_md_file.write(header)
current_md_file.write(code_block)
current_file_size += entry_size
def process_directory(dir_path, relative_path):
"""
디렉토리 내의 모든 파일을 재귀적으로 처리한다
"""
for item in sorted(os.listdir(dir_path)):
item_path = os.path.join(dir_path, item)
item_relative_path = os.path.join(relative_path, item)
if os.path.isfile(item_path):
write_file_content(item_path, item_relative_path)
elif os.path.isdir(item_path):
process_directory(item_path, item_relative_path)
# 저장소의 처리를 개시
process_directory(repo_path, "")
# 최후의 Markdown 파일을 닫는다
if current_md_file:
current_md_file.close()
# 실행 예
if __name__ == "__main__":
repository_path = "./my_repository" # 저장소 패스를 지정
output_directory = "./output_markdown" # Markdown 파일의 출력처를 지정
max_file_size_mb = 10 # 각 Markdown 파일의 최대 사이즈를 MB 단위로 지정
write_code_to_markdown_split(repository_path, output_directory, max_file_size_mb)
print(f"Markdown files created in: {output_directory}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment