git_utils.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import os
  2. from git.repo import Repo
  3. from git.repo.fun import is_git_dir
  4. class GitRepository(object):
  5. """
  6. git仓库管理
  7. """
  8. def __init__(self, local_path, repo_url, branch='master'):
  9. self.local_path = local_path
  10. self.repo_url = repo_url
  11. self.repo = None
  12. self.initial(self.repo_url, branch)
  13. def initial(self, repo_url, branch):
  14. """
  15. 初始化git仓库
  16. :param repo_url:
  17. :param branch:
  18. :return:
  19. """
  20. if not os.path.exists(self.local_path):
  21. os.makedirs(self.local_path)
  22. git_local_path = os.path.join(self.local_path, '.git')
  23. if not is_git_dir(git_local_path):
  24. self.repo = Repo.clone_from(repo_url, to_path=self.local_path, branch=branch)
  25. else:
  26. self.repo = Repo(self.local_path)
  27. def pull(self):
  28. """
  29. 从线上拉最新代码
  30. :return:
  31. """
  32. self.repo.git.pull()
  33. def branches(self):
  34. """
  35. 获取所有分支
  36. :return:
  37. """
  38. branches = self.repo.remote().refs
  39. return [item.remote_head for item in branches if item.remote_head not in ['HEAD', ]]
  40. def commits(self):
  41. """
  42. 获取所有提交记录
  43. :return:
  44. """
  45. commit_log = self.repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}',
  46. max_count=50,
  47. date='format:%Y-%m-%d %H:%M')
  48. log_list = commit_log.split("\n")
  49. return [eval(item) for item in log_list]
  50. def tags(self):
  51. """
  52. 获取所有tag
  53. :return:
  54. """
  55. return [tag.name for tag in self.repo.tags]
  56. def tags_exists(self, tag):
  57. """
  58. tag是否存在
  59. :return:
  60. """
  61. return tag in self.tags()
  62. def change_to_branch(self, branch):
  63. """
  64. 切换分支
  65. :param branch:
  66. :return:
  67. """
  68. self.repo.git.checkout(branch)
  69. def change_to_commit(self, branch, commit):
  70. """
  71. 切换commit
  72. :param branch:
  73. :param commit:
  74. :return:
  75. """
  76. self.change_to_branch(branch=branch)
  77. self.repo.git.reset('--hard', commit)
  78. def change_to_tag(self, tag):
  79. """
  80. 切换tag
  81. :param tag:
  82. :return:
  83. """
  84. self.repo.git.checkout(tag)
  85. # if __name__ == '__main__':
  86. # local_path = os.path.join('codes', 't1')
  87. # repo = GitRepository(local_path, remote_path)
  88. # branch_list = repo.branches()
  89. # print(branch_list)
  90. # repo.change_to_branch('dev')
  91. # repo.pull()