gitcode.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. '''
  4. @Contact : liuyuqi.gov@msn.cn
  5. @Time : 2024/12/16 19:26:29
  6. @License : Copyright © 2017-2022 liuyuqi. All Rights Reserved.
  7. @Desc : hauwei and csdn'
  8. api docs:
  9. https://docs.gitcode.com/docs/openapi/guide/
  10. api 和 gitcode 类似
  11. '''
  12. from .base_platform import BasePlatform
  13. from repo_sync.utils.colors import bcolors
  14. import os, subprocess,json
  15. from repo_sync.utils.logger import logger
  16. class GitcodeIE(BasePlatform):
  17. """ gitcode platform """
  18. def __init__(self, username:str, token:str, host:str =None ,params: dict = None) -> None:
  19. super().__init__(username=username,token=token)
  20. self.sess.headers.update(
  21. {
  22. 'Accept': 'application/json',
  23. 'Content-Type': 'application/json',
  24. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36',
  25. 'Authorization': f'Bearer {self.token}',
  26. }
  27. )
  28. self._host = 'https://api.gitcode.com' if host is None else host
  29. self._api: str = self._host + '/api/v5'
  30. self.repo_private = True if params.get('gitcode_private', "true").lower() == 'true' else False
  31. def create_repo(self, repo_name: str):
  32. """ create a repo """
  33. if not self._repo_exists(repo_name=repo_name):
  34. url = f'{self._api}/user/repos'
  35. form_data = {
  36. 'name': repo_name,
  37. 'private': self.repo_private,
  38. }
  39. # r = self.sess.post(url, params=json.dumps(form_data))
  40. r = self.sess.post(url, data=json.dumps(form_data))
  41. if r.status_code != 200:
  42. logger.error(f'create repo {repo_name} failed, status code {r.status_code}')
  43. return
  44. logger.info(f'create repo {repo_name} success')
  45. logger.info(f'{self._host}/{self.username}/{repo_name}')
  46. def delete(self, repo_name: str):
  47. """ delete a repo """
  48. url = f'{self._api}/repos/{self.username}/{repo_name}'
  49. response = self.sess.delete(url)
  50. if response.status_code == 204:
  51. logger.info(f'Repository: {repo_name} deleted from gitcode successfully!')
  52. else:
  53. logger.error(f'Failed to delete repository: {repo_name} from gitcode. Error {response.status_code}: {response.text}')
  54. def get_repo_list(self) -> list:
  55. """ get repo list """
  56. pass
  57. def clone(self):
  58. pass
  59. def push(self, local_repo_path: str):
  60. if local_repo_path[-1] == os.path.sep:
  61. local_repo_path = local_repo_path[:-1]
  62. repo_name = local_repo_path.split(os.path.sep)[-1]
  63. logger.info(f'push repo:{self.username}/{repo_name} to gitcode')
  64. self.create_repo(repo_name)
  65. os.chdir(local_repo_path)
  66. os.system('git remote remove origin_gitcode')
  67. os.system(f'git remote add origin_gitcode https://{self.username}:{self.token}@gitcode.com/{self.username}/{repo_name}.git')
  68. result = subprocess.run(['git', 'symbolic-ref', '--short', 'HEAD'], capture_output=True, text=True, encoding='utf-8')
  69. current_branch = result.stdout.strip()
  70. os.system(f'git pull origin_gitcode {current_branch}')
  71. os.system(f'git push -u origin_gitcode {current_branch}')
  72. os.system('git remote remove origin_gitcode')
  73. os.chdir('..')
  74. logger.info(f'push to gitcode success')
  75. def pull(self, local_repo_path: str):
  76. if local_repo_path[-1] == os.path.sep:
  77. local_repo_path = local_repo_path[:-1]
  78. repo_name = local_repo_path.split(os.path.sep)[-1]
  79. logger.info(f'pull repo:{self.username}/{repo_name} from gitcode')
  80. os.chdir(local_repo_path)
  81. os.system('git remote remove origin_gitcode')
  82. os.system(f'git remote add origin_gitcode https://{self.username}:{self.token}@gitcode.com/{self.username}/{repo_name}.git')
  83. result = subprocess.run(['git', 'symbolic-ref', '--short', 'HEAD'], capture_output=True, text=True, encoding='utf-8')
  84. current_branch = result.stdout.strip()
  85. os.system(f'git pull origin_gitcode {current_branch}')
  86. os.system('git remote remove origin_gitcode')
  87. os.chdir('..')
  88. logger.info(f'pull from gitcode success')
  89. def _repo_exists(self, repo_name: str) -> bool:
  90. """ check if repo exists """
  91. url = f"{self._api}/repos/{self.username}/{repo_name}/contributors"
  92. try:
  93. response = self.sess.get(url)
  94. if response.status_code == 200:
  95. logger.info(f'repo: {repo_name} is existed.')
  96. return True
  97. except Exception as e:
  98. return False
  99. @classmethod
  100. def suitable(cls, extractor: str) -> bool:
  101. """check if this extractor is suitable for this platform"""
  102. if extractor == 'gitcode':
  103. return True
  104. else:
  105. return False