Skip to content

Commit

Permalink
Change: Allow to run GitHub scripts from modules
Browse files Browse the repository at this point in the history
This will allow to included some GitHub script as a module and install
it into the current Python environment.
  • Loading branch information
bjoernricks committed Jul 3, 2023
1 parent 1845f1a commit 5bda591
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
24 changes: 19 additions & 5 deletions pontos/github/script/load.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,22 @@ def load_script(
with load_script("path/to/script.py") as module:
module.func()
with load_script("some.python.module") as module:
module.func()
"""
path = Path(script)
module_name = path.stem
if path.suffix == ".py":
module_name = path.stem

with add_sys_path(path.parent.absolute()), ensure_unload_module(
module_name
):
yield importlib.import_module(module_name)
with add_sys_path(path.parent.absolute()), ensure_unload_module(
module_name
):
yield importlib.import_module(module_name)
else:
module_name = str(path)
with ensure_unload_module(module_name):
yield importlib.import_module(module_name)


def run_github_script_function(
Expand Down Expand Up @@ -92,6 +100,9 @@ def run_github_script_function(
with load_script("path/to/script.py") as module:
return run_github_script_function(module, token, 60.0, args)
with load_script("some.python.module") as module:
return run_github_script_function(module, token, 60.0, args)
"""
if not hasattr(module, GITHUB_SCRIPT_FUNCTION_NAME):
raise GitHubScriptError(
Expand Down Expand Up @@ -152,6 +163,9 @@ def run_add_arguments_function(
with load_script("path/to/script.py") as module:
run_add_arguments_function(module, parser)
with load_script("some.python.module") as module:
run_add_arguments_function(module, parser)
"""
func = getattr(module, GITHUB_SCRIPT_PARSER_FUNCTION_NAME, None)
if func:
Expand Down
10 changes: 9 additions & 1 deletion tests/github/script/test_load.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
run_add_arguments_function,
run_github_script_function,
)
from pontos.testing import temp_file
from pontos.testing import temp_file, temp_python_module
from tests import IsolatedAsyncioTestCase


Expand All @@ -39,6 +39,14 @@ def test_load_script(self):
self.assertIsNotNone(module.foo)
self.assertEqual(module.foo(), 1)

def test_load_script_module(self):
with temp_python_module(
"def foo():\n\treturn 1", name="github-foo-script"
), load_script("github-foo-script") as module:
self.assertIsNotNone(module)
self.assertIsNotNone(module.foo)
self.assertEqual(module.foo(), 1)

def test_load_script_failure(self):
with self.assertRaisesRegex(
ModuleNotFoundError, "No module named 'baz'"
Expand Down

0 comments on commit 5bda591

Please sign in to comment.