coding.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. """
  4. @Contact : liuyuqi.gov@msn.cn
  5. @Time : 2023/09/27 10:35:25
  6. @License : Copyright © 2017-2022 liuyuqi. All Rights Reserved.
  7. @Desc : coding.net repo sync
  8. 两种授权: token 授权,OAuth2.0 授权
  9. """
  10. import os,subprocess
  11. from repo_sync.platform.base_platform import BasePlatform
  12. from .project import Project
  13. from .repo import Repo
  14. class CodingIE(BasePlatform):
  15. """coding util"""
  16. client_id = ''
  17. client_serect = ''
  18. _host = 'https://e.coding.net' # 新版接口统一地址
  19. def __init__(self, username:str, token:str,host:str =None ,params: dict = None) -> None:
  20. """init"""
  21. super().__init__(username , token)
  22. self.project_name = params.get('coding_project', '')
  23. def create_project(self):
  24. ''' createt a project '''
  25. url = f'{self._host}/open-api'
  26. data = {
  27. 'Action': 'CreateCodingProject',
  28. 'Name': '',
  29. 'DisplayName': '',
  30. 'Description': '',
  31. 'GitReadmeEnabled': False,
  32. 'VscType': 'git',
  33. 'CreateSvnLayout': False,
  34. 'Shared': 1,
  35. 'ProjectTemplateId': 'DEV_OPS',
  36. }
  37. r = self.sess.post(url, json=data)
  38. if r.status_code == 200:
  39. res_data = r.json()
  40. return True
  41. else:
  42. return False
  43. def delete_project(self):
  44. url = f'{self._host}/open-api'
  45. data = {
  46. 'Action': 'DeleteOneProject',
  47. 'ProjectId': 0,
  48. }
  49. r = self.sess.post(url, json=data)
  50. if r.status_code == 200:
  51. res_data = r.json()
  52. return True
  53. else:
  54. return False
  55. def get_project_list(self):
  56. pass
  57. def get_repo_list(self, username: str):
  58. """get repo list"""
  59. url = f'{self._host}/open-api'
  60. data = {
  61. 'Action': 'DescribeTeamDepotInfoList',
  62. 'ProjectName': '',
  63. 'DepotName': '',
  64. 'PageNumber': 1,
  65. 'PageSize': 50
  66. }
  67. r = self.sess.post(url, json=data)
  68. def get_repo_info(self, repo_name: str):
  69. """get repo list"""
  70. url = f'{self._host}/open-api'
  71. data = {
  72. 'Action': 'DescribeTeamDepotInfoList',
  73. 'ProjectName': self.project_name,
  74. 'DepotName': repo_name,
  75. 'PageNumber': 1,
  76. 'PageSize': 50
  77. }
  78. r = self.sess.post(url, json=data)
  79. if r.status_code == 200:
  80. res_data = r.json()
  81. if res_data['Response']["DepotData"]["Page"]["TotalRow"] > 0:
  82. DepotList = res_data['Response']["DepotData"]["Depots"]
  83. depot = Repo(
  84. Id=DepotList[0]['Id'],
  85. Name=DepotList[0]['Name'],
  86. HttpsUrl=DepotList[0]['HttpsUrl'],
  87. ProjectId=DepotList[0]['ProjectId'],
  88. SshUrl=DepotList[0]['SshUrl'],
  89. WebUrl=DepotList[0]['WebUrl'],
  90. ProjectName=DepotList[0]['ProjectName'],
  91. Description=DepotList[0]['Description'],
  92. CreatedAt=DepotList[0]['CreatedAt'],
  93. GroupId=DepotList[0]['GroupId'],
  94. GroupName=DepotList[0]['GroupName']
  95. )
  96. return depot
  97. def get_project_info(self)->Project:
  98. url = f'{self._host}/open-api'
  99. data = {
  100. "Action": "DescribeCodingProjects",
  101. "ProjectName": self.project_name,
  102. "DepotName": "",
  103. "PageNumber": 1,
  104. "PageSize": 50
  105. }
  106. r = self.sess.post(url, json=data)
  107. if r.status_code == 200:
  108. res_data = r.json()
  109. if res_data['Response']["Data"]["TotalCount"] > 0:
  110. ProjectList = res_data['Response']["Data"]["ProjectList"]
  111. projet = Project(
  112. Id=ProjectList[0]['Id'],
  113. Name=ProjectList[0]['Name'],
  114. DisplayName=ProjectList[0]['DisplayName'],
  115. Description=ProjectList[0]['Description'],
  116. TeamOwnerId=ProjectList[0]['TeamOwnerId'],
  117. TeamId=ProjectList[0]['TeamId']
  118. )
  119. return projet
  120. def create_repo(self, repo_name: str):
  121. """create a repo"""
  122. # get project id
  123. project = self.get_project_info()
  124. url = f'{self._host}/open-api/repos'
  125. data = {
  126. "Action": "CreateGitDepot",
  127. "ProjectId": project.Id,
  128. "DepotName": repo_name,
  129. "Shared": False,
  130. "Description": ""
  131. }
  132. r = self.sess.post(url, json=data)
  133. if r.status_code == 200:
  134. print(f'create repo {repo_name} success', data,r.json())
  135. return True
  136. else:
  137. return False
  138. def delete(self, repo_name: str):
  139. """delete a repo"""
  140. repo = self.get_repo_info(repo_name=repo_name)
  141. url = f'{self._host}/open-api/repos'
  142. data = {
  143. "Action": "DeleteGitDepot",
  144. "DepotId": repo.Id
  145. }
  146. r = self.sess.post(url, json=data)
  147. if r.status_code == 200:
  148. print(f'delete repo {repo_name} success', data,r.json())
  149. return True
  150. else:
  151. return False
  152. def pull(self, local_repo_path: str):
  153. ''' pull a repo from remote
  154. Args: local_repo_path: local repo path
  155. '''
  156. if local_repo_path[-1] == os.path.sep:
  157. local_repo_path = local_repo_path[:-1]
  158. repo_name = local_repo_path.split(os.path.sep)[-1]
  159. print(f'pull repo:{self.username}/{repo_name} from coding')
  160. os.chdir(local_repo_path)
  161. try:
  162. os.system('git remote remove origin_coding')
  163. except Exception as e:
  164. pass
  165. os.system(
  166. f'git remote add origin_coding https://{self.username}:{self.token}@e.coding.net/{self.username}/{self.project_name}/{repo_name}.git'
  167. )
  168. result = subprocess.run(
  169. ['git', 'symbolic-ref', '--short', 'HEAD'], capture_output=True, text=True)
  170. current_branch = result.stdout.strip()
  171. os.system(f'git pull origin_gogs {current_branch}')
  172. os.system('git remote remove origin_coding')
  173. os.chdir('..')
  174. print('pull success')
  175. def push(self, local_repo_path: str):
  176. ''' push a local repo to remote
  177. Args: local_repo_path: local repo path
  178. '''
  179. if local_repo_path[-1] == os.path.sep:
  180. local_repo_path = local_repo_path[:-1]
  181. repo_name = local_repo_path.split(os.path.sep)[-1]
  182. print(f'push repo:{self.username}/{repo_name} to coding')
  183. os.chdir(local_repo_path)
  184. os.system('git remote remove origin_coding')
  185. os.system(
  186. f'git remote add origin_coding https://{self.username}:{self.token}@e.coding.net/{self.username}/{self.project_name}/{repo_name}.git'
  187. )
  188. os.system('git push -u origin_coding')
  189. os.system('git remote remove origin_coding')
  190. os.chdir('..')
  191. print('push success')
  192. def clone(self, repo_name: str):
  193. pass
  194. @classmethod
  195. def suitable(cls, extractor: str) -> bool:
  196. """check if this extractor is suitable for this platform"""
  197. if extractor == 'coding':
  198. return True
  199. else:
  200. return False