本文整理汇总了Python中osclib.comments.CommentAPI.delete方法的典型用法代码示例。如果您正苦于以下问题:Python CommentAPI.delete方法的具体用法?Python CommentAPI.delete怎么用?Python CommentAPI.delete使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类osclib.comments.CommentAPI
的用法示例。
在下文中一共展示了CommentAPI.delete方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: remind_comment
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import delete [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)
示例2: update_status_comments
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import delete [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)
示例3: OpenQAReport
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import delete [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
#.........这里部分代码省略.........
示例4: StagingReport
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import delete [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()
#.........这里部分代码省略.........
示例5: TestCommentOBS
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import delete [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)
示例6: ReviewBot
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import delete [as 别名]
#.........这里部分代码省略.........
# Copy original values to revert changes made to them.
self.review_messages = self.DEFAULT_REVIEW_MESSAGES.copy()
if self.only_one_action and len(req.actions) != 1:
self.review_messages['declined'] = 'Only one action per request supported'
return False
if self.comment_handler is not False:
self.comment_handler_add()
overall = True
for a in req.actions:
# Store in-case sub-classes need direct access to original values.
self.action = a
func = getattr(self, self.action_method(a))
ret = func(req, a)
# In the case of multiple actions take the "lowest" result where the
# order from lowest to highest is: False, None, True.
if overall is not False:
if ((overall is True and ret is not True) or
(overall is None and ret is False)):
overall = ret
return overall
def action_method(self, action):
method_prefix = 'check_action'
method_type = action.type
method_suffix = None
if method_type == 'delete':
method_suffix = 'project'
if action.tgt_package is not None:
method_suffix = 'package'
elif action.tgt_repository is not None:
method_suffix = 'repository'
if method_suffix:
method = '_'.join([method_prefix, method_type, method_suffix])
if hasattr(self, method):
return method
method = '_'.join([method_prefix, method_type])
if hasattr(self, method):
return method
method_type = '_default'
return '_'.join([method_prefix, method_type])
@staticmethod
def _is_patchinfo(pkgname):
return pkgname == 'patchinfo' or pkgname.startswith('patchinfo.')
def check_action_maintenance_incident(self, req, a):
if self._is_patchinfo(a.src_package):
self.logger.debug('ignoring patchinfo action')
return True
# Duplicate src_package as tgt_package since prior to assignment to a
# specific incident project there is no target package (odd API). After
# assignment it is still assumed the target will match the source. Since
# the ultimate goal is the tgt_releaseproject the incident is treated
# similar to staging in that the intermediate result is not the final
示例7: ABIChecker
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import delete [as 别名]
#.........这里部分代码省略.........
# self.logger.debug("request %s already done, result: %s"%(req.reqid, result))
# return
self.dblogger.request_id = req.reqid
self.reports = []
self.text_summary = ''
try:
ret = ReviewBot.ReviewBot.check_one_request(self, req)
except Exception as e:
import traceback
self.logger.error("unhandled exception in ABI checker")
self.logger.error(traceback.format_exc())
ret = None
result = None
if ret is not None:
state = 'done'
result = 'accepted' if ret else 'declined'
else:
# we probably don't want abichecker to spam here
# FIXME don't delete comment in this case
#if state is None and not self.text_summary:
# self.text_summary = 'abichecker will take a look later'
state = 'seen'
self.save_reports_to_db(req, state, result)
if ret is not None and self.text_summary == '':
# if for some reason save_reports_to_db didn't produce a
# summary we add one
self.text_summary = "ABI checker result: [%s](%s/request/%s)"%(result, WEB_URL, req.reqid)
if commentid and not self.dryrun:
self.commentapi.delete(commentid)
self.post_comment(req, state, result)
self.review_messages = { 'accepted': self.text_summary, 'declined': self.text_summary }
if self.no_review:
ret = None
self.dblogger.request_id = None
return ret
def check_request_already_done(self, reqid):
try:
request = self.session.query(DB.Request).filter(DB.Request.id == reqid).one()
if request.state == 'done':
return True
except sqlalchemy.orm.exc.NoResultFound as e:
pass
return False
def save_reports_to_db(self, req, state, result):
try:
request = self.session.query(DB.Request).filter(DB.Request.id == req.reqid).one()
for i in self.session.query(DB.ABICheck).filter(DB.ABICheck.request_id == request.id).all():
# yeah, we could be smarter here and update existing reports instead
self.session.delete(i)
self.session.flush()
request.state = state
request.result = result
except sqlalchemy.orm.exc.NoResultFound as e:
示例8: Leaper
# 需要导入模块: from osclib.comments import CommentAPI [as 别名]
# 或者: from osclib.comments.CommentAPI import delete [as 别名]
#.........这里部分代码省略.........
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)
return False
# TODO: make generic, move to Reviewbot. Used by multiple bots
def add_comment(self, req, msg, state, result=None):
if not self.do_comments:
return
comment = "<!-- leaper state=%s%s -->\n" % (state, ' result=%s' % result if result else '')
comment += "\n" + msg
(comment_id, comment_state, comment_result, comment_text) = self.find_obs_request_comment(req, state)
if comment_id is not None and state == comment_state:
# count number of lines as aproximation to avoid spamming requests
# for slight wording changes in the code
if len(comment_text.split('\n')) == len(comment.split('\n')):
self.logger.debug("not worth the update, previous comment %s is state %s", comment_id, comment_state)
return
self.logger.debug("adding comment to %s, state %s result %s", req.reqid, state, result)
self.logger.debug("message: %s", msg)
if not self.dryrun:
if comment_id is not None:
self.commentapi.delete(comment_id)
self.commentapi.add_comment(request_id=req.reqid, comment=str(comment))
def find_obs_request_comment(self, req, state=None):
"""Return previous comments (should be one)."""
if self.do_comments:
comments = self.commentapi.get_comments(request_id=req.reqid)
for c in comments.values():
m = self.comment_marker_re.match(c['comment'])
if m and (state is None or state == m.group('state')):
return c['id'], m.group('state'), m.group('result'), c['comment']
return None, None, None, None
def check_action__default(self, req, a):
self.logger.info("unhandled request type %s"%a.type)
self.needs_release_manager = True
return True