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).

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):

Add workdir argument to `repobee.run`
It should be possible for callees to specify which directory to run RepoBee in.
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)

pip install -e .[TEST]
parse_log_pytest
requirements.txt
pytest pytest-cov pytest-mock
apt-get update apt-get install -y curl
3.6
requirements/app.txt requirements/test.txt
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
appdirs==1.4.4
attrs==22.2.0
bandit==1.7.1
black==22.8.0
certifi==2021.5.30
cffi==1.15.1
charset-normalizer==2.0.12
click==8.0.4
codecov==2.1.13
colored==1.4.4
coverage==6.2
daiquiri==3.2.1
dataclasses==0.8
Deprecated==1.2.18
flake8==5.0.4
gitdb==4.0.9
GitPython==3.1.18
idna==3.10
importlib-metadata==4.2.0
iniconfig==1.1.1
mccabe==0.7.0
mypy-extensions==1.0.0
packaging==21.3
pathspec==0.9.0
pbr==6.1.1
platformdirs==2.4.0
pluggy==0.13.1
py==1.11.0
pycodestyle==2.9.1
pycparser==2.21
pyflakes==2.5.0
PyGithub==1.56
PyJWT==2.4.0
PyNaCl==1.5.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
pytest-mock==3.6.1
python-gitlab==1.15.0
python-json-logger==2.0.7
PyYAML==6.0.1
-e git+https://github.com/repobee/repobee.git@9cb6d548a33d53380cf4a5cc8c75fd45b119f506#egg=repobee
requests==2.27.1
six==1.17.0
smmap==5.0.0
stevedore==3.5.2
tomli==1.2.3
typed-ast==1.5.5
typing_extensions==4.1.1
urllib3==1.26.20
wrapt==1.16.0
zipp==3.6.0

name: repobee
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2021.5.30=py36h06a4308_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.3=he6710b0_2
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - pip=21.2.2=py36h06a4308_0
  - python=3.6.13=h12debd9_1
  - readline=8.2=h5eee18b_0
  - setuptools=58.0.4=py36h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - wheel=0.37.1=pyhd3eb1b0_0
  - xz=5.6.4=h5eee18b_1
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - appdirs==1.4.4
      - attrs==22.2.0
      - bandit==1.7.1
      - black==22.8.0
      - cffi==1.15.1
      - charset-normalizer==2.0.12
      - click==8.0.4
      - codecov==2.1.13
      - colored==1.4.4
      - coverage==6.2
      - daiquiri==3.2.1
      - dataclasses==0.8
      - deprecated==1.2.18
      - flake8==5.0.4
      - gitdb==4.0.9
      - gitpython==3.1.18
      - idna==3.10
      - importlib-metadata==4.2.0
      - iniconfig==1.1.1
      - mccabe==0.7.0
      - mypy-extensions==1.0.0
      - packaging==21.3
      - pathspec==0.9.0
      - pbr==6.1.1
      - platformdirs==2.4.0
      - pluggy==0.13.1
      - py==1.11.0
      - pycodestyle==2.9.1
      - pycparser==2.21
      - pyflakes==2.5.0
      - pygithub==1.56
      - pyjwt==2.4.0
      - pynacl==1.5.0
      - pyparsing==3.1.4
      - pytest==7.0.1
      - pytest-cov==4.0.0
      - pytest-mock==3.6.1
      - python-gitlab==1.15.0
      - python-json-logger==2.0.7
      - pyyaml==6.0.1
      - requests==2.27.1
      - six==1.17.0
      - smmap==5.0.0
      - stevedore==3.5.2
      - tomli==1.2.3
      - typed-ast==1.5.5
      - typing-extensions==4.1.1
      - urllib3==1.26.20
      - wrapt==1.16.0
      - zipp==3.6.0
prefix: /opt/conda/envs/repobee

tests/unit_tests/repobee/test_main.py::TestRun::test_operates_in_specified_workdir
tests/unit_tests/repobee/test_main.py::test_happy_path tests/unit_tests/repobee/test_main.py::test_exit_status_1_on_exception_in_parsing tests/unit_tests/repobee/test_main.py::test_exit_status_1_on_exception_in_handling_parsed_args tests/unit_tests/repobee/test_main.py::test_plugins_args tests/unit_tests/repobee/test_main.py::test_no_plugins_arg tests/unit_tests/repobee/test_main.py::test_no_plugins_with_configured_plugins tests/unit_tests/repobee/test_main.py::test_configured_plugins_are_loaded tests/unit_tests/repobee/test_main.py::test_dist_plugins_are_loaded_when_dist_install tests/unit_tests/repobee/test_main.py::test_plugin_with_subparser_name tests/unit_tests/repobee/test_main.py::test_plug_arg_incompatible_with_no_plugins tests/unit_tests/repobee/test_main.py::test_invalid_plug_options tests/unit_tests/repobee/test_main.py::test_does_not_raise_on_exception_in_dispatch tests/unit_tests/repobee/test_main.py::test_logs_traceback_on_exception_in_dispatch_if_traceback tests/unit_tests/repobee/test_main.py::test_show_all_opts_correctly_separated tests/unit_tests/repobee/test_main.py::test_non_zero_exit_status_on_exception tests/unit_tests/repobee/test_main.py::test_show_config_custom_config tests/unit_tests/repobee/test_main.py::TestRun::test_operates_in_current_workdir_by_default
src/_repobee/main.py
src/_repobee/main.py