Browse Source

完成控制台带颜色输出

liuyuqi-dellpc 8 months ago
parent
commit
642a652125

+ 6 - 6
repo_sync/platform/coding/coding.py

@@ -235,7 +235,7 @@ class CodingIE(BasePlatform):
                     }
                 r = self.sess.post(self.url, json=data)
                 if r.status_code == 200:
-                    print(f'delete repo {repo_name} success', data,r.json())
+                    print(f'{bcolors.OKGREEN}delete repo {repo_name} success{bcolors.ENDC}', data, r.json())
                     return True
                 else:
                     return False
@@ -247,7 +247,7 @@ class CodingIE(BasePlatform):
         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(f'pull repo:{self.username}/{repo_name} from coding')
+        print(f'{bcolors.OKGREEN} pull repo:{self.username}/{repo_name} from coding{bcolors.ENDC}')
         os.chdir(local_repo_path)
         try:
             os.system('git remote remove origin_coding')
@@ -262,7 +262,7 @@ class CodingIE(BasePlatform):
         os.system(f'git pull origin_coding {current_branch}')
         os.system('git remote remove origin_coding')
         os.chdir('..')
-        print('pull success')
+        print(f'{bcolors.OKGREEN}pull from coding success{bcolors.ENDC}')
 
     def push(self, local_repo_path: str):
         ''' push a local repo to remote
@@ -273,7 +273,7 @@ class CodingIE(BasePlatform):
         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(f'push repo:{self.username}/{repo_name} to coding')
+        print(f'{bcolors.OKGREEN}push repo:{self.username}/{repo_name} to coding{bcolors.ENDC}')
         os.chdir(local_repo_path)
 
         os.system('git remote remove origin_coding')
@@ -288,7 +288,7 @@ class CodingIE(BasePlatform):
         os.system(f'git push -u origin_coding {current_branch}')
         os.system('git remote remove origin_coding')
         os.chdir('..')
-        print('push success')
+        print(f'{bcolors.OKGREEN}push to coding success{bcolors.ENDC}')
 
     def clone(self, repo_path: str):
         ''' clone all repo from remote
@@ -300,7 +300,7 @@ class CodingIE(BasePlatform):
                 cmd = f'git clone https://{self.username}:{self.token}@e.coding.net/{self.username}/{self.project_name}/{repo["Name"]}.git {repo_path}/{repo["Name"]}'
                 # print(cmd)
                 os.system(cmd)
-                print(f'clone repo:{repo["Name"]} success')
+                print(f'{bcolors.OKGREEN}clone success{bcolors.ENDC}')
             except Exception as e:
                 pass
 

+ 22 - 22
repo_sync/platform/github.py

@@ -26,19 +26,20 @@ class GithubIE(BasePlatform):
 
     def create_repo(self, repo_name: str):
         """create a repo"""
-        url = f'{self._host}/user/repos'
-        payload = {
-            'name': repo_name,
-            'private': self.repo_private,
-            'has_issues': True,
-            'has_projects': False,
-            'has_wiki': False,
-        }
-        r = self.sess.post(url, data=json.dumps(payload))
-        if r.status_code != 201:
-            print(f'{bcolors.FAIL}create repo {repo_name} failed, status code {r.status_code}{bcolors.ENDC}')
-            return
-        print(f'{bcolors.OKGREEN}create repo {repo_name} success{bcolors.ENDC}')
+        if not self._repo_exists(repo_name=repo_name):
+            url = f'{self._host}/user/repos'
+            payload = {
+                'name': repo_name,
+                'private': self.repo_private,
+                'has_issues': True,
+                'has_projects': False,
+                'has_wiki': False,
+            }
+            r = self.sess.post(url, data=json.dumps(payload))
+            if r.status_code != 201:
+                print(f'{bcolors.FAIL}create repo {repo_name} failed, status code {r.status_code}{bcolors.ENDC}')
+                return
+            print(f'{bcolors.OKGREEN}create repo {repo_name} success{bcolors.ENDC}')
 
     def delete(self, repo_name: str):
         """delete a repo, maybe request a confirm by input"""
@@ -50,13 +51,13 @@ class GithubIE(BasePlatform):
             print(f'{bcolors.FAIL}Failed to delete repository: {repo_name} from github. Error {response.status_code}: {response.text}{bcolors.ENDC}')
         print(f'{bcolors.WARNING}delete repo: {repo_name} from github success{bcolors.ENDC}')
 
-    def repo_exists(self, repo_name: str):
+    def _repo_exists(self, repo_name: str):
         """check if a repo exists"""
         url = f'{self._host}/repos/{self.username}/{repo_name}'
-        print(f'{bcolors.INFO}check repo: {repo_name}{bcolors.ENDC}')
         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
@@ -66,7 +67,7 @@ class GithubIE(BasePlatform):
         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(f'{bcolors.INFO}pull repo: {self.username}/{repo_name} from github{bcolors.ENDC}')
+        print(f'{bcolors.OKGREEN}pull repo: {self.username}/{repo_name} from github{bcolors.ENDC}')
         
         os.chdir(local_repo_path)
         os.system('git remote remove origin_github')
@@ -80,16 +81,15 @@ class GithubIE(BasePlatform):
         os.system(f'git pull origin_github {current_branch}')
         os.system('git remote remove origin_github')
         os.chdir('..')
-        print(f'{bcolors.SUCCESS}pull from github success{bcolors.ENDC}')
+        print(f'{bcolors.OKGREEN}pull from github success{bcolors.ENDC}')
 
     def push(self, local_repo_path: str):
         """push a local repo to remote"""
         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(f'{bcolors.INFO}push repo: {self.username}/{repo_name} to github{bcolors.ENDC}')
-        if not self.repo_exists(repo_name):
-            self.create_repo(repo_name)
+        print(f'{bcolors.OKGREEN}push repo: {self.username}/{repo_name} to github{bcolors.ENDC}')
+        self.create_repo(repo_name)
         os.chdir(local_repo_path)
         os.system('git remote remove origin_github')
         os.system(
@@ -104,12 +104,12 @@ class GithubIE(BasePlatform):
         os.system(f'git push -u origin_github {current_branch}')
         os.system('git remote remove origin_github')
         os.chdir('..')
-        print(f'{bcolors.SUCCESS}push to github success{bcolors.ENDC}')
+        print(f'{bcolors.OKGREEN}push to github success{bcolors.ENDC}')
 
     def get_repo_list(self) -> list:
         """get all repo list of a user"""
         if os.path.exists(self.repo_list_path):
-            print(f'{bcolors.INFO}repo is exist, please read from {self.repo_list_path} file{bcolors.ENDC}')
+            print(f'{bcolors.OKGREEN}repo is exist, please read from {self.repo_list_path} file{bcolors.ENDC}')
             with open(self.repo_list_path, 'r', newline='') as csvfile:
                 reader = csv.reader(csvfile)
                 for row in reader:

+ 44 - 26
repo_sync/platform/gitlab.py

@@ -27,22 +27,23 @@ class GitlabIE(BasePlatform):
         """create a repo
         and save project id to csv: gitlab_repo_list.csv
         """
-        url = f"{self.host}/api/v4/projects"
-        payload = {
-            "name": repo_name,
-            "visibility": self.repo_private,
-        }
-        r = self.sess.post(url, data=json.dumps(payload))
-        if r.status_code != 201:
-            print(f"{bcolors.FAIL}create repo {repo_name} failed, status code {r.status_code}{bcolors.ENDC}")
-            return
-        print(f"{bcolors.OKGREEN}create repo {repo_name} success{bcolors.ENDC}")
-        for repo in self.repos:
-            if repo.name == repo_name:
-                repo.url = r.json()["web_url"]
-                repo.id = r.json()["id"]
-                break
-        self.save_csv()
+        if not self._repo_exists(repo_name):
+            url = f"{self.host}/api/v4/projects"
+            payload = {
+                "name": repo_name,
+                "visibility": self.repo_private,
+            }
+            r = self.sess.post(url, data=json.dumps(payload))
+            if r.status_code != 201:
+                print(f"{bcolors.FAIL}create repo {repo_name} failed, status code {r.status_code}{bcolors.ENDC}")
+                return
+            print(f"{bcolors.OKGREEN}create repo {repo_name} success{bcolors.ENDC}")
+            # for repo in self.repos:
+            #     if repo.name == repo_name:
+            #         repo.url = r.json()["web_url"]
+            #         repo.id = r.json()["id"]
+            #         break
+            # self.save_csv()
     
     def delete(self, repo_name: str):
         """delete a repo,
@@ -51,15 +52,18 @@ class GitlabIE(BasePlatform):
         project_id = ""
         r = self.sess.get(f"{self.host}/api/v4/users/{self.username}/projects?search={repo_name}")
         if r.status_code == 200:
-            project_id = r.json()[0]["id"]
-            url = f"{self.host}/api/v4/projects/{project_id}"
-            response = self.sess.delete(url)
-            if response.status_code == 202:
-                print(f"{bcolors.OKGREEN}Repository: {repo_name} deleted from gitlab successfully!{bcolors.ENDC}")
-            else:
-                print(
-                    f"{bcolors.FAIL}Failed to delete repository: {repo_name} from gitlab. Error {response.status_code}: {response.text}{bcolors.ENDC}"
-                )
+            try:
+                project_id = r.json()[0]["id"]
+                url = f"{self.host}/api/v4/projects/{project_id}"
+                response = self.sess.delete(url)
+                if response.status_code == 202:
+                    print(f"{bcolors.OKGREEN}Repository: {repo_name} deleted from gitlab successfully!{bcolors.ENDC}")
+                else:
+                    print(
+                        f"{bcolors.FAIL}Failed to delete repository: {repo_name} from gitlab. Error {response.status_code}: {response.text}{bcolors.ENDC}"
+                    )
+            except Exception as e:
+                print(f"{bcolors.FAIL}Failed to delete repository: {repo_name} from gitlab. Error {e}, check repo is exist first.{bcolors.ENDC}")
         else:
             print(f"{bcolors.FAIL}Failed to delete repository: {repo_name} from gitlab. Error {r.status_code}: {r.text}{bcolors.ENDC}")
     
@@ -132,7 +136,21 @@ class GitlabIE(BasePlatform):
     
     def clone(self):
         pass
-    
+
+    def _repo_exists(self, repo_name: str):
+        """ check if a repo exists
+        if not exist, return [] empty list
+        """
+        project_id = ""
+        r = self.sess.get(f"{self.host}/api/v4/users/{self.username}/projects?search={repo_name}")
+        if r.status_code == 200:
+            try:
+                project_id = r.json()[0]["id"]
+                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"""

+ 6 - 5
repo_sync/repo_sync.py

@@ -69,6 +69,7 @@ class RepoSync(object):
                 self.repos.append(repo)
         except Exception as e:
             print(f"{bcolors.OKGREEN}skip {path} because of {e}{bcolors.ENDC}")
+
     def run(self):
         '''
         run repo
@@ -94,13 +95,13 @@ class RepoSync(object):
                         repo = Repo()
                         repo.__dict__ = row
                         if command == 'create':
-                            current_platform(username,token, host, self.params).create_repo(repo.name)
+                            current_platform(username, token, host, self.params).create_repo(repo.name)
                         if command == 'push':
-                            current_platform(username,token, host, self.params).push(repo.local_path)
+                            current_platform(username, token, host, self.params).push(repo.local_path)
                         elif command == 'delete':
-                            current_platform(username,token, host, self.params).delete(repo.name)
-                        elif command =='pull':
-                            current_platform(username,token, host, self.params).pull(repo.local_path)
+                            current_platform(username, token, host, self.params).delete(repo.name)
+                        elif command == 'pull':
+                            current_platform(username, token, host, self.params).pull(repo.local_path)
             else:
                 logging.info(
                     'repo list is not exist, please run list_local command first'