Minor fixes

This commit is contained in:
Maxim Khomutov 2022-07-22 16:06:14 +03:00 committed by SantaSpeen
parent 999ca70916
commit e86c40a610

41
main.py
View File

@ -9,7 +9,7 @@
# Удобная и встроенная в Python библиотека логирования. Подробнее: https://docs.python.org/3.10/library/logging.html # Удобная и встроенная в Python библиотека логирования. Подробнее: https://docs.python.org/3.10/library/logging.html
import logging import logging
# Встроенные библиотеки. Нужны для некоторых функций прогрммы. # Встроенные библиотеки. Нужны для некоторых функций программы.
import os import os
import sys import sys
import time import time
@ -70,7 +70,7 @@ class GitSwitch:
self.session: requests.Session = None self.session: requests.Session = None
def authorization(self) -> NoReturn: def authorization(self) -> NoReturn:
""" Авторизуемся и получаем список репозиториев с GitHub """ """ Авторизуемся и получаем список репозиториев из GitHub """
gf_session = GitflicAuth(self.gf_token) gf_session = GitflicAuth(self.gf_token)
self.gf = Gitflic(gf_session) self.gf = Gitflic(gf_session)
self.session = gf_session.session self.session = gf_session.session
@ -84,7 +84,7 @@ class GitSwitch:
self.get_login = lambda repo_info: repo_info.organization.login if repo_info.organization else self.gh_user_name self.get_login = lambda repo_info: repo_info.organization.login if repo_info.organization else self.gh_user_name
def get_github_repo(self, repo_info) -> Union[Repo, None]: def get_github_repo(self, repo_info) -> Union[Repo, None]:
""" Получаем репозиторий с GitHub """ """ Получаем репозиторий из GitHub """
login = self.get_login(repo_info) login = self.get_login(repo_info)
name = repo_info.name name = repo_info.name
path = os.path.join(self.clone_folder, login, name) path = os.path.join(self.clone_folder, login, name)
@ -101,18 +101,18 @@ class GitSwitch:
""" Создаём репозиторий на гитфлике """ """ Создаём репозиторий на гитфлике """
login = self.get_login(repo_info) login = self.get_login(repo_info)
title = f"{login}-{repo_info.name}" if login != self.gh_user_name else repo_info.name title = f"{login}-{repo_info.name}" if login != self.gh_user_name else repo_info.name
congfig = { config = {
"title": title, "title": title,
"description": f"{repo_info.description}", "description": f"{repo_info.description}",
"alias": title, "alias": title,
"language": f"{repo_info.language}", "language": f"{repo_info.language}",
"private": "true" "private": "true"
} }
repo_object = self.session.post("https://api.gitflic.ru/project", json=congfig) repo_object = self.session.post("https://api.gitflic.ru/project", json=config)
code = repo_object.status_code code = repo_object.status_code
if code != 200: if code != 200:
log.error(f"GitGlic api send {repo_object.status_code} HTTP Error.") log.error(f"GitFlic api send {repo_object.status_code} HTTP Error.")
if code == 429: if code == 429:
log.info("Waiting 10 seconds and try again.") log.info("Waiting 10 seconds and try again.")
time.sleep(10) time.sleep(10)
@ -121,7 +121,7 @@ class GitSwitch:
return return
jsn = repo_object.json() jsn = repo_object.json()
log.info(f"Sucsessfully created new empty repo: {jsn['httpTransportUrl'][:-3]}") log.info(f"Successfully created new empty repo: {jsn['httpTransportUrl'][:-3]}")
return jsn return jsn
@staticmethod @staticmethod
@ -129,10 +129,11 @@ class GitSwitch:
""" Пушим репозиторий на GitFlic """ """ Пушим репозиторий на GitFlic """
try: try:
remote = repo.create_remote("gitflic", url=url) remote = repo.create_remote("gitflic", url=url)
log.info(f"Pushing repository.")
remote.push(refspec='--all') remote.push(refspec='--all')
return True return True
except Exception as e: except Exception as e:
print(f"Exception while pushing: {e}") log.error(f"Exception while pushing: {e}")
return False return False
def is_skip(self, repo_info) -> bool: def is_skip(self, repo_info) -> bool:
@ -146,12 +147,18 @@ class GitSwitch:
def run(self) -> NoReturn: def run(self) -> NoReturn:
""" Запуск основной части """ """ Запуск основной части """
for repo_info in self.github_repos: for repo_info in self.github_repos:
if self.is_skip(repo_info): continue if self.is_skip(repo_info):
continue
github_repo = self.get_github_repo(repo_info) github_repo = self.get_github_repo(repo_info)
if not github_repo: continue if not github_repo:
continue
gitflic_repo = self.get_gitflic_repo(repo_info) gitflic_repo = self.get_gitflic_repo(repo_info)
if not gitflic_repo: continue if not gitflic_repo:
if self.push_into_gitflic(github_repo, gitflic_repo['sshTransportUrl' if self.use_ssh else 'httpTransportUrl']): continue
if self.push_into_gitflic(
github_repo,
gitflic_repo['sshTransportUrl' if self.use_ssh else 'httpTransportUrl']
):
log.info(f"Repository {self.get_login(repo_info)}/{repo_info.name} successfully cloned.") log.info(f"Repository {self.get_login(repo_info)}/{repo_info.name} successfully cloned.")
def start(self) -> NoReturn: def start(self) -> NoReturn:
@ -167,7 +174,7 @@ class GitSwitch:
continue continue
i += 1 i += 1
log.info(f'GitGub => {self.get_login(repo)} : {repo.name}') log.info(f'GitGub => {self.get_login(repo)} : {repo.name}')
log.info(f"Repositories found: {i+j}. Repositories to copy: {i}. Ignored repositories: {j}.") log.info(f"Repositories found: {i + j}. Repositories to copy: {i}. Ignored repositories: {j}.")
if input("Do you agree to copying these repositories to GitFlic? (y/n) ").lower() != "y": if input("Do you agree to copying these repositories to GitFlic? (y/n) ").lower() != "y":
log.info("Stopped by the user.") log.info("Stopped by the user.")
@ -189,14 +196,14 @@ class GitSwitch:
def main(**kwargs): def main(**kwargs):
log.info("New log start.") log.info("New log start.")
log.info(f"Local time: {time.asctime()}") log.info(f"Local time: {time.asctime()}")
log.info(f"GitSwitch start with: {sys.argv} argumets.") log.info(f"GitSwitch start with: {sys.argv} arguments.")
try: try:
gs = GitSwitch(**kwargs) gs = GitSwitch(**kwargs)
gs.start() gs.start()
except Exception: except Exception as e:
log.exception("GitSwitch send error:") log.exception(f"GitSwitch send error: {e}")
finally: finally:
log.info(f"Exiting at {time.asctime()}\n{'-----'*20}") log.info(f"Exiting at {time.asctime()}\n{'-----' * 20}")
if __name__ == '__main__': if __name__ == '__main__':