|
| 1 | +''' |
| 2 | +Author: LetMeFly |
| 3 | +Date: 2024-06-11 21:59:50 |
| 4 | +LastEditors: LetMeFly |
| 5 | +LastEditTime: 2024-06-11 22:21:22 |
| 6 | +''' |
| 7 | +""" |
| 8 | +写一个Python脚本,实现以下功能: |
| 9 | +在一个Git仓库中,将每次commit打包成Zip文件。 |
| 10 | +文件命名格式为对应commit的{日期}{时间}{commitHash}.zip,例如20240622-220603-54a2e7fe41081489e8913436daa7bee5ae878d26.zip |
| 11 | +""" |
| 12 | +import os |
| 13 | +import zipfile |
| 14 | +import git |
| 15 | +from datetime import datetime |
| 16 | +import shutil |
| 17 | + |
| 18 | +def zip_commit(repo_path, commit: git.Commit): |
| 19 | + # 提取 commit 日期和时间 |
| 20 | + print(commit.message) |
| 21 | + commit_datetime = datetime.fromtimestamp(commit.committed_date) |
| 22 | + date_str = commit_datetime.strftime('%Y%m%d') |
| 23 | + time_str = commit_datetime.strftime('%H%M%S') |
| 24 | + |
| 25 | + # 构造 zip 文件名 |
| 26 | + zip_filename = f"archived/{date_str}-{time_str}-{commit.hexsha}.zip" |
| 27 | + |
| 28 | + # 创建一个临时目录来存储这个 commit 的文件 |
| 29 | + temp_dir = f"temp" |
| 30 | + os.makedirs(temp_dir, exist_ok=True) |
| 31 | + |
| 32 | + # 导出 commit 的文件 |
| 33 | + repo.git.checkout(commit) |
| 34 | + for item in repo.tree().traverse(): |
| 35 | + if item.type == 'blob': # 确保这是一个文件而不是一个子目录 |
| 36 | + item_path = os.path.join(repo_path, item.path) |
| 37 | + os.makedirs(os.path.dirname(os.path.join(temp_dir, item.path)), exist_ok=True) |
| 38 | + with open(item_path, 'rb') as fsrc, open(os.path.join(temp_dir, item.path), 'wb') as fdst: |
| 39 | + fdst.write(fsrc.read()) |
| 40 | + |
| 41 | + # 打包成 zip 文件 |
| 42 | + with zipfile.ZipFile(zip_filename, 'w') as zipf: |
| 43 | + for root, _, files in os.walk(temp_dir): |
| 44 | + for file in files: |
| 45 | + zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), temp_dir)) |
| 46 | + |
| 47 | + # 清理临时目录 |
| 48 | + shutil.rmtree(temp_dir) |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + # 指定你的 Git 仓库路径 |
| 52 | + repo_path = 'repo' |
| 53 | + os.makedirs('archived', exist_ok=True) |
| 54 | + |
| 55 | + # 打开仓库 |
| 56 | + repo = git.Repo(repo_path) |
| 57 | + |
| 58 | + # 遍历所有的 commit |
| 59 | + for commit in repo.iter_commits(): |
| 60 | + zip_commit(repo_path, commit) |
| 61 | + |
| 62 | + # 切换回默认分支(例如 'main' 或 'master') |
| 63 | + repo.git.checkout('master') |
0 commit comments