Exemplo n.º 1
0
def main():
    """
    The main method of Barman
    """
    p = ArghParser(epilog='Barman by 2ndQuadrant (www.2ndQuadrant.com)')
    p.add_argument(
        '-v',
        '--version',
        action='version',
        version='%s\n\nBarman by 2ndQuadrant (www.2ndQuadrant.com)' %
        barman.__version__)
    p.add_argument('-c',
                   '--config',
                   help='uses a configuration file '
                   '(defaults: %s)' %
                   ', '.join(barman.config.Config.CONFIG_FILES),
                   default=SUPPRESS)
    p.add_argument('-q', '--quiet', help='be quiet', action='store_true')
    p.add_argument('-d', '--debug', help='debug output', action='store_true')
    p.add_argument('-f',
                   '--format',
                   help='output format',
                   choices=output.AVAILABLE_WRITERS.keys(),
                   default=output.DEFAULT_WRITER)
    p.add_commands([
        archive_wal,
        backup,
        check,
        check_backup,
        cron,
        delete,
        diagnose,
        get_wal,
        list_backup,
        list_files,
        list_server,
        put_wal,
        rebuild_xlogdb,
        receive_wal,
        recover,
        show_backup,
        show_server,
        replication_status,
        status,
        switch_wal,
        switch_xlog,
    ])
    # noinspection PyBroadException
    try:
        p.dispatch(pre_call=global_config)
    except KeyboardInterrupt:
        msg = "Process interrupted by user (KeyboardInterrupt)"
        output.error(msg)
    except Exception as e:
        msg = "%s\nSee log file for more details." % e
        output.exception(msg)

    # cleanup output API and exit honoring output.error_occurred and
    # output.error_exit_code
    output.close_and_exit()
Exemplo n.º 2
0
def main():
    parser = ArghParser(description='Simple static gallery generator.')
    parser.add_commands([init, build, serve])
    parser.add_argument('--version',
                        action='version',
                        version='%(prog)s {}'.format(__version__))
    parser.dispatch()
Exemplo n.º 3
0
def main():
    l18n.init()

    parser = ArghParser()
    parser.add_argument('-a', '--auth',
                        action='store_true',
                        help=_('Authenticate and show all problems'
                               ' on this machine'))

    parser.add_argument('-v', '--version',
                        action='version',
                        version=config.VERSION)

    parser.add_commands([
        backtrace,
        di_install,
        gdb,
        info,
        list_problems,
        remove,
        report,
        retrace,
        status,
    ])

    argcomplete.autocomplete(parser)

    try:
        parser.dispatch()
    except KeyboardInterrupt:
        sys.exit(1)

    sys.exit(0)
Exemplo n.º 4
0
Arquivo: ctl.py Projeto: baloon11/npui
def main():
	parser = ArghParser()

	parser.add_commands(
		(
			module_list,
			module_install,
			module_uninstall,
			module_enable,
			module_disable
		),
		namespace='module',
		title='Module commands',
		description='Group of commands related to listing or (un)installing modules'
	)

	ini_file='production.ini'
	if 'NP_INI_FILE' in os.environ:
		ini_file = os.environ['NP_INI_FILE']

	ini_name='netprofile'
	if 'NP_INI_NAME' in os.environ:
		ini_name = os.environ['NP_INI_NAME']

	parser.add_argument('--ini-file', '-i', default=ini_file, help='Specify .ini file to use')
	parser.add_argument('--application', '-a', default=ini_name, help='Default app section of .ini file to use')

	parser.dispatch()
Exemplo n.º 5
0
def main():
    reload(sys)
    sys.setdefaultencoding("utf-8")
    
    parser = ArghParser(description='Simple static gallery generator.')
    parser.add_commands([init, build, serve])
    parser.add_argument('--version', action='version',
                        version='%(prog)s {}'.format(__version__))
    parser.dispatch()
Exemplo n.º 6
0
def main():
    parser = ArghParser()
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version=__version__)
    enabled_commands = [init, build, watch, po, runserver]

    parser.add_commands(enabled_commands)
    parser.dispatch()
Exemplo n.º 7
0
def main():
    """
    Main entrypoint for console_script (commandline script)
    """
    parser = ArghParser()
    parser.add_argument("-v", "--version", action="version", version=client_version)
    enabled_commands = [register]

    parser.add_commands(enabled_commands)
    parser.dispatch()
Exemplo n.º 8
0
def main():
    reload(sys)
    sys.setdefaultencoding("utf-8")

    parser = ArghParser(description='Simple static gallery generator.')
    parser.add_commands([init, build, serve])
    parser.add_argument('--version',
                        action='version',
                        version='%(prog)s {}'.format(__version__))
    parser.dispatch()
Exemplo n.º 9
0
def main():
    """
    Main entrypoint for console_script (commandline script)
    """
    parser = ArghParser()
    parser.add_argument('-v', '--version', action='version', version=client_version)
    enabled_commands = [pull, push]
    
    parser.add_commands(enabled_commands)
    parser.dispatch()
Exemplo n.º 10
0
def main():
    commands = pack, watch, shell, libs
    names = [f.__name__ for f in commands] + [ 'help' ]

    parser = ArghParser()
    parser.add_argument('-v', '--version', action='version', version=VERSION, help='Show zeta version')
    parser.add_commands(commands)
    argv = sys.argv[1:]
    if argv and not argv[0] in names and not argv[0] in ['-v', '--version']:
        argv.insert(0, 'pack')
    parser.dispatch(argv)
Exemplo n.º 11
0
def main():
    """
    The main method of Barman
    """
    p = ArghParser(epilog='Barman by 2ndQuadrant (www.2ndQuadrant.com)')
    p.add_argument('-v', '--version', action='version',
                   version='%s\n\nBarman by 2ndQuadrant (www.2ndQuadrant.com)'
                           % barman.__version__)
    p.add_argument('-c', '--config',
                   help='uses a configuration file '
                        '(defaults: %s)'
                        % ', '.join(barman.config.Config.CONFIG_FILES),
                   default=SUPPRESS)
    p.add_argument('-q', '--quiet', help='be quiet', action='store_true')
    p.add_argument('-d', '--debug', help='debug output', action='store_true')
    p.add_argument('-f', '--format', help='output format',
                   choices=output.AVAILABLE_WRITERS.keys(),
                   default=output.DEFAULT_WRITER)
    p.add_commands(
        [
            archive_wal,
            backup,
            check,
            cron,
            delete,
            diagnose,
            get_wal,
            list_backup,
            list_files,
            list_server,
            rebuild_xlogdb,
            receive_wal,
            recover,
            show_backup,
            show_server,
            replication_status,
            status,
            switch_xlog,
        ]
    )
    # noinspection PyBroadException
    try:
        p.dispatch(pre_call=global_config)
    except KeyboardInterrupt:
        msg = "Process interrupted by user (KeyboardInterrupt)"
        output.error(msg)
    except Exception as e:
        msg = "%s\nSee log file for more details." % e
        output.exception(msg)

    # cleanup output API and exit honoring output.error_occurred and
    # output.error_exit_code
    output.close_and_exit()
Exemplo n.º 12
0
def get_base_parser():
    dist = pkg_resources.get_distribution("awstools")
    parser = ArghParser(version=dist.version)
    parser.add_argument('--config',
                        default=None,
                        help="path of an alternative configuration file")
    parser.add_argument(
        '--settings',
        default=None,
        help="path of the application settings configuration file")

    return parser
Exemplo n.º 13
0
def get_base_parser():
    dist = pkg_resources.get_distribution("awstools")
    parser = ArghParser(version=dist.version)
    parser.add_argument(
        '--config',
        default=None,
        help="path of an alternative configuration file")
    parser.add_argument(
        '--settings',
        default=None,
        help="path of the application settings configuration file")

    return parser
Exemplo n.º 14
0
def main():
    """
    Main entrypoint for console_script (commandline script)
    """
    parser = ArghParser()
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version=client_version)
    enabled_commands = [register]

    parser.add_commands(enabled_commands)
    parser.dispatch()
Exemplo n.º 15
0
def main():
    parser = ArghParser()
    parser.add_argument('-v', '--version', action='version', version=__version__)
    enabled_commands = [init, build, watch, po]
    
    # Enabling runserver command if cherrypy is installed
    try:
        import cherrypy
    except ImportError:
        pass
    else:
        from optimus.cli.runserver import runserver
        enabled_commands.append(runserver)
    
    parser.add_commands(enabled_commands)
    parser.dispatch()
Exemplo n.º 16
0
Arquivo: cli.py Projeto: girgen/barman
def main():
    """
    The main method of Barman
    """
    p = ArghParser()
    p.add_argument("-v", "--version", action="version", version=barman.__version__)
    p.add_argument(
        "-c",
        "--config",
        help="uses a configuration file " "(defaults: %s)" % ", ".join(barman.config.Config.CONFIG_FILES),
        default=SUPPRESS,
    )
    p.add_argument("-q", "--quiet", help="be quiet", action="store_true")
    p.add_argument("-d", "--debug", help="debug output", action="store_true")
    p.add_argument(
        "-f", "--format", help="output format", choices=output.AVAILABLE_WRITERS.keys(), default=output.DEFAULT_WRITER
    )
    p.add_commands(
        [
            archive_wal,
            backup,
            check,
            cron,
            delete,
            diagnose,
            get_wal,
            list_backup,
            list_files,
            list_server,
            rebuild_xlogdb,
            receive_wal,
            recover,
            show_backup,
            show_server,
            status,
        ]
    )
    # noinspection PyBroadException
    try:
        p.dispatch(pre_call=global_config)
    except KeyboardInterrupt:
        msg = "Process interrupted by user (KeyboardInterrupt)"
        output.exception(msg)
    except Exception, e:
        msg = "%s\nSee log file for more details." % e
        output.exception(msg)
Exemplo n.º 17
0
def main():
    """
    The main method of Barman
    """
    p = ArghParser()
    p.add_argument('-v', '--version', action='version',
                   version=barman.__version__)
    p.add_argument('-c', '--config',
                   help='uses a configuration file '
                        '(defaults: %s)'
                        % ', '.join(barman.config.Config.CONFIG_FILES),
                   default=SUPPRESS)
    p.add_argument('-q', '--quiet', help='be quiet', action='store_true')
    p.add_argument('-d', '--debug', help='debug output', action='store_true')
    p.add_argument('-f', '--format', help='output format',
                   choices=output.AVAILABLE_WRITERS.keys(),
                   default=output.DEFAULT_WRITER)
    p.add_commands(
        [
            archive_wal,
            cron,
            list_server,
            show_server,
            status,
            check,
            diagnose,
            backup,
            list_backup,
            show_backup,
            list_files,
            get_wal,
            recover,
            delete,
            rebuild_xlogdb,
        ]
    )
    # noinspection PyBroadException
    try:
        p.dispatch(pre_call=global_config)
    except KeyboardInterrupt:
        msg = "Process interrupted by user (KeyboardInterrupt)"
        output.exception(msg)
    except Exception, e:
        msg = "%s\nSee log file for more details." % e
        output.exception(msg)
Exemplo n.º 18
0
Arquivo: cli.py Projeto: jfilak/abrt
def main():
    l18n.init()

    parser = ArghParser()
    parser.add_argument(
        "-a", "--auth", action="store_true", help=_("Authenticate and show all problems" " on this machine")
    )

    parser.add_argument("-v", "--version", action="version", version=config.VERSION)

    parser.add_commands([backtrace, di_install, gdb, info, list_problems, remove, report, retrace, status])

    argcomplete.autocomplete(parser)

    try:
        parser.dispatch()
    except KeyboardInterrupt:
        sys.exit(1)

    sys.exit(0)
Exemplo n.º 19
0
def main():
    ''' The main method of Barman '''
    p = ArghParser()
    p.add_argument('-v', '--version', action='version', version=barman.__version__)
    p.add_argument('-c', '--config', help='uses a configuration file (defaults: $HOME/.barman.conf, /etc/barman.conf)')
    p.add_argument('-q', '--quiet', help='be quiet', action='store_true')
    p.add_commands(
        [
            cron,
            list_server,
            show_server,
            status,
            check,
            backup,
            list_backup,
            show_backup,
            list_files,
            recover,
            delete,
        ]
    )
    try:
        p.dispatch(pre_call=global_config, output_file=_output_stream)
    except Exception:
        msg = "ERROR: Unhandled exception. See log file for more details."
        logging.exception(msg)
        raise SystemExit(msg)
Exemplo n.º 20
0
def main():
    ''' The main method of Barman '''
    p = ArghParser()
    p.add_argument('-v',
                   '--version',
                   action='version',
                   version=barman.__version__)
    p.add_argument(
        '-c',
        '--config',
        help=
        'uses a configuration file (defaults: $HOME/.barman.conf, /etc/barman.conf)'
    )
    p.add_argument('-q', '--quiet', help='be quiet', action='store_true')
    p.add_commands([
        cron,
        list_server,
        show_server,
        status,
        check,
        backup,
        list_backup,
        show_backup,
        list_files,
        recover,
        delete,
    ])
    try:
        p.dispatch(pre_call=global_config, output_file=_output_stream)
    except Exception:
        msg = "ERROR: Unhandled exception. See log file for more details."
        logging.exception(msg)
        raise SystemExit(msg)
Exemplo n.º 21
0
def main():  # pragma: no cover
    '''Console entry point.

    Constructs and dispatches the argument parser.
    '''
    parser = ArghParser(prog='pageit', description=pageit.__doc__,
                        epilog=pageit.__epilog__)
    parser.add_argument('--version', action='version',
                        version='%(prog)s ' + pageit.__version__)
    parser.add_argument('-v', '--verbose', dest='verbosity', action='count',
                        default=1, help='show logging messages')
    parser.add_argument('-q', '--quiet', dest='verbosity',
                        action='store_const', const=0,
                        help='suppress logging messages')
    parser.set_default_command(render)
    parser.dispatch()
Exemplo n.º 22
0
def main():
    parser = ArghParser(description='Simple static gallery generator.')
    parser.add_commands([init, build, serve])
    parser.add_argument('--version', action='version',
                        version='%(prog)s {}'.format(__version__))
    parser.dispatch()
Exemplo n.º 23
0
Arquivo: parser.py Projeto: Malex/pyg
def init_parser(version=None):
    import sys
    import os
    import _opts as opts
    from pyg.locations import INSTALL_DIR, USER_SITE
    from pyg.parser.formatter import _formatter
    from pyg.core import args_manager
    from argh import ArghParser, arg, command


    parser = ArghParser(prog='pyg')
    parser.add_argument('-d', '--debug', action='store_true', help='Set logger to DEBUG level')
    parser.add_argument('--verbose', action='store_true', help='Set logger to VERBOSE level')
    if version is not None:
        parser.add_argument('-v', '--version', action='version', version=version)
    parser.add_argument('--no-colors', action='store_true', help='Disable colors')
    #parser.add_argument('-i', '--index-url', default='http://pypi.python.org', metavar="<url>", help='Base URL of Python Package Index (default to %(default)s)')


    @arg('packname', nargs='*')
    @arg('-e', '--editable', action='store_true', help='Install a package from an online repository in editable mode')
    @arg('-r', '--req-file', metavar='<path>', action='append', help='Install packages from the specified requirement file')
    @arg('-U', '--upgrade', action='store_true', help='If the package is already installed re-install it again')
    @arg('-A', '--upgrade-all', action='store_true', help='Install again dependencies too')
    @arg('-n', '--no-deps', action='store_true', help='Do not install dependencies')
    @arg('-g', '--ignore', action='store_true', help='Ignore local files or directories')
    @arg('-i', '--index-url', default='http://pypi.python.org', metavar='<url>', help='Base URL of Python Package Index (default to %(default)s)')
    @arg('-d', '--install-dir', default=INSTALL_DIR, metavar='<path>', help='Base installation directory')
    @arg('-u', '--user', action='store_true', help='Install to user site')
    @arg('--no-scripts', action='store_true', help='Do not install scripts')
    @arg('--no-data', action='store_true', help='Do not install data files')
    @arg('--force-egg-install', action='store_true', help='Allow installing eggs with a different Python version')
    def install(args):
        '''
        Install a package
        '''

        if args.no_deps:
            args_manager['install']['no_deps'] = True
        if args.upgrade:
            args_manager['install']['upgrade'] = True
        if args.no_scripts:
            args_manager['install']['no_scripts'] = True
        if args.no_data:
            args_manager['install']['no_data'] = True
        if args.ignore:
            args_manager['install']['ignore'] = True
        if args.force_egg_install:
            args_manager['install']['force_egg_install'] = True

        if isinstance(args.index_url, ITERABLE_T):
            args.index_url = args.index_url[0]
        args_manager['install']['packages_url'] = args.index_url + '/simple'
        args_manager['install']['index_url'] = args.index_url + '/pypi'

        if args.upgrade_all:
            args_manager['install']['upgrade_all'] = True
            args_manager['install']['upgrade'] = True
        if args.user:
            args_manager['install']['user'] = True
            args_manager['install']['install_dir'] = USER_SITE
        if args.install_dir != INSTALL_DIR:
            dir = os.path.abspath(args.install_dir)
            args_manager['install']['install_dir'] = dir
            if any(os.path.basename(dir) == p for p in args.packname):
                ## Automatically set ignore=True when INSTALL_DIR has the same
                ## name of one of the packages to install
                args_manager['install']['ignore'] = True
        opts.install_func(args.packname, args.req_file, args.editable,
                          args_manager['install']['ignore'])

    @arg('packname', nargs='+')
    @arg('-r', '--req-file', metavar='<path>', help='Uninstall all the packages listed in the given requirement file')
    @arg('-y', '--yes', action='store_true', help='Do not ask confirmation of uninstall deletions')
    @arg('-i', '--info', action='store_true', help='Only list files to delete')
    def remove(args):
        '''
        Remove a package
        '''

        if args.yes:
            args_manager['remove']['yes'] = True
        if args.info:
            args_manager['remove']['info'] = True
        opts.remove_func(args.packname, args.req_file,
                         args_manager['remove']['yes'], args_manager['remove']['info'])

    @arg('packname', nargs=1)
    @arg('-i', '--index-url', nargs=1, default='http://pypi.python.org', metavar='<url>', help='Base URL of Python Package Index (default to %(default)s)')
    def list(args):
        '''
        List all versions for a package
        '''

        if isinstance(args.index_url, ITERABLE_T):
            args.index_url = args.index_url[0]

        args_manager['install']['packages_url'] = args.index_url + '/simple'
        args_manager['install']['index_url'] = args.index_url + '/pypi'

        opts.list_func(args.packname[0])

    @arg('-c', '--count', action='store_true', help='Only returns requirements count')
    @arg('-n', '--no-info', action='store_true', help='Do not add site information')
    @arg('-f', '--file', metavar='<path>', help='Writes requirements into the specified file')
    def site(args):
        '''
        Show installed packages and some site information
        '''

        if args.count:
            args_manager['site']['count'] = True
        if args.no_info:
            args_manager['site']['no_info'] = True
        if args.file:
            args_manager['site']['file'] = args.file
        count, no_info, file = args_manager['site']['count'], \
            args_manager['site']['no_info'], args_manager['site']['file']
        opts.site_func(count, no_info, file)

    @command
    def link(path):
        '''
        Add a directory to PYTHONPATH
        '''

        opts.link_func(path)

    @arg('path', nargs='?')
    @arg('-a', '--all', action='store_true', help='Remove all links')
    def unlink(args):
        '''
        Remove a previously added directory (with link) from PYTHONPATH
        '''

        if args.all:
            args_manager['unlink']['all'] = True
        opts.unlink_func(args)

    @arg('query', nargs='+')
    @arg('-i', '--index-url', default='http://pypi.python.org', metavar='<url>', help='Base URL of Python Package Index (default to %(default)s)')
    @arg('-e', '--exact', action='store_true', help='List only exact hits')
    @arg('-a', '--all', action='store_true', help='Show all versions for specified package')
    def search(args):
        '''
        Search PyPI
        '''

        if isinstance(args.index_url, ITERABLE_T):
            args.index_url = args.index_url[0]

        args_manager['install']['packages_url'] = args.index_url + '/simple'
        args_manager['install']['index_url'] = args.index_url + '/pypi'

        opts.search_func(args.query, args.exact, args.all)

    @arg('packname')
    @arg('-i', '--info', action='store_true', help='Show infos for specified package')
    def check(args):
        '''
        Check if a package is installed
        '''

        opts.check_func(args.packname, args.info)

    @arg('packname')
    @arg('-i', '--index-url', default='http://pypi.python.org', metavar='<url>', help='Base URL of Python Package Index (default to %(default)s)')
    @arg('-u', '--unpack', action='store_true', help='Once downloaded, unpack the package')
    @arg('-d', '--download-dir', default='.', metavar='<path>', help='The destination directory')
    @arg('-p', '--prefer', metavar='<ext>', help='The preferred file type for the download')
    def download(args):
        '''
        Download a package
        '''

        if isinstance(args.index_url, ITERABLE_T):
            args.index_url = args.index_url[0]

        args_manager['install']['packages_url'] = args.index_url + '/simple'
        args_manager['install']['index_url'] = args.index_url + '/pypi'

        if args.download_dir != args_manager['download']['download_dir']:
            args_manager['download']['download_dir'] = args.download_dir
        if args.prefer != args_manager['download']['prefer']:
            args_manager['download']['prefer'] = args.prefer
        if args.unpack:
            args_manager['download']['unpack'] = True
        opts.download_func(args)

    @arg('-i', '--index-url', default='http://pypi.python.org', metavar='<url>', help='Base URL of Python Package Index (default to %(default)s)')
    @arg('-y', '--yes', action='store_true', help='Do not ask confirmation for the upgrade')
    def update(args):
        '''
        Check for updates for installed packages
        '''

        if isinstance(args.index_url, ITERABLE_T):
            args.index_url = args.index_url[0]

        args_manager['install']['packages_url'] = args.index_url + '/simple'
        args_manager['install']['index_url'] = args.index_url + '/pypi'

        if args.yes:
            args_manager['update']['yes'] = True
        opts.update_func()

    @command
    def shell():
        '''
        Fire up Pyg Shell
        '''

        opts.shell_func()

    @arg('bundlename', help='Name of the bundle to create')
    @arg('packages', nargs='*', help='Name of the package(s) to bundle')
    @arg('-i', '--index-url', default='http://pypi.python.org', metavar='<url>', help='Base URL of Python Package Index (default to %(default)s)')
    @arg('-r', '--req-file', action='append', metavar='<path>', help='Requirement files which contains packages to bundle')
    @arg('-e', '--exclude', action='append', default=[], metavar='<requirement>', help='Exclude packages matching `requirement`')
    @arg('-d', '--use-develop', action='store_true', help='Look for local packages before downloading them')
    def bundle(args):
        '''
        Create bundles (like Pip's ones)
        '''

        if isinstance(args.index_url, ITERABLE_T):
            args.index_url = args.index_url[0]
        args_manager['install']['packages_url'] = args.index_url + '/simple'
        args_manager['install']['index_url'] = args.index_url + '/pypi'

        if args.exclude:
            args_manager['bundle']['exclude'] = args.exclude
        if args.use_develop:
            args_manager['bundle']['use_develop'] = True
        exclude, use_develop = args_manager['bundle']['exclude'], args_manager['bundle']['use_develop']
        opts.bundle_func(args.packages, args.bundlename, exclude, args.req_file, use_develop)

    @arg('packname', help='Name of the pack to create')
    @arg('package', help='Name of the package to pack')
    @arg('-i', '--index-url', default='http://pypi.python.org', metavar='<url>', help='Base URL of Python Package Index (default to %(default)s)')
    @arg('-d', '--use-develop', action='store_true', help='Look for local packages before downloading them')
    @arg('-e', '--exclude', action='append', default=[], metavar='<requirement>', help='Exclude packages matching `requirement`')
    def pack(args):
        '''
        Create packs
        '''

        if isinstance(args.index_url, ITERABLE_T):
            args.index_url = args.index_url[0]
        args_manager['install']['packages_url'] = args.index_url + '/simple'
        args_manager['install']['index_url'] = args.index_url + '/pypi'

        # XXX: Duplication is evil. (See above.)
        if args.exclude:
            args_manager['pack']['exclude'] = args.exclude
        if args.use_develop:
            args_manager['pack']['use_develop'] = True
        exclude, use_develop = args_manager['pack']['exclude'], args_manager['pack']['use_develop']
        return opts.pack_func(args.package, args.packname, exclude, use_develop)

    @command
    def help():
        '''
        Show this help and exit
        '''

        return

    parser.add_commands([install, remove, site, link, unlink, list, pack,
                         search, check, download, update, shell, bundle, help])
    parser.formatter_class = _formatter(parser)
    if parser.parse_args(sys.argv[1:]).no_colors:
        args_manager['global']['no_colors'] = True
    return parser
Exemplo n.º 24
0
Arquivo: cli.py Projeto: blylei/frabit
def main():
    """
    The main method of Frabit
    """
    p = ArghParser(epilog='Frabit by Frabit (www.frabit.com)')
    p.add_argument(
        '-v',
        '--version',
        action='version',
        version='{version}\n\nFrabit by Frabit (www.frabit.com)'.format(
            version=frabit.__version__))
    p.add_argument('-c',
                   '--config',
                   help='uses a configuration file (defaults: %s)' %
                   ', '.join(frabit.config.Config.CONFIG_FILES),
                   default=SUPPRESS)
    p.add_argument('--color',
                   '--colour',
                   help='Whether to use colors in the output',
                   choices=['never', 'always', 'auto'],
                   default='auto')
    p.add_argument('--log-level',
                   help='Override the default log level',
                   choices=list(get_log_levels()),
                   default=SUPPRESS)
    p.add_argument('-q', '--quiet', help='be quiet', action='store_true')
    p.add_argument('-d', '--debug', help='debug output', action='store_true')
    p.add_argument('-f',
                   '--format',
                   help='output format',
                   choices=output.AVAILABLE_WRITERS.keys(),
                   default=output.DEFAULT_WRITER)
    p.add_commands([
        archive_wal,
        backup,
        check,
        check_backup,
        cron,
        delete,
        diagnose,
        get_wal,
        list_backup,
        list_files,
        list_server,
        put_wal,
        rebuild_xlogdb,
        receive_wal,
        recover,
        show_backup,
        show_server,
        replication_status,
        status,
        switch_wal,
        switch_xlog,
        sync_info,
        sync_backup,
        sync_wals,
    ])
    # noinspection PyBroadException
    try:
        p.dispatch(pre_call=global_config)
    except KeyboardInterrupt:
        msg = "Process interrupted by user (KeyboardInterrupt)"
        output.error(msg)
    except Exception as e:
        msg = "%s\nSee log file for more details." % e
        output.exception(msg)

    # cleanup output API and exit honoring output.error_occurred and
    # output.error_exit_code
    output.close_and_exit()
Exemplo n.º 25
0
@arg('-t', '--tags',
     help='Only list containers with the specified tags '
          '(supplied as a comma-separated list)')
@arg('-x', '--exclude-tags',
     help='Exclude containers with the specified tags '
          '(supplied as a comma-separated list)')
@arg('-q', '--quiet', default=False)
@expects_obj
def ports(args):
    gantry = Gantry(args.docker_url)
    tags = args.tags.split(',') if args.tags else None
    exclude_tags = args.exclude_tags.split(',') if args.exclude_tags else None
    if not args.quiet:
        print("%10s %10s" % ("host_port", "guest_port"))
    for p in gantry.ports(args.repository,
                          tags=tags,
                          exclude_tags=exclude_tags):
        print("%10d %10d" % (p[0], p[1]))

parser = ArghParser(version=__version__)
parser.add_argument('--docker-url', default=DOCKER_DEFAULT_URL)
parser.add_commands([deploy, containers, ports])


def main():
    parser.dispatch()


if __name__ == '__main__':
    main()
Exemplo n.º 26
0
        args.command = None

    patterns, ignore_patterns = parse_patterns(args.patterns, args.ignore_patterns)
    handler = ShellCommandTrick(
        shell_command=args.command,
        patterns=patterns,
        ignore_patterns=ignore_patterns,
        ignore_directories=args.ignore_directories,
    )
    observer = Observer(timeout=args.timeout)
    observe_with(observer, handler, args.directories, args.recursive)


epilog = """Copyright (C) 2011 Yesudeep Mangalapilly <*****@*****.**>.

Licensed under the terms of the Apache license, version 2.0. Please see
LICENSE in the source code for more information."""

parser = ArghParser(epilog=epilog)
parser.add_commands([tricks_from, tricks_generate_yaml, log, shell_command])
parser.add_argument("--version", action="version", version="%(prog)s " + VERSION_STRING)


def main():
    """Entry-point function."""
    parser.dispatch()


if __name__ == "__main__":
    main()
Exemplo n.º 27
0
        parsed_args = vars(parsed_args)
        parsed_args.pop('_functions_stack', None)
        if not include_app:
            parsed_args.pop('app')
        return f(**parsed_args)
    return inner


# Create a parent group so that arguments such as --verbose can be added
# to all commands.
parent = ArghParser(add_help=False)

# Create a mutually exclusive group to control the verbosity. verbose
# and quiet will be provided under kwargs.
chatter = parent.add_mutually_exclusive_group()
chatter.add_argument('--verbose', '-v', action='count', help='verbose mode')
chatter.add_argument('--quiet', '-q', action='count', help='quiet mode')

# Define a parser and add commands to it.
parser = ArghParser()
parser.add_argument('--version', action='version', version=__version__)

# Add an argument to import an application to load its CLI extensions.
parser.add_argument(
    '-a', '--app',
    action=_ApplicationAction,
    help='the path to the application to run',
)

parser.add_commands([run], func_kwargs={'parents': [parent]})
Exemplo n.º 28
0
from __future__ import print_function

import json

from argh import ArghParser, arg
from ghtools import cli
from ghtools.github.organisation import Organisation

parser = ArghParser(description="Interact with a GitHub organisation")
parser.add_argument('org',
                    help='Organisation identifier '
                    '(e.g. rails, enterprise:mycorp)')

json_arg = arg('-j',
               '--json',
               default=False,
               action='store_true',
               help='Print full JSON representations')


@json_arg
def repos(args):
    """
    Print a list of organisation repositories
    """
    with cli.catch_api_errors():
        org = Organisation(args.org)
        for repo in org.list_repos():
            if args.json:
                print(json.dumps(repo, indent=2))
            else:
Exemplo n.º 29
0
	if package_json is not None:
		description = package_json['description']
		version = 'v' + package_json['version']
		epilog = '''
author:  {0}
version: {1}
license: {2}
url:     {3}
		'''.format(package_json['author'],
					version,
					package_json['license'],
					package_json['repository']['url'])

	return description, epilog, version


# TODO: Export JWT_SECRET_KEY (generate if not already present) before running the backend application.
# TODO: DataDog CLI. command for start / stop, another for start-service / stop-service. install-service. etc.
# TODO: Command to check if it can be installed (correct python version, distribution, packages, maybe node / npm, etc.)
# TODO: Check out nvm (node version manager) for its commands and how it works.
if __name__ == '__main__':
	"""Entry-point function."""
	init()
	description, epilog, version = package_info()

	parent_parser = ArghParser(description = description, epilog = epilog)
	parent_parser.add_commands([update, start, stop, restart])
	parent_parser.add_argument('-v', '--version', action = 'version', version = version)

	parent_parser.dispatch()
Exemplo n.º 30
0
def main():
    """
    The main method of Barman
    """
    p = ArghParser(epilog="Barman by EnterpriseDB (www.enterprisedb.com)")
    p.add_argument(
        "-v",
        "--version",
        action="version",
        version="%s\n\nBarman by EnterpriseDB (www.enterprisedb.com)"
        % barman.__version__,
    )
    p.add_argument(
        "-c",
        "--config",
        help="uses a configuration file "
        "(defaults: %s)" % ", ".join(barman.config.Config.CONFIG_FILES),
        default=SUPPRESS,
    )
    p.add_argument(
        "--color",
        "--colour",
        help="Whether to use colors in the output",
        choices=["never", "always", "auto"],
        default="auto",
    )
    p.add_argument(
        "--log-level",
        help="Override the default log level",
        choices=list(get_log_levels()),
        default=SUPPRESS,
    )
    p.add_argument("-q", "--quiet", help="be quiet", action="store_true")
    p.add_argument("-d", "--debug", help="debug output", action="store_true")
    p.add_argument(
        "-f",
        "--format",
        help="output format",
        choices=output.AVAILABLE_WRITERS.keys(),
        default=output.DEFAULT_WRITER,
    )
    p.add_commands(
        [
            archive_wal,
            backup,
            check,
            check_backup,
            cron,
            delete,
            diagnose,
            get_wal,
            list_backup,
            list_files,
            list_server,
            put_wal,
            rebuild_xlogdb,
            receive_wal,
            recover,
            show_backup,
            show_server,
            replication_status,
            status,
            switch_wal,
            switch_xlog,
            sync_info,
            sync_backup,
            sync_wals,
        ]
    )
    # noinspection PyBroadException
    try:
        p.dispatch(pre_call=global_config)
    except KeyboardInterrupt:
        msg = "Process interrupted by user (KeyboardInterrupt)"
        output.error(msg)
    except Exception as e:
        msg = "%s\nSee log file for more details." % e
        output.exception(msg)

    # cleanup output API and exit honoring output.error_occurred and
    # output.error_exit_code
    output.close_and_exit()
Exemplo n.º 31
0
     '(supplied as a comma-separated list)')
@arg('-x',
     '--exclude-tags',
     help='Exclude containers with the specified tags '
     '(supplied as a comma-separated list)')
@arg('-q', '--quiet', default=False)
@expects_obj
def ports(args):
    gantry = Gantry(args.docker_url)
    tags = args.tags.split(',') if args.tags else None
    exclude_tags = args.exclude_tags.split(',') if args.exclude_tags else None
    if not args.quiet:
        print("%10s %10s" % ("host_port", "guest_port"))
    for p in gantry.ports(args.repository,
                          tags=tags,
                          exclude_tags=exclude_tags):
        print("%10d %10d" % (p[0], p[1]))


parser = ArghParser(version=__version__)
parser.add_argument('--docker-url', default=DOCKER_DEFAULT_URL)
parser.add_commands([deploy, containers, ports])


def main():
    parser.dispatch()


if __name__ == '__main__':
    main()
Exemplo n.º 32
0
Arquivo: cli.py Projeto: afcarl/Henson
        if not include_app:
            parsed_args.pop('app')
        return f(**parsed_args)

    return inner


# Create a parent group so that arguments such as --verbose can be added
# to all commands.
parent = ArghParser(add_help=False)

# Create a mutually exclusive group to control the verbosity. verbose
# and quiet will be provided under kwargs.
chatter = parent.add_mutually_exclusive_group()
chatter.add_argument('--verbose', '-v', action='count', help='verbose mode')
chatter.add_argument('--quiet', '-q', action='count', help='quiet mode')

# Define a parser and add commands to it.
parser = ArghParser()
parser.add_argument('--version', action='version', version=__version__)

# Add an argument to import an application to load its CLI extensions.
parser.add_argument(
    '-a',
    '--app',
    action=_ApplicationAction,
    help='the path to the application to run',
)

parser.add_commands([run], func_kwargs={'parents': [parent]})
Exemplo n.º 33
0
def main():
    parser = ArghParser(description="Simple static gallery generator.")
    parser.add_commands([init, build, serve])
    parser.add_argument("--version", action="version", version="%(prog)s {}".format(__version__))
    parser.dispatch()
Exemplo n.º 34
0
    handler.start()
    observer = Observer(timeout=args.timeout)
    observe_with(observer, handler, args.directories, args.recursive)
    handler.stop()


epilog = """Copyright 2011 Yesudeep Mangalapilly <*****@*****.**>.
Copyright 2012 Google, Inc.

Licensed under the terms of the Apache license, version 2.0. Please see
LICENSE in the source code for more information."""

parser = ArghParser(epilog=epilog)
parser.add_commands([tricks_from,
                     tricks_generate_yaml,
                     log,
                     shell_command,
                     auto_restart])
parser.add_argument('--version',
                    action='version',
                    version='%(prog)s ' + VERSION_STRING)


def main():
    """Entry-point function."""
    parser.dispatch()


if __name__ == '__main__':
    main()
Exemplo n.º 35
0
  handler.start()
  observer = Observer(timeout=args.timeout)
  observe_with(observer, handler, args.directories, args.recursive)
  handler.stop()


epilog = """Copyright 2011 Yesudeep Mangalapilly <*****@*****.**>.
Copyright 2012 Google, Inc.

Licensed under the terms of the Apache license, version 2.0. Please see
LICENSE in the source code for more information."""

parser = ArghParser(epilog=epilog)
parser.add_commands([tricks_from,
                     tricks_generate_yaml,
                     log,
                     shell_command,
                     auto_restart])
parser.add_argument('--version',
                    action='version',
                    version='%(prog)s ' + VERSION_STRING)


def main():
  """Entry-point function."""
  parser.dispatch()


if __name__ == '__main__':
  main()
Exemplo n.º 36
0
from __future__ import print_function

import json
import logging

from argh import ArghParser
from ghtools import cli
from ghtools.github.repo import Repo

log = logging.getLogger(__name__)
parser = ArghParser(description="Interact with GitHub repos")
parser.add_argument("repo", help="Repo identifier, e.g. defunkt/resque, enterprise:mycorp/myproj")


def delete(args):
    """
    Delete the specified repository
    """
    repo = Repo(args.repo)

    with cli.catch_api_errors():
        repo.delete()


parser.add_commands([delete])


def get(args):
    """
    Print the JSON representation of the specified repository to STDOUT
    """
Exemplo n.º 37
0
    def argh_main(progname, commands,default_verbosity=None, default_file_verbosity=None):
        default_verbosity=default_verbosity or "CRITICAL"
        default_file_verbosity=default_file_verbosity or "CRITICAL"
        parser = ArghParser()
        parser.add_argument("--very_verbose", action="store_true")
        parser.add_argument("--logfile",type=str, default="{0}.log".format(progname))
        parser.add_argument("--verbosity","-v",type=str, default=default_verbosity)
        parser.add_argument("--file_verbosity","-fv",type=str, default=default_file_verbosity)
        parser.add_argument("--timing","-t", default=False, action='store_true')
        parser.add_argument("--args","-a", default=False, action='store_true')
        #mylog.command_line(parser, progname, default_verbosity="CRITICAL", default_file_verbosity="INFO")

        parser.add_commands(commands)
        args = parser.parse_args()
    
        log = mylog.default_logger(progname,
                                    logfile=args.logfile,
                                    verbosity=args.verbosity, 
                                    file_verbosity=args.file_verbosity)

        if args.args:
            d=vars(args)
            log.info(",".join(["{0}={1}".format(k,v) for k,v in d.items()]))
                     
        if args.timing:
            import datetime
            start = datetime.datetime.now()
            log.info("Start time: {0}".format(start))
            
        try:
            parser.dispatch()
            if args.timing:
                import datetime
                end = datetime.datetime.now()
                log.info("End time: {0}".format(end))
                log.info("Run time: {0}".format((end-start).total_seconds()))

        except KeyboardInterrupt as e:
            log.info("Exiting on Keyboard Interrupt")
            print("Exiting on Keyboard Interrupt")
        except Exception as e:
            print("ERROR: {0}".format(e))
            log.error(e)
            if args.very_verbose:
                raise
            else:
                sys.exit(1)
Exemplo n.º 38
0
from __future__ import print_function

import json

from argh import ArghParser, arg
from ghtools import cli
from ghtools.github.organisation import Organisation

parser = ArghParser(description="Interact with a GitHub organisation")
parser.add_argument("org", help="Organisation identifier " "(e.g. rails, enterprise:mycorp)")

json_arg = arg("-j", "--json", default=False, action="store_true", help="Print full JSON representations")


@json_arg
def repos(args):
    """
    Print a list of organisation repositories
    """
    with cli.catch_api_errors():
        org = Organisation(args.org)
        for repo in org.list_repos():
            if args.json:
                print(json.dumps(repo, indent=2))
            else:
                print(repo["name"])


parser.add_commands([repos])