Exemple #1
0
def get_main_parser():
    parser = argparse.ArgumentParser(prog="pathcomplete")
    shtab.add_argument_to(parser, ["-s", "--print-completion"])  # magic!
    # file & directory tab complete
    parser.add_argument("file", nargs="?").complete = shtab.FILE
    parser.add_argument("--dir", default=".").complete = shtab.DIRECTORY
    return parser
Exemple #2
0
def get_main_parser():
    main_parser = argparse.ArgumentParser(prog="customcomplete")
    subparsers = main_parser.add_subparsers()
    # make required (py3.7 API change); vis. https://bugs.python.org/issue16308
    subparsers.required = True
    subparsers.dest = "subcommand"

    parser = subparsers.add_parser("completion")
    shtab.add_argument_to(parser, "shell")  # magic!

    parser = subparsers.add_parser("process")
    # `*.txt` file tab completion
    parser.add_argument("input_txt", nargs="?").complete = TXT_FILE
    # file tab completion builtin shortcut
    parser.add_argument("-i", "--input-file").complete = shtab.FILE
    parser.add_argument(
        "-o",
        "--output-name",
        help=(
            "output file name. Completes directory names to avoid users"
            " accidentally overwriting existing files."
        ),
    ).complete = shtab.DIRECTORY  # directory tab completion builtin shortcut
    parser.set_defaults(func=process)
    return main_parser
Exemple #3
0
def main():
    parser = create_parser()
    # use shtab magic
    # add global optional argument for generating shell completion script
    shtab.add_argument_to(parser, ["-s", "--shell-completion"],
                          help="Generate tab completion script for your shell")
    args = parser.parse_args()
    return args.func(args)
Exemple #4
0
def test_add_argument_to_optional(shell, caplog):
    parser = ArgumentParser(prog="test")
    shtab.add_argument_to(parser, ["-s", "--shell"])
    with caplog.at_level(logging.INFO):
        completion = shtab.complete(parser, shell=shell)
    print(completion)

    if shell == "bash":
        shell = Bash(completion)
        shell.compgen('-W "$_shtab_test_options_"', "--s", "--shell")

    assert not caplog.record_tuples
Exemple #5
0
def main():
    parser = create_parser()
    # use shtab magic
    # add global optional argument for generating shell completion script
    shtab.add_argument_to(parser, ["-s", "--shell-completion"],
                          help="Generate tab completion script for your shell")
    parser.add_argument("--version",
                        "-v",
                        action=PrintCurrentVersionAction,
                        nargs=0,
                        help="Get current opera package version")
    args = parser.parse_args()
    return args.func(args)
Exemple #6
0
def test_add_argument_to_positional(shell, caplog):
    parser = ArgumentParser(prog="test")
    subparsers = parser.add_subparsers()
    sub = subparsers.add_parser("completion")
    shtab.add_argument_to(sub, "shell")
    with caplog.at_level(logging.INFO):
        completion = shtab.complete(parser, shell=shell)
    print(completion)

    if shell == "bash":
        shell = Bash(completion)
        shell.compgen('-W "$_shtab_test_completion"', "ba", "bash")
        shell.compgen('-W "$_shtab_test_completion"', "z", "zsh")

    assert not caplog.record_tuples
Exemple #7
0
def main() -> None:
    parser = argparse.ArgumentParser("scratch")
    subparsers = parser.add_subparsers(
        dest="subcommand", required=True, description="", help="subparsers"
    )
    for name, configure, run, description in [
        ("login", login.configure_parser, login.run, "Log in to AWS SSO"),
        (
            "create",
            create.configure_parser,
            create.run,
            "Create a new scratch instance",
        ),
        ("mine", mine.configure_parser, mine.run, "Show active scratch instance"),
        ("ssh", ssh.configure_parser, ssh.run, "Connect to scratch instance via ssh"),
        (
            "sftp",
            sftp.configure_parser,
            sftp.run,
            "Connect to scratch instance via sftp",
        ),
        (
            "destroy",
            destroy.configure_parser,
            destroy.run,
            "Destroy a scratch instance",
        ),
        (
            "push",
            push.configure_parser,
            push.run,
            "Push current HEAD (or a specific git commit) to scratch instance",
        ),
        (
            "completion",
            lambda p: shtab.add_argument_to(p, "shell", parent=parser),
            lambda: None,
            "Generate shell completion script",
        ),
    ]:
        s = subparsers.add_parser(name, description=description, help=description)
        configure(s)
        s.set_defaults(run=run)

    args = parser.parse_args()
    args.run(args)
Exemple #8
0
def get_main_parser():
    parser = argparse.ArgumentParser()
    shtab.add_argument_to(parser, ["-s", "--print-completion"])  # magic!

    parser.add_argument('-v',
                        '--verbosity',
                        help='Set verbosity level',
                        choices=['warning', 'info', 'debug'],
                        default='info')
    subparsers = parser.add_subparsers(help='Desired action to perform',
                                       dest='command')

    # help
    subparsers.add_parser('help', help='Print this help message')

    # Create parent subparser for {dl_docs, check}-parsers with common arguments
    parent_parser = argparse.ArgumentParser(add_help=False)

    # Subparsers based on parent

    parser_login = subparsers.add_parser(
        'login',
        parents=[parent_parser],
        help=
        'Check if credentials file exists. If not create it and ask for input. Try to login. Ask for device reset if needed',
    )
    parser_login.add_argument(
        '-n',
        '--phone_no',
        help='TradeRepbulic phone number (international format)')
    parser_login.add_argument('-p', '--pin', help='TradeRepbulic pin')

    subparsers.add_parser('portfolio',
                          parents=[parent_parser],
                          help='Show current portfolio')

    parser_dl_docs = subparsers.add_parser(
        'dl_docs',
        parents=[parent_parser],
        help=
        'Download all pdf documents from the timeline and sort them into folders',
    )
    parser_dl_docs.add_argument('output',
                                help='Output directory',
                                metavar='PATH')

    parser_get_price_alarms = subparsers.add_parser(
        'get_price_alarms',
        parents=[parent_parser],
        help='Get overview of current price alarms')
    parser_details = subparsers.add_parser('details',
                                           parents=[parent_parser],
                                           help='Get details for an ISIN')
    parser_details.add_argument('isin', help='ISIN of intrument')
    parser_set_price_alarms = subparsers.add_parser(
        'set_price_alarms',
        parents=[parent_parser],
        help='Set price alarms based on diff from current price')
    parser_set_price_alarms.add_argument(
        '-p',
        '--percent',
        help='Percentage +/-',
        # choices=range(-1000, 1001),
        metavar='[-1000 ... 1000]',
        type=int,
        default=-10,
    )
    return parser
Exemple #9
0
def get_main_parser(gui_mode=True, argparser=MyParser):
    import miutil.cuinfo
    import niftypad.api
    import niftypad.models

    from amypet import centiloid, dcm2nii, imscroll, imtrimup

    def fix_subparser(subparser, gui_mode=gui_mode):
        subparser.add_argument(
            "--dry-run",
            action="store_true",
            help="don't run command (implies print_command)" if gui_mode else SUPPRESS,
        )
        return subparser

    parser = fix_subparser(argparser(prog=None if gui_mode else "amypet"), gui_mode=gui_mode)
    sub_kwargs = {}
    if sys.version_info[:2] >= (3, 7):
        sub_kwargs["required"] = True
    subparsers = parser.add_subparsers(help="pipeline to run", **sub_kwargs)
    if not gui_mode:
        subparser = subparsers.add_parser("completion", help="Print tab completion scripts")
        shtab.add_argument_to(subparser, "shell", parent=parser)

    def argparser(prog, description=None, epilog=None, formatter_class=None):
        """handle (prog, description, epilog) => (title, help)"""
        return fix_subparser(
            subparsers.add_parser(
                {"miutil.cuinfo": "cuinfo"}.get(prog, prog),               # override
                help="\n".join([description or "", epilog or ""]).strip(),
            ),
            gui_mode=gui_mode,
        )

    Func(imscroll.run, imscroll.__doc__, version=niftypad.__version__,
         python_deps=["miutil[nii,plot]>=0.9.0", "tqdm"], argparser=argparser)

    Func(dcm2nii.run, dcm2nii.__doc__, version=niftypad.__version__, python_deps=["nimpa"],
         argparser=argparser)

    Func(imtrimup.run, imtrimup.__doc__, version=niftypad.__version__, python_deps=["nimpa"],
         argparser=argparser)

    Func(centiloid.run, centiloid.__doc__, version=niftypad.__version__,
         python_deps=["miutil[nii]", "setuptools", "spm12", "tqdm"], argparser=argparser)

    kinetic_model = Func(
        niftypad.api.kinetic_model, """\
        Kinetic modelling

        Usage:
          kinetic_model [options] <src>

        Arguments:
          <src>  : Input file/folder [default: FileChooser]

        Options:
          --dst PATH           : Output file/folder (default: input folder)
            [default: FileChooser]
          --model MODEL        : model [default: srtmb_basis]
          --params FILE        : config file hint (relative to `src` input).
            Default: search for {config,params}.{yaml,json}.
          --w W                : (default: None)
          --r1 R1              : [default: 0.905:float]
          --k2p K2P            : [default: 0.000250:float]
          --beta_lim BETA_LIM  : (default: None)
          --n_beta N_BETA      : [default: 40:int]
          --linear_phase_start LINEAR_PHASE_START  : [default: 500:int]
          --linear_phase_end LINEAR_PHASE_END      : (default: None)
          --km_outputs KM_OUTPUTS                  : (default: None)
          --thr THR                                : [default: 0.1:float]
        """, version=niftypad.__version__, python_deps=["niftypad>=1.1.1"], argparser=argparser)
    opts = kinetic_model.parser._get_optional_actions()
    model = next(i for i in opts if i.dest == "model")
    model.choices = niftypad.models.NAMES

    # example of how to wrap any CLI command using an `argopt`-style docstring
    Cmd([sys.executable, "-m", "miutil.cuinfo"], miutil.cuinfo.__doc__, version=miutil.__version__,
        python_deps=["miutil[cuda]>=0.8.0"], argparser=argparser)

    return parser
Exemple #10
0
def create_parser() -> ArgumentParser:
    parser = ArgumentParser(prog="tldr",
                            usage="tldr command [options]",
                            description="Python command line client for tldr")
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='%(prog)s {} (Client Specification {})'.format(
                            __version__, __client_specification__))

    parser.add_argument("--search",
                        metavar='"KEYWORDS"',
                        type=str,
                        help="Search for a specific command from a query")

    parser.add_argument('-u',
                        '--update_cache',
                        action='store_true',
                        help="Update the local cache of pages and exit")

    parser.add_argument(
        '-p',
        '--platform',
        nargs=1,
        default=None,
        type=str,
        choices=['linux', 'osx', 'sunos', 'windows', 'common'],
        metavar='PLATFORM',
        help=
        "Override the operating system [linux, osx, sunos, windows, common]")

    parser.add_argument(
        '-l',
        '--list',
        default=False,
        action='store_true',
        help="List all available commands for operating system")

    parser.add_argument('-s',
                        '--source',
                        default=PAGES_SOURCE_LOCATION,
                        type=str,
                        help="Override the default page source")

    parser.add_argument('-c',
                        '--color',
                        default=None,
                        action='store_const',
                        const=False,
                        help="Override color stripping")

    parser.add_argument('-r',
                        '--render',
                        default=False,
                        action='store_true',
                        help='Render local markdown files')

    parser.add_argument('-L',
                        '--language',
                        nargs=1,
                        default=None,
                        type=str,
                        help='Override the default language')

    parser.add_argument('-m',
                        '--markdown',
                        default=False,
                        action='store_true',
                        help='Just print the plain page file.')

    parser.add_argument('command',
                        type=str,
                        nargs='*',
                        help="command to lookup",
                        metavar='command').complete = {
                            "bash": "shtab_tldr_cmd_list",
                            "zsh": "shtab_tldr_cmd_list"
                        }

    shtab.add_argument_to(parser,
                          preamble={
                              'bash':
                              r'''shtab_tldr_cmd_list(){{
          compgen -W "$("{py}" -m tldr --list | sed 's/\W/ /g')" -- "$1"
        }}'''.format(py=sys.executable),
                              'zsh':
                              r'''shtab_tldr_cmd_list(){{
          _describe 'command' "($("{py}" -m tldr --list | sed 's/\W/ /g'))"
        }}'''.format(py=sys.executable)
                          })

    return parser
Exemple #11
0
def tool() -> None:
    """
    Provides the CLI of PyFunceble.
    """

    # pylint: disable=too-many-locals

    # We start with loading the configuration. That way, we don't have to
    # think of this anymore as soon as the CLI is called.
    # As the merging is now done on demand and not on first hand, this will
    # give us a bit of agility.
    PyFunceble.facility.ConfigLoader.start()

    colorama.init(autoreset=True)

    description = (
        f"{colorama.Style.BRIGHT}{colorama.Fore.GREEN}PyFunceble"
        f"{colorama.Style.RESET_ALL} - "
        "The tool to check the availability or syntax of domain, IP or URL.")

    our_epilog = (
        f"{colorama.Style.BRIGHT}{colorama.Fore.YELLOW}For an in-depth usage, "
        "explanation and examples of the arguments,\n"
        f"you should read the documentation at{colorama.Fore.GREEN} "
        "https://pyfunceble.readthedocs.io/en/latest/"
        f"{colorama.Style.RESET_ALL}\n\n")

    parser = OurArgumentParser(
        description=description,
        epilog=our_epilog + PyFunceble.cli.storage.STD_EPILOG,
        add_help=False,
        formatter_class=argparse.RawTextHelpFormatter,
    )

    # pylint:  disable=possibly-unused-variable

    shtab.add_argument_to(
        parser,
        option_string=["--show-completion"],
        help="Show Shell completion script and exit.",
    )
    source_group = parser.add_argument_group("Test sources")
    filtering_group = parser.add_argument_group(
        "Source filtering, decoding, conversion and expansion")
    test_control_group = parser.add_argument_group("Test control")
    dns_control_group = parser.add_argument_group("DNS control")
    database_control_group = parser.add_argument_group("Databases")
    output_control_group = parser.add_argument_group("Output control")
    multiprocessing_group = parser.add_argument_group("Multiprocessing")
    ci_group = parser.add_argument_group("CI / CD")

    funcs = [
        get_source_group_data,
        get_filtering_group_data,
        get_test_control_group_data,
        get_dns_control_group_data,
        get_database_control_group_data,
        get_output_control_group_data,
        get_multiprocessing_group_data,
        get_ci_group_data,
    ]

    for func in funcs:
        parser_name = func.__name__.replace("get_", "").replace("_data", "")

        try:
            add_arguments_to_parser(locals()[parser_name], func())
        except ValueError as exception:
            exception_message = str(exception)
            if "configuration" not in exception_message:
                raise exception

            missing_key = RegexHelper(r"<entry>\s\(\'(.*)\'\)").match(
                exception_message, return_match=True, group=1)

            if ask_authorization_to_merge_config(missing_key):
                PyFunceble.facility.ConfigLoader.set_merge_upstream(
                    True).start()
                add_arguments_to_parser(locals()[parser_name], func())
            else:
                print(
                    f"{colorama.Fore.RED}{colorama.Style.BRIGHT}Could not find "
                    f"the {missing_key!r} in your configuration.\n"
                    f"{colorama.Fore.MAGENTA}Please fix your "
                    "configuration file manually or fill a new issue if you "
                    "don't understand this error.")
                sys.exit(1)

    add_arguments_to_parser(parser, get_default_group_data())

    args = parser.parse_args()

    if any(
            getattr(args, x)
            for x in ["domains", "urls", "files", "url_files"]):
        SystemIntegrator(args).start()
        SystemLauncher(args).start()
Exemple #12
0
def get_main_parser():
    def formatter(prog):
        return argparse.HelpFormatter(prog, max_help_position=25)

    parser = argparse.ArgumentParser(formatter_class=formatter)
    shtab.add_argument_to(parser, ['-s', '--print-completion'])  # magic!

    parser.add_argument(
        '-v',
        '--verbosity',
        help='Set verbosity level (default: info)',
        choices=['warning', 'info', 'debug'],
        default='info',
    )
    parser.add_argument('--applogin',
                        help='Use app login instead of  web login',
                        action='store_true')
    parser.add_argument('-V',
                        '--version',
                        help='Print version information and quit',
                        action='store_true')
    parser_cmd = parser.add_subparsers(help='Desired action to perform',
                                       dest='command')

    # help
    parser_cmd.add_parser('help', help='Print this help message')

    # Create parent subparser with common login arguments
    parser_login_args = argparse.ArgumentParser(add_help=False)
    parser_login_args.add_argument(
        '-n',
        '--phone_no',
        help='TradeRepbulic phone number (international format)')
    parser_login_args.add_argument('-p', '--pin', help='TradeRepbulic pin')

    # login
    parser_login = parser_cmd.add_parser(
        'login',
        parents=[parser_login_args],
        help=
        'Check if credentials file exists. If not create it and ask for input.'
        + ' Try to login. Ask for device reset if needed',
    )
    # dl_docs
    parser_dl_docs = parser_cmd.add_parser(
        'dl_docs',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        parents=[parser_login_args],
        help=
        'Download all pdf documents from the timeline and sort them into folders',
    )
    parser_dl_docs.add_argument('output',
                                help='Output directory',
                                metavar='PATH',
                                type=Path)
    parser_dl_docs.add_argument(
        '--format',
        help='available variables:\tiso_date, time, title, doc_num, subtitle',
        metavar='FORMAT_STRING',
        default='{iso_date}{time} {title}{doc_num}',
    )
    parser_dl_docs.add_argument(
        '--last_days',
        help='Number of last days to include (use 0 get all days)',
        metavar='DAYS',
        default=0,
        type=int)
    # portfolio
    parser_cmd.add_parser('portfolio',
                          parents=[parser_login_args],
                          help='Show current portfolio')
    parser_details = parser_cmd.add_parser('details',
                                           parents=[parser_login_args],
                                           help='Get details for an ISIN')
    # details
    parser_details.add_argument('isin', help='ISIN of intrument')
    # get_price_alarms
    parser_get_price_alarms = parser_cmd.add_parser(
        'get_price_alarms',
        parents=[parser_login_args],
        help='Get overview of current price alarms',
    )
    # set_price_alarms
    parser_set_price_alarms = parser_cmd.add_parser(
        'set_price_alarms',
        parents=[parser_login_args],
        help='Set price alarms based on diff from current price',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser_set_price_alarms.add_argument('-%',
                                         '--percent',
                                         help='Percentage +/-',
                                         metavar='[-1000 ... 1000]',
                                         type=int,
                                         default=-10)
    # export_transactions
    parser_export_transactions = parser_cmd.add_parser(
        'export_transactions',
        help=
        'Create a CSV with the deposits and removals ready for importing into Portfolio Performance',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser_export_transactions.add_argument(
        'input',
        help='Input path to JSON (use other_events.json from dl_docs)',
        metavar='INPUT',
        type=Path)
    parser_export_transactions.add_argument('output',
                                            help='Output path of CSV file',
                                            metavar='OUTPUT',
                                            type=Path)
    parser_export_transactions.add_argument(
        '-l',
        '--lang',
        help='Two letter language code or "auto" for system language',
        default='auto')

    return parser
Exemple #13
0
#!/usr/bin/env python
"""Greetings and partings.

Usage:
  greeter [options] [<you>] [<me>]

Options:
  -g, --goodbye  : Say "goodbye" (instead of "hello")

Arguments:
  <you>  : Your name [default: Anon]
  <me>  : My name [default: Casper]
"""
import sys, argopt, shtab  # NOQA

parser = argopt.argopt(__doc__)
shtab.add_argument_to(parser, ["-s", "--print-completion"])  # magic!
if __name__ == "__main__":
    args = parser.parse_args()

    msg = "k thx bai!" if args.goodbye else "hai!"
    print("{} says '{}' to {}".format(args.me, msg, args.you))