gitRouter.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import os, json,hashlib,re
  2. from fastapi import APIRouter, BackgroundTasks
  3. from base_config import path, avatar_url
  4. from git import Repo, GitCommandError
  5. from pydantic import BaseModel
  6. from models.gitModels import Users
  7. class RequestBody(BaseModel):
  8. uuid: str
  9. repo_url: str
  10. class CommitHash(BaseModel):
  11. uuid: str
  12. repo_url: str
  13. commit_hash: str
  14. def generate_repo_path(uuid, repo_url):
  15. repo_name = repo_url.split("/")[-1].replace(".git", "")
  16. base_path = os.path.join(path, uuid)
  17. return os.path.join(base_path, repo_name), repo_name
  18. def get_repo(uuid, repo_url):
  19. path, _ = generate_repo_path(uuid, repo_url)
  20. if not os.path.exists(path):
  21. return 0
  22. return Repo(path)
  23. def git_stats_to_json(text):
  24. pattern = r",?\s*(\d+)\s*files changed|,?\s*(\d+)\s*insertions\(\+\)|,?\s*(\d+)\s+deletions\(\-\)"
  25. data = re.findall(pattern, text)
  26. result = {}
  27. for item in data:
  28. if item[0]:
  29. result["files_changed"] = int(item[0])
  30. if item[1]:
  31. result["insertions"] = int(item[1])
  32. if item[2]:
  33. result["deletions"] = int(item[2])
  34. return result
  35. gitrouter = APIRouter()
  36. @gitrouter.post("/clone")
  37. async def clone(request: RequestBody, background_tasks: BackgroundTasks):
  38. local_path, repo_name = generate_repo_path(request.uuid, request.repo_url)
  39. if os.path.exists(local_path):
  40. return {"status": "400", "msg": "仓库已存在", "uuid": request.uuid, "repo_url": request.repo_url,
  41. "path": local_path}
  42. else:
  43. background_tasks.add_task(Repo.clone_from, request.repo_url, local_path)
  44. response = {"status": "200", "msg": "成功创建克隆任务", "uuid": request.uuid, "repo_name": repo_name,
  45. "local_path": local_path}
  46. return response
  47. @gitrouter.post("/log")
  48. async def log(request: RequestBody):
  49. local_path, _ = generate_repo_path(request.uuid, request.repo_url)
  50. repo = get_repo(request.uuid, request.repo_url)
  51. if not repo:
  52. return {
  53. "status": "404",
  54. "msg": "仓库不存在",
  55. "uuid": request.uuid,
  56. "repo_url": request.repo_url,
  57. "local_path": local_path
  58. }
  59. # 使用git log --numstat一次性获取所有必要信息
  60. git_log_format = '--pretty=format:%h|%an|%ce|%s|%cd'
  61. try:
  62. log_output = repo.git.log(
  63. git_log_format,
  64. '--numstat',
  65. '--no-renames',
  66. date='format:%Y-%m-%d %H:%M'
  67. )
  68. except GitCommandError as e:
  69. return {"status": "500", "msg": f"获取日志失败: {str(e)}"}
  70. log = []
  71. current_commit = None
  72. for line in log_output.split('\n'):
  73. if not line.strip():
  74. continue # 跳过空行
  75. if '\t' in line and len(line.split('\t')) == 3:
  76. # 处理numstat行,例如 "10\t5\tfile.txt"
  77. if current_commit is None:
  78. continue # 防止数据错误
  79. insertions_str, deletions_str, _ = line.split('\t')
  80. try:
  81. insertions = int(insertions_str) if insertions_str != '-' else 0
  82. deletions = int(deletions_str) if deletions_str != '-' else 0
  83. except ValueError:
  84. insertions, deletions = 0, 0
  85. current_commit['change']['insertions'] += insertions
  86. current_commit['change']['deletions'] += deletions
  87. current_commit['change']['files'] += 1
  88. else:
  89. # 处理提交信息行,例如 "abc123|Author|email|summary|2023-10-01 12:34"
  90. if current_commit is not None:
  91. # 生成avatar的md5
  92. email = current_commit['email']
  93. email_md5 = hashlib.md5(email.encode('utf-8')).hexdigest()
  94. current_commit['avatar'] = f"{avatar_url}{email_md5}?d=identicon"
  95. log.append(current_commit)
  96. try:
  97. commit_hash, author, email, summary, date = line.split('|', 4)
  98. current_commit = {
  99. "commit": commit_hash,
  100. "author": author,
  101. "email": email,
  102. "summary": summary,
  103. "date": date,
  104. "avatar": "",
  105. "change": {
  106. "insertions": 0,
  107. "deletions": 0,
  108. "files": 0
  109. }
  110. }
  111. except ValueError:
  112. current_commit = None # 忽略格式错误行
  113. # 添加最后一个提交
  114. if current_commit is not None:
  115. email = current_commit['email']
  116. email_md5 = hashlib.md5(email.encode('utf-8')).hexdigest()
  117. current_commit['avatar'] = f"{avatar_url}{email_md5}?d=identicon"
  118. log.append(current_commit)
  119. # 按时间倒序排列(git log默认最新在前)
  120. return {
  121. "status": "200",
  122. "msg": "成功获取日志",
  123. "uuid": request.uuid,
  124. "repo_url": request.repo_url,
  125. "local_path": local_path,
  126. "git_log": log
  127. }
  128. @gitrouter.post("/status")
  129. async def status(request: RequestBody):
  130. repo = get_repo(request.uuid, request.repo_url)
  131. # 手动获取所有数据
  132. active_branch = repo.active_branch
  133. tracking_branch = active_branch.tracking_branch()
  134. ahead = sum(1 for _ in repo.iter_commits(f"{active_branch}..{tracking_branch}"))
  135. behind = sum(1 for _ in repo.iter_commits(f"{tracking_branch}..{active_branch}"))
  136. conflicts = repo.index.unmerged_blobs()
  137. conflicted = [path for path, entries in conflicts.items()]
  138. created_files = repo.untracked_files
  139. current = repo.active_branch.name
  140. head_commit = repo.head.commit
  141. tree = head_commit.tree
  142. all_files = [item.path for item in tree.traverse() if item.type == 'blob']
  143. diffs = repo.index.diff(None)
  144. deleted = [d.a_path for d in diffs if d.change_type == 'D']
  145. detached = repo.head.is_detached
  146. ignored_files = repo.git.execute(["git", "ls-files", "--others", "--ignored", "--exclude-standard"]).split("\n")
  147. modified_files = [d.a_path for d in diffs]
  148. untracked_files = repo.untracked_files
  149. staged_entries = repo.index.entries
  150. staged = [path[0] for path, _ in staged_entries.items()]
  151. tracking = active_branch.tracking_branch().name
  152. status = {"ahead": ahead, "behind": behind, "conflicted": conflicted, "created": created_files,
  153. "current": current, "deleted": deleted, "detached": detached, "files": all_files,
  154. "ignored": ignored_files,
  155. "modified": modified_files, "not_added": untracked_files, "staged": staged, "tracking": tracking}
  156. return status
  157. @gitrouter.post("/change")
  158. async def change(request: CommitHash):
  159. repo = get_repo(request.uuid, request.repo_url)
  160. if not repo:
  161. return {"status": "404", "msg": "仓库不存在", "uuid": request.uuid, "repo_url": request.repo_url}
  162. commit = repo.commit(request.commit_hash)
  163. if not commit.parents:
  164. print("首次提交,无父提交对比")
  165. return
  166. parent = commit.parents[0]
  167. diffs = commit.diff(commit,create_patch=True, no_renames=True)
  168. print(diffs)
  169. for diff in diffs:
  170. print(f"文件 {diff.a_path} ({diff.change_type}):")
  171. print(diff.diff.decode('utf-8'))