Browse Source

feat: add support for GitCode platform and improve repo lookup logic in Coding platform

liuyuqi-dellpc 4 months ago
parent
commit
5c4d13dac9
5 changed files with 144 additions and 17 deletions
  1. 1 1
      repo_sync/options.py
  2. 20 15
      repo_sync/platform/coding/coding.py
  3. 113 0
      repo_sync/platform/gitcode.py
  4. 10 0
      repo_sync/utils/colors.py
  5. 0 1
      scripts/sync.xys

+ 1 - 1
repo_sync/options.py

@@ -30,7 +30,7 @@ def parser_args(overrideArguments=None):
         '-p',
         '--platform',
         help='set a platform',
-        choices=['github', 'gitee', 'gitlab', 'gogs', 'gitea', 'bitbucket', 'coding'],
+        choices=['github', 'gitee', 'gitlab', 'gogs', 'gitea', 'bitbucket', 'coding', 'gitcode'],
         default='github',
     )
     argparser.add_argument('-token', '--token', help='set a token')

+ 20 - 15
repo_sync/platform/coding/coding.py

@@ -153,19 +153,26 @@ class CodingIE(BasePlatform):
             try:
                 if res_data['Response']["DepotData"]["Page"]["TotalRow"] > 0:
                     DepotList = res_data['Response']["DepotData"]["Depots"]
-                    depot = Repo(
-                        Id=DepotList[0]['Id'],
-                        Name=DepotList[0]['Name'],
-                        HttpsUrl=DepotList[0]['HttpsUrl'],
-                        ProjectId=DepotList[0]['ProjectId'],
-                        SshUrl=DepotList[0]['SshUrl'],
-                        WebUrl=DepotList[0]['WebUrl'],
-                        ProjectName=DepotList[0]['ProjectName'],
-                        Description=DepotList[0]['Description'],
-                        CreatedAt=DepotList[0]['CreatedAt'],
-                        GroupId=DepotList[0]['GroupId'],
-                        GroupName=DepotList[0]['GroupName']
-                    )
+                    for repo in DepotList:
+                        if repo['Name'] == repo_name:
+                            depot = Repo(
+                                Id=repo['Id'],
+                                Name=repo['Name'],
+                                HttpsUrl=repo['HttpsUrl'],
+                                ProjectId=repo['ProjectId'],
+                                SshUrl=repo['SshUrl'],
+                                WebUrl=repo['WebUrl'],
+                                ProjectName=repo['ProjectName'],
+                                Description=repo['Description'],
+                                CreatedAt=repo['CreatedAt'],
+                                GroupId=repo['GroupId'],
+                                GroupName=repo['GroupName']
+                            )
+                        break
+                    if depot is None:
+                        print(bcolors.WARNING + f'Cannot find repo {repo_name} in project {self.project_name}' + bcolors.ENDC)
+                    else:
+                        print(bcolors.OKGREEN + f'Find repo {repo_name} in project {self.project_name}' + bcolors.ENDC)
                     return depot
                 else:
                     print(bcolors.WARNING + f'Cannot find repo {repo_name} in project {self.project_name}' + bcolors.ENDC)
@@ -220,8 +227,6 @@ class CodingIE(BasePlatform):
                 else:
                     print(bcolors.FAIL + 'Failed to create repo' + bcolors.ENDC)
                     return False
-            else:
-                print(bcolors.WARNING + f"Repo: {repo_name} already exists" + bcolors.ENDC)
         else:
             print(bcolors.FAIL + f"Project: {self.project_name} does not exist, cannot create repo in it." + bcolors.ENDC)
     

+ 113 - 0
repo_sync/platform/gitcode.py

@@ -0,0 +1,113 @@
+#!/usr/bin/env python
+# -*- encoding: utf-8 -*-
+'''
+@Contact :   liuyuqi.gov@msn.cn
+@Time    :   2024/12/16 19:26:29
+@License :   Copyright © 2017-2022 liuyuqi. All Rights Reserved.
+@Desc    :   hauwei and csdn'
+
+api docs:
+https://docs.gitcode.com/docs/openapi/guide/
+
+api 和 gitee 类似
+'''
+from .base_platform import BasePlatform
+from repo_sync.utils.colors import bcolors
+import os, subprocess
+class Gitcode(BasePlatform):
+    """ gitcode platform """
+    
+    def __init__(self, username:str, token:str, host:str =None ,params: dict = None) -> None:
+        super().__init__(username=username,token=token)
+        self._host = 'https://api.gitcode.com' if host is None else host
+        self._api = self._host + '/api/v5'
+        
+    
+    def create_repo(self, repo_name: str):
+        """ create a repo """
+        if not self._repo_exists(repo_name=repo_name):
+            url = f'{self._api}/user/repos'
+            form_data = {
+                'name': repo_name, 
+                'private': self.repo_private,
+            }
+            r = self.sess.post(url, params=form_data)
+            if r.status_code != 201:
+                print(bcolors.FAIL + f'create repo {repo_name} failed, status code {r.status_code}' + bcolors.ENDC)
+                return
+            print(bcolors.OKGREEN + f'create repo {repo_name} success' + bcolors.ENDC)
+    
+    def delete(self, repo_name: str):
+        """ delete a repo """
+        url = f'{self._api}/repos/{self.username}/{repo_name}'
+        response = self.sess.delete(url)
+        if response.status_code == 204:
+            print(bcolors.OKBLUE + f'Repository: {repo_name} deleted from gitee successfully!' + bcolors.ENDC)
+        else:
+            print(bcolors.FAIL + f'Failed to delete repository: {repo_name} from gitee. Error {response.status_code}: {response.text}' + bcolors.ENDC)
+    
+
+    def get_repo_list(self) -> list:
+        """ get repo list """
+        pass
+    
+    def clone(self):
+        pass
+        
+    def push(self, local_repo_path: str):
+        if local_repo_path[-1] == os.path.sep:
+            local_repo_path = local_repo_path[:-1]
+        repo_name = local_repo_path.split(os.path.sep)[-1]
+        print(bcolors.WARNING + f'push repo:{self.username}/{repo_name} to gitee' + bcolors.ENDC)
+        self.create_repo(repo_name)
+        os.chdir(local_repo_path)
+        os.system('git remote remove origin_gitee')
+        os.system(f'git remote add origin_gitee https://{self.username}:{self.token}@gitee.com/{self.username}/{repo_name}.git')
+        
+        result = subprocess.run(['git', 'symbolic-ref', '--short', 'HEAD'], capture_output=True, text=True, encoding='utf-8')
+        current_branch = result.stdout.strip()
+        
+        os.system(f'git pull origin_gitee {current_branch}')
+        os.system(f'git push -u origin_gitee {current_branch}')
+        os.system('git remote remove origin_gitee')
+        os.chdir('..')
+        
+        print(bcolors.OKGREEN + 'push to gitee success' + bcolors.ENDC)
+
+    def pull(self, local_repo_path: str):
+        if local_repo_path[-1] == os.path.sep:
+            local_repo_path = local_repo_path[:-1]
+        repo_name = local_repo_path.split(os.path.sep)[-1]
+        print(bcolors.WARNING + f'pull repo:{self.username}/{repo_name} from gitee' + bcolors.ENDC)
+        
+        os.chdir(local_repo_path)
+        os.system('git remote remove origin_gitee')
+        os.system(f'git remote add origin_gitee https://{self.username}:{self.token}@gitee.com/{self.username}/{repo_name}.git')
+        
+        result = subprocess.run(['git', 'symbolic-ref', '--short', 'HEAD'], capture_output=True, text=True, encoding='utf-8')
+        current_branch = result.stdout.strip()
+        os.system(f'git pull origin_gitee {current_branch}')
+        os.system('git remote remove origin_gitee')
+        os.chdir('..')
+        
+        print(bcolors.OKGREEN + 'pull from gitee success' + bcolors.ENDC)
+    
+    def _repo_exists(self, repo_name: str) -> bool:
+        """ check if repo exists """
+        url = f"{self._api}/repos/{self.username}/{repo_name}/contributors"
+        try:
+            response = self.sess.get(url)
+            if response.status_code == 200:
+                print(f'{bcolors.OKGREEN}repo: {repo_name} is existed. {bcolors.ENDC}')
+                return True
+        except Exception as e:
+            return False
+
+    @classmethod
+    def suitable(cls, extractor: str) -> bool:
+        """check if this extractor is suitable for this platform"""
+        if extractor == 'gitcode':
+            return True
+        else:
+            return False
+        

+ 10 - 0
repo_sync/utils/colors.py

@@ -17,3 +17,13 @@ class bcolors:
     ENDC = '\033[0m'
     BOLD = '\033[1m'
     UNDERLINE = '\033[4m'
+
+
+if __name__=='__main__':
+    print(bcolors.HEADER+"Hello World!"+bcolors.ENDC)
+    print(bcolors.OKBLUE+"Hello World!"+bcolors.ENDC)
+    print(bcolors.OKGREEN+"Hello World!"+bcolors.ENDC)
+    print(bcolors.WARNING+"Hello World!"+bcolors.ENDC)
+    print(bcolors.FAIL+"Hello World!"+bcolors.ENDC)
+    print(bcolors.BOLD+"Hello World!"+bcolors.ENDC)
+    print(bcolors.UNDERLINE+"Hello World!"+bcolors.ENDC)

File diff suppressed because it is too large
+ 0 - 1
scripts/sync.xys


Some files were not shown because too many files changed in this diff