75 lines
2.3 KiB
Python
75 lines
2.3 KiB
Python
import os
|
|
from git import Repo, InvalidGitRepositoryError, RemoteProgress, GitCommandError
|
|
from config import cfg
|
|
import logging as log
|
|
|
|
|
|
def check_remote_repo(repo: Repo):
|
|
log.info("check remote repo ")
|
|
if cfg.git.branch not in [r.name for r in repo.remotes]:
|
|
repo.create_remote(
|
|
name=cfg.git.branch,
|
|
url=f"{cfg.git.protocol}://{cfg.git.username}:"
|
|
f"{cfg.git.token}@{cfg.git.remote}",
|
|
)
|
|
log.info("set remote repo %r", cfg.git.branch)
|
|
|
|
remote = repo.remote(name=cfg.git.branch)
|
|
remote.fetch()
|
|
|
|
repo.git.merge(f"{cfg.git.branch}/{cfg.git.branch}")
|
|
log.info(
|
|
"merge from remote repo ",
|
|
)
|
|
|
|
else:
|
|
remote = repo.remote(name=cfg.git.branch)
|
|
remote.set_url(
|
|
f"{cfg.git.protocol}://{cfg.git.username}:"
|
|
f"{cfg.git.token}@{cfg.git.remote}"
|
|
)
|
|
log.info("update remote repo url %r", cfg.git.branch)
|
|
|
|
|
|
def check_bcp_repo(path: str = cfg.bcp.dir) -> None:
|
|
log.info("check local repo %r", path)
|
|
try:
|
|
repo = Repo(path)
|
|
log.info("local repo exists %r", path)
|
|
if cfg.git.push:
|
|
check_remote_repo(repo)
|
|
|
|
except InvalidGitRepositoryError:
|
|
repo = Repo.init(path=path, initial_branch=cfg.git.branch)
|
|
log.info("init repo in %r", path)
|
|
with repo.config_writer() as config:
|
|
config.set_value("user", "name", cfg.git.user)
|
|
config.set_value("user", "email", cfg.git.mail)
|
|
if cfg.git.push:
|
|
check_remote_repo(repo)
|
|
|
|
except Exception as e:
|
|
log.warning("Error: %r", e)
|
|
|
|
|
|
def add_file_and_commit(file_name: str) -> None:
|
|
repo = Repo(cfg.bcp.dir)
|
|
if file_name in repo.untracked_files:
|
|
repo.git.add(file_name)
|
|
log.info("%r added in repo", file_name)
|
|
repo.index.commit("add file %s" % file_name)
|
|
|
|
if bool(repo.git.diff(file_name)):
|
|
repo.index.add([file_name])
|
|
repo.index.commit("update file %s" % file_name)
|
|
log.info("change in %r commited", file_name)
|
|
else:
|
|
log.info("no changed in file %r", file_name)
|
|
|
|
|
|
def push_to_remote():
|
|
repo = Repo(cfg.bcp.dir)
|
|
remote = repo.remote(name=cfg.git.branch)
|
|
remote.push(refspec=f"{cfg.git.branch}:{cfg.git.branch}")
|
|
log.info("push to remote repo %r", cfg.git.branch)
|