Repository: repobee/repobee

Issue:
Add workdir argument to `repobee.run`
It should be possible for callees to specify which directory to run RepoBee in.

Discussion:
codecov[bot]: # [Codecov](https://codecov.io/gh/repobee/repobee/pull/524?src=pr&el=h1) Report
> Merging [#524](https://codecov.io/gh/repobee/repobee/pull/524?src=pr&el=desc) into [master](https://codecov.io/gh/repobee/repobee/commit/9cb6d548a33d53380cf4a5cc8c75fd45b119f506&el=desc) will **decrease** coverage by `0.01%`.
> The diff coverage is `100.00%`.

[![Impacted file tree graph](https://codecov.io/gh/repobee/repobee/pull/524/graphs/tree.svg?width=650&height=150&src=pr&token=5vOKgkphZe)](https://codecov.io/gh/repobee/repobee/pull/524?src=pr&el=tree)

```diff
@@            Coverage Diff             @@
##           master     #524      +/-   ##
==========================================
- Coverage   88.51%   88.50%   -0.02%     
==========================================
  Files          47       47              
  Lines        2491     2488       -3     
  Branches      406      405       -1     
==========================================
- Hits         2205     2202       -3     
  Misses        239      239              
  Partials       47       47              
```


| [Impacted Files](https://codecov.io/gh/repobee/repobee/pull/524?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [src/\_repobee/main.py](https://codecov.io/gh/repobee/repobee/pull/524/diff?src=pr&el=tree#diff-c3JjL19yZXBvYmVlL21haW4ucHk=) | `90.80% <100.00%> (+1.19%)` | :arrow_up: |
| [src/\_repobee/ext/query.py](https://codecov.io/gh/repobee/repobee/pull/524/diff?src=pr&el=tree#diff-c3JjL19yZXBvYmVlL2V4dC9xdWVyeS5weQ==) | `48.48% <0.00%> (-1.52%)` | :arrow_down: |
| [src/\_repobee/ext/gitlab.py](https://codecov.io/gh/repobee/repobee/pull/524/diff?src=pr&el=tree#diff-c3JjL19yZXBvYmVlL2V4dC9naXRsYWIucHk=) | `63.86% <0.00%> (-0.40%)` | :arrow_down: |
| [src/repobee\_plug/cli/\_corecommand.py](https://codecov.io/gh/repobee/repobee/pull/524/diff?src=pr&el=tree#diff-c3JjL3JlcG9iZWVfcGx1Zy9jbGkvX2NvcmVjb21tYW5kLnB5) | `92.30% <0.00%> (-0.20%)` | :arrow_down: |
| [src/repobee\_plug/\_pluginmeta.py](https://codecov.io/gh/repobee/repobee/pull/524/diff?src=pr&el=tree#diff-c3JjL3JlcG9iZWVfcGx1Zy9fcGx1Z2lubWV0YS5weQ==) | `94.38% <0.00%> (-0.13%)` | :arrow_down: |
| [src/\_repobee/ext/defaults/github.py](https://codecov.io/gh/repobee/repobee/pull/524/diff?src=pr&el=tree#diff-c3JjL19yZXBvYmVlL2V4dC9kZWZhdWx0cy9naXRodWIucHk=) | `90.29% <0.00%> (-0.11%)` | :arrow_down: |
| [src/\_repobee/plugin.py](https://codecov.io/gh/repobee/repobee/pull/524/diff?src=pr&el=tree#diff-c3JjL19yZXBvYmVlL3BsdWdpbi5weQ==) | `93.54% <0.00%> (-0.05%)` | :arrow_down: |
| [src/repobee\_plug/\_corehooks.py](https://codecov.io/gh/repobee/repobee/pull/524/diff?src=pr&el=tree#diff-c3JjL3JlcG9iZWVfcGx1Zy9fY29yZWhvb2tzLnB5) | `100.00% <0.00%> (ø)` | |
| [src/repobee\_plug/\_exceptions.py](https://codecov.io/gh/repobee/repobee/pull/524/diff?src=pr&el=tree#diff-c3JjL3JlcG9iZWVfcGx1Zy9fZXhjZXB0aW9ucy5weQ==) | `100.00% <0.00%> (ø)` | |

------

[Continue to review full report at Codecov](https://codecov.io/gh/repobee/repobee/pull/524?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/repobee/repobee/pull/524?src=pr&el=footer). Last update [9cb6d54...1c4a393](https://codecov.io/gh/repobee/repobee/pull/524?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


Patch:
diff --git a/src/_repobee/main.py b/src/_repobee/main.py
index 5b4d638..1faa256 100644
--- a/src/_repobee/main.py
+++ b/src/_repobee/main.py
@@ -7,7 +7,9 @@
 """
 
 import pathlib
+import contextlib
 import sys
+import os
 from typing import List, Optional, Union, Mapping
 from types import ModuleType
 
@@ -40,6 +42,7 @@ def run(
     show_all_opts: bool = False,
     config_file: Union[str, pathlib.Path] = "",
     plugins: Optional[List[Union[ModuleType, plug.Plugin]]] = None,
+    workdir: Union[str, pathlib.Path] = ".",
 ) -> Mapping[str, List[plug.Result]]:
     """Run RepoBee with the provided options. This function is mostly intended
     to be used for testing plugins.
@@ -78,10 +81,21 @@ def run(
         show_all_opts: Equivalent to the ``--show-all-opts`` flag.
         config_file: Path to the configuration file.
         plugins: A list of plugin modules and/or plugin classes.
+        workdir: The working directory to run RepoBee in.
     Returns:
         A mapping (plugin_name -> plugin_results).
     """
     config_file = pathlib.Path(config_file)
+    cur_workdir = pathlib.Path(".").absolute()
+    requested_workdir = pathlib.Path(str(workdir)).resolve(strict=True)
+
+    @contextlib.contextmanager
+    def _in_requested_workdir():
+        try:
+            os.chdir(requested_workdir)
+            yield
+        finally:
+            os.chdir(cur_workdir)
 
     def _ensure_is_module(p: Union[ModuleType, plug.Plugin]):
         if issubclass(p, plug.Plugin):
@@ -95,18 +109,20 @@ def run(
             raise TypeError(f"not plugin or module: {p}")
 
     wrapped_plugins = list(map(_ensure_is_module, plugins or []))
-    try:
-        _repobee.cli.parsing.setup_logging()
-        plugin.initialize_default_plugins()
-        plugin.register_plugins(wrapped_plugins)
-        parsed_args, api, ext_commands = _parse_args(
-            cmd, config_file, show_all_opts
-        )
-        return _repobee.cli.dispatch.dispatch_command(
-            parsed_args, api, config_file, ext_commands
-        )
-    finally:
-        plugin.unregister_all_plugins()
+
+    with _in_requested_workdir():
+        try:
+            _repobee.cli.parsing.setup_logging()
+            plugin.initialize_default_plugins()
+            plugin.register_plugins(wrapped_plugins)
+            parsed_args, api, ext_commands = _parse_args(
+                cmd, config_file, show_all_opts
+            )
+            return _repobee.cli.dispatch.dispatch_command(
+                parsed_args, api, config_file, ext_commands
+            )
+        finally:
+            plugin.unregister_all_plugins()
 
 
 def main(sys_args: List[str], unload_plugins: bool = True):


Test patch:
diff --git a/tests/unit_tests/repobee/test_main.py b/tests/unit_tests/repobee/test_main.py
index a2afd02..367b3b4 100644
--- a/tests/unit_tests/repobee/test_main.py
+++ b/tests/unit_tests/repobee/test_main.py
@@ -1,3 +1,4 @@
+import os
 import argparse
 import tempfile
 import pathlib
@@ -439,3 +440,24 @@ user = some-unlikely-user
         main.main(sys_args)
 
     show_config_mock.assert_called_once_with(config_file)
+
+
+class TestRun:
+    """Tests for the run function."""
+
+    class Workdir(plug.Plugin, plug.cli.Command):
+        def command(self, args, api):
+            return plug.Result(
+                name="workdir",
+                msg="workdir",
+                status=plug.Status.SUCCESS,
+                data={"cwd": os.getcwd()},
+            )
+
+    def test_operates_in_current_workdir_by_default(self):
+        results = main.run(["workdir"], plugins=[self.Workdir])
+        assert results["workdir"][0].data["cwd"] == os.getcwd()
+
+    def test_operates_in_specified_workdir(self, tmpdir):
+        results = main.run(["workdir"], plugins=[self.Workdir], workdir=tmpdir)
+        assert results["workdir"][0].data["cwd"] == str(tmpdir)