Browse Source

Merge branch 'release/1.7.0'

liuyuqi-dellpc 4 months ago
parent
commit
5518ad6a0b

+ 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')

+ 1 - 0
repo_sync/platform/__init__.py

@@ -5,6 +5,7 @@ from .gitea import GiteaIE
 from .gitlab import GitlabIE
 from .gogs import GogsIE
 from .coding import CodingIE
+from .gitcode import GitcodeIE
 
 _ALL_CLASSES = [klass for name, klass in globals().items()
                 if name.endswith('IE')]

+ 24 - 18
repo_sync/platform/coding/coding.py

@@ -138,7 +138,7 @@ class CodingIE(BasePlatform):
             except Exception as e:
                 print(bcolors.FAIL + str(e) + bcolors.ENDC)
         
-    def _get_repo_info(self, repo_name: str):
+    def _repo_exists(self, repo_name: str):
         """get repo list"""
         data = {
             'Action': 'DescribeTeamDepotInfoList',
@@ -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)
@@ -204,7 +211,7 @@ class CodingIE(BasePlatform):
         # get project id
         project = self.get_project_info()
         if project is not None:
-            repo = self._get_repo_info(repo_name=repo_name)
+            repo = self._repo_exists(repo_name=repo_name)
             if repo is None:
                 data = {
                     "Action": "CreateGitDepot",
@@ -220,14 +227,12 @@ 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)
     
     def delete(self, repo_name: str):
             """delete a repo"""
-            repo = self._get_repo_info(repo_name=repo_name)
+            repo = self._repo_exists(repo_name=repo_name)
             if repo is not None:
                 data = {
                     "Action": "DeleteGitDepot",
@@ -274,6 +279,7 @@ class CodingIE(BasePlatform):
             local_repo_path = local_repo_path[:-1]
         repo_name = local_repo_path.split(os.path.sep)[-1]
         print(f'{bcolors.OKGREEN}push repo:{self.username}/{repo_name} to coding{bcolors.ENDC}')
+        self.create_repo(repo_name=repo_name)
         os.chdir(local_repo_path)
 
         os.system('git remote remove origin_coding')

+ 123 - 0
repo_sync/platform/gitcode.py

@@ -0,0 +1,123 @@
+#!/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 和 gitcode 类似
+'''
+from .base_platform import BasePlatform
+from repo_sync.utils.colors import bcolors
+import os, subprocess
+class GitcodeIE(BasePlatform):
+    """ gitcode platform """
+    
+    def __init__(self, username:str, token:str, host:str =None ,params: dict = None) -> None:
+        super().__init__(username=username,token=token)
+        self.sess.headers.update(
+            {
+                'Accept': 'application/json',
+                'Content-Type': 'application/json',
+                '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',
+                'Authorization': f'Bearer {self.token}',
+            }
+        )
+        self._host = 'https://api.gitcode.com' if host is None else host
+        self._api = self._host + '/api/v5'
+        self.repo_private = True if params.get('gitcode_private', "true").lower() == 'true' else False
+
+    
+    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 != 200:
+                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 gitcode successfully!' + bcolors.ENDC)
+        else:
+            print(bcolors.FAIL + f'Failed to delete repository: {repo_name} from gitcode. 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 gitcode' + bcolors.ENDC)
+        self.create_repo(repo_name)
+        os.chdir(local_repo_path)
+        os.system('git remote remove origin_gitcode')
+        os.system(f'git remote add origin_gitcode https://{self.username}:{self.token}@gitcode.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_gitcode {current_branch}')
+        os.system(f'git push -u origin_gitcode {current_branch}')
+        os.system('git remote remove origin_gitcode')
+        os.chdir('..')
+        
+        print(bcolors.OKGREEN + 'push to gitcode 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 gitcode' + bcolors.ENDC)
+        
+        os.chdir(local_repo_path)
+        os.system('git remote remove origin_gitcode')
+        os.system(f'git remote add origin_gitcode https://{self.username}:{self.token}@gitcode.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_gitcode {current_branch}')
+        os.system('git remote remove origin_gitcode')
+        os.chdir('..')
+        
+        print(bcolors.OKGREEN + 'pull from gitcode 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
+        

+ 29 - 12
repo_sync/platform/gitee.py

@@ -24,17 +24,18 @@ class GiteeIE(BasePlatform):
         self.repo_private = True if params.get('gitee_private', "true").lower() == 'true' else False
     
     def create_repo(self, repo_name: str):
-        """create a repo"""        
-        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)
+        """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"""
@@ -92,7 +93,7 @@ class GiteeIE(BasePlatform):
             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')
@@ -107,6 +108,22 @@ class GiteeIE(BasePlatform):
         
         print(bcolors.OKGREEN + 'push to gitee success' + bcolors.ENDC)
     
+    def _repo_exists(self, repo_name: str):
+        """check if a repo exists
+        不存在,{
+                "message": "Not Found Project"
+                }
+        存在:返回 repo 数据
+        """
+        url = f'{self._api}/repos/{self.username}/{repo_name}'
+        try:
+            response = self.sess.get(url)
+            if response.status_code == 200 and response.json()['message'] != 'Not Found Project':
+                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"""

+ 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