本文整理汇总了Python中osclib.comments.CommentAPI.add_comment方法的典型用法代码示例。如果您正苦于以下问题:Python CommentAPI.add_comment方法的具体用法?Python CommentAPI.add_comment怎么用?Python CommentAPI.add_comment使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类osclib.comments.CommentAPI
的用法示例。
在下文中一共展示了CommentAPI.add_comment方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: IgnoreCommand
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import add_comment [as 别名]
class IgnoreCommand(object):
MESSAGE = 'Ignored: removed from active backlog.'
def __init__(self, api):
self.api = api
self.comment = CommentAPI(self.api.apiurl)
def perform(self, requests, message=None):
"""
Ignore a request from "list" and "adi" commands until unignored.
"""
requests_ignored = self.api.get_ignored_requests()
length = len(requests_ignored)
for request_id in RequestFinder.find_sr(requests, self.api):
if request_id in requests_ignored:
print('{}: already ignored'.format(request_id))
continue
print('{}: ignored'.format(request_id))
requests_ignored[request_id] = message
comment = message if message else self.MESSAGE
self.comment.add_comment(request_id=str(request_id), comment=comment)
diff = len(requests_ignored) - length
if diff > 0:
self.api.set_ignored_requests(requests_ignored)
print('Ignored {} requests'.format(diff))
else:
print('No new requests to ignore')
return True
示例2: remind_comment
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import add_comment [as 别名]
def remind_comment(apiurl, repeat_age, request_id, project, package=None):
comment_api = CommentAPI(apiurl)
comments = comment_api.get_comments(request_id=request_id)
comment, _ = comment_api.comment_find(comments, BOT_NAME)
if comment:
delta = datetime.utcnow() - comment['when']
if delta.days < repeat_age:
print(' skipping due to previous reminder from {} days ago'.format(delta.days))
return
# Repeat notification so remove old comment.
try:
comment_api.delete(comment['id'])
except HTTPError as e:
if e.code == 403:
# Gracefully skip when previous reminder was by another user.
print(' unable to remove previous reminder')
return
raise e
userids = sorted(maintainers_get(apiurl, project, package))
if len(userids):
users = ['@' + userid for userid in userids]
message = '{}: {}'.format(', '.join(users), REMINDER)
else:
message = REMINDER
print(' ' + message)
message = comment_api.add_marker(message, BOT_NAME)
comment_api.add_comment(request_id=request_id, comment=message)
示例3: UnignoreCommand
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import add_comment [as 别名]
class UnignoreCommand(object):
MESSAGE = 'Unignored: returned to active backlog.'
def __init__(self, api):
self.api = api
self.comment = CommentAPI(self.api.apiurl)
def perform(self, requests, cleanup=False):
"""
Unignore a request by removing from ignore list.
"""
requests_ignored = self.api.get_ignored_requests()
length = len(requests_ignored)
if len(requests) == 1 and requests[0] == 'all':
requests_ignored = {}
else:
for request_id in RequestFinder.find_sr(requests, self.api):
if request_id in requests_ignored:
print('{}: unignored'.format(request_id))
del requests_ignored[request_id]
self.comment.add_comment(request_id=str(request_id), comment=self.MESSAGE)
if cleanup:
now = datetime.now()
for request_id in set(requests_ignored):
request = get_request(self.api.apiurl, str(request_id))
if request.state.name not in ('new', 'review'):
changed = dateutil.parser.parse(request.state.when)
diff = now - changed
if diff.days > 3:
print('Removing {} which was {} {} days ago'
.format(request_id, request.state.name, diff.days))
del requests_ignored[request_id]
diff = length - len(requests_ignored)
if diff > 0:
self.api.set_ignored_requests(requests_ignored)
print('Unignored {} requests'.format(diff))
else:
print('No requests to unignore')
return True
示例4: update_status_comments
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import add_comment [as 别名]
def update_status_comments(self, project, command):
"""
Refresh the status comments, used for notification purposes, based on
the current list of requests. To ensure that all involved users
(and nobody else) get notified, old status comments are deleted and
a new one is created.
:param project: project name
:param command: name of the command to include in the message
"""
# TODO: we need to discuss the best way to keep track of status
# comments. Right now they are marked with an initial markdown
# comment. Maybe a cleaner approach would be to store something
# like 'last_status_comment_id' in the pseudometa. But the current
# OBS API for adding comments doesn't return the id of the created
# comment.
comment_api = CommentAPI(self.apiurl)
comments = comment_api.get_comments(project_name=project)
for comment in comments.values():
# TODO: update the comment removing the user mentions instead of
# deleting the whole comment. But there is currently not call in
# OBS API to update a comment
if comment['comment'].startswith('<!--- osc staging'):
comment_api.delete(comment['id'])
break # There can be only one! (if we keep deleting them)
meta = self.get_prj_pseudometa(project)
lines = ['<!--- osc staging %s --->' % command]
lines.append('The list of requests tracked in %s has changed:\n' % project)
for req in meta['requests']:
author = req.get('autor', None)
if not author:
# Old style metadata
author = get_request(self.apiurl, str(req['id'])).get_creator()
lines.append(' * Request#%s for package %s submitted by @%s' % (req['id'], req['package'], author))
msg = '\n'.join(lines)
comment_api.add_comment(project_name=project, comment=msg)
示例5: OpenQAReport
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import add_comment [as 别名]
class OpenQAReport(object):
def __init__(self, api):
self.api = api
self.comment = CommentAPI(api.apiurl)
def _package_url(self, package):
link = "https://build.opensuse.org/package/live_build_log/%s/%s/%s/%s"
link = link % (package["project"], package["package"], package["repository"], package["arch"])
text = "[%s](%s)" % (package["arch"], link)
return text
def _openQA_url(self, job):
test_name = job["name"].split("-")[-1]
link = "%s/tests/%s" % (self.api.copenqa, job["id"])
text = "[%s](%s)" % (test_name, link)
return text
def _openQA_module_url(self, job, module):
link = "%s/tests/%s/modules/%s/steps/1" % (self.api.copenqa, job["id"], module["name"])
text = "[%s](%s)" % (module["name"], link)
return text
def old_enough(self, _date):
time_delta = datetime.utcnow() - _date
safe_margin = timedelta(hours=MARGIN_HOURS)
return safe_margin <= time_delta
def get_info(self, project):
_prefix = "{}:".format(self.api.cstaging)
if project.startswith(_prefix):
project = project.replace(_prefix, "")
query = {"format": "json"}
url = self.api.makeurl(("project", "staging_projects", self.api.project, project), query=query)
info = json.load(self.api.retried_GET(url))
return info
def get_broken_package_status(self, info):
status = info["broken_packages"]
subproject = info["subproject"]
if subproject:
status.extend(subproject["broken_packages"])
return status
def get_openQA_status(self, info):
status = info["openqa_jobs"]
subproject = info["subproject"]
if subproject:
status.extend(subproject["openqa_jobs"])
return status
def is_there_openqa_comment(self, project):
"""Return True if there is a previous comment."""
signature = "<!-- openQA status -->"
comments = self.comment.get_comments(project_name=project)
comment = [c for c in comments.values() if signature in c["comment"]]
return len(comment) > 0
def update_status_comment(self, project, report, force=False):
signature = "<!-- openQA status -->"
report = "%s\n%s" % (signature, str(report))
write_comment = False
comments = self.comment.get_comments(project_name=project)
comment = [c for c in comments.values() if signature in c["comment"]]
if comment and len(comment) > 1:
print "ERROR. There are more than one openQA status comment in %s" % project
# for c in comment:
# self.comment.delete(c['id'])
# write_comment = True
elif comment and comment[0]["comment"] != report and self.old_enough(comment[0]["when"]):
self.comment.delete(comment[0]["id"])
write_comment = True
elif not comment:
write_comment = True
if write_comment or force:
if osc.conf.config["debug"]:
print "Updating comment"
self.comment.add_comment(project_name=project, comment=report)
def _report_broken_packages(self, info):
broken_package_status = self.get_broken_package_status(info)
# Group packages by name
groups = defaultdict(list)
for package in broken_package_status:
groups[package["package"]].append(package)
failing_lines = [
"* Build failed %s (%s)" % (key, ", ".join(self._package_url(p) for p in value))
for key, value in groups.iteritems()
]
report = "\n".join(failing_lines[:MAX_LINES])
if len(failing_lines) > MAX_LINES:
report += "* and more (%s) ..." % (len(failing_lines) - MAX_LINES)
return report
#.........这里部分代码省略.........
示例6: AcceptCommand
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import add_comment [as 别名]
class AcceptCommand(object):
def __init__(self, api):
self.api = api
self.comment = CommentAPI(self.api.apiurl)
def find_new_requests(self, project):
query = "match=state/@name='new'+and+(action/target/@project='{}'+and+action/@type='submit')".format(project)
url = self.api.makeurl(['search', 'request'], query)
f = http_GET(url)
root = ET.parse(f).getroot()
rqs = []
for rq in root.findall('request'):
pkgs = []
actions = rq.findall('action')
for action in actions:
targets = action.findall('target')
for t in targets:
pkgs.append(str(t.get('package')))
rqs.append({'id': int(rq.get('id')), 'packages': pkgs})
return rqs
def perform(self, project):
"""
Accept the staging LETTER for review and submit to factory
Then disable the build to disabled
:param project: staging project we are working with
"""
status = self.api.check_project_status(project)
if not status:
print('The project "{}" is not yet acceptable.'.format(project))
return False
meta = self.api.get_prj_pseudometa(project)
requests = []
packages = []
for req in meta['requests']:
self.api.rm_from_prj(project, request_id=req['id'], msg='ready to accept')
requests.append(req['id'])
packages.append(req['package'])
msg = 'Accepting staging review for {}'.format(req['package'])
print(msg)
for req in requests:
change_request_state(self.api.apiurl, str(req), 'accepted', message='Accept to factory')
# A single comment should be enough to notify everybody, since they are
# already mentioned in the comments created by select/unselect
pkg_list = ", ".join(packages)
cmmt = 'Project "{}" accepted. The following packages have been submitted to factory: {}.'.format(project, pkg_list)
self.comment.add_comment(project_name=project, comment=cmmt)
# XXX CAUTION - AFAIK the 'accept' command is expected to clean the messages here.
self.comment.delete_from(project_name=project)
self.api.build_switch_prj(project, 'disable')
if self.api.project_exists(project + ':DVD'):
self.api.build_switch_prj(project + ':DVD', 'disable')
return True
def accept_other_new(self):
changed = False
for req in self.find_new_requests('openSUSE:{}'.format(self.api.opensuse)):
print 'Accepting request %d: %s' % (req['id'], ','.join(req['packages']))
change_request_state(self.api.apiurl, str(req['id']), 'accepted', message='Accept to factory')
changed = True
return changed
def update_factory_version(self):
"""Update openSUSE (Factory, 13.2, ...) version if is necessary."""
project = 'openSUSE:{}'.format(self.api.opensuse)
url = self.api.makeurl(['source', project, '_product', 'openSUSE.product'])
product = http_GET(url).read()
curr_version = date.today().strftime('%Y%m%d')
new_product = re.sub(r'<version>\d{8}</version>', '<version>%s</version>' % curr_version, product)
if product != new_product:
http_PUT(url + '?comment=Update+version', data=new_product)
示例7: AcceptCommand
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import add_comment [as 别名]
class AcceptCommand(object):
def __init__(self, api):
self.api = api
self.comment = CommentAPI(self.api.apiurl)
def find_new_requests(self, project):
query = "match=state/@name='new'+and+(action/target/@project='{}'+and+action/@type='submit')".format(project)
url = self.api.makeurl(['search', 'request'], query)
f = http_GET(url)
root = ET.parse(f).getroot()
rqs = []
for rq in root.findall('request'):
pkgs = []
actions = rq.findall('action')
for action in actions:
targets = action.findall('target')
for t in targets:
pkgs.append(str(t.get('package')))
rqs.append({'id': int(rq.get('id')), 'packages': pkgs})
return rqs
def perform(self, project, force=False):
"""Accept the staging project for review and submit to Factory /
openSUSE 13.2 ...
Then disable the build to disabled
:param project: staging project we are working with
"""
status = self.api.check_project_status(project)
if not status:
print('The project "{}" is not yet acceptable.'.format(project))
if not force:
return False
meta = self.api.get_prj_pseudometa(project)
requests = []
packages = []
for req in meta['requests']:
self.api.rm_from_prj(project, request_id=req['id'], msg='ready to accept')
requests.append(req['id'])
packages.append(req['package'])
msg = 'Accepting staging review for {}'.format(req['package'])
print(msg)
oldspecs = self.api.get_filelist_for_package(pkgname=req['package'],
project=self.api.project,
extension='spec')
change_request_state(self.api.apiurl,
str(req['id']),
'accepted',
message='Accept to %s' % self.api.project)
self.create_new_links(self.api.project, req['package'], oldspecs)
# A single comment should be enough to notify everybody, since
# they are already mentioned in the comments created by
# select/unselect
pkg_list = ", ".join(packages)
cmmt = 'Project "{}" accepted.' \
' The following packages have been submitted to {}: {}.'.format(project,
self.api.project,
pkg_list)
self.comment.add_comment(project_name=project, comment=cmmt)
# XXX CAUTION - AFAIK the 'accept' command is expected to clean the messages here.
self.comment.delete_from(project_name=project)
self.api.build_switch_prj(project, 'disable')
if self.api.item_exists(project + ':DVD'):
self.api.build_switch_prj(project + ':DVD', 'disable')
return True
def cleanup(self, project):
if not self.api.item_exists(project):
return False
pkglist = self.api.list_packages(project)
clean_list = set(pkglist) - set(self.api.cstaging_nocleanup)
for package in clean_list:
print "[cleanup] deleted %s/%s" % (project, package)
delete_package(self.api.apiurl, project, package, force=True, msg="autocleanup")
return True
def accept_other_new(self):
changed = False
rqlist = self.find_new_requests(self.api.project)
if self.api.cnonfree:
rqlist += self.find_new_requests(self.api.cnonfree)
for req in rqlist:
oldspecs = self.api.get_filelist_for_package(pkgname=req['packages'][0], project=self.api.project, extension='spec')
print 'Accepting request %d: %s' % (req['id'], ','.join(req['packages']))
change_request_state(self.api.apiurl, str(req['id']), 'accepted', message='Accept to %s' % self.api.project)
#.........这里部分代码省略.........
示例8: StagingReport
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import add_comment [as 别名]
class StagingReport(object):
def __init__(self, api):
self.api = api
self.comment = CommentAPI(api.apiurl)
def _package_url(self, package):
link = '/package/live_build_log/%s/%s/%s/%s'
link = link % (package['project'],
package['package'],
package['repository'],
package['arch'])
text = '[%s](%s)' % (package['arch'], link)
return text
def old_enough(self, _date):
time_delta = datetime.utcnow() - _date
safe_margin = timedelta(hours=MARGIN_HOURS)
return safe_margin <= time_delta
def update_status_comment(self, project, report, force=False, only_replace=False):
report = self.comment.add_marker(report, MARKER)
comments = self.comment.get_comments(project_name=project)
comment, _ = self.comment.comment_find(comments, MARKER)
if comment:
write_comment = (report != comment['comment'] and self.old_enough(comment['when']))
else:
write_comment = not only_replace
if write_comment or force:
if osc.conf.config['debug']:
print('Updating comment')
if comment:
self.comment.delete(comment['id'])
self.comment.add_comment(project_name=project, comment=report)
def _report_broken_packages(self, info):
broken_package_status = info['broken_packages']
# Group packages by name
groups = defaultdict(list)
for package in broken_package_status:
groups[package['package']].append(package)
failing_lines = [
'* Build failed %s (%s)' % (key, ', '.join(self._package_url(p) for p in value))
for key, value in groups.iteritems()
]
report = '\n'.join(failing_lines[:MAX_LINES])
if len(failing_lines) > MAX_LINES:
report += '* and more (%s) ...' % (len(failing_lines) - MAX_LINES)
return report
def report_checks(self, info):
failing_lines, green_lines = [], []
links_state = {}
for check in info['checks']:
links_state.setdefault(check['state'], [])
links_state[check['state']].append('[{}]({})'.format(check['name'], check['url']))
lines = []
failure = False
for state, links in links_state.items():
if len(links) > MAX_LINES:
extra = len(links) - MAX_LINES
links = links[:MAX_LINES]
links.append('and {} more...'.format(extra))
lines.append('- {}'.format(state))
if state != 'success':
lines.extend([' - {}'.format(link) for link in links])
failure = True
else:
lines[-1] += ': {}'.format(', '.join(links))
return '\n'.join(lines).strip(), failure
def report(self, project, aggregate=True, force=False):
info = self.api.project_status(project, aggregate)
# Do not attempt to process projects without staging info, or projects
# in a pending state that will change before settling. This avoids
# intermediate notifications that may end up being spammy and for
# long-lived stagings where checks may be re-triggered multiple times
# and thus enter pending state (not seen on first run) which is not
# useful to report.
if not info or not self.api.project_status_final(info):
return
report_broken_packages = self._report_broken_packages(info)
report_checks, check_failure = self.report_checks(info)
if report_broken_packages or check_failure:
if report_broken_packages:
report_broken_packages = 'Broken:\n\n' + report_broken_packages
if report_checks:
report_checks = 'Checks:\n\n' + report_checks
report = '\n\n'.join((report_broken_packages, report_checks))
report = report.strip()
#.........这里部分代码省略.........
示例9: TestCommentOBS
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import add_comment [as 别名]
class TestCommentOBS(OBSLocalTestCase):
def setUp(self):
super(TestCommentOBS, self).setUp()
self.api = CommentAPI(self.apiurl)
# Ensure different test runs operate in unique namespace.
self.bot = '::'.join([type(self).__name__, str(random.getrandbits(8))])
def test_basic(self):
self.osc_user('staging-bot')
self.assertFalse(self.comments_filtered(self.bot)[0])
self.assertTrue(self.api.add_comment(
project_name=PROJECT, comment=self.api.add_marker(COMMENT, self.bot)))
comment, _ = self.comments_filtered(self.bot)
self.assertTrue(comment)
self.assertTrue(self.api.delete(comment['id']))
self.assertFalse(self.comments_filtered(self.bot)[0])
def test_delete_nested(self):
self.osc_user('staging-bot')
comment_marked = self.api.add_marker(COMMENT, self.bot)
# Allow for existing comments by basing assertion on delta from initial count.
comment_count = len(self.api.get_comments(project_name=PROJECT))
self.assertFalse(self.comments_filtered(self.bot)[0])
self.assertTrue(self.api.add_comment(project_name=PROJECT, comment=comment_marked))
comment, _ = self.comments_filtered(self.bot)
self.assertTrue(comment)
for i in range(0, 3):
self.assertTrue(self.api.add_comment(
project_name=PROJECT, comment=comment_marked, parent_id=comment['id']))
comments = self.api.get_comments(project_name=PROJECT)
parented_count = 0
for comment in comments.values():
if comment['parent']:
parented_count += 1
self.assertEqual(parented_count, 3)
self.assertTrue(len(comments) == comment_count + 4)
self.api.delete_from(project_name=PROJECT)
self.assertFalse(len(self.api.get_comments(project_name=PROJECT)))
def test_delete_batch(self):
users = ['factory-auto', 'repo-checker', 'staging-bot']
for user in users:
self.osc_user(user)
from osc import conf
bot = '::'.join([self.bot, user])
comment = self.api.add_marker(COMMENT, bot)
self.assertFalse(self.comments_filtered(bot)[0])
self.assertTrue(self.api.add_comment(project_name=PROJECT, comment=comment))
self.assertTrue(self.comments_filtered(bot)[0])
# Allow for existing comments by basing assertion on delta from initial count.
comment_count = len(self.api.get_comments(project_name=PROJECT))
self.assertTrue(comment_count >= len(users))
self.api.delete_from_where_user(users[0], project_name=PROJECT)
self.assertTrue(len(self.api.get_comments(project_name=PROJECT)) == comment_count - 1)
self.api.delete_from(project_name=PROJECT)
self.assertFalse(len(self.api.get_comments(project_name=PROJECT)))
def comments_filtered(self, bot):
comments = self.api.get_comments(project_name=PROJECT)
return self.api.comment_find(comments, bot)
示例10: ReviewBot
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import add_comment [as 别名]
#.........这里部分代码省略.........
kwargs['package_name'] = package
else:
if request is None:
request = self.request
kwargs = {'request_id': request.reqid}
debug_key = '/'.join(kwargs.values())
if message is None:
if not len(self.comment_handler.lines):
self.logger.debug('skipping empty comment for {}'.format(debug_key))
return
message = '\n\n'.join(self.comment_handler.lines)
bot_name = self.bot_name
if bot_name_suffix:
bot_name = '::'.join([bot_name, bot_name_suffix])
info = {'state': state, 'result': result}
if info_extra and info_extra_identical:
info.update(info_extra)
comments = self.comment_api.get_comments(**kwargs)
comment, _ = self.comment_api.comment_find(comments, bot_name, info)
if info_extra and not info_extra_identical:
# Add info_extra once comment has already been matched.
info.update(info_extra)
message = self.comment_api.add_marker(message, bot_name, info)
message = self.comment_api.truncate(message.strip())
if (comment is not None and
((identical and
# Remove marker from comments since handled during comment_find().
self.comment_api.remove_marker(comment['comment']) ==
self.comment_api.remove_marker(message)) or
(not identical and comment['comment'].count('\n') == message.count('\n')))
):
# Assume same state/result and number of lines in message is duplicate.
self.logger.debug('previous comment too similar on {}'.format(debug_key))
return
if comment is None:
self.logger.debug('broadening search to include any state on {}'.format(debug_key))
comment, _ = self.comment_api.comment_find(comments, bot_name)
if comment is not None:
self.logger.debug('removing previous comment on {}'.format(debug_key))
if not self.dryrun:
self.comment_api.delete(comment['id'])
elif only_replace:
self.logger.debug('no previous comment to replace on {}'.format(debug_key))
return
self.logger.debug('adding comment to {}: {}'.format(debug_key, message))
if not self.dryrun:
self.comment_api.add_comment(comment=message, **kwargs)
self.comment_handler_remove()
def _check_matching_srcmd5(self, project, package, rev, history_limit = 5):
"""check if factory sources contain the package and revision. check head and history"""
self.logger.debug("checking %s in %s"%(package, project))
try:
osc.core.show_package_meta(self.apiurl, project, package)
except (HTTPError, URLError):
self.logger.debug("new package")
return None
si = self.get_sourceinfo(project, package)
if rev == si.verifymd5:
self.logger.debug("srcmd5 matches")
return True
if history_limit:
self.logger.debug("%s not the latest version, checking history", rev)
u = osc.core.makeurl(self.apiurl, [ 'source', project, package, '_history' ], { 'limit': history_limit })
try:
r = osc.core.http_GET(u)
except HTTPError as e:
self.logger.debug("package has no history!?")
return None
root = ET.parse(r).getroot()
# we need this complicated construct as obs doesn't honor
# the 'limit' parameter use above for obs interconnect:
# https://github.com/openSUSE/open-build-service/issues/2545
for revision, i in zip(reversed(root.findall('revision')), count()):
node = revision.find('srcmd5')
if node is None:
continue
self.logger.debug("checking %s"%node.text)
if node.text == rev:
self.logger.debug("got it, rev %s"%revision.get('rev'))
return True
if i == history_limit:
break
self.logger.debug("srcmd5 not found in history either")
return False
示例11: AcceptCommand
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import add_comment [as 别名]
class AcceptCommand(object):
def __init__(self, api):
self.api = api
self.comment = CommentAPI(self.api.apiurl)
def find_new_requests(self, project):
query = "match=state/@name='new'+and+(action/target/@project='{}'+and+action/@type='submit')".format(project)
url = self.api.makeurl(['search', 'request'], query)
f = http_GET(url)
root = ET.parse(f).getroot()
rqs = []
for rq in root.findall('request'):
pkgs = []
actions = rq.findall('action')
for action in actions:
targets = action.findall('target')
for t in targets:
pkgs.append(str(t.get('package')))
rqs.append({'id': int(rq.get('id')), 'packages': pkgs})
return rqs
def perform(self, project, force=False):
"""Accept the staging project for review and submit to Factory /
openSUSE 13.2 ...
Then disable the build to disabled
:param project: staging project we are working with
"""
status = self.api.check_project_status(project)
if not status:
print('The project "{}" is not yet acceptable.'.format(project))
if not force:
return False
meta = self.api.get_prj_pseudometa(project)
requests = []
packages = []
for req in meta['requests']:
self.api.rm_from_prj(project, request_id=req['id'], msg='ready to accept')
requests.append(req['id'])
packages.append(req['package'])
msg = 'Accepting staging review for {}'.format(req['package'])
print(msg)
oldspecs = self.api.get_filelist_for_package(pkgname=req['package'],
project=self.api.project,
extension='spec')
change_request_state(self.api.apiurl,
str(req['id']),
'accepted',
message='Accept to %s' % self.api.project)
self.create_new_links(self.api.project, req['package'], oldspecs)
# A single comment should be enough to notify everybody, since
# they are already mentioned in the comments created by
# select/unselect
pkg_list = ", ".join(packages)
cmmt = 'Project "{}" accepted.' \
' The following packages have been submitted to {}: {}.'.format(project,
self.api.project,
pkg_list)
self.comment.add_comment(project_name=project, comment=cmmt)
# XXX CAUTION - AFAIK the 'accept' command is expected to clean the messages here.
self.comment.delete_from(project_name=project)
self.api.build_switch_prj(project, 'disable')
if self.api.item_exists(project + ':DVD'):
self.api.build_switch_prj(project + ':DVD', 'disable')
return True
def cleanup(self, project):
if not self.api.item_exists(project):
return False
pkglist = self.api.list_packages(project)
clean_list = set(pkglist) - set(self.api.cstaging_nocleanup)
for package in clean_list:
print "[cleanup] deleted %s/%s" % (project, package)
delete_package(self.api.apiurl, project, package, force=True, msg="autocleanup")
# wipe Test-DVD binaries and breaks kiwi build
if project.startswith('openSUSE:'):
for package in pkglist:
if package.startswith('Test-DVD-'):
# intend to break the kiwi file
arch = package.split('-')[-1]
fakepkgname = 'I-am-breaks-kiwi-build'
oldkiwifile = self.api.load_file_content(project, package, 'PRODUCT-'+arch+'.kiwi')
if oldkiwifile is not None:
newkiwifile = re.sub(r'<repopackage name="openSUSE-release"/>', '<repopackage name="%s"/>' % fakepkgname, oldkiwifile)
self.api.save_file_content(project, package, 'PRODUCT-' + arch + '.kiwi', newkiwifile)
#.........这里部分代码省略.........
示例12: ABIChecker
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import add_comment [as 别名]
#.........这里部分代码省略.........
self.text_summary += "%s seems to be ABI [compatible](%s/request/%s):\n\n"%(r.dst_package, WEB_URL, req.reqid)
else:
self.text_summary += "Warning: bad news from ABI check, "
self.text_summary += "%s may be ABI [**INCOMPATIBLE**](%s/request/%s):\n\n"%(r.dst_package, WEB_URL, req.reqid)
for lr in r.reports:
libreport = DB.LibReport(
abicheck = abicheck,
src_repo = lr.src_repo,
src_lib = lr.src_lib,
dst_repo = lr.dst_repo,
dst_lib = lr.dst_lib,
arch = lr.arch,
htmlreport = lr.htmlreport,
result = lr.result,
)
self.session.add(libreport)
self.session.commit()
self.text_summary += "* %s (%s): [%s](%s/report/%d)\n"%(lr.dst_lib, lr.arch,
"compatible" if lr.result else "***INCOMPATIBLE***",
WEB_URL, libreport.id)
self.reports = []
def post_comment(self, req, state, result):
if not self.text_summary:
return
msg = "<!-- abichecker state=%s%s -->\n"%(state, ' result=%s'%result if result else '')
msg += self.text_summary
self.logger.info("add comment: %s"%msg)
if not self.dryrun:
#self.commentapi.delete_from_where_user(self.review_user, request_id = req.reqid)
self.commentapi.add_comment(request_id = req.reqid, comment = msg)
def run_abi_checker(self, libname, old, new, output):
cmd = ['abi-compliance-checker',
'-lib', libname,
'-old', old,
'-new', new,
'-report-path', output
]
self.logger.debug(cmd)
r = subprocess.Popen(cmd, close_fds=True, cwd=CACHEDIR).wait()
if not r in (0, 1):
self.logger.error('abi-compliance-checker failed')
# XXX: record error
return None
return r == 0
def run_abi_dumper(self, output, base, filename):
cmd = ['abi-dumper',
'-o', output,
'-lver', os.path.basename(filename),
'/'.join([base, filename])]
debuglib = '%s/usr/lib/debug/%s.debug'%(base, filename)
if os.path.exists(debuglib):
cmd.append(debuglib)
self.logger.debug(cmd)
r = subprocess.Popen(cmd, close_fds=True, cwd=CACHEDIR).wait()
if r != 0:
self.logger.error("failed to dump %s!"%filename)
# XXX: record error
return False
return True
示例13: Leaper
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import add_comment [as 别名]
#.........这里部分代码省略.........
if len(req.actions) != 1:
msg = "only one action per request please"
self.review_messages['declined'] = msg
return False
request_ok = ReviewBot.ReviewBot.check_one_request(self, req)
has_correct_maintainer = self.maintbot.check_one_request(req)
self.logger.debug("review result: %s", request_ok)
self.logger.debug("has_correct_maintainer: %s", has_correct_maintainer)
if self.pending_factory_submission:
self.logger.info("submission is waiting for a Factory request to complete")
elif self.source_in_factory:
self.logger.info("the submitted sources are in or accepted for Factory")
elif self.source_in_factory == False:
self.logger.info("the submitted sources are NOT in Factory")
if request_ok == False:
self.logger.info("NOTE: if you think the automated review was wrong here, please talk to the release team before reopening the request")
elif self.needs_release_manager:
self.logger.info("request needs review by release management")
if self.comment_log:
result = None
if request_ok is None:
state = 'seen'
elif request_ok:
state = 'done'
result = 'accepted'
else:
state = 'done'
result = 'declined'
self.add_comment(req, '\n\n'.join(self.comment_log), state)
self.comment_log = None
if self.needs_release_manager:
add_review = True
for r in req.reviews:
if r.by_group == self.release_manager_group and (r.state == 'new' or r.state == 'accepted'):
add_review = False
self.logger.debug("%s already is a reviewer", self.release_manager_group)
break
if add_review:
if self.add_review(req, by_group = self.release_manager_group) != True:
self.review_messages['declined'] += '\nadding %s failed' % self.release_manager_group
return False
if self.needs_reviewteam:
add_review = True
self.logger.info("%s needs review by opensuse-review-team"%req.reqid)
for r in req.reviews:
if r.by_group == 'opensuse-review-team':
add_review = False
self.logger.debug("opensuse-review-team already is a reviewer")
break
if add_review:
if self.add_review(req, by_group = "opensuse-review-team") != True:
self.review_messages['declined'] += '\nadding opensuse-review-team failed'
return False
return request_ok
def check_action__default(self, req, a):
# decline all other requests for fallback reviewer
self.logger.debug("auto decline request type %s"%a.type)