Skip to content

Instantly share code, notes, and snippets.

@we684123
Created September 21, 2024 09:34
Show Gist options
  • Save we684123/32bdf77e2fa7b032a8f07c21ba9fc91e to your computer and use it in GitHub Desktop.
Save we684123/32bdf77e2fa7b032a8f07c21ba9fc91e to your computer and use it in GitHub Desktop.
集合 code 到一個檔案
import fnmatch
from pathlib import Path
def read_gitignore(gitignore_path):
ignore_patterns = []
if gitignore_path.exists():
with gitignore_path.open(encoding="utf-8") as f:
for line_text in f:
line = line_text.strip()
if line and not line.startswith("#"):
ignore_patterns.append(line)
return ignore_patterns
def is_ignored(path, ignore_patterns):
for pattern in ignore_patterns:
if pattern.endswith("/"):
# 忽略資料夾
if path.match(pattern[:-1] + "*"):
return True
elif path.name == pattern or fnmatch.fnmatch(str(path), pattern):
return True
return False
def scan_and_write_to_file(folder_path, output_file, gitignore_path):
ignore_patterns = read_gitignore(gitignore_path)
with output_file.open("a", encoding="utf-8") as f_out:
for file_path in folder_path.rglob("*"):
relative_path = file_path.relative_to(folder_path)
if is_ignored(relative_path, ignore_patterns):
continue
if file_path.is_file():
try:
with file_path.open(encoding="utf-8") as f_in:
content = f_in.read()
f_out.write(f"```.{folder_path}/{relative_path}\n")
f_out.write(f"{content}\n")
f_out.write("```\n\n")
except Exception as e:
print(f"無法讀取檔案: {file_path},錯誤訊息: {e}")
# 使用範例
# folder_list = ["app"] # 指定要掃描的資料夾
folder_list = ["app", "migrations"] # 指定要掃描的資料夾
output_file = Path("統整.md") # 指定輸出的統整檔案名稱
gitignore_path = Path(".gitignore") # 指定 .gitignore 檔案的位置
for folder in folder_list:
folder_path = Path(folder)
scan_and_write_to_file(folder_path, output_file, gitignore_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment