Skip to content
Myr

repo.py

This file

Path

examples/repo/repo.py

166 lines · 4.6 KiB · Python

Last changed by

add codespell pre-commit hook (#3373)David Lordbefore adoption8bd8b4a

History of this file

Take it

1import os2import posixpath3import sys45import click678class Repo:9    def __init__(self, home):10        self.home = home11        self.config = {}12        self.verbose = False1314    def set_config(self, key, value):15        self.config[key] = value16        if self.verbose:17            click.echo(f"  config[{key}] = {value}", file=sys.stderr)1819    def __repr__(self):20        return f"<Repo {self.home}>"212223pass_repo = click.make_pass_decorator(Repo)242526@click.group()27@click.option(28    "--repo-home",29    envvar="REPO_HOME",30    default=".repo",31    metavar="PATH",32    help="Changes the repository folder location.",33)34@click.option(35    "--config",36    nargs=2,37    multiple=True,38    metavar="KEY VALUE",39    help="Overrides a config key/value pair.",40)41@click.option("--verbose", "-v", is_flag=True, help="Enables verbose mode.")42@click.version_option("1.0")43@click.pass_context44def cli(ctx, repo_home, config, verbose):45    """Repo is a command line tool that showcases how to build complex46    command line interfaces with Click.4748    This tool is supposed to look like a distributed version control49    system to show how something like this can be structured.50    """51    # Create a repo object and remember it as the context object.  From52    # this point onwards other commands can refer to it by using the53    # @pass_repo decorator.54    ctx.obj = Repo(os.path.abspath(repo_home))55    ctx.obj.verbose = verbose56    for key, value in config:57        ctx.obj.set_config(key, value)585960@cli.command()61@click.argument("src")62@click.argument("dest", required=False)63@click.option(64    "--shallow/--deep",65    default=False,66    help="Makes a checkout shallow or deep.  Deep by default.",67)68@click.option(69    "--rev", "-r", default="HEAD", help="Clone a specific revision instead of HEAD."70)71@pass_repo72def clone(repo, src, dest, shallow, rev):73    """Clones a repository.7475    This will clone the repository at SRC into the folder DEST.  If DEST76    is not provided this will automatically use the last path component77    of SRC and create that folder.78    """79    if dest is None:80        dest = posixpath.split(src)[-1] or "."81    click.echo(f"Cloning repo {src} to {os.path.basename(dest)}")82    repo.home = dest83    if shallow:84        click.echo("Making shallow checkout")85    click.echo(f"Checking out revision {rev}")868788@cli.command()89@click.confirmation_option()90@pass_repo91def delete(repo):92    """Deletes a repository.9394    This will throw away the current repository.95    """96    click.echo(f"Destroying repo {repo.home}")97    click.echo("Deleted!")9899100@cli.command()101@click.option("--username", prompt=True, help="The developer's shown username.")102@click.option("--email", prompt="E-Mail", help="The developer's email address")103@click.password_option(help="The login password.")104@pass_repo105def setuser(repo, username, email, password):106    """Sets the user credentials.107108    This will override the current user config.109    """110    repo.set_config("username", username)111    repo.set_config("email", email)112    repo.set_config("password", "*" * len(password))113    click.echo("Changed credentials.")114115116@cli.command()117@click.option(118    "--message",119    "-m",120    multiple=True,121    help="The commit message.  If provided multiple times each"122    " argument gets converted into a new line.",123)124@click.argument("files", nargs=-1, type=click.Path())125@pass_repo126def commit(repo, files, message):127    """Commits outstanding changes.128129    Commit changes to the given files into the repository.  You will need to130    "repo push" to push up your changes to other repositories.131132    If a list of files is omitted, all changes reported by "repo status"133    will be committed.134    """135    if not message:136        marker = "# Files to be committed:"137        hint = ["", "", marker, "#"]138        for file in files:139            hint.append(f"#   U {file}")140        message = click.edit("\n".join(hint))141        if message is None:142            click.echo("Aborted!")143            return144        msg = message.split(marker)[0].rstrip()145        if not msg:146            click.echo("Aborted! Empty commit message")147            return148    else:149        msg = "\n".join(message)150    click.echo(f"Files to be committed: {files}")151    click.echo(f"Commit message:\n{msg}")152153154@cli.command(short_help="Copies files.")155@click.option(156    "--force", is_flag=True, help="forcibly copy over an existing managed file"157)158@click.argument("src", nargs=-1, type=click.Path())159@click.argument("dst", type=click.Path())160@pass_repo161def copy(repo, src, dst, force):162    """Copies one or multiple files to a new location.  This copies all163    files from SRC to DST.164    """165    for fn in src:166        click.echo(f"Copy from {fn} -> {dst}")