def spin(self, msg, args): if not glob(msg.frm, self.bot_config.BOT_ADMINS): return "You're not my dad!" if not self.config: return "This plugin needs to be configured... run !plugin config Raffle and follow the directions." try: room = msg.frm.room except AttributeError: room = self._bot.rooms()[0] viewers = [ x for x in room.occupants if not glob(x.person, self.config['IGNORED']) ] if not viewers: return "sorry, pool's empty." winner = random.choice(viewers).nick prefix_text = self.config['PREFIX'] dest = room if msg.is_group else msg.frm self.send(dest, tenv().get_template('prefix.html').render(viewers=viewers)) if not (args == 'quick'): sleep(1) for i in range(5): self.send(dest, ' :catface: ' * i) sleep(1) sleep(2) self.send( dest, tenv().get_template('winner.html').render(prefix=prefix_text, winner=winner))
def spin(self, msg, args): if not glob(msg.frm, self.bot_config.BOT_ADMINS): return "You're not my dad!" if not self.config: return "This plugin needs to be configured... run !plugin config Raffle and follow the directions." try: room = msg.frm.room except AttributeError: room = self._bot.rooms()[0] viewers = [x for x in room.occupants if not glob(x.person, self.config['IGNORED'])] if not viewers: return "sorry, pool's empty." winner = random.choice(viewers).nick prefix_text = self.config['PREFIX'] dest = room if msg.is_group else msg.frm self.send(dest, tenv().get_template('prefix.html').render( viewers=viewers )) if not (args == 'quick'): sleep(1) for i in range(5): self.send(dest, ' :catface: ' * i) sleep(1) sleep(2) self.send(dest, tenv().get_template('winner.html').render( prefix=prefix_text, winner=winner ))
def invite_cmd(self, msg, match): """ Invite given user to given team. By default it invites to "newcomers" team. """ invitee = match.group(1) inviter = msg.frm.nick team = 'newcomers' if match.group(2) is None else match.group(2) team = team.lower() is_developer = self.TEAMS[self.GH_ORG_NAME + ' developers'].is_member(inviter) is_maintainer = self.TEAMS[self.GH_ORG_NAME + ' maintainers'].is_member(inviter) self.log.info('{} invited {} to {}'.format(inviter, invitee, team)) valid_teams = ['newcomers', 'developers', 'maintainers'] if team not in valid_teams: return 'Please select from one of the valid teams: ' + ', '.join( valid_teams) def invite(invitee, team): team_mapping = { 'newcomers': self.GH_ORG_NAME + ' newcomers', 'developers': self.GH_ORG_NAME + ' developers', 'maintainers': self.GH_ORG_NAME + ' maintainers' } self.TEAMS[team_mapping[team]].invite(invitee) if not self.is_room_member(invitee, msg): return '@{} is not a member of this room.'.format(invitee) if is_maintainer: invite(invitee, team) return tenv().get_template( 'labhub/promotions/{}.jinja2.md'.format(team)).render( target=invitee, ) elif is_developer: if team == 'newcomers': invite(invitee, team) return tenv().get_template( 'labhub/promotions/{}.jinja2.md'.format(team)).render( target=invitee, ) else: return tenv().get_template( 'labhub/errors/not-eligible-invite.jinja2.md').render( action='invite someone to developers or maintainers', designation='maintainer', target=inviter, ) else: return tenv().get_template( 'labhub/errors/not-eligible-invite.jinja2.md').render( action='invite other people', designation='developer/maintainer', target=inviter, )
def _report_info(self, tgt): """Attempts to find and report information about a given target through the chat bot.""" if tgt in self['info']: info = self['info'][tgt] info_yml = yaml.dump(info, default_flow_style=False, explicit_end=None) return tenv().get_template("info.md").render(target=tgt, info=info_yml) else: return tenv().get_template("miss_info.md").render(target=tgt)
def _report_sighting(self, tgt): """Attempts to find and report a sighting of the given target.""" args = {'target': tgt} if tgt in self['sightings']: sighting = self['sightings'][tgt] args['location'] = sighting['location'] args['user'] = sighting['user'] args['timestamp'] = human_readable_offset(datetime.datetime.now(), sighting['timestamp']) if 'location' not in args: return tenv().get_template('miss.md').render(target=tgt) else: return tenv().get_template('report.md').render(**args)
def invite_cmd(self, msg, match): """ Invite given user to given team. By default it invites to "newcomers" team. """ invitee = match.group(1) inviter = msg.frm.nick if invitee == 'me': user = msg.frm.nick response = tenv().get_template( 'labhub/promotions/newcomers.jinja2.md' ).render( username=user, ) self.send(msg.frm, response) self.TEAMS[self.GH_ORG_NAME + ' newcomers'].invite(user) self.invited_users.add(user) return team = 'newcomers' if match.group(2) is None else match.group(2) self.log.info('{} invited {} to {}'.format(inviter, invitee, team)) if self.TEAMS[self.GH_ORG_NAME + ' maintainers'].is_member(inviter): valid_teams = ['newcomers', 'developers', 'maintainers'] if team.lower() not in valid_teams: return 'Please select from one of the ' + ', '.join(valid_teams) team_mapping = { 'newcomers': self.GH_ORG_NAME + ' newcomers', 'developers': self.GH_ORG_NAME + ' developers', 'maintainers': self.GH_ORG_NAME + ' maintainers' } # send the invite self.TEAMS[team_mapping[team.lower()]].invite(invitee) return tenv().get_template( 'labhub/promotions/{}.jinja2.md'.format(team.lower()) ).render( target=invitee, ) else: return tenv().get_template( 'labhub/errors/not-maintainer.jinja2.md' ).render( action='invite other people', target=invitee, )
def get_template(backend, func): """ Selects a template based on the current backend """ templates = [ "".join([backend, "_", func, ".md"]), "".join(["default_", func, ".md"]) ] return tenv().get_or_select_template(templates).name
def create_issue_cmd(self, msg, match): """Create issues on GitHub and GitLab repositories.""" # Ignore QuotesBear, LineLengthBear, PyCodeStyleBear user = msg.frm.nick if not user: yield 'ERROR: The above command cannot be operated without nick.' return repo_name = match.group(1) iss_title = match.group(2) iss_description = match.group(3) if match.group(3) is not None else '' extra_msg = '\nOpened by @{username} at [{backend}]({msg_link})'.format( username=user, backend=self.bot_config.BACKEND, msg_link=message_link(self, msg) ) if repo_name in self.REPOS: repo = self.REPOS[repo_name] iss = repo.create_issue(iss_title, iss_description + extra_msg) yield 'Here you go: {}'.format(iss.web_url) else: yield tenv().get_template( 'labhub/errors/no-repository.jinja2.md' ).render( target=user, )
def process_reply(reply_): # integrated templating if template_name: reply_ = tenv().get_template(template_name + '.html').render(**reply_) # Reply should be all text at this point (See https://github.com/gbin/err/issues/96) return str(reply_)
def msg_commit_comment(body, repo): user = body['comment']['user']['login'] url = body['comment']['html_url'] line = body['comment']['line'] sha = body['comment']['commit_id'] return tenv().get_template('commit_comment.html').render( locals().copy())
def push_news(self, request): # self.log.debug(repr(request)) if not self.validate_incoming(request): abort(400) data = request.json response = tenv().get_template('news.j2').render(data=data) for user in self.bot_config.BOT_ADMINS: return self.send(self.build_identifier(user), response)
def response(self, args): minions = self._input['return'][0].keys() data = self._input['return'][0] command = args[1] response = tenv().get_template('grain.j2').render(minions=minions, data=data, command=command) return response
def msg_issue_comment(body, repo): action = body['action'] user = body['comment']['user']['login'] number = body['issue']['number'] title = body['issue']['title'] url = body['issue']['html_url'] if action == 'created': action = 'commented' return tenv().get_template('issue_comment.html').render(locals().copy())
def sendReply(self, mess, args, updates, types): reps = self.prepareReply(updates, types) compResponse = "" for rep in reps: response = tenv().get_template('buffer.md').render({'type': rep[0], 'nameSocialNetwork': rep[1], 'updates': rep[2]}) compResponse = compResponse + response return(compResponse)
def callback_message(self, msg): """Invite the user whose message includes the holy 'hello world'""" if re.search(r'hello\s*,?\s*world', msg.body, flags=re.IGNORECASE): user = msg.frm.nick if (not self.is_team_member(user, 'newcomers') and user not in self.hello_world_users): response = tenv().get_template( 'labhub/hello-world.jinja2.md').render(target=user, ) self.send(msg.frm, response) self.hello_world_users.add(user)
def msg_issue_comment(body, repo): action = body['action'] user = body['comment']['user']['login'] number = body['issue']['number'] title = body['issue']['title'] url = body['issue']['html_url'] if action == 'created': action = 'commented' return tenv().get_template('issue_comment.html').render( locals().copy())
def msg_pull_request_review_comment(body, repo): action = body['action'] user = body['comment']['user']['login'] line = body['comment']['position'] l_url = body['comment']['html_url'] pr = body['pull_request']['number'] url = body['pull_request']['html_url'] if action == 'created': action = 'commented' return tenv().get_template('pull_request_review_comment.html').render(locals().copy())
def _format_kill(self, kill, loss): """ Format the kill JSON into a nice string we can output""" verb = "LOSS" if loss else "KILL" ship = self._ship_name(int(kill["victim"]["shipTypeID"])) url = "https://zkillboard.com/kill/%s/" % kill["killID"] value = self._value(kill) response = tenv().get_template('killmail.html').render(loss=loss, name=kill['victim']['characterName'], alliance=kill['victim']['allianceName'], ship=ship, value=value, link=url) return response
def msg_issues(body, repo): action = body['action'] number = body['issue']['number'] title = body['issue']['title'] user = body['issue']['user']['login'] url = body['issue']['url'] is_assigned = body['issue']['assignee'] if is_assigned is not None: assignee = body['issue']['assignee']['login'] return tenv().get_template('issues.html').render(locals().copy())
def msg_pull_request_review_comment(body, repo): action = body['action'] user = body['comment']['user']['login'] line = body['comment']['position'] l_url = body['comment']['html_url'] pr = body['pull_request']['number'] url = body['pull_request']['html_url'] if action == 'created': action = 'commented' return tenv().get_template('pull_request_review_comment.html').render( locals().copy())
def callback_message(self, msg): """ Alert the user that his/her message is too long or has too many lines. """ if (len(msg.body) > self.config['MAX_MSG_LEN'] or msg.body.count('\n') >= self.config['MAX_LINES']): user = msg.frm.nick response = tenv().get_template('spam_alert.jinja2.md').render( target=user) self.send(msg.frm, response)
def msg_pull_request(body, repo): action = body['action'] number = body['pull_request']['number'] user = body['pull_request']['user']['login'] url = body['pull_request']['html_url'] merged = body['pull_request']['merged'] if action == 'closed' and merged: user = body['pull_request']['merged_by']['login'] action = 'merged' if action == 'synchronize': action = 'updated' return tenv().get_template('pull_request.html').render(locals().copy())
def execute_and_send(template_name): try: reply = self.commands[cmd](mess, args) # integrated templating if template_name: reply = tenv().get_template(template_name + '.html').render(**reply) except Exception, e: logging.exception(u'An error happened while processing '\ u'a message ("%s") from %s: %s"' % (text, jid, traceback.format_exc(e))) reply = self.MSG_ERROR_OCCURRED + ':\n %s' % e
def callback_message(self, msg): """Invite the user whose message includes the holy 'hello world'""" if re.search(r'hello\s*,?\s*world', msg.body, flags=re.IGNORECASE): user = msg.frm.nick if (not self.TEAMS[self.GH_ORG_NAME + ' newcomers'].is_member(user) and user not in self.invited_users): # send the invite response = tenv().get_template( 'labhub/promotions/newcomers.jinja2.md').render( target=user, ) self.send(msg.frm, response) self.TEAMS[self.GH_ORG_NAME + ' newcomers'].invite(user) self.invited_users.add(user)
def _update_blog_post(self, clone_path: str, donations: Dict, donation_total: float) -> List[str]: """ Updates the blog post from our template using the donations dict and total """ blog_post = (tenv().get_template("blog-post.md").render( total=donation_total, donations=donations)) article_path = os.path.join( clone_path, "content/articles/SADevs-season-of-giving-2020.md") with open(article_path, "w") as file: file.write(blog_post) return [article_path]
def startvmotion(self, msg, args): """vMotion from 7mode datastore to bbcs datastore""" environment = args.pop(0) numbers = args.pop(0) dc = args.pop(0) datastore = args.pop(0) script = '/root/stephen/storage_migrations/start-env-atu.sh' + " -e " + environment + " -n " + numbers + " -d " + dc + " -s " + datastore res = self.remote_excute(script) if res == 0: response = tenv().get_template('start.md').render(environment=environment) else: response = "Err....Something went wrong" self.send(msg.frm, response, message_type=msg.type)
def tran(self, msg, args): url = 'http://www.zaragoza.es/api/recurso/urbanismo-infraestructuras/tranvia?rf=html&results_only=false&srsname=utm30n' if args: stop = args.upper() else: stop = "CAMPUS RIO EBRO" dataOut = {} request = urllib.request.Request(url) headers = {"Accept": "application/json"} response = requests.get(url, headers = headers) resProc = response.json() if resProc["totalCount"] > 0: tit = 0 ii = 0 for i in range(int(resProc["totalCount"])): if (resProc["result"][i]["title"].find(stop) >= 0): if (tit == 0): dataOut = {'stop': resProc["result"][i]["title"]} tit = 1 for j in range(len(resProc["result"][i]["destinos"])): key = 'time'+str(ii+1)+str(j+1) dataOut[key] = resProc["result"][i]["destinos"][j]["minutos"] key = 'destination'+str(ii+1) ii = ii + 1 dataOut[key] = resProc["result"][i]["destinos"][j]["destino"] if dataOut: reply = tenv().get_template('tran.md').render(dataOut) else: reply = tenv().get_template('tran.md').render({'stop':'%s Not found' % stop}) yield(reply) else: yield {'stop':'Not found'} yield end()
def execute_and_send(template_name): try: reply = self.commands[cmd](mess, args) # integrated templating if template_name: reply = tenv().get_template(template_name + '.html').render(**reply) # Reply should be all text at this point (See https://github.com/gbin/err/issues/96) reply = unicode(reply) except Exception, e: logging.exception(u'An error happened while processing ' u'a message ("%s") from %s: %s"' % (text, jid, traceback.format_exc(e))) reply = self.MSG_ERROR_OCCURRED + ':\n %s' % e
def startvmotion(self, msg, args): """vMotion from 7mode datastore to bbcs datastore""" environment = args.pop(0) numbers = args.pop(0) dc = args.pop(0) datastore = args.pop(0) script = '/root/stephen/storage_migrations/start-env-atu.sh' + " -e " + environment + " -n " + numbers + " -d " + dc + " -s " + datastore res = self.remote_excute(script) if res == 0: response = tenv().get_template('start.md').render( environment=environment) else: response = "Err....Something went wrong" self.send(msg.frm, response, message_type=msg.type)
def migrate(self, msg, args): """Migrate Storage from 7mode to BBCS""" user = args.pop(0) environment = args.pop(0) numbers = args.pop(0) nfs = args.pop(0) script = "/root/stephen/storage_migrations/migrate-env-atu.sh" + " -u " + user + " -e " + environment + " -n " + numbers + " -s " + nfs res = self.remote_excute(script) if res == 0: response = tenv().get_template('migrate.md').render(environment=environment) else: response = "Err...Something went wrong" self.send(msg.frm, response, message_type=msg.type)
def migrate(self, msg, args): """Migrate Storage from 7mode to BBCS""" user = args.pop(0) environment = args.pop(0) numbers = args.pop(0) nfs = args.pop(0) script = "/root/stephen/storage_migrations/migrate-env-atu.sh" + " -u " + user + " -e " + environment + " -n " + numbers + " -s " + nfs res = self.remote_excute(script) if res == 0: response = tenv().get_template('migrate.md').render( environment=environment) else: response = "Err...Something went wrong" self.send(msg.frm, response, message_type=msg.type)
def explain(self, msg, match): """Explain various terms.""" # Ignore QuotesBear user = msg.frm.nick response = '' filename = 'explain/{}.jinja2.md'.format(match.group(1).lower()) if match.group(1).lower() in self.KNOWN_KEYS: if match.group(2): response += '@{}: \n'.format(match.group(2)) response += tenv().get_template(filename).render( username=user, target=match.group(2), bot_prefix=self.bot_config.BOT_PREFIX, ) else: response = self.ERROR_MSG return response
def execute_and_send(template_name): try: reply = self.commands[cmd](mess, args) # integrated templating if template_name: reply = tenv().get_template(template_name + '.html').render(**reply) # Reply should be all text at this point (See https://github.com/gbin/err/issues/96) reply = str(reply) except Exception as e: tb = traceback.format_exc() logging.exception('An error happened while processing ' 'a message ("%s") from %s: %s"' % (text, jid, tb)) reply = self.MSG_ERROR_OCCURRED + ':\n %s' % e if reply: if len(reply) > self.MESSAGE_SIZE_LIMIT: reply = reply[:self.MESSAGE_SIZE_LIMIT - len(self.MESSAGE_SIZE_ERROR_MESSAGE)] + self.MESSAGE_SIZE_ERROR_MESSAGE self.send_simple_reply(mess, reply, cmd in DIVERT_TO_PRIVATE)
def manageCommand(self, chan, msgJ, msg): self.log.info("Starting manage command") listCommands = self._bot.all_commands if msgJ['cmd'].startswith(self._bot.bot_config.BOT_PREFIX): # Consider avoiding it (?) # Maybe we could also have separated the command from # args cmd = msgJ['cmd'][len(self._bot.bot_config.BOT_PREFIX):] self.log.debug("Cmd: %s" % cmd) if cmd in listCommands: self.log.debug("I'd execute -%s- args -%s-" % (cmd, msgJ['args'])) method = listCommands[cmd] self.log.debug("template -%s-" % method._err_command_template) txtR = '' if inspect.isgeneratorfunction(method): replies = method("", msgJ['args']) for reply in replies: if isinstance(reply, str): txtR = txtR + '\n' + reply else: reply = method("", msgJ['args']) if isinstance(reply, str): txtR = txtR + reply else: # What happens if ther is no template? # https://github.com/errbotio/errbot/blob/master/errbot/core.py self.log.debug("tenv -> %s%s" % (method._err_command_template, '.md')) txtR = txtR + tenv().get_template( method._err_command_template + '.md').render(reply) self.publishSlack(typ='Rep', usr=msgJ['userName'], host=msgJ['userHost'], frm=msgJ['frm'], args=txtR) self.deleteSlack(chan, msg['ts']) self.log.info("End manage command")
def get_promotion_status(branch): def get_date(text): repo_lines = [i for i in text.splitlines() if 'delorean.repo' in i] if repo_lines: line = repo_lines[0] if date_re.search(line): date_txt = date_re.search(line).group(1) return datetime.datetime.strptime(date_txt, '%Y-%m-%d %H:%M') return def calculate_diff(t): return (datetime.datetime.utcnow() - t).days if branch == 'all': branches = BRANCHES else: branches = [branch] br_list = [] for b in branches: res = { 'name': b, 'consistent': 'N/A', 'tripleoci': 'N/A', 'phase1': 'N/A', 'phase2': 'N/A' } for repo_url in REPO_URL: url = repo_url.format(b) web = requests.get(url) if web is None or not web.ok: continue date = get_date(web.text) if not date: continue days = calculate_diff(date) key = REPO_URL[repo_url] res[key] = days br_list.append(res) return tenv().get_template('promotion_status.md').render(branches=br_list)
def msg_push(body, repo): user = body['pusher']['name'] commits = len(body['commits']) branch = body['ref'].split('/')[-1] url = body['compare'] return tenv().get_template('push.html').render(locals().copy())
def render_template(self, template='generic', **kwargs): kwargs['repo_name'] = kwargs.get('repo_name') or self.name return tenv().get_template('{0}.html'.format(template)).render(**kwargs)
def templ(self, msg, args): response = tenv().get_template('hello.md').render(name=args) self.send(msg.frm, response)
def find(self, mess, ip): # a command callable with !tryme res = self.reader.city(ip) country = res.country.names['zh-CN'] response = tenv().get_template('geoip_res.md').render(res=res, country=country) self.send(mess.frm, response)
def msg_generic(body, repo, event_type): return tenv().get_template('generic.html').render(locals().copy())
def assign_cmd(self, msg, match): """Assign to GitLab and GitHub issues.""" # Ignore QuotesBear org = match.group(2) repo_name = match.group(3)[:-1] iss_number = match.group(4) user = msg.frm.nick try: assert org == self.GH_ORG_NAME or org == self.GL_ORG_NAME except AssertionError: yield 'Repository not owned by our org.' return checks = [] def register_check(function): checks.append(function) return function if self.GH_ORG_NAME == 'coala' and self.GL_ORG_NAME == 'coala': @register_check def difficulty_level(user, iss): """ True if: 1. A newcomer is asking for assignment to low or newcomer issue. 2. The user belongs to developers or maintainers team as well as newcomers team. False if 1. A newcomer asks for assignment to an issue that has no difficulty label. 2. A newcomer asks for assignment to an issue with difficulty higher than low. """ if (self.TEAMS[self.GH_ORG_NAME + ' newcomers'].is_member(user) and not (self.TEAMS[self.GH_ORG_NAME + ' developers'].is_member( user ) or self.TEAMS[self.GH_ORG_NAME + ' maintainers'].is_member( user ))): diff_labels = filter( lambda x: 'difficulty' in x, iss.labels) if list(filter(lambda x: ('low' in x) or ('newcomer' in x), diff_labels)): return True else: return False elif self.GH3_ORG.is_member(user): return True def eligible(user, iss): for chk in checks: if not chk(user, iss): return False return True try: iss = self.REPOS[repo_name].get_issue(int(iss_number)) except KeyError: yield 'Repository doesn\'t exist.' else: if not iss.assignees: if eligible(user, iss): iss.assign(user) yield ('Congratulations! You\'ve been assigned to the ' 'issue. :tada:') else: yield 'You are not eligible to be assigned to this issue.' yield tenv().get_template( 'labhub/errors/not-eligible.jinja2.md' ).render( organization=self.GH_ORG_NAME, ) elif user in iss.assignees: yield ('The issue is already assigned to you.') else: yield tenv().get_template( 'labhub/errors/already-assigned.jinja2.md' ).render( username=user, )
def invite_cmd(self, msg, match): """ Invite given user to given team. By default it invites to "newcomers" team. """ invitee = match.group(1) inviter = msg.frm.nick if not inviter: yield 'ERROR: The above command cannot be operated without nick.' return team = 'newcomers' if match.group(2) is None else match.group(2) team = team.lower() is_developer = self.is_team_member(inviter, 'developers') is_maintainer = self.is_team_member(inviter, 'maintainers') self.log.info('{} invited {} to {}'.format(inviter, invitee, team)) valid_teams = self.team_mapping() if team not in valid_teams: yield 'Please select from one of the valid teams: ' + ', '.join( valid_teams) return def invite(invitee, team): self.team_mapping()[team].invite(invitee) if not self.is_room_member(invitee, msg): yield '@{} is not a member of this room.'.format(invitee) return if is_maintainer: invite(invitee, team) yield tenv().get_template( 'labhub/promotions/{}.jinja2.md'.format(team) ).render( target=invitee, ) elif is_developer: if team == 'newcomers': invite(invitee, team) yield tenv().get_template( 'labhub/promotions/{}.jinja2.md'.format(team) ).render( target=invitee, ) else: yield tenv().get_template( 'labhub/errors/not-eligible-invite.jinja2.md' ).render( action='invite someone to developers or maintainers', designation='maintainer', target=inviter, ) else: yield tenv().get_template( 'labhub/errors/not-eligible-invite.jinja2.md' ).render( action='invite other people', designation='developer/maintainer', target=inviter, )
def render_template(self, template='generic', **kwargs): kwargs['provider'] = kwargs.get('provider') or self.name return tenv().get_template('{0}.html'.format(template)).render(**kwargs)
def msg_commit_comment(body, repo): user = body['comment']['user']['login'] url = body['comment']['html_url'] line = body['comment']['line'] sha = body['comment']['commit_id'] return tenv().get_template('commit_comment.html').render(locals().copy())
def assign_cmd(self, msg, match): """Assign to GitLab and GitHub issues.""" # Ignore QuotesBear org = match.group(2) repo_name = match.group(3)[:-1] iss_number = match.group(4) user = msg.frm.nick try: assert org == self.GH_ORG_NAME or org == self.GL_ORG_NAME except AssertionError: yield 'Repository not owned by our org.' return checks = [] def register_check(function): checks.append(function) return function if self.GH_ORG_NAME == 'coala' and self.GL_ORG_NAME == 'coala': @register_check def difficulty_level(user, iss): """ True if: 1. A newcomer is asking for assignment to low or newcomer issue. 2. The user belongs to developers or maintainers team as well as newcomers team. False if: 1. A newcomer asks for assignment to an issue that has no difficulty label. 2. A newcomer asks for assignment to an issue with difficulty higher than low. """ if (self.is_team_member(user, 'newcomers') and not (self.is_team_member(user, 'developers') or self.is_team_member(user, 'maintainers'))): diff_labels = filter(lambda x: 'difficulty' in x, iss.labels) if list( filter(lambda x: ('low' in x) or ('newcomer' in x), diff_labels)): return True else: return False elif self.GH3_ORG.is_member(user): return True @register_check def newcomer_issue_check(user, iss): """ True if: Issue is not labeled `difficulty/newcomer` and user is not a newcomer. False if: A `difficulty/newcomer` issue is already assigned to the user. """ if (self.is_newcomer_issue(iss) and self.is_team_member(user, 'newcomers')): search_query = 'user:coala assignee:{} ' \ 'label:difficulty/newcomer'.format(user) result = GitHub.raw_search( GitHubToken(self.config['GH_TOKEN']), search_query) return not (sum(1 for _ in result) >= 1) else: return True @register_check def block_gci_issue_assignment(user, iss): """ True if the issue is not labelled with 'initiatives/gci'. False if the issue has been labelled with 'initiatives/gci'. """ return 'initiatives/gci' not in iss.labels def eligible(user, iss): for chk in checks: if not chk(user, iss): return False return True try: iss = self.REPOS[repo_name].get_issue(int(iss_number)) except KeyError: yield 'Repository doesn\'t exist.' else: if not iss.assignees: if eligible(user, iss): iss.assign(user) yield ('Congratulations! You\'ve been assigned to the ' 'issue. :tada:') else: yield 'You are not eligible to be assigned to this issue.' yield tenv().get_template( 'labhub/errors/not-eligible.jinja2.md').render( organization=self.GH_ORG_NAME, ) elif user in iss.assignees: yield ('The issue is already assigned to you.') else: yield tenv().get_template( 'labhub/errors/already-assigned.jinja2.md').render( username=user, )
def generate_response(res): return tenv().get_template('gerrit_result.md').render(args=res)