Repository: repobee/repobee

Issue:
Add mutually exclusive groups to declarative extension commands
I'd imagine it would look something like this.

```python
# command.py
import repobee_plug as plug

class Greeting(plug.Plugin, plug.cli.Command):
    greeting_mutex = plug.cli.MutexGroup(
        name=plug.cli.Option(help="your name"),
        location=plug.cli.Option(help="your location),
        required=True,
    )

    def command_callback(self, args, api):
        assert not (args.name and args.location)
        if args.name:
            print(f"Your name is {args.name}")
        else:
            print(f"Your location is {args.location}")
```

Then we can call it like so:

```
$ repobee -p command.py greeting --name Alice
Your name is Alice
$ repobee -p command.py greeting --location Stockholm
Your location is Stockholm
$ repobee -p command.py greeting --name Alice --location Stockholm
usage: repobee greeting [-h] (--name NAME | --location LOCATION)
repobee: error: argument --location: not allowed with argument --name
```

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

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

```diff
@@            Coverage Diff             @@
##           master     #510      +/-   ##
==========================================
- Coverage   91.88%   88.26%   -3.62%     
==========================================
  Files          43       43              
  Lines        2476     2480       +4     
  Branches      401      404       +3     
==========================================
- Hits         2275     2189      -86     
- Misses        160      247      +87     
- Partials       41       44       +3     
```


| [Impacted Files](https://codecov.io/gh/repobee/repobee/pull/510?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [src/repobee\_plug/\_containers.py](https://codecov.io/gh/repobee/repobee/pull/510/diff?src=pr&el=tree#diff-c3JjL3JlcG9iZWVfcGx1Zy9fY29udGFpbmVycy5weQ==) | `93.08% <100.00%> (-0.05%)` | :arrow_down: |
| [src/repobee\_plug/\_pluginmeta.py](https://codecov.io/gh/repobee/repobee/pull/510/diff?src=pr&el=tree#diff-c3JjL3JlcG9iZWVfcGx1Zy9fcGx1Z2lubWV0YS5weQ==) | `97.56% <100.00%> (+0.09%)` | :arrow_up: |
| [src/repobee\_plug/cli.py](https://codecov.io/gh/repobee/repobee/pull/510/diff?src=pr&el=tree#diff-c3JjL3JlcG9iZWVfcGx1Zy9jbGkucHk=) | `100.00% <100.00%> (ø)` | |
| [src/\_repobee/ext/gitlab.py](https://codecov.io/gh/repobee/repobee/pull/510/diff?src=pr&el=tree#diff-c3JjL19yZXBvYmVlL2V4dC9naXRsYWIucHk=) | `63.86% <0.00%> (-28.56%)` | :arrow_down: |
| [src/\_repobee/cli/parsing.py](https://codecov.io/gh/repobee/repobee/pull/510/diff?src=pr&el=tree#diff-c3JjL19yZXBvYmVlL2NsaS9wYXJzaW5nLnB5) | `87.57% <0.00%> (-4.35%)` | :arrow_down: |
| [src/\_repobee/git.py](https://codecov.io/gh/repobee/repobee/pull/510/diff?src=pr&el=tree#diff-c3JjL19yZXBvYmVlL2dpdC5weQ==) | `96.62% <0.00%> (-3.38%)` | :arrow_down: |
| [src/\_repobee/command/repos.py](https://codecov.io/gh/repobee/repobee/pull/510/diff?src=pr&el=tree#diff-c3JjL19yZXBvYmVlL2NvbW1hbmQvcmVwb3MucHk=) | `91.80% <0.00%> (-3.28%)` | :arrow_down: |
| [src/\_repobee/ext/query.py](https://codecov.io/gh/repobee/repobee/pull/510/diff?src=pr&el=tree#diff-c3JjL19yZXBvYmVlL2V4dC9xdWVyeS5weQ==) | `48.48% <0.00%> (-1.52%)` | :arrow_down: |
| [src/\_repobee/ext/defaults/github.py](https://codecov.io/gh/repobee/repobee/pull/510/diff?src=pr&el=tree#diff-c3JjL19yZXBvYmVlL2V4dC9kZWZhdWx0cy9naXRodWIucHk=) | `90.29% <0.00%> (-0.11%)` | :arrow_down: |
| ... and [5 more](https://codecov.io/gh/repobee/repobee/pull/510/diff?src=pr&el=tree-more) | |

------

[Continue to review full report at Codecov](https://codecov.io/gh/repobee/repobee/pull/510?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/510?src=pr&el=footer). Last update [c342753...6c0fa0b](https://codecov.io/gh/repobee/repobee/pull/510?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


Patch:
diff --git a/src/repobee_plug/_containers.py b/src/repobee_plug/_containers.py
index 79b0fee..fb7147e 100644
--- a/src/repobee_plug/_containers.py
+++ b/src/repobee_plug/_containers.py
@@ -123,7 +123,7 @@ class BaseParser(enum.Enum):
     MASTER_ORG = "master-org"
 
 
-class _ImmutableMixin:
+class ImmutableMixin:
     """Make a class (more or less) immutable."""
 
     def __setattr__(self, name, value):
@@ -133,7 +133,7 @@ class _ImmutableMixin:
         self.__setattr__(name, value)
 
 
-class Category(_ImmutableMixin, abc.ABC):
+class Category(ImmutableMixin, abc.ABC):
     """Class describing a command category for RepoBee's CLI. The purpose of
     this class is to make it easy to programmatically access the different
     commands in RepoBee.
@@ -214,7 +214,7 @@ class Category(_ImmutableMixin, abc.ABC):
         return hash(repr(self))
 
 
-class Action(_ImmutableMixin):
+class Action(ImmutableMixin):
     """Class describing a RepoBee CLI action.
 
     Attributes:
@@ -272,7 +272,7 @@ class Action(_ImmutableMixin):
         return (self.category.name, self.name)
 
 
-class _CoreCommand(_ImmutableMixin):
+class _CoreCommand(ImmutableMixin):
     """Parser category signifying where an extension parser belongs."""
 
     def iter_actions(self) -> Iterable[Action]:
diff --git a/src/repobee_plug/_pluginmeta.py b/src/repobee_plug/_pluginmeta.py
index ae12f8f..a37075e 100644
--- a/src/repobee_plug/_pluginmeta.py
+++ b/src/repobee_plug/_pluginmeta.py
@@ -92,7 +92,9 @@ class _PluginMeta(type):
 
 def _extract_cli_options(
     attrdict,
-) -> List[Tuple[str, Union[cli.Option, cli.Positional]]]:
+) -> List[
+    Tuple[str, Union[cli.Option, cli.Positional, cli.MutuallyExclusiveGroup]]
+]:
     """Return any members that are CLI options as a list of tuples on the form
     (member_name, option). Other types of CLI arguments, such as positionals,
     are converted to :py:class:`~cli.Option`s.
@@ -100,7 +102,9 @@ def _extract_cli_options(
     return [
         (key, value)
         for key, value in attrdict.items()
-        if isinstance(value, (cli.Option, cli.Positional))
+        if isinstance(
+            value, (cli.Option, cli.Positional, cli.MutuallyExclusiveGroup)
+        )
     ]
 
 
@@ -173,12 +177,26 @@ def _generate_command_func(attrdict: Mapping[str, Any]) -> Callable:
 
 def _add_option(
     name: str,
-    opt: Union[cli.Positional, cli.Option],
+    opt: Union[cli.Positional, cli.Option, cli.MutuallyExclusiveGroup],
     configured_value: str,
     show_all_opts: bool,
     parser: argparse.ArgumentParser,
 ) -> None:
     """Add an option to the parser based on the cli option."""
+    if isinstance(opt, cli.MutuallyExclusiveGroup):
+        mutex_parser = parser.add_mutually_exclusive_group(
+            required=opt.required
+        )
+        for (mutex_opt_name, mutex_opt) in opt.options:
+            _add_option(
+                mutex_opt_name,
+                mutex_opt,
+                configured_value,
+                show_all_opts,
+                mutex_parser,
+            )
+        return
+
     args = []
     kwargs = opt.argparse_kwargs or {}
 
diff --git a/src/repobee_plug/cli.py b/src/repobee_plug/cli.py
index 6192fa7..f37485c 100644
--- a/src/repobee_plug/cli.py
+++ b/src/repobee_plug/cli.py
@@ -1,7 +1,16 @@
 """Plugin functionality for creating extensions to the RepoBee CLI."""
 import collections
+from typing import List, Tuple
 
-__all__ = ["Option", "Command", "CommandExtension"]
+from repobee_plug import _containers
+
+__all__ = [
+    "Option",
+    "Positional",
+    "MutuallyExclusiveGroup",
+    "Command",
+    "CommandExtension",
+]
 
 
 Option = collections.namedtuple(
@@ -25,6 +34,45 @@ Positional = collections.namedtuple(
 Positional.__new__.__defaults__ = (None,) * len(Positional._fields)
 
 
+class MutuallyExclusiveGroup(_containers.ImmutableMixin):
+    """A group of mutually exclusive CLI options.
+
+    Attributes:
+        ALLOWED_TYPES: The types that are allowed to be passed in the
+            constructor kwargs.
+        options: The options that have been stored in this group.
+        required: Whether or not this mutex group is required.
+    """
+
+    ALLOWED_TYPES = (Option,)
+    options: List[Tuple[str, Option]]
+    required: bool
+
+    def __init__(self, *, __required__: bool = False, **kwargs):
+        """
+        Args:
+            __required__: Whether or not this mutex group is required.
+            kwargs: Keyword arguments on the form ``name=plug.cli.Option()``.
+        """
+
+        def _check_type(key, value):
+            if not isinstance(value, self.ALLOWED_TYPES):
+                raise TypeError(
+                    f"{value.__class__.__name__} "
+                    f"not allowed in mutex group: {key}={value}"
+                )
+            return True
+
+        options = [
+            (key, value)
+            for key, value in kwargs.items()
+            if _check_type(key, value)
+        ]
+
+        object.__setattr__(self, "options", options)
+        object.__setattr__(self, "required", __required__)
+
+
 class CommandExtension:
     """Mixin class for use with the Plugin class. Marks the extending class as
     a command extension, that adds options to an existing command.


Test patch:
diff --git a/tests/unit_tests/repobee_plug/test_pluginmeta.py b/tests/unit_tests/repobee_plug/test_pluginmeta.py
index 475b693..af3acce 100644
--- a/tests/unit_tests/repobee_plug/test_pluginmeta.py
+++ b/tests/unit_tests/repobee_plug/test_pluginmeta.py
@@ -286,6 +286,73 @@ class TestDeclarativeExtensionCommand:
         assert parsed_args.name == name
         assert parsed_args.age == age
 
+    def test_mutex_group_arguments_are_mutually_exclusive(self, capsys):
+        """Test that mutually exclusive arguments can't be provided at the same
+        time.
+        """
+
+        class Greeting(plug.Plugin, plug.cli.Command):
+            age_mutex = plug.cli.MutuallyExclusiveGroup(
+                age=plug.cli.Option(converter=int),
+                old=plug.cli.Option(
+                    argparse_kwargs=dict(action="store_const", const=1337),
+                ),
+                __required__=True,
+            )
+
+            def command_callback(self, args, api):
+                pass
+
+        ext_cmd = Greeting("g").create_extension_command()
+        parser = argparse.ArgumentParser()
+        ext_cmd.parser(config={}, show_all_opts=False, parser=parser)
+
+        with pytest.raises(SystemExit):
+            parser.parse_args("--age 12 --old".split())
+
+        assert (
+            "error: argument --old: not allowed with argument --age"
+            in capsys.readouterr().err
+        )
+
+    def test_positionals_not_allowed_in_mutex_group(self):
+        """Positional arguments don't make sense in a mutex group."""
+
+        with pytest.raises(TypeError) as exc_info:
+            plug.cli.MutuallyExclusiveGroup(
+                age=plug.cli.Positional(converter=int),
+                old=plug.cli.Option(
+                    argparse_kwargs=dict(action="store_const", const=1337),
+                ),
+                __required__=True,
+            )
+
+        assert "Positional not allowed in mutex group" in str(exc_info.value)
+
+    def test_mutex_group_allows_one_argument(self):
+        """Test that a mutex group allows one argument to be specified."""
+        old = 1337
+
+        class Greeting(plug.Plugin, plug.cli.Command):
+            age_mutex = plug.cli.MutuallyExclusiveGroup(
+                age=plug.cli.Option(converter=int),
+                old=plug.cli.Option(
+                    argparse_kwargs=dict(action="store_const", const=old),
+                ),
+                __required__=True,
+            )
+
+            def command_callback(self, args, api):
+                pass
+
+        ext_cmd = Greeting("g").create_extension_command()
+        parser = argparse.ArgumentParser()
+        ext_cmd.parser(config={}, show_all_opts=False, parser=parser)
+
+        parsed_args = parser.parse_args(["--old"])
+
+        assert parsed_args.old == old
+
 
 class TestDeclarativeCommandExtension:
     """Test creating command extensions to existing commands."""