Skip to content

Commit

Permalink
Read github template before doing anything based on label.
Browse files Browse the repository at this point in the history
  • Loading branch information
hrshdhgd committed Jul 5, 2023
1 parent 5cc2356 commit 5e40cdf
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 26 deletions.
66 changes: 46 additions & 20 deletions src/ontobot_change_agent/api.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
# -*- coding: utf-8 -*-
"""API section."""

import json
import re
from os.path import join, splitext
from pathlib import Path
from typing import Generator, Optional

import kgcl_schema.grammar.parser as kgcl_parser
import requests
import yaml
from github import Github
from github.Issue import Issue
from oaklib.cli import query_terms_iterator
Expand All @@ -31,7 +34,7 @@
# Save the token in a txt file as named below.
SRC = Path(__file__).parent
TOKEN_FILE = join(SRC, "token.txt")

ISSUE_TEMPLATE_DIR = ".github/ISSUE_TEMPLATE"
# Example for API: https://pygithub.readthedocs.io/en/latest/examples.html

RAW_DATA = "_rawData"
Expand Down Expand Up @@ -76,6 +79,8 @@ def get_issues(

g = Github(token)
repo = g.get_repo(repository_name)
global ISSUE_TEMPLATE_DIR
ISSUE_TEMPLATE_DIR = repo.contents_url.replace("{+path}", ISSUE_TEMPLATE_DIR)
label_object = None
if label:
label_object = repo.get_label(label)
Expand Down Expand Up @@ -169,28 +174,49 @@ def process_issue_via_oak(input: str, commands: list, output: str = None):


def process_new_term_template(body, prefix):
"""Process an issue generated via new term request template."""
"""Process an issue generated via new term request template.
:param body: Body of the issue.
:param prefix: Prefix of the ontology corresponding to the repository.
:return: Command list and body as a dict. If Issue does not match template: (None, None)
:raises ValueError: If prefix is absent.
"""
split_body = body.replace("\r", "").strip("#").split("\n\n###")
CURIE = prefix + ":XXXXXX"
if prefix:
CURIE = prefix + ":XXXXXX"
else:
raise (ValueError("Prefix must be provided in the command."))

body_as_dict = {}

for line in split_body:
if line.split("\n\n")[1].strip() not in ["_No response_", "None"]:
body_as_dict[line.split("\n\n")[0].strip()] = line.split("\n\n")[1].strip()

kgcl_command_list = [f"create node {CURIE} '{body_as_dict['Label']}'"]

if SYNONYMS in body_as_dict:
body_as_dict[SYNONYMS] = body_as_dict[SYNONYMS].split(",")
for synonym in body_as_dict[SYNONYMS]:
if SYNONYM_TYPE in body_as_dict:
kgcl_command_list.append(
f"create {body_as_dict[SYNONYM_TYPE]} synonym '{synonym.strip()}' for {CURIE}"
)
else:
kgcl_command_list.append(f"create synonym {synonym.strip()} for {CURIE}")

if DEFINITION in body_as_dict:
kgcl_command_list.append(f"add definition '{body_as_dict[DEFINITION].strip()}' to {CURIE}")

return (kgcl_command_list, body_as_dict)
response_1 = requests.get(ISSUE_TEMPLATE_DIR + "/add-term.yml", allow_redirects=True, timeout=5)
metadata = json.loads(response_1.content.decode("utf-8"))
download_url = metadata["download_url"]
response_2 = requests.get(download_url, allow_redirects=True, timeout=5)
content = response_2.content.decode("utf8")
template = yaml.safe_load(content)
list_of_template_keys = [x["attributes"]["label"] for x in template["body"] if "id" in x]
if all(key in list_of_template_keys for key in body_as_dict.keys()):
kgcl_command_list = [f"create node {CURIE} '{body_as_dict['Label']}'"]

if SYNONYMS in body_as_dict:
body_as_dict[SYNONYMS] = body_as_dict[SYNONYMS].split(",")
for synonym in body_as_dict[SYNONYMS]:
if SYNONYM_TYPE in body_as_dict:
kgcl_command_list.append(
f"create {body_as_dict[SYNONYM_TYPE]} synonym '{synonym.strip()}' for {CURIE}" # noqa
)
else:
kgcl_command_list.append(f"create synonym {synonym.strip()} for {CURIE}")

if DEFINITION in body_as_dict:
kgcl_command_list.append(
f"add definition '{body_as_dict[DEFINITION].strip()}' to {CURIE}"
)

return (kgcl_command_list, body_as_dict)
else:
return (None, None)
15 changes: 9 additions & 6 deletions src/ontobot_change_agent/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,14 @@ def process_issue(
if NEW_TERM_LABEL in issue["labels"]:
formatted_body = "The following input was provided: </br> "
KGCL_COMMANDS, body_as_dict = process_new_term_template(issue["body"], prefix)
formatted_body += _convert_to_markdown(body_as_dict)
formatted_body += "</br> The following commands were executed: </br> "
if KGCL_COMMANDS is not None and body_as_dict is not None:
formatted_body += _convert_to_markdown(body_as_dict)
formatted_body += "</br> The following commands were executed: </br> "
else:
click.echo(
f"""{issue[TITLE]} does not need ontobot's attention since the issue does not match the 'New Term request' template.""", # noqa
)
break

elif re.match(r"(.*)ontobot(.*)apply(.*):(.*)", issue[BODY]):
formatted_body = "The following commands were executed: </br> "
Expand All @@ -194,10 +200,7 @@ def process_issue(
click.echo(f"""Issue number:{number} is either closed or does not exist.""")
break

if output:
new_output = output
else:
new_output = input
new_output = output if output else input

if issue["number"] == number and len(KGCL_COMMANDS) > 0: # noqa W503 # noqa W503
process_issue_via_oak(
Expand Down
1 change: 1 addition & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ ignore =
DAR101 # Missing parameter(s) in Docstring: - with_git_hash
DAR201 # Missing "Returns" in Docstring: - return
DAR301 # Missing "Yields" in Docstring: - yield
DAR401 # Missing exception(s) in Raises section: -r ValueError
E111 # indentation is not a multiple of 4
T201 # print found.
max-line-length = 100
Expand Down

0 comments on commit 5e40cdf

Please sign in to comment.