Добавлен прогрессбар при скачивании.

Множественные исправления по получению данных из репозитория
master3.3
Mike khiretskiy 10 years ago
parent fd2f069396
commit 1b2ad0e41d

@ -19,33 +19,86 @@ import re
import sys
import time
from os import path
from calculate.lib.utils.files import process,getProgPath,STDOUT,removeDir
from calculate.lib.utils.files import (process,getProgPath,STDOUT,removeDir,
processProgress)
class UpdateError(Exception):
"""Update Error"""
class CloneRepError(Exception):
"""Clone repository error"""
class GitError(Exception):
"""Git Error"""
def __init__(self, msg, addon=None):
self.message = msg
self.addon = addon
Exception.__init__(self,msg)
from calculate.lib.cl_lang import setLocalTranslate,getLazyLocalTranslate
setLocalTranslate('cl_update3',sys.modules[__name__])
__ = getLazyLocalTranslate(_)
class Update:
"""Основной объект для выполнения действий связанных с обновлением системы
class PercentProgress(processProgress):
"""
Объект выдает прогресс, ища в выводе \d+%
Args:
part: количество прогрессов в программе
delimeter: разделители строк по умолчанию \n и \r
cachefilter: фильтр вывода программы (регулярная строка)
"""
def init(self,*args,**kwargs):
self.rePerc = re.compile("(\d+)%",re.S)
self.part = kwargs.get("part",1)
self.add_offset = 100 / self.part
self.offset = 0
self.stderr = STDOUT
self.delimeter = re.compile("[%s]"%kwargs.get("delimeter","\n\r"))
self.cachedata = re.compile(kwargs.get("cachefilter",
"((?:error|warning|fatal):.*)"))
def processInit(self):
self.percent = 0
self.showval = 0
return 0
def processEnd(self):
self.percent = 100
return 100
def processString(self,strdata):
match = self.rePerc.search(strdata)
resSearch = self.cachedata.search(strdata)
if resSearch:
self.cacheresult.append(resSearch.group(1))
if match:
percent = int(match.group(1))
if percent < self.percent:
self.offset = self.offset + self.add_offset
percent = percent / self.part
if percent != self.percent:
self.percent = percent
showval = min(99,self.percent + self.offset)
if showval != self.showval:
self.showval = showval
return self.showval
class Git:
"""
Объект для управление git репозиторием
"""
def __init__(self):
self._git = self.__getGit()
def _checkExistsRep(self,rpath):
"""
Проверить путь на наличие репозитория
"""
if path.exists(rpath):
if not path.isdir(rpath):
raise UpdateError(
raise GitError(
_("Repository {path} is not directory").format(
path=rpath))
if not path.isdir(self.__gitDir(rpath)):
raise UpdateError(
raise GitError(
_("Repository {path} is not git").format(
path=rpath))
return True
@ -57,13 +110,13 @@ class Update:
"""
git = getProgPath("/usr/bin/git")
if not git:
raise UpdateError(_("Git utility is not found"))
raise GitError(_("Git utility is not found"))
return git
def __gitDir(self,rpath):
return path.join(rpath,".git")
def _cloneRepository(self, url, rpath, branch):
def _cloneRepository(self, url, rpath, branch, cb_progress=None):
"""
Сделать локальную копию репозитория
@ -72,21 +125,26 @@ class Update:
rpath: куда сохранять репозиторий
branch: ветка на которую необходимо переключиться
"""
git = self.__getGit()
gitClone = process(git,"clone","-q","--no-single-branch",
"--depth=1","-b",branch,url,rpath,stderr=STDOUT)
if cb_progress:
gitClone = PercentProgress(self._git,"clone","-q",
"--no-single-branch","--progress","--verbose",
"--depth=1","-b",branch,url,rpath,part=3,stderr=STDOUT)
for perc in gitClone.progress():
cb_progress(perc)
else:
gitClone = process(self._git,"clone","-q","--no-single-branch",
"--depth=1","-b",branch,url,rpath,stderr=STDOUT)
if gitClone.failed():
error = gitClone.read()
if "Remote branch %s not found"%branch in error:
raise UpdateError(
raise GitError(
_("Branch {branch} not found in {url} repository").format(
branch=branch,url=url))
self.printERROR(error)
raise UpdateError(_("Failed to clone {url} repository").format(
url=url))
raise GitError(_("Failed to clone {url} repository").format(
url=url),error)
return True
def _cloneRevRepository(self, url, rpath, branch,revision):
def _cloneRevRepository(self, url, rpath, branch,revision,cb_progress=None):
"""
Сделать локальную копию репозитория с указанной ревизией
@ -95,72 +153,114 @@ class Update:
rpath: куда сохранять репозиторий
branch: ветка на которую необходимо переключиться
revision: если указана - сделать ревизию текущей
Return:
Возвращает True если клонирование произведено с установкой на
указанную ревизию. False если клонирование произведено с
установкой на последнюю ревизию. В остальных случаях GitError
"""
git = self.__getGit()
git_dir = self.__gitDir(rpath)
for cmd in (["init",rpath],
["remote","add","origin",url],
["fetch","--depth=1"],
["checkout","-b",branch,revision],
["branch",branch,"-u","origin/%s"%branch]):
if cmd[0] == "init":
gitCmd = process(*[git]+cmd,stderr=STDOUT)
error = []
def command(cmd,startpart=0):
"""
Выполнить одну из команд необходимой для клонирования репозитория
"""
commands = {# инициализация пустого репозитория
'init': ["init",rpath],
# подключить указанный удаленный как origin
'add_remote':["remote","add","origin",url],
# скачать последние коммиты веток
'fetchshallow': ["fetch","--depth=1"],
# проверить есть указанный коммит
'has_revision': ["log","-n1",revision],
# проверить есть указанный коммит
'has_branch': ["log","-n1","remotes/origin/%s"%branch],
# получить ревизию из revs тэгов
'get_rev_tag': ["fetch","--depth=1","origin",
"+refs/heads/*:refs/remotes/origin/*",
"+refs/revs/%s"%revision],
# переключиться на указанную ревизию указанной веткой
'checkout_revision': ["checkout","-b",branch,revision],
# переключить на указанную ветку
'checkout': ["checkout",branch],
# установить upstream для локальной ветки
'set_track': ["branch",branch,'-u',"origin/%s"%branch]
}
if cmd == "init":
wholeCommand = [self._git]+commands[cmd]
else:
gitCmd = process(*[git,"--git-dir",git_dir,
"--work-tree",rpath]+cmd,stderr=STDOUT)
wholeCommand = [self._git,"--git-dir",git_dir,
"--work-tree",rpath]+commands[cmd]
if cb_progress and commands[cmd][0] == "fetch":
gitClone = PercentProgress(*wholeCommand+["--progress","--verbose"],
part=3,stderr=STDOUT)
for perc in gitClone.progress():
cb_progress(perc)
else:
gitCmd = process(*wholeCommand,stderr=STDOUT)
if gitCmd.failed():
error = gitCmd.read()
if "reference is not a tree" in error:
raise UpdateError(
_("Commit {revision} not found in {url} repository"
).format(revision=revision,url=url))
elif "upstream branch '%s' does not exist"%("origin/%s"%branch):
raise UpdateError(
error.append(gitCmd.read())
return False
return True
# получить последние коммиты из удаленного репозитория
if command("init") and command("add_remote"):
if command("get_rev_tag") or command("fetchshallow"):
if not command("has_branch"):
raise GitError(
_("Branch {branch} not found in {url} repository"
).format(branch=branch,url=url))
else:
self.printERROR(error)
raise UpdateError(_("Failed to clone {url} repository").format(
url=url))
return True
# если среди коммитов есть указанный коммит
if command("has_revision"):
# переключаемся на нужный коммита, устанавливаем связь
if command("checkout_revision") and command("set_track"):
return True
elif command("checkout"):
return False
raise GitError(_("Failed to clone {url} repository").format(
url=url),error[-1])
def _pullRepository(self,rpath,quiet_error=False):
def _pullRepository(self,rpath,quiet_error=False,cb_progress=None):
"""
Обновить репозиторий до последней версии
"""
git = self.__getGit()
gitPull = process(git,"--git-dir",self.__gitDir(rpath),
gitPull = process(self._git,"--git-dir",self.__gitDir(rpath),
"pull","--ff-only",stderr=STDOUT)
if gitPull.failed():
if not quiet_error:
self.printERROR(gitPull.read())
raise UpdateError(
error = gitPull.read()
raise GitError(
_("Failed to update repository in {rpath}").format(
rpath=rpath))
rpath=rpath),error)
return False
return True
def _fetchRepository(self,rpath):
def _fetchRepository(self, rpath, cb_progress=None):
"""
Получить изменения из удаленно репозитория
"""
git = self.__getGit()
gitFetch = process(git,"--git-dir",self.__gitDir(rpath),
if cb_progress:
gitFetch = PercentProgress(self._git,"--git-dir",self.__gitDir(rpath),
"fetch","--progress","--verbose",part=3,stderr=STDOUT)
for perc in gitFetch.progress():
cb_progress(perc)
else:
gitFetch = process(self._git,"--git-dir",self.__gitDir(rpath),
"fetch",stderr=STDOUT)
if gitFetch.failed():
self.printERROR(gitFetch.read())
raise UpdateError(
error = gitFetch.read()
raise GitError(
_("Failed to update repository in {rpath}").format(
rpath=rpath))
rpath=rpath),error)
return True
def _checkChanges(self,rpath):
"""
Проверить наличие изменений пользователем файлов в репозитории
"""
git = self.__getGit()
git_dir = self.__gitDir(rpath)
git_status = process(git,"--git-dir",git_dir,"--work-tree",rpath,
git_status = process(self._git,"--git-dir",git_dir,"--work-tree",rpath,
"status","--porcelain",stderr=STDOUT)
if git_status.success():
for i in git_status:
@ -169,7 +269,7 @@ class Update:
else:
return True
else:
raise UpdateError(
raise GitError(
_("Wrong repository in {rpath} directory").format(
rpath=rpath))
@ -206,14 +306,13 @@ class Update:
"""
Получить текущий коммит в репозитории
"""
git = self.__getGit()
git_dir = self.__gitDir(rpath)
git_show = process(git,"--git-dir",git_dir,"show","--format=format:%H",
git_show = process(self._git,"--git-dir",git_dir,"show","--format=format:%H",
"--quiet",stderr=STDOUT)
if git_show.success():
return git_show.read().strip()
else:
raise UpdateError(
raise GitError(
_("Failed to get status of repository in "
"{rpath} directory").format(
rpath=rpath))
@ -225,20 +324,19 @@ class Update:
Returns:
Словарь выдаваемый функцией _parseStatusInfo
"""
git = self.__getGit()
git_dir = self.__gitDir(rpath)
git_status = process(git,"--git-dir",git_dir,"--work-tree",rpath,
git_status = process(self._git,"--git-dir",git_dir,"--work-tree",rpath,
"status","-b","--porcelain",stderr=STDOUT)
if git_status.success():
retDict = self._parseStatusInfo(git_status.read())
if not retDict:
raise UpdateError(
raise GitError(
_("Failed to get status of repository in "
"{rpath} directory").format(
rpath=rpath))
return retDict
else:
raise UpdateError(
raise GitError(
_("Wrong repository in {rpath} directory").format(
rpath=rpath))
@ -252,17 +350,19 @@ class Update:
to_rev: откатить все изменения до определенной ревизии
info: использовать уже полученную информация об изменения в репозитории
"""
git = self.__getGit()
git_dir = self.__gitDir(rpath)
if to_origin and not info:
info = self._getStatusInfo(rpath)
commit = (info['origin'] if to_origin else to_rev) or "HEAD"
git_reset = process(git,"--git-dir",git_dir,"--work-tree",rpath,
git_reset = process(self._git,"--git-dir",git_dir,"--work-tree",rpath,
"reset","--hard", commit, stderr=STDOUT)
git_clean = process(git,"--git-dir",git_dir,"--work-tree",rpath,
git_clean = process(self._git,"--git-dir",git_dir,"--work-tree",rpath,
"clean","-fd",stderr=STDOUT)
if git_reset.failed() or git_clean.failed():
raise UpdateError(_("Failed to clean {rpath} repository").format(
print "ERROR:"
print git_reset.read()
print git_clean.read()
raise GitError(_("Failed to clean {rpath} repository").format(
rpath=rpath))
def _getBranch(self,rpath):
@ -275,56 +375,83 @@ class Update:
"""
Сменить ветку
"""
git = self.__getGit()
git_dir = self.__gitDir(rpath)
git_checkout = process(git,"--git-dir",git_dir,
git_checkout = process(self._git,"--git-dir",git_dir,
"--work-tree", rpath,
"checkout","-f",branch, stderr=STDOUT)
if git_checkout.failed():
error = git_checkout.read()
if "pathspec '%s' did not match"%branch in error:
raise UpdateError(
raise GitError(
_("Branch {branch} not found in {rpath} repository").format(
branch=branch,rpath=rpath))
self.printERROR(error)
raise UpdateError(
raise GitError(
_("Failed to change branch to {branch} in "
"{rpath} repository").format(branch=branch,
rpath=rpath))
rpath=rpath),error)
return True
def syncRepositories(self,repositories):
class Update:
"""Основной объект для выполнения действий связанных с обновлением системы
"""
def _syncRepository(self,name,url,rpath,revision,branch,
cb_progress=None):
"""
Синхронизировать репозиторий
"""
git = Git()
if not git._checkExistsRep(rpath):
if revision == "last":
git._cloneRepository(url, rpath, branch,
cb_progress=cb_progress)
else:
git._cloneRevRepository(url, rpath, branch, revision,
cb_progress=cb_progress)
else:
# если нужно обновиться до конкретной ревизии
if revision != "last":
if revision == git._getCurrentCommit(rpath):
if git._getBranch(rpath) == branch:
return
# получить изменения из удаленного репозитория
git._fetchRepository(rpath,cb_progress=cb_progress)
# если текущая ветка не соответствует нужной
repInfo = git._getStatusInfo(rpath)
if repInfo['branch'] != branch:
# меняем ветку
git._checkoutBranch(rpath,branch)
if revision == "last":
git._resetRepository(rpath, to_origin=True)
else:
git._resetRepository(rpath, to_rev=revision)
return True
def syncRepositories(self,repname,clean_on_error=True):
"""
Синхронизировать репозитории
"""
# TODO: удалять не git репозиторий
# TODO: прогресс скачивания
# TODO: оновление shallow репозитория возможно придется
# скачивать конкретную ревизию через refs/revs
# TODO: прогресс скачивания (обновление shallow)
dv = self.clVars
for name, url, rpath, revision, branch in (reversed(
filter(lambda x:x[0] in repositories,
dv.Get('cl_update_rep_data')))):
if not self._checkExistsRep(rpath):
if revision == "last":
self._cloneRepository(url, rpath, branch)
else:
self._cloneRevRepository(url, rpath, branch, revision)
else:
# если нужно обновиться до конкретной ревизии
if revision != "last":
if revision == self._getCurrentCommit(rpath):
if self._getBranch(rpath) == branch:
continue
# получить изменения из удаленного репозитория
self._fetchRepository(rpath)
# если текущая ветка не соответствует нужной
repInfo = self._getStatusInfo(rpath)
if repInfo['branch'] != branch:
# меняем ветку
self._checkoutBranch(rpath,branch)
if revision == "last":
self._resetRepository(rpath, to_origin=True,
info=repInfo)
else:
self._resetRepository(rpath, to_rev=revision,
info=repInfo)
url, rpath, revision, branch = (
dv.Select(["cl_update_rep_url","cl_update_rep_path",
"cl_update_rep_rev","cl_update_branch_name"],
where="cl_update_rep_name",eq=repname,limit=1))
self.addProgress()
if clean_on_error:
try:
self._syncRepository(repname,url,rpath,revision,branch,
cb_progress=self.setProgress)
return True
except GitError as e:
if e.addon:
self.printWARNING(str(e.addon))
self.printWARNING(str(e))
self.printWARNING(_("Re-fetch {name} repository"
).format(name=name))
removeDir(rpath)
self._syncRepository(name,url,rpath,revision,branch)
return True

@ -20,7 +20,7 @@ from calculate.lib.cl_lang import setLocalTranslate,getLazyLocalTranslate
from calculate.lib.utils.files import FilesError
from calculate.install.install import (MigrationError, TemplatesError,
InstallError)
from calculate.update.update import UpdateError
from calculate.update.update import UpdateError,GitError
setLocalTranslate('cl_update3',sys.modules[__name__])
__ = getLazyLocalTranslate(_)
@ -30,7 +30,7 @@ class ClUpdateAction(Action):
Действие обновление конфигурационных файлов
"""
# ошибки, которые отображаются без подробностей
native_error = (FilesError,UpdateError)
native_error = (FilesError,UpdateError,GitError)
successMessage = None
failedMessage = __("Update failed")
@ -39,8 +39,9 @@ class ClUpdateAction(Action):
# список задач для дейсвия
tasks = [
{'name':'sync_reps',
'message' : __("Syncing {cl_update_sync_rep} repositories"),
'method':'Update.syncRepositories(update.cl_update_sync_rep)',
'foreach':'cl_update_sync_rep',
'message' : __("Syncing {eachvar} repository"),
'method':'Update.syncRepositories(eachvar,cl_update_rep_data)',
'condition':lambda Get:Get('cl_update_sync_rep')
},
{'name':'dispatch',

@ -236,6 +236,11 @@ class VariableClUpdateSyncRep(Variable):
def init(self):
self.help = _("synchronize repositories (all by default)")
self.label = _("Synchronize repositories")
def set(self,value):
orderList = self.Get('cl_update_rep_name')
return sorted(value,key=lambda x:
(orderList.index(x) if x in orderList else -1),reverse=True)
def get(self):
return self.Get('cl_update_rep_name')

@ -20,7 +20,7 @@ from calculate.lib.datavars import VariableError,DataVarsError,DataVars
from calculate.core.server.func import WsdlBase
from calculate.install.install import InstallError
from calculate.update.update import Update,UpdateError
from calculate.update.update import Update,UpdateError,GitError
from utils.cl_update import ClUpdateAction
from calculate.lib.cl_lang import setLocalTranslate,getLazyLocalTranslate
setLocalTranslate('cl_update3',sys.modules[__name__])
@ -54,7 +54,7 @@ class Wsdl(WsdlBase):
# объект переменных
'datavars':"update",
'native_error':(VariableError,DataVarsError,
InstallError),
InstallError,UpdateError,GitError),
# значения по умолчанию для переменных этого метода
'setvars':{'cl_action!':'sync'},
# описание груп (список лямбда функций)

Loading…
Cancel
Save