<commit_before>from __future__ import print_function

import os
import time
start = time.time()
from textwrap import fill, dedent
from sys import stdout, stderr
from . import public_relay
from .. import __version__
from ..timing import DebugTiming
from ..errors import WrongPasswordError, WelcomeError, KeyFormatError
from twisted.internet.defer import inlineCallbacks, maybeDeferred
from twisted.python.failure import Failure
from twisted.internet.task import react

import click
top_import_finish = time.time()


class Config(object):
    """
    Union of config options that we pass down to (sub) commands.
    """
    def __init__(self):
        # This only holds attributes which are *not* set by CLI arguments.
        # Everything else comes from Click decorators, so we can be sure
        # we're exercising the defaults.
        self.timing = DebugTiming()
        self.cwd = os.getcwd()
        self.stdout = stdout
        self.stderr = stderr
        self.tor = False  # XXX?

def _compose(*decorators):
    def decorate(f):
        for d in reversed(decorators):
            f = d(f)
        return f
    return decorate


ALIASES = {
    "tx": "send",
    "rx": "receive",
    "recieve": "receive",
    "recv": "receive",
}
class AliasedGroup(click.Group):
    def get_command(self, ctx, cmd_name):
        cmd_name = ALIASES.get(cmd_name, cmd_name)
        return click.Group.get_command(self, ctx, cmd_name)


# top-level command ("wormhole ...")
@click.group(cls=AliasedGroup)
@click.option(
    "--relay-url", default=public_relay.RENDEZVOUS_RELAY,
    metavar="URL",
    help="rendezvous relay to use",
)
@click.option(
    "--transit-helper", default=public_relay.TRANSIT_RELAY,
    metavar="tcp:HOST:PORT",
    help="transit relay to use",
)
@click.option(
    "--dump-timing", type=type(u""), # TODO: hide from --help output
    default=None,
    metavar="FILE.json",
    help="(debug) write timing data to file",
)
@click.version_option(
    message="magic-wormhole %(version)s",
    version=__version__,
)
@click.pass_context
def wormhole(context, dump_timing, transit_helper, relay_url):
    """
    Create a Magic Wormhole and communicate through it.

    Wormholes are created by speaking the same magic CODE in two
    different places at the same time.  Wormholes are secure against
    anyone who doesn't use the same code.
    """
    context.obj = cfg = Config()
    cfg.relay_url = relay_url
    cfg.transit_helper = transit_helper
    cfg.dump_timing = dump_timing


@inlineCallbacks
def _dispatch_command(reactor, cfg, command):
    """
    Internal helper. This calls the given command (a no-argument
    callable) with the Config instance in cfg and interprets any
    errors for the user.
    """
    cfg.timing.add("command dispatch")
    cfg.timing.add("import", when=start, which="top").finish(when=top_import_finish)

    try:
        yield maybeDeferred(command)
    except WrongPasswordError as e:
        msg = fill("ERROR: " + dedent(e.__doc__))
        print(msg, file=stderr)
    except WelcomeError as e:
        msg = fill("ERROR: " + dedent(e.__doc__))
        print(msg, file=stderr)
        print(file=stderr)
        print(str(e), file=stderr)
    except KeyFormatError as e:
        msg = fill("ERROR: " + dedent(e.__doc__))
        print(msg, file=stderr)
    except Exception as e:
        # this prints a proper traceback, whereas
        # traceback.print_exc() just prints a TB to the "yield"
        # line above ...
        Failure().printTraceback(file=stderr)
        print("ERROR:", e, file=stderr)
        raise SystemExit(1)

    cfg.timing.add("exit")
    if cfg.dump_timing:
        cfg.timing.write(cfg.dump_timing, stderr)


CommonArgs = _compose(
    click.option("-0", "zeromode", default=False, is_flag=True,
                 help="enable no-code anything-goes mode",
                 ),
    click.option("-c", "--code-length", default=2, metavar="NUMWORDS",
                 help="length of code (in bytes/words)",
                 ),
    click.option("-v", "--verify", is_flag=True, default=False,
                 help="display verification string (and wait for approval)",
                 ),
    click.option("--hide-progress", is_flag=True, default=False,<commit_msg>CLI: exit with rc=1 upon errors<commit_after>from __future__ import print_function

import os
import time
start = time.time()
from textwrap import fill, dedent
from sys import stdout, stderr
from . import public_relay
from .. import __version__
from ..timing import DebugTiming
from ..errors import WrongPasswordError, WelcomeError, KeyFormatError
from twisted.internet.defer import inlineCallbacks, maybeDeferred
from twisted.python.failure import Failure
from twisted.internet.task import react

import click
top_import_finish = time.time()


class Config(object):
    """
    Union of config options that we pass down to (sub) commands.
    """
    def __init__(self):
        # This only holds attributes which are *not* set by CLI arguments.
        # Everything else comes from Click decorators, so we can be sure
        # we're exercising the defaults.
        self.timing = DebugTiming()
        self.cwd = os.getcwd()
        self.stdout = stdout
        self.stderr = stderr
        self.tor = False  # XXX?

def _compose(*decorators):
    def decorate(f):
        for d in reversed(decorators):
            f = d(f)
        return f
    return decorate


ALIASES = {
    "tx": "send",
    "rx": "receive",
    "recieve": "receive",
    "recv": "receive",
}
class AliasedGroup(click.Group):
    def get_command(self, ctx, cmd_name):
        cmd_name = ALIASES.get(cmd_name, cmd_name)
        return click.Group.get_command(self, ctx, cmd_name)


# top-level command ("wormhole ...")
@click.group(cls=AliasedGroup)
@click.option(
    "--relay-url", default=public_relay.RENDEZVOUS_RELAY,
    metavar="URL",
    help="rendezvous relay to use",
)
@click.option(
    "--transit-helper", default=public_relay.TRANSIT_RELAY,
    metavar="tcp:HOST:PORT",
    help="transit relay to use",
)
@click.option(
    "--dump-timing", type=type(u""), # TODO: hide from --help output
    default=None,
    metavar="FILE.json",
    help="(debug) write timing data to file",
)
@click.version_option(
    message="magic-wormhole %(version)s",
    version=__version__,
)
@click.pass_context
def wormhole(context, dump_timing, transit_helper, relay_url):
    """
    Create a Magic Wormhole and communicate through it.

    Wormholes are created by speaking the same magic CODE in two
    different places at the same time.  Wormholes are secure against
    anyone who doesn't use the same code.
    """
    context.obj = cfg = Config()
    cfg.relay_url = relay_url
    cfg.transit_helper = transit_helper
    cfg.dump_timing = dump_timing


@inlineCallbacks
def _dispatch_command(reactor, cfg, command):
    """
    Internal helper. This calls the given command (a no-argument
    callable) with the Config instance in cfg and interprets any
    errors for the user.
    """
    cfg.timing.add("command dispatch")
    cfg.timing.add("import", when=start, which="top").finish(when=top_import_finish)

    try:
        yield maybeDeferred(command)
    except (WrongPasswordError, KeyFormatError) as e:
        msg = fill("ERROR: " + dedent(e.__doc__))
        print(msg, file=stderr)
        raise SystemExit(1)
    except WelcomeError as e:
        msg = fill("ERROR: " + dedent(e.__doc__))
        print(msg, file=stderr)
        print(file=stderr)
        print(str(e), file=stderr)
        raise SystemExit(1)
    except Exception as e:
        # this prints a proper traceback, whereas
        # traceback.print_exc() just prints a TB to the "yield"
        # line above ...
        Failure().printTraceback(file=stderr)
        print("ERROR:", e, file=stderr)
        raise SystemExit(1)

    cfg.timing.add("exit")
    if cfg.dump_timing:
        cfg.timing.write(cfg.dump_timing, stderr)


CommonArgs = _compose(
    click.option("-0", "zeromode", default=False, is_flag=True,
                 help="enable no-code anything-goes mode",
                 ),
    click.option("-c", "--code-length", default=2, metavar="NUMWORDS",
                 help="length of code (in bytes/words)",
                 ),
    click.option("-v", "--verify", is_flag=True, default=False,
                 help="display verification string (and wait for approval)",
                 ),
    click.option("--hide-progress", is_flag=True, default=False,
{'fraction_non_alphanumeric': 0.11446778380929903, 'fraction_numerical': 0.001062072220911022, 'mean_word_length': 2.9565826330532214, 'pattern_counts': {'":': 8, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5413924', 'n_tokens_mistral': 2623, 'n_tokens_neox': 2571, 'n_words': 724}