| 1 |
import configparser |
| 2 |
import os |
| 3 |
|
| 4 |
import click |
| 5 |
|
| 6 |
|
| 7 |
class Config: |
| 8 |
"""The config in this example only holds aliases.""" |
| 9 |
|
| 10 |
def __init__(self): |
| 11 |
self.path = os.getcwd() |
| 12 |
self.aliases = {} |
| 13 |
|
| 14 |
def add_alias(self, alias, cmd): |
| 15 |
self.aliases.update({alias: cmd}) |
| 16 |
|
| 17 |
def read_config(self, filename): |
| 18 |
parser = configparser.RawConfigParser() |
| 19 |
parser.read([filename]) |
| 20 |
try: |
| 21 |
self.aliases.update(parser.items("aliases")) |
| 22 |
except configparser.NoSectionError: |
| 23 |
pass |
| 24 |
|
| 25 |
def write_config(self, filename): |
| 26 |
parser = configparser.RawConfigParser() |
| 27 |
parser.add_section("aliases") |
| 28 |
for key, value in self.aliases.items(): |
| 29 |
parser.set("aliases", key, value) |
| 30 |
with open(filename, "wb") as file: |
| 31 |
parser.write(file) |
| 32 |
|
| 33 |
|
| 34 |
pass_config = click.make_pass_decorator(Config, ensure=True) |
| 35 |
|
| 36 |
|
| 37 |
class AliasedGroup(click.Group): |
| 38 |
"""This subclass of a group supports looking up aliases in a config |
| 39 |
file and with a bit of magic. |
| 40 |
""" |
| 41 |
|
| 42 |
def get_command(self, ctx, cmd_name): |
| 43 |
# Step one: bulitin commands as normal |
| 44 |
rv = click.Group.get_command(self, ctx, cmd_name) |
| 45 |
if rv is not None: |
| 46 |
return rv |
| 47 |
|
| 48 |
# Step two: find the config object and ensure it's there. This |
| 49 |
# will create the config object is missing. |
| 50 |
cfg = ctx.ensure_object(Config) |
| 51 |
|
| 52 |
# Step three: look up an explicit command alias in the config |
| 53 |
if cmd_name in cfg.aliases: |
| 54 |
actual_cmd = cfg.aliases[cmd_name] |
| 55 |
return click.Group.get_command(self, ctx, actual_cmd) |
| 56 |
|
| 57 |
# Alternative option: if we did not find an explicit alias we |
| 58 |
# allow automatic abbreviation of the command. "status" for |
| 59 |
# instance will match "st". We only allow that however if |
| 60 |
# there is only one command. |
| 61 |
matches = [ |
| 62 |
x for x in self.list_commands(ctx) if x.lower().startswith(cmd_name.lower()) |
| 63 |
] |
| 64 |
if not matches: |
| 65 |
return None |
| 66 |
elif len(matches) == 1: |
| 67 |
return click.Group.get_command(self, ctx, matches[0]) |
| 68 |
ctx.fail(f"Too many matches: {', '.join(sorted(matches))}") |
| 69 |
|
| 70 |
def resolve_command(self, ctx, args): |
| 71 |
# always return the command's name, not the alias |
| 72 |
_, cmd, args = super().resolve_command(ctx, args) |
| 73 |
return cmd.name, cmd, args |
| 74 |
|
| 75 |
|
| 76 |
def read_config(ctx, param, value): |
| 77 |
"""Callback that is used whenever --config is passed. We use this to |
| 78 |
always load the correct config. This means that the config is loaded |
| 79 |
even if the group itself never executes so our aliases stay always |
| 80 |
available. |
| 81 |
""" |
| 82 |
cfg = ctx.ensure_object(Config) |
| 83 |
if value is None: |
| 84 |
value = os.path.join(os.path.dirname(__file__), "aliases.ini") |
| 85 |
cfg.read_config(value) |
| 86 |
return value |
| 87 |
|
| 88 |
|
| 89 |
@click.command(cls=AliasedGroup) |
| 90 |
@click.option( |
| 91 |
"--config", |
| 92 |
type=click.Path(exists=True, dir_okay=False), |
| 93 |
callback=read_config, |
| 94 |
expose_value=False, |
| 95 |
help="The config file to use instead of the default.", |
| 96 |
) |
| 97 |
def cli(): |
| 98 |
"""An example application that supports aliases.""" |
| 99 |
|
| 100 |
|
| 101 |
@cli.command() |
| 102 |
def push(): |
| 103 |
"""Pushes changes.""" |
| 104 |
click.echo("Push") |
| 105 |
|
| 106 |
|
| 107 |
@cli.command() |
| 108 |
def pull(): |
| 109 |
"""Pulls changes.""" |
| 110 |
click.echo("Pull") |
| 111 |
|
| 112 |
|
| 113 |
@cli.command() |
| 114 |
def clone(): |
| 115 |
"""Clones a repository.""" |
| 116 |
click.echo("Clone") |
| 117 |
|
| 118 |
|
| 119 |
@cli.command() |
| 120 |
def commit(): |
| 121 |
"""Commits pending changes.""" |
| 122 |
click.echo("Commit") |
| 123 |
|
| 124 |
|
| 125 |
@cli.command() |
| 126 |
@pass_config |
| 127 |
def status(config): |
| 128 |
"""Shows the status.""" |
| 129 |
click.echo(f"Status for {config.path}") |
| 130 |
|
| 131 |
|
| 132 |
@cli.command() |
| 133 |
@pass_config |
| 134 |
@click.argument("alias_", metavar="ALIAS", type=click.STRING) |
| 135 |
@click.argument("cmd", type=click.STRING) |
| 136 |
@click.option( |
| 137 |
"--config_file", type=click.Path(exists=True, dir_okay=False), default="aliases.ini" |
| 138 |
) |
| 139 |
def alias(config, alias_, cmd, config_file): |
| 140 |
"""Adds an alias to the specified configuration file.""" |
| 141 |
config.add_alias(alias_, cmd) |
| 142 |
config.write_config(config_file) |
| 143 |
click.echo(f"Added '{alias_}' as alias for '{cmd}'") |