gitRouter.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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
  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 {"status": "404", "msg": "仓库不存在", "uuid": request.uuid, "repo_url": request.repo_url,
  53. "local_path": local_path}
  54. log_ = repo.git.log('--pretty={"commit":"%h","author":"%an","email":"%ce","summary":"%s","date":"%cd"}', max_count=50,
  55. date='format:%Y-%m-%d %H:%M').split("\n")
  56. log = list(map(json.loads, log_))
  57. for i in log:
  58. email = i["email"]
  59. email_md5 = hashlib.md5(email.encode(encoding='UTF-8')).hexdigest()
  60. i["avatar"] = avatar_url+email_md5+"?d=identicon"
  61. status=repo.git.execute(["git", "show",i["commit"] , "--shortstat"]).split("\n")[-1]
  62. i["change"]=git_stats_to_json(status)
  63. response = {"status": "200", "msg": "成功获取日志", "uuid": request.uuid, "repo_url": request.repo_url,
  64. "local_path": local_path, "git_log": log}
  65. return response
  66. @gitrouter.post("/status")
  67. async def status(request: RequestBody):
  68. repo = get_repo(request.uuid, request.repo_url)
  69. # 手动获取所有数据
  70. active_branch = repo.active_branch
  71. tracking_branch = active_branch.tracking_branch()
  72. ahead = sum(1 for _ in repo.iter_commits(f"{active_branch}..{tracking_branch}"))
  73. behind = sum(1 for _ in repo.iter_commits(f"{tracking_branch}..{active_branch}"))
  74. conflicts = repo.index.unmerged_blobs()
  75. conflicted = [path for path, entries in conflicts.items()]
  76. created_files = repo.untracked_files
  77. current = repo.active_branch.name
  78. head_commit = repo.head.commit
  79. tree = head_commit.tree
  80. all_files = [item.path for item in tree.traverse() if item.type == 'blob']
  81. diffs = repo.index.diff(None)
  82. deleted = [d.a_path for d in diffs if d.change_type == 'D']
  83. detached = repo.head.is_detached
  84. ignored_files = repo.git.execute(["git", "ls-files", "--others", "--ignored", "--exclude-standard"]).split("\n")
  85. modified_files = [d.a_path for d in diffs]
  86. untracked_files = repo.untracked_files
  87. staged_entries = repo.index.entries
  88. staged = [path[0] for path, _ in staged_entries.items()]
  89. tracking = active_branch.tracking_branch().name
  90. status = {"ahead": ahead, "behind": behind, "conflicted": conflicted, "created": created_files,
  91. "current": current, "deleted": deleted, "detached": detached, "files": all_files,
  92. "ignored": ignored_files,
  93. "modified": modified_files, "not_added": untracked_files, "staged": staged, "tracking": tracking}
  94. return status
  95. @gitrouter.post("/change")
  96. async def change(request: CommitHash):
  97. repo = get_repo(request.uuid, request.repo_url)
  98. if not repo:
  99. return {"status": "404", "msg": "仓库不存在", "uuid": request.uuid, "repo_url": request.repo_url}
  100. commit = repo.commit(request.commit_hash)
  101. if not commit.parents:
  102. print("首次提交,无父提交对比")
  103. return
  104. parent = commit.parents[0]
  105. diffs = commit.diff(commit,create_patch=True, no_renames=True)
  106. print(diffs)
  107. for diff in diffs:
  108. print(f"文件 {diff.a_path} ({diff.change_type}):")
  109. print(diff.diff.decode('utf-8'))