Skip to content

Commit f16effd

Browse files
authored
Merge pull request #55 from hrshdhgd/new-term-template
Add new term based on template
2 parents 1daf30b + 0fe50c1 commit f16effd

File tree

4 files changed

+89
-40
lines changed

4 files changed

+89
-40
lines changed

src/ontobot_change_agent/api.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ def _extract_info_from_issue_object(issue: Issue) -> dict:
9797
important_info = {k: issue_as_dict[RAW_DATA][k] for k in ISSUE_KEYS}
9898
important_info["body"] = _make_sense_of_body(important_info["body"])
9999
important_info["user"] = issue_as_dict["_rawData"]["user"]["login"]
100+
important_info["labels"] = [label["name"] for label in issue_as_dict["_rawData"]["labels"]]
100101
return important_info
101102

102103

@@ -163,3 +164,28 @@ def process_issue_via_oak(input: str, commands: list, output: str = None):
163164
impl_obj.apply_patch(change)
164165

165166
impl_obj.dump(output, output_format)
167+
168+
169+
def process_new_term_template(body, prefix):
170+
"""Process an issue generated via new term request template."""
171+
split_body = body.replace("\r", "").strip("#").split("\n\n###")
172+
CURIE = prefix + ":XXXXXX"
173+
body_as_dict = {}
174+
175+
for line in split_body:
176+
if line.split("\n\n")[1].strip() not in ["_No response_", "None"]:
177+
body_as_dict[line.split("\n\n")[0].strip()] = line.split("\n\n")[1].strip()
178+
179+
kgcl_command_list = [f"create node {CURIE} '{body_as_dict['Label']}'"]
180+
181+
if "Synonyms" in body_as_dict:
182+
body_as_dict["Synonyms"] = body_as_dict["Synonyms"].split(",")
183+
for synonym in body_as_dict["Synonyms"]:
184+
if "Synonym type" in body_as_dict:
185+
kgcl_command_list.append(
186+
f"create {body_as_dict['Synonym type']} synonym '{synonym.strip()}' for {CURIE}"
187+
)
188+
else:
189+
kgcl_command_list.append(f"create synonym {synonym.strip()} for {CURIE}")
190+
191+
return (kgcl_command_list, body_as_dict)

src/ontobot_change_agent/cli.py

Lines changed: 58 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,18 @@
55
import logging
66
import os
77
import re
8-
from typing import TextIO
8+
from typing import TextIO, Union
99

1010
import click
1111

1212
from ontobot_change_agent import __version__
13-
from ontobot_change_agent.api import get_all_labels_from_repo, get_issues, process_issue_via_oak
13+
from ontobot_change_agent.api import (
14+
get_all_labels_from_repo,
15+
get_issues,
16+
process_issue_via_oak,
17+
process_new_term_template,
18+
)
19+
from ontobot_change_agent.constants import NEW_TERM_LABEL
1420

1521
__all__ = [
1622
"main",
@@ -71,6 +77,8 @@ def main(verbose: int, quiet: bool):
7177
help="Filter based on a search for label of issue.",
7278
)
7379

80+
prefix_option = click.option("-p", "--prefix", help="Assign prefix based on ontology resource.")
81+
7482
state_option = click.option(
7583
"-s",
7684
"--state",
@@ -140,29 +148,35 @@ def get_labels(repo: str, token: str):
140148
@input_argument
141149
@repo_option
142150
@token_option
151+
@prefix_option
143152
@label_option
144153
@issue_number_option
145154
@state_option
146155
@output_option
147156
def process_issue(
148-
input: str, repo: str, token: str, label: str, number: int, state: str, output: str
157+
input: str, repo: str, prefix: str, token: str, label: str, number: int, state: str, output: str
149158
):
150159
"""Run processes based on issue label.
151160
152161
:param repo: GitHub repository name [org/repo_name]
153162
:param label: Label of issues.
154163
:param state: State of issue ["open", "close" etc.]
155164
"""
156-
formatted_body = "The following commands were executed: </br> "
157-
158165
for issue in get_issues(
159166
repository_name=repo, token=token, label=label, number=number, state=state
160167
):
161168
# Make sure ontobot_change_agent needs to be triggered or no.
162169
if issue:
163-
if re.match(r"(.*)ontobot(.*)apply(.*):(.*)", issue[BODY]):
170+
KGCL_COMMANDS = []
171+
if NEW_TERM_LABEL in issue["labels"]:
172+
formatted_body = "The following input was provided: </br> "
173+
KGCL_COMMANDS, body_as_dict = process_new_term_template(issue["body"], prefix)
174+
formatted_body += _convert_to_markdown(body_as_dict)
175+
formatted_body += "</br> The following commands were executed: </br> "
176+
177+
elif re.match(r"(.*)ontobot(.*)apply(.*):(.*)", issue[BODY]):
178+
formatted_body = "The following commands were executed: </br> "
164179
bullet_starters = ["* ", "- "]
165-
KGCL_COMMANDS = []
166180
for bullet in bullet_starters:
167181
KGCL_COMMANDS.extend(
168182
[
@@ -171,47 +185,54 @@ def process_issue(
171185
if item.lstrip().startswith(bullet)
172186
]
173187
)
174-
if output:
175-
new_output = output
176-
else:
177-
new_output = input
178188

179189
KGCL_COMMANDS = [x.strip() for x in KGCL_COMMANDS]
180-
if issue["number"] == number and len(KGCL_COMMANDS) > 0: # noqa W503 # noqa W503
181-
process_issue_via_oak(
182-
input=input,
183-
commands=KGCL_COMMANDS,
184-
output=new_output,
185-
)
186190

187-
formatted_body += _list_to_markdown(KGCL_COMMANDS)
188-
formatted_body += "</br>Fixes #" + str(issue["number"])
189-
# TODO: remove `set-output` when env var setting is confirmed.
190-
if os.getenv("GITHUB_ENV"):
191-
with open(os.getenv("GITHUB_ENV"), "a") as env: # type: ignore
192-
print(f"PR_BODY={formatted_body}", file=env)
193-
print(f"PR_TITLE={issue[TITLE]}", file=env)
194-
print(f"ISSUE_CREATOR={issue[USER]}", file=env)
195-
196-
click.echo(
197-
f"""
198-
PR_BODY={formatted_body}
199-
PR_TITLE={issue[TITLE]}
200-
ISSUE_CREATOR={issue[USER]}
201-
"""
202-
)
203191
else:
204192
click.echo(f"""{issue[TITLE]} does not need ontobot's attention.""")
205193
else:
206194
click.echo(f"""Issue number:{number} is either closed or does not exist.""")
207195
break
208196

209-
210-
def _list_to_markdown(list: list) -> str:
197+
if output:
198+
new_output = output
199+
else:
200+
new_output = input
201+
202+
if issue["number"] == number and len(KGCL_COMMANDS) > 0: # noqa W503 # noqa W503
203+
process_issue_via_oak(
204+
input=input,
205+
commands=KGCL_COMMANDS,
206+
output=new_output,
207+
)
208+
209+
formatted_body += _convert_to_markdown(KGCL_COMMANDS)
210+
formatted_body += "</br>Fixes #" + str(issue["number"])
211+
212+
if os.getenv("GITHUB_ENV"):
213+
with open(os.getenv("GITHUB_ENV"), "a") as env: # type: ignore
214+
print(f"PR_BODY={formatted_body}", file=env)
215+
print(f"PR_TITLE={issue[TITLE]}", file=env)
216+
print(f"ISSUE_CREATOR={issue[USER]}", file=env)
217+
218+
click.echo(
219+
f"""
220+
PR_BODY={formatted_body}
221+
PR_TITLE={issue[TITLE]}
222+
ISSUE_CREATOR={issue[USER]}
223+
"""
224+
)
225+
226+
227+
def _convert_to_markdown(item: Union[list, dict]) -> str:
211228
bullet = "* "
212229
md = ""
213-
for line in list:
214-
md += bullet + line + "</br>"
230+
if isinstance(item, list):
231+
for line in item:
232+
md += bullet + line + "</br>"
233+
elif isinstance(item, dict):
234+
for k, v in item.items():
235+
md += bullet + k + ":" + str(v) + "</br>"
215236
return md
216237

217238

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"""Constants."""
2+
NEW_TERM_LABEL = "New term request"
3+
SYNONYM_LABEL = "synonym"

tests/test_api.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,20 +28,19 @@ def test_get_issues_with_label(self):
2828
self.assertTrue(type(issues[0]), Issue)
2929
self.assertTrue(issues[0]["number"], 2)
3030
self.assertTrue(issues[0]["title"], self.issue_title)
31-
self.assertTrue(issues[0]["labels"][0]["name"], self.label)
31+
self.assertTrue(issues[0]["labels"][0], self.label)
3232

3333
def test_get_issues_with_title(self):
3434
"""Test if 'get_issues' returns the correct title."""
3535
issues = []
3636
for issue in get_issues(repository_name=self.repo_name, title_search=self.issue_title):
3737
if issue:
3838
issues.append(issue)
39-
4039
self.assertEqual(len(issues), 1)
4140
self.assertTrue(type(issues[0]), Issue)
4241
self.assertTrue(issues[0]["number"], 2)
4342
self.assertTrue(issues[0]["title"], self.issue_title)
44-
self.assertTrue(issues[0]["labels"][0]["name"], self.label)
43+
self.assertTrue(issues[0]["labels"][0], self.label)
4544

4645
def test_get_issues_with_number(self):
4746
"""Test return the correct issue by number."""

0 commit comments

Comments
 (0)