coding.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. self.repo_shared = False if params.get('coding_private', "true").lower() == 'true' else True
  24. def create_project(self):
  25. ''' createt a project '''
  26. url = f'{self._host}/open-api'
  27. data = {
  28. 'Action': 'CreateCodingProject',
  29. 'Name': '',
  30. 'DisplayName': '',
  31. 'Description': '',
  32. 'GitReadmeEnabled': False,
  33. 'VscType': 'git',
  34. 'CreateSvnLayout': False,
  35. 'Shared': 1,
  36. 'ProjectTemplateId': 'DEV_OPS',
  37. }
  38. r = self.sess.post(url, json=data)
  39. if r.status_code == 200:
  40. res_data = r.json()
  41. return True
  42. else:
  43. return False
  44. def delete_project(self):
  45. url = f'{self._host}/open-api'
  46. data = {
  47. 'Action': 'DeleteOneProject',
  48. 'ProjectId': 0,
  49. }
  50. r = self.sess.post(url, json=data)
  51. if r.status_code == 200:
  52. res_data = r.json()
  53. return True
  54. else:
  55. return False
  56. def get_project_list(self):
  57. pass
  58. def get_repo_list(self, username: str):
  59. """get repo list"""
  60. url = f'{self._host}/open-api'
  61. data = {
  62. 'Action': 'DescribeTeamDepotInfoList',
  63. 'ProjectName': '',
  64. 'DepotName': '',
  65. 'PageNumber': 1,
  66. 'PageSize': 50
  67. }
  68. r = self.sess.post(url, json=data)
  69. def get_repo_info(self, repo_name: str):
  70. """get repo list"""
  71. url = f'{self._host}/open-api'
  72. data = {
  73. 'Action': 'DescribeTeamDepotInfoList',
  74. 'ProjectName': self.project_name,
  75. 'DepotName': repo_name,
  76. 'PageNumber': 1,
  77. 'PageSize': 50
  78. }
  79. r = self.sess.post(url, json=data)
  80. if r.status_code == 200:
  81. res_data = r.json()
  82. try:
  83. if res_data['Response']["DepotData"]["Page"]["TotalRow"] > 0:
  84. DepotList = res_data['Response']["DepotData"]["Depots"]
  85. depot = Repo(
  86. Id=DepotList[0]['Id'],
  87. Name=DepotList[0]['Name'],
  88. HttpsUrl=DepotList[0]['HttpsUrl'],
  89. ProjectId=DepotList[0]['ProjectId'],
  90. SshUrl=DepotList[0]['SshUrl'],
  91. WebUrl=DepotList[0]['WebUrl'],
  92. ProjectName=DepotList[0]['ProjectName'],
  93. Description=DepotList[0]['Description'],
  94. CreatedAt=DepotList[0]['CreatedAt'],
  95. GroupId=DepotList[0]['GroupId'],
  96. GroupName=DepotList[0]['GroupName']
  97. )
  98. return depot
  99. else:
  100. print(f'can not find repo {repo_name} in project {self.project_name}')
  101. exit(1)
  102. except Exception as e:
  103. raise Exception(f'can not find repo {repo_name} in project {self.project_name}')
  104. def get_project_info(self)->Project:
  105. url = f'{self._host}/open-api'
  106. data = {
  107. "Action": "DescribeCodingProjects",
  108. "ProjectName": self.project_name,
  109. "DepotName": "",
  110. "PageNumber": 1,
  111. "PageSize": 50
  112. }
  113. r = self.sess.post(url, json=data)
  114. if r.status_code == 200:
  115. res_data = r.json()
  116. if res_data['Response']["Data"]["TotalCount"] > 0:
  117. ProjectList = res_data['Response']["Data"]["ProjectList"]
  118. projet = Project(
  119. Id=ProjectList[0]['Id'],
  120. Name=ProjectList[0]['Name'],
  121. DisplayName=ProjectList[0]['DisplayName'],
  122. Description=ProjectList[0]['Description'],
  123. TeamOwnerId=ProjectList[0]['TeamOwnerId'],
  124. TeamId=ProjectList[0]['TeamId']
  125. )
  126. return projet
  127. def create_repo(self, repo_name: str):
  128. """create a repo"""
  129. # get project id
  130. project = self.get_project_info()
  131. url = f'{self._host}/open-api/repos'
  132. data = {
  133. "Action": "CreateGitDepot",
  134. "ProjectId": project.Id,
  135. "DepotName": repo_name,
  136. "Shared": self.repo_shared,
  137. "Description": "this is your first depot"
  138. }
  139. r = self.sess.post(url, json=data)
  140. if r.status_code == 200:
  141. print(f'create repo {repo_name} success', data,r.json())
  142. return True
  143. else:
  144. return False
  145. def delete(self, repo_name: str):
  146. """delete a repo"""
  147. repo = self.get_repo_info(repo_name=repo_name)
  148. url = f'{self._host}/open-api/repos'
  149. data = {
  150. "Action": "DeleteGitDepot",
  151. "DepotId": repo.Id
  152. }
  153. r = self.sess.post(url, json=data)
  154. if r.status_code == 200:
  155. print(f'delete repo {repo_name} success', data,r.json())
  156. return True
  157. else:
  158. return False
  159. def pull(self, local_repo_path: str):
  160. ''' pull a repo from remote
  161. Args: local_repo_path: local repo path
  162. '''
  163. if local_repo_path[-1] == os.path.sep:
  164. local_repo_path = local_repo_path[:-1]
  165. repo_name = local_repo_path.split(os.path.sep)[-1]
  166. print(f'pull repo:{self.username}/{repo_name} from coding')
  167. os.chdir(local_repo_path)
  168. try:
  169. os.system('git remote remove origin_coding')
  170. except Exception as e:
  171. pass
  172. os.system(
  173. f'git remote add origin_coding https://{self.username}:{self.token}@e.coding.net/{self.username}/{self.project_name}/{repo_name}.git'
  174. )
  175. result = subprocess.run(
  176. ['git', 'symbolic-ref', '--short', 'HEAD'], capture_output=True, text=True, encoding='utf-8')
  177. current_branch = result.stdout.strip()
  178. os.system(f'git pull origin_coding {current_branch}')
  179. os.system('git remote remove origin_coding')
  180. os.chdir('..')
  181. print('pull success')
  182. def push(self, local_repo_path: str):
  183. ''' push a local repo to remote
  184. Args: local_repo_path: local repo path
  185. '''
  186. if local_repo_path[-1] == os.path.sep:
  187. local_repo_path = local_repo_path[:-1]
  188. repo_name = local_repo_path.split(os.path.sep)[-1]
  189. print(f'push repo:{self.username}/{repo_name} to coding')
  190. os.chdir(local_repo_path)
  191. os.system('git remote remove origin_coding')
  192. os.system(
  193. f'git remote add origin_coding https://{self.username}:{self.token}@e.coding.net/{self.username}/{self.project_name}/{repo_name}.git'
  194. )
  195. result = subprocess.run(
  196. ['git', 'symbolic-ref', '--short', 'HEAD'], capture_output=True, text=True, encoding='utf-8')
  197. current_branch = result.stdout.strip()
  198. os.system(f'git pull origin_coding {current_branch}')
  199. os.system(f'git push -u origin_coding {current_branch}')
  200. os.system('git remote remove origin_coding')
  201. os.chdir('..')
  202. print('push success')
  203. def clone(self, repo_name: str):
  204. pass
  205. @classmethod
  206. def suitable(cls, extractor: str) -> bool:
  207. """check if this extractor is suitable for this platform"""
  208. if extractor == 'coding':
  209. return True
  210. else:
  211. return False