diff options
-rw-r--r-- | docs/advanced.rst | 8 | ||||
-rw-r--r-- | examples/aliases/aliases.py | 24 |
2 files changed, 29 insertions, 3 deletions
diff --git a/docs/advanced.rst b/docs/advanced.rst index f8c0ed8..f2569fe 100644 --- a/docs/advanced.rst +++ b/docs/advanced.rst @@ -12,9 +12,11 @@ Click. This page should give some insight into what can be accomplished. Command Aliases --------------- -Many tools support aliases for commands. For instance, you can configure -``git`` to accept ``git ci`` as alias for ``git commit``. Other tools -also support auto-discovery for aliases by automatically shortening them. +Many tools support aliases for commands (see `Command alias example +<https://github.com/pallets/click/tree/master/examples/aliases>`_). +For instance, you can configure ``git`` to accept ``git ci`` as alias for +``git commit``. Other tools also support auto-discovery for aliases by +automatically shortening them. Click does not support this out of the box, but it's very easy to customize the :class:`Group` or any other :class:`MultiCommand` to provide this diff --git a/examples/aliases/aliases.py b/examples/aliases/aliases.py index 38ef72c..299d3a5 100644 --- a/examples/aliases/aliases.py +++ b/examples/aliases/aliases.py @@ -14,6 +14,9 @@ class Config(object): self.path = os.getcwd() self.aliases = {} + def add_alias(self, alias, cmd): + self.aliases.update({alias: cmd}) + def read_config(self, filename): parser = configparser.RawConfigParser() parser.read([filename]) @@ -22,6 +25,14 @@ class Config(object): except configparser.NoSectionError: pass + def write_config(self, filename): + parser = configparser.RawConfigParser() + parser.add_section('aliases') + for key, value in self.aliases.items(): + parser.set('aliases', key, value) + with open(filename, 'wb') as file: + parser.write(file) + pass_config = click.make_pass_decorator(Config, ensure=True) @@ -109,3 +120,16 @@ def commit(): def status(config): """Shows the status.""" click.echo('Status for %s' % config.path) + + +@cli.command() +@pass_config +@click.argument("alias_", metavar='ALIAS', type=click.STRING) +@click.argument("cmd", type=click.STRING) +@click.option('--config_file', type=click.Path(exists=True, dir_okay=False), + default="aliases.ini") +def alias(config, alias_, cmd, config_file): + """Adds an alias to the specified configuration file.""" + config.add_alias(alias_, cmd) + config.write_config(config_file) + click.echo('Added %s as alias for %s' % (alias_, cmd)) |