예제 #1
0
파일: vc.py 프로젝트: wxtim/rose
def checkout():
    """CLI function: checkout."""
    opt_parser = RoseOptionParser(
        usage='rosie checkout [OPTIONS] ID ...',
        description='''
Checkout local copies of suites.

For each `ID` in the argument list, checkout a working copy of the suite
identified by `ID` to the standard location.
        ''',
    ).add_my_options("force_mode")
    opt_parser.modify_option(
        'force_mode',
        help=('If working copy for suite identified by `ID` already exists,'
              ' remove it. Continue to the next `ID` if checkout of a suite'
              ' fails.'),
    )
    opts, args = opt_parser.parse_args()
    verbosity = opts.verbosity - opts.quietness
    report = Reporter(verbosity)
    client = RosieVCClient(event_handler=report, force_mode=opts.force_mode)
    SuiteId.svn.event_handler = client.event_handler
    ret_code = 0
    for arg in args:
        try:
            client.checkout(arg)
        except (FileExistError, RosePopenError, SuiteIdPrefixError) as exc:
            ret_code = 1
            report(exc)
            if not opts.force_mode:
                sys.exit(1)
    if ret_code:
        sys.exit(ret_code)
예제 #2
0
def lookup(argv):
    """CLI command to run the various search types"""
    opt_parser = RoseOptionParser().add_my_options(
        "address_mode", "all_revs", "lookup_mode", "no_headers", "prefixes",
        "print_format", "query_mode", "reverse", "search_mode", "sort")
    opts, args = opt_parser.parse_args(argv)
    if not args:
        sys.exit(opt_parser.print_usage())
    if not opts.lookup_mode:
        if args[0].startswith("http"):
            opts.lookup_mode = "address"
        else:
            opts.lookup_mode = "search"
    ws_client = RosieWSClient(
        prefixes=opts.prefixes,
        event_handler=Reporter(opts.verbosity - opts.quietness))
    try:
        if opts.lookup_mode == "address":
            data_and_url_list = ws_client.address_lookup(url=args[0])
        elif opts.lookup_mode == "query":
            q_items = ws_client.query_split(args)
            for i, q_item in enumerate(q_items):
                q_items[i] = " ".join(q_item)
            data_and_url_list = ws_client.query(
                q_items, all_revs=int(opts.all_revs))
        else:  # if opts.lookup_mode == "search":
            data_and_url_list = ws_client.search(
                args, all_revs=int(opts.all_revs))
    except RosieWSClientError as exc:
        if opts.debug_mode:
            traceback.print_exc()
        sys.exit(str(exc))
    for data, url in data_and_url_list:
        _display_maps(opts, ws_client, data, url)
예제 #3
0
def main():
    """Implement "rose suite-hook" command."""
    opt_parser = RoseOptionParser()
    opt_parser.add_my_options("mail_cc", "mail", "retrieve_job_logs",
                              "shutdown")
    opts, args = opt_parser.parse_args()
    for key in ["mail_cc"]:
        values = []
        if getattr(opts, key):
            for value in getattr(opts, key):
                values.extend(value.split(","))
        setattr(opts, key, values)
    report = Reporter(opts.verbosity - opts.quietness - 1)  # Reduced default
    popen = RosePopener(event_handler=report)
    suite_engine_proc = SuiteEngineProcessor.get_processor(
        event_handler=report, popen=popen)
    args = suite_engine_proc.process_suite_hook_args(*args, **vars(opts))
    hook = RoseSuiteHook(event_handler=report,
                         popen=popen,
                         suite_engine_proc=suite_engine_proc)
    hook(*args,
         should_mail=opts.mail,
         mail_cc_list=opts.mail_cc,
         should_shutdown=opts.shutdown,
         should_retrieve_job_logs=opts.retrieve_job_logs)
예제 #4
0
파일: vc.py 프로젝트: wxtim/rose
def delete():
    """CLI function: delete."""
    opt_parser = RoseOptionParser(usage='rosie delete [OPTIONS] [--] [ID ...]',
                                  description='''
Delete suites.

Check the standard working copy location for a checked out suite
matching `ID` and remove it if there is no uncommitted change (or if
`--force` is specified).

Delete the suite directory structure from the HEAD of the central
repository matching the `ID`.

If no `ID` is specified and `$PWD` is a working copy of a suite, use the
`ID` of the suite in the working copy.
        ''').add_my_options("force_mode", "non_interactive", "local_only")
    opt_parser.modify_option(
        'force_mode',
        help=("Remove working copies even if there are uncommitted changes."
              "\nContinue with the next `ID` if delete of a suite fails."),
    )
    opts, args = opt_parser.parse_args()
    report = Reporter(opts.verbosity - opts.quietness)
    client = RosieVCClient(event_handler=report, force_mode=opts.force_mode)
    SuiteId.svn.event_handler = client.event_handler
    if not args:
        args.append(SuiteId(location=os.getcwd()))
    interactive_mode = not opts.non_interactive
    prompt = PROMPT_DELETE
    if opts.local_only:
        prompt = PROMPT_DELETE_LOCAL
    ret_code = 0
    for arg in args:
        if interactive_mode:
            try:
                response = input(prompt % arg)
            except EOFError:
                ret_code = 1
                continue
            if response == YES_TO_ALL:
                interactive_mode = False
            elif response != YES:
                ret_code = 1
                continue
        if opts.debug_mode:
            client.delete(arg, opts.local_only)
        else:
            try:
                client.delete(arg, opts.local_only)
            except (
                    LocalCopyStatusError,
                    RosePopenError,
                    SuiteIdPrefixError,
            ) as exc:
                client.event_handler(exc)
                ret_code = 1
                if not opts.force_mode:
                    sys.exit(1)
    if ret_code:
        sys.exit(ret_code)
예제 #5
0
def main():
    """Implement "rose suite-shutdown"."""
    argv = sys.argv[1:]
    method_name = argv.pop(0)
    opt_parser = RoseOptionParser()
    opt_parser.add_my_options("name", "non_interactive")
    opts, args = opt_parser.parse_args(argv)
    event_handler = Reporter(opts.verbosity - opts.quietness)
    suite_control = SuiteControl(event_handler=event_handler)
    method = getattr(suite_control, method_name)
    confirm = None
    suite_names = []
    if not opts.non_interactive:
        confirm = prompt
    else:
        if opts.name:
            suite_names.append(opts.name)
        else:
            try:
                suite_name = get_suite_name(event_handler)
                suite_names.append(suite_name)
            except SuiteNotFoundError as exc:
                event_handler(exc)
                sys.exit(1)

    if opts.debug_mode:
        for sname in suite_names:
            method(sname, confirm, sys.stderr, sys.stdout, *args)
    else:
        for sname in suite_names:
            try:
                method(sname, confirm, sys.stderr, sys.stdout, *args)
            except Exception as exc:
                event_handler(exc)
                sys.exit(1)
예제 #6
0
def main():
    """Launcher for command line invokation of metomi.rose stem."""

    # Process options
    opt_parser = RoseOptionParser()

    option_keys = SuiteRunner.OPTIONS + OPTIONS
    opt_parser.add_my_options(*option_keys)
    opts, args = opt_parser.parse_args()

    # Set up a runner instance and process the options
    stem = StemRunner(opts)
    if opts.debug_mode:
        opts = stem.process()
    else:
        try:
            opts = stem.process()
        except Exception as exc:
            stem.reporter(exc)
            sys.exit(1)

    # Get the suiterunner object and execute
    runner = SuiteRunner(event_handler=stem.reporter,
                         popen=stem.popen,
                         fs_util=stem.fs_util)
    if opts.debug_mode:
        sys.exit(runner(opts, args))
    try:
        sys.exit(runner(opts, args))
    except Exception as exc:
        runner.handle_event(exc)
        if isinstance(exc, RosePopenError):
            sys.exit(exc.ret_code)
        else:
            sys.exit(1)
예제 #7
0
def main():
    """Implement the "rose config-dump" command."""
    opt_parser = RoseOptionParser()
    opt_parser.add_my_options("conf_dir", "files", "no_pretty_mode")
    opts = opt_parser.parse_args()[0]
    verbosity = opts.verbosity - opts.quietness
    report = Reporter(verbosity)
    fs_util = FileSystemUtil(report)
    if opts.conf_dir:
        fs_util.chdir(opts.conf_dir)
    file_names = []
    if opts.files:
        file_names = opts.files
    else:
        for dirpath, _, filenames in os.walk("."):
            for filename in fnmatch.filter(filenames, "rose-*.conf"):
                path = os.path.join(dirpath, filename)[2:]  # remove leading ./
                file_names.append(path)
    for file_name in file_names:
        handle = NamedTemporaryFile()
        node = ConfigLoader()(file_name)
        if (not opts.no_pretty_mode
                and os.path.basename(file_name) != META_CONFIG_NAME):
            pretty_format_config(node, ignore_error=True)
        ConfigDumper()(node, handle)
        handle.seek(0)
        if not filecmp.cmp(handle.name, file_name, shallow=False):
            report(ConfigDumpEvent(file_name))
            ConfigDumper()(node, file_name)
예제 #8
0
def main():
    """rose task-env."""
    opt_parser = RoseOptionParser()
    opt_parser.add_my_options("cycle", "cycle_offsets", "path_globs",
                              "prefix_delim", "suffix_delim")
    opts, args = opt_parser.parse_args()
    report = Reporter(opts.verbosity - opts.quietness - 1)
    suite_engine_proc = SuiteEngineProcessor.get_processor(
        event_handler=report)
    kwargs = dict(vars(opts))
    try:
        task_props = suite_engine_proc.get_task_props(*args, **kwargs)
        for key, value in task_props:
            report(str(EnvExportEvent(key, value)) + "\n", level=0)
        path_globs = opts.path_globs
        if path_globs is None:
            path_globs = []
        prepend_paths_map = get_prepend_paths(report,
                                              task_props.suite_dir,
                                              path_globs,
                                              full_mode=True)
        for key, prepend_paths in prepend_paths_map.items():
            orig_paths = []
            orig_v = os.getenv(key, "")
            if orig_v:
                orig_paths = orig_v.split(os.pathsep)
            path = os.pathsep.join(prepend_paths + orig_paths)
            report(str(EnvExportEvent(key, path)) + "\n", level=0)
    except Exception as exc:
        report(exc)
        if opts.debug_mode:
            traceback.print_exc()
        sys.exit(1)
예제 #9
0
def parse_cli(*args, **kwargs):
    """Parse command line, start/stop ad-hoc server.

    Return a CLI instruction tuple for a valid command instruction, else False:
        ("start", Boolean, port):
            start server on 'port', [2]==True indicating non_interactive mode.
        ("stop", Boolean):
            stop server, [2]==True indicating service_root_mode.
        None:
            bare command, requesting to print server status
    """
    opt_parser = RoseOptionParser()
    opt_parser.add_my_options("non_interactive", "service_root_mode")
    opts, args = opt_parser.parse_args()

    arg = None
    if args:
        arg = args[0]

    if arg == "start":
        port = DEFAULT_PORT
        if args[1:]:
            try:
                port = int(args[1])
            except ValueError:
                print("Invalid port specified. Using the default port.")
        return ("start", opts.service_root_mode, port)
    elif arg == "stop":
        return ("stop", opts.non_interactive)
    elif arg:  # unrecognised (invalid) argument, to ignore
        return False  # False to distinguish from None for no arguments given
예제 #10
0
def main():
    """Implement "rose env-cat"."""
    opt_parser = RoseOptionParser()
    opt_parser.add_my_options("match_mode", "output_file", "unbound")
    opts, args = opt_parser.parse_args()
    if not args:
        args = ["-"]
    if not opts.output_file or opts.output_file == "-":
        out_handle = sys.stdout
    else:
        out_handle = open(opts.output_file, "wb")
    for arg in args:
        if arg == "-":
            in_handle = sys.stdin
        else:
            in_handle = open(arg)
        line_num = 0
        while True:
            line_num += 1
            line = in_handle.readline()
            if not line:
                break
            try:
                out_handle.write(
                    env_var_process(line, opts.unbound, opts.match_mode))
            except UnboundEnvironmentVariableError as exc:
                name = arg
                if arg == "-":
                    name = "<STDIN>"
                sys.exit("%s:%s: %s" % (name, line_num, str(exc)))
        in_handle.close()
    out_handle.close()
예제 #11
0
def hello(argv):
    """Set up connection to a Rosie web service."""
    opt_parser = RoseOptionParser().add_my_options("prefixes")
    opts = opt_parser.parse_args(argv)[0]
    report = Reporter(opts.verbosity - opts.quietness)
    ws_client = RosieWSClient(prefixes=opts.prefixes, event_handler=report)
    for response_data, response_url in ws_client.hello():
        report("%s: %s" % (response_url, response_data), level=0)
예제 #12
0
def main():
    """Launcher for the CLI."""
    opt_parser = RoseOptionParser(
        usage='%prog [OPTIONS] [--] [COMMAND ...]',
        description='''
Run an application according to its configuration.

May run a builtin application (if the `mode` setting in the configuration
specifies the name of a builtin application) or a command.

Determine the command to run in this order:

1. If `COMMAND` is specified, invoke the command.
2. If the `--command-key=KEY` option is defined, invoke the command
   specified in `[command]KEY`.
3. If the `ROSE_APP_COMMAND_KEY` environment variable is set, the command
   specified in the `[command]KEY` setting in the application
   configuration whose `KEY` matches it is used.
4. If the environment variable `ROSE_TASK_NAME` is defined and a setting
   in the `[command]` section has a key matching the value of the
   environment variable, then the value of the setting is used as the
   command.
5. Invoke the command specified in `[command]default`.
        ''',
        epilog='''
ENVIRONMENT VARIABLES
    optional ROSE_APP_COMMAND_KEY
        Switch to a particular command specified in `[command]KEY`.
    optional ROSE_APP_MODE
        Specifies a builtin application to run.
    optional ROSE_APP_OPT_CONF_KEYS
        Each `KEY` in this space delimited list switches on an optional
        configuration. The configurations are applied first-to-last.
    optional ROSE_FILE_INSTALL_ROOT
        If specified, change to the specified directory to install files.
        '''
    )
    option_keys = AppRunner.OPTIONS
    opt_parser.add_my_options(*option_keys)
    opts, args = opt_parser.parse_args()
    event_handler = Reporter(opts.verbosity - opts.quietness)
    runner = AppRunner(event_handler)
    try:
        sys.exit(runner(opts, args))
    except Exception as exc:
        runner.handle_event(exc)
        if opts.debug_mode:
            traceback.print_exc()
        if isinstance(exc, RosePopenError):
            sys.exit(exc.ret_code)
        else:
            sys.exit(1)
예제 #13
0
파일: task_run.py 프로젝트: wxtim/rose
def main():
    """Launcher for the CLI."""
    opt_parser = RoseOptionParser(
        usage='rose task-run [OPTIONS] [--] [APP-COMMAND ...]',
        description='''
Provide an environment to run a suite task.

Provides environment variables documented in `rose task-env`. It is worth
noting that if the environment variables are already provided by
`rose task-env`, this command will not override them.

Normally, the suite task will select a Rose application configuration
that has the same name as the task. This can be overridden by the
`--app-key=KEY` option or the `ROSE_TASK_APP` environment variable.

SHORT OPTIONS
    All options of `rose app-run` and `rose task-env` are supported.
    Additional options are:

    --app-key=KEY
        Specify a named application configuration.
        ''',
        epilog='''
ENVIRONMENT VARIABLES
    All environment variables of `rose app-run` and `rose task-env` are
    supported. All environment variables documented in `rose task-env` are
    passed to the application `rose task-run` runs.
    The following environment variables are used by `rose task-run`:

    ROSE_TASK_APP
        Specify a named application configuration.

SEE ALSO
    * `rose app-run`
    * `rose task-env`
        ''',
    )
    option_keys = TaskRunner.OPTIONS
    opt_parser.add_my_options(*option_keys)
    opts, args = opt_parser.parse_args()
    event_handler = Reporter(opts.verbosity - opts.quietness)
    runner = TaskRunner(event_handler)
    try:
        sys.exit(runner(opts, args))
    except Exception as exc:
        runner.handle_event(exc)
        if opts.debug_mode:
            traceback.print_exc()
        if isinstance(exc, RosePopenError):
            sys.exit(exc.ret_code)
        else:
            sys.exit(1)
예제 #14
0
def main():
    """Implement "rosa svn-post-commit"."""
    opt_parser = RoseOptionParser()
    opts, args = opt_parser.parse_args()
    report = Reporter(opts.verbosity - opts.quietness)
    hook = RosieSvnPostCommitHook(report)
    try:
        repos, revision = args[0:2]
        hook.run(repos, revision)
    except Exception as exc:
        report(exc)
        if opts.debug_mode:
            traceback.print_exc()
        sys.exit(1)
예제 #15
0
def main():
    """Implement "rosa svn-pre-commit"."""
    add_meta_paths()
    opt_parser = RoseOptionParser()
    opts, args = opt_parser.parse_args()
    repos, txn = args
    report = Reporter(opts.verbosity - opts.quietness)
    hook = RosieSvnPreCommitHook(report)
    try:
        hook(repos, txn)
    except Exception as exc:
        report(exc)
        if opts.debug_mode:
            traceback.print_exc()
        sys.exit(1)
예제 #16
0
파일: date.py 프로젝트: MartinDix/rose
def main():
    """Implement "rose date"."""
    opt_parser = RoseOptionParser()
    opt_parser.add_my_options(
        "calendar",
        "diff",
        "offsets1",
        "offsets2",
        "parse_format",
        "print_format",
        "task_cycle_time_mode",
        "as_total",
        "utc_mode",
    )
    opts, args = opt_parser.parse_args()
    report = Reporter(opts.verbosity - opts.quietness)

    ref_point_str = None
    if opts.task_cycle_time_mode:
        ref_point_str = os.getenv(RoseDateTimeOperator.TASK_CYCLE_TIME_ENV)
        if ref_point_str is None:
            exc = UnboundEnvironmentVariableError(
                RoseDateTimeOperator.TASK_CYCLE_TIME_ENV)
            report(exc)
            if opts.debug_mode:
                raise exc
            sys.exit(1)

    date_time_oper = RoseDateTimeOperator(
        parse_format=opts.parse_format,
        utc_mode=opts.utc_mode,
        calendar_mode=opts.calendar,
        ref_point_str=ref_point_str,
    )

    try:
        if len(args) < 2:
            if opts.duration_print_format:
                _convert_duration(date_time_oper, opts, args)
            else:
                _print_time_point(date_time_oper, opts, args)
        else:
            _print_duration(date_time_oper, opts, args)
    except OffsetValueError as exc:
        report(exc)
        if opts.debug_mode:
            raise exc
        sys.exit(1)
예제 #17
0
def main():
    """Implement "rose suite-log" CLI."""
    opt_parser = RoseOptionParser()
    opt_parser.add_my_options("archive_mode", "force_mode", "name",
                              "non_interactive", "prune_remote_mode",
                              "update_mode", "user", "view_mode")
    opts, args = opt_parser.parse_args()
    report = Reporter(opts.verbosity - opts.quietness)

    try:
        suite_log_view(opts, args, report)
    except Exception as exc:
        report(exc)
        if opts.debug_mode:
            traceback.print_exc()
        sys.exit(1)
예제 #18
0
def main():
    """CLI for "rose namelist-dump"."""
    opt_parser = RoseOptionParser(
        usage='rose-namelist-dump [OPTIONS] [FILE ...]',
        description='''
Convert namelist files into a Rose application configuration snippet.
Each argument should be the path to an empty file or a file containing
Fortran namelist groups. A `-` can be used once in the argument list to
specify the standard input. If no argument is given, it assumes the
standard input is specified. Where possible, use relative path for file
names, as the file names appear as-specified in the generated
configuration.
        ''',
    )
    opt_parser.add_my_options("case_mode", "lower", "output_file", "upper")
    opts, args = opt_parser.parse_args()
    return namelist_dump(args, opts.output_file, opts.case_mode)
예제 #19
0
def main():
    """Implement "rose env-cat"."""
    opt_parser = RoseOptionParser(usage='rose env-cat [OPTIONS] [FILE ...]',
                                  description=r'''
Substitute environment variables in input files and print.

If no argument is specified, read from STDIN. One `FILE` argument may be
`-`, which means read from STDIN.

In `match-mode=default`, the command will look for `$NAME` or `${NAME}`
syntax and substitute them with the value of the environment variable
`NAME`. A backslash in front of the syntax, e.g. `\$NAME` or `\${NAME}`
will escape the substitution.

In `match-mode=brace`, the command will look for `${NAME}` syntax only.

EXAMPLES
    rose env-cat [OPTIONS] [FILE ...]
        ''')
    opt_parser.add_my_options("match_mode", "output_file", "unbound")
    opt_parser.modify_option(
        'output_file',
        help=("Specify an output file."
              "\nIf no output file is specified or if `FILE`"
              "is `-`, write output to STDOUT."),
    )
    opts, args = opt_parser.parse_args()
    rose_env_cat(args, opts)
예제 #20
0
def main():
    """Launcher for the CLI."""
    opt_parser = RoseOptionParser()
    opt_parser.add_my_options('name')
    opts, args = opt_parser.parse_args(sys.argv[1:])
    event_handler = Reporter(opts.verbosity - opts.quietness)
    suite_vc_cmp = SuiteVCComparator(event_handler)
    suite_name = opts.name
    if not suite_name and args:
        suite_name = args[0]
    if not suite_name:
        suite_name = os.getenv(suite_vc_cmp.suite_engine_proc.SUITE_NAME_ENV)
    if not suite_name:
        opt_parser.print_usage(sys.stderr)
        sys.exit(2)
    try:
        lines = suite_vc_cmp.cmp_source_vc_info(suite_name=suite_name)
    except Exception as exc:
        event_handler(exc)
        traceback.print_exc()
        sys.exit(2)
    else:
        if lines is None:
            event_handler(
                '%s: rose-suite-run.version: VC info not found' % (
                    suite_name),
                kind=Reporter.KIND_ERR, level=Reporter.FAIL)
            sys.exit(2)
        lines = list(line for line in lines)
        for line in lines:
            event_handler('%s\n' % line, prefix='')
        if lines:
            sys.exit(1)
        else:
            sys.exit(0)
예제 #21
0
def list_local_suites(argv):
    """CLI command to list all the locally checked out suites"""
    opt_parser = RoseOptionParser().add_my_options(
        "no_headers", "prefixes", "print_format", "reverse", "sort", "user")
    opts = opt_parser.parse_args(argv)[0]
    report = Reporter(opts.verbosity - opts.quietness)

    if opts.user:
        alternative_roses_dir = SuiteId.get_local_copy_root(opts.user)
        report(UserSpecificRoses(alternative_roses_dir), prefix=None)

    ws_client = RosieWSClient(prefixes=opts.prefixes, event_handler=report)
    if ws_client.unreachable_prefixes:
        bad_prefix_string = " ".join(ws_client.unreachable_prefixes)
        report(
            RosieWSClientError(
                ERR_PREFIX_UNREACHABLE.format(bad_prefix_string)))
    _display_maps(opts, ws_client, ws_client.query_local_copies(opts.user))
예제 #22
0
def main():
    """Launcher for the CLI."""
    opt_parser = RoseOptionParser()
    option_keys = AppRunner.OPTIONS
    opt_parser.add_my_options(*option_keys)
    opts, args = opt_parser.parse_args(sys.argv[1:])
    event_handler = Reporter(opts.verbosity - opts.quietness)
    runner = AppRunner(event_handler)
    try:
        sys.exit(runner(opts, args))
    except Exception as exc:
        runner.handle_event(exc)
        if opts.debug_mode:
            traceback.print_exc()
        if isinstance(exc, RosePopenError):
            sys.exit(exc.ret_code)
        else:
            sys.exit(1)
예제 #23
0
def main():
    """Implement the "rose suite-id" command."""
    opt_parser = RoseOptionParser()
    opt_parser.add_my_options("latest", "next", "to_local_copy", "to_origin",
                              "to_output", "to_web")
    opts, args = opt_parser.parse_args()
    report = Reporter(opts.verbosity - opts.quietness)
    SuiteId.svn.event_handler = report  # FIXME: ugly?
    arg = None
    if args:
        arg = args[0]

    try:
        if opts.to_origin:
            for arg in args:
                report(str(SuiteId(id_text=arg).to_origin()) + "\n", level=0)
        elif opts.to_local_copy:
            for arg in args:
                report(str(SuiteId(id_text=arg).to_local_copy()) + "\n",
                       level=0)
        elif opts.to_output:
            for arg in args:
                url = SuiteId(id_text=arg).to_output()
                report(str(url) + "\n", level=0)
        elif opts.to_web:
            for arg in args:
                report(str(SuiteId(id_text=arg).to_web()) + "\n", level=0)
        elif opts.latest:
            suite_id = SuiteId.get_latest(prefix=arg)
            if suite_id is not None:
                report(str(suite_id) + "\n", level=0)
        elif opts.next:
            suite_id = SuiteId.get_next(prefix=arg)
            if suite_id is not None:
                report(str(suite_id) + "\n", level=0)
        else:
            if not arg:
                arg = os.getcwd()
            report(str(SuiteId(location=arg)) + "\n", level=0)
    except (NoSuiteLogError, SuiteIdError) as exc:
        report(exc)
        if opts.debug_mode:
            traceback.print_exc()
        sys.exit(1)
예제 #24
0
파일: vc.py 프로젝트: oliver-sanders/rose
def delete(argv):
    """CLI function: delete."""
    opt_parser = RoseOptionParser().add_my_options(
        "force_mode", "non_interactive", "local_only"
    )
    opts, args = opt_parser.parse_args(argv)
    report = Reporter(opts.verbosity - opts.quietness)
    client = RosieVCClient(event_handler=report, force_mode=opts.force_mode)
    SuiteId.svn.event_handler = client.event_handler
    if not args:
        args.append(SuiteId(location=os.getcwd()))
    interactive_mode = not opts.non_interactive
    prompt = PROMPT_DELETE
    if opts.local_only:
        prompt = PROMPT_DELETE_LOCAL
    ret_code = 0
    for arg in args:
        if interactive_mode:
            try:
                response = input(prompt % arg)
            except EOFError:
                ret_code = 1
                continue
            if response == YES_TO_ALL:
                interactive_mode = False
            elif response != YES:
                ret_code = 1
                continue
        if opts.debug_mode:
            client.delete(arg, opts.local_only)
        else:
            try:
                client.delete(arg, opts.local_only)
            except (
                LocalCopyStatusError,
                RosePopenError,
                SuiteIdPrefixError,
            ) as exc:
                client.event_handler(exc)
                ret_code = 1
                if not opts.force_mode:
                    sys.exit(1)
    if ret_code:
        sys.exit(ret_code)
예제 #25
0
def checkout(argv):
    """CLI function: checkout."""
    opt_parser = RoseOptionParser().add_my_options("force_mode")
    opts, args = opt_parser.parse_args(argv)
    verbosity = opts.verbosity - opts.quietness
    report = Reporter(verbosity)
    client = RosieVCClient(event_handler=report, force_mode=opts.force_mode)
    SuiteId.svn.event_handler = client.event_handler
    ret_code = 0
    for arg in args:
        try:
            client.checkout(arg)
        except (FileExistError, RosePopenError, SuiteIdPrefixError) as exc:
            ret_code = 1
            report(exc)
            if not opts.force_mode:
                sys.exit(1)
    if ret_code:
        sys.exit(ret_code)
예제 #26
0
파일: config_dump.py 프로젝트: wxtim/rose
def main():
    """Implement the "rose config-dump" command."""
    opt_parser = RoseOptionParser(description='''
Re-dump Rose configuration files in the common format.

Load and dump `"rose-*.conf"` files in place. Apply format-specific
pretty-printing.

By default, it recursively loads and dumps all `rose-*.conf` files in the
current working directory.

EXAMPLES
    rose config-dump
    rose config-dump -C /path/to/conf/dir
    rose config-dump -f /path/to/file1 -f /path/to/file2
        ''')
    opt_parser.add_my_options("conf_dir", "files", "no_pretty_mode")
    opts = opt_parser.parse_args()[0]
    verbosity = opts.verbosity - opts.quietness
    report = Reporter(verbosity)
    fs_util = FileSystemUtil(report)
    if opts.conf_dir:
        fs_util.chdir(opts.conf_dir)
    file_names = []
    if opts.files:
        file_names = opts.files
    else:
        for dirpath, _, filenames in os.walk("."):
            for filename in fnmatch.filter(filenames, "rose-*.conf"):
                path = os.path.join(dirpath, filename)[2:]  # remove leading ./
                file_names.append(path)
    for file_name in file_names:
        handle = NamedTemporaryFile()
        node = ConfigLoader()(file_name)
        if (not opts.no_pretty_mode
                and os.path.basename(file_name) != META_CONFIG_NAME):
            pretty_format_config(node, ignore_error=True)
        ConfigDumper()(node, handle)
        handle.seek(0)
        if not filecmp.cmp(handle.name, file_name, shallow=False):
            report(ConfigDumpEvent(file_name))
            ConfigDumper()(node, file_name)
예제 #27
0
def main():
    """Launcher for the CLI."""
    opt_parser = RoseOptionParser()
    opt_parser.add_my_options("host", "name")
    opts, args = opt_parser.parse_args(sys.argv[1:])
    event_handler = Reporter(opts.verbosity - opts.quietness)
    suite_restarter = SuiteRestarter(event_handler)
    try:
        sys.exit(suite_restarter.restart(
            suite_name=opts.name,
            host=opts.host,
            args=args))
    except Exception as exc:
        event_handler(exc)
        if opts.debug_mode:
            traceback.print_exc()
        if isinstance(exc, RosePopenError):
            sys.exit(exc.ret_code)
        else:
            sys.exit(1)
예제 #28
0
def main():
    """Implement the "rose host-select" command."""
    opt_parser = RoseOptionParser()
    opt_parser.add_my_options("choice", "rank_method", "thresholds", "timeout")
    opts, args = opt_parser.parse_args()
    report = Reporter(opts.verbosity - opts.quietness)
    popen = RosePopener(event_handler=report)
    select = HostSelector(event_handler=report, popen=popen)
    try:
        host_score_list = select(names=args,
                                 rank_method=opts.rank_method,
                                 thresholds=opts.thresholds,
                                 ssh_cmd_timeout=opts.timeout)
    except (NoHostError, NoHostSelectError) as exc:
        report(exc)
        if opts.debug_mode:
            traceback.print_exc()
        sys.exit(1)
    opts.choice = int(opts.choice)
    report(choice(host_score_list[0:opts.choice])[0] + "\n", level=0)
예제 #29
0
파일: ws.py 프로젝트: wxtim/rose
def parse_cli(*args, **kwargs):
    """Parse command line, start/stop ad-hoc server.

    Return a CLI instruction tuple for a valid command instruction, else False:
        ("start", Boolean, port):
            start server on 'port', [2]==True indicating non_interactive mode.
        ("stop", Boolean):
            stop server, [2]==True indicating service_root_mode.
        None:
            bare command, requesting to print server status
    """
    opt_parser = RoseOptionParser(description='''
Start/stop ad-hoc Rosie suite discovery web service server.

For `rosie disco start`, if `PORT` is not specified, use port 8080.

Examples:
    rosie disco start [PORT] # start ad-hoc web service server (on PORT)
    rosie disco stop         # stop ad-hoc web service server
    rosie disco stop -y      # stop ad-hoc web service server w/o prompting
    rosie disco              # print status of ad-hoc web service server
        ''', )
    opt_parser.add_my_options("non_interactive", "service_root_mode")
    opts, args = opt_parser.parse_args()

    arg = None
    if args:
        arg = args[0]

    if arg == "start":
        port = DEFAULT_PORT
        if args[1:]:
            try:
                port = int(args[1])
            except ValueError:
                print("Invalid port specified. Using the default port.")
        return ("start", opts.service_root_mode, port)
    elif arg == "stop":
        return ("stop", opts.non_interactive)
    elif arg:  # unrecognised (invalid) argument, to ignore
        return False  # False to distinguish from None for no arguments given
예제 #30
0
파일: env_cat.py 프로젝트: wxtim/rose
def main():
    """Implement "rose env-cat"."""
    opt_parser = RoseOptionParser(usage='rose env-cat [OPTIONS] [FILE ...]',
                                  description=r'''
Substitute environment variables in input files and print.

If no argument is specified, read from STDIN. One `FILE` argument may be
`-`, which means read from STDIN.

In `match-mode=default`, the command will look for `$NAME` or `${NAME}`
syntax and substitute them with the value of the environment variable
`NAME`. A backslash in front of the syntax, e.g. `\$NAME` or `\${NAME}`
will escape the substitution.

In `match-mode=brace`, the command will look for `${NAME}` syntax only.

EXAMPLES
    rose env-cat [OPTIONS] [FILE ...]
        ''')
    opt_parser.add_my_options("match_mode", "output_file", "unbound")
    opt_parser.modify_option(
        'output_file',
        help=("Specify an output file."
              "\nIf no output file is specified or if `FILE`"
              "is `-`, write output to STDOUT."),
    )
    opts, args = opt_parser.parse_args()
    if not args:
        args = ["-"]
    if not opts.output_file or opts.output_file == "-":
        out_handle = sys.stdout
    else:
        out_handle = open(opts.output_file, "wb")
    for arg in args:
        if arg == "-":
            in_handle = sys.stdin
        else:
            in_handle = open(arg)
        line_num = 0
        while True:
            line_num += 1
            line = in_handle.readline()
            if not line:
                break
            try:
                out_handle.write(
                    env_var_process(line, opts.unbound, opts.match_mode))
            except UnboundEnvironmentVariableError as exc:
                name = arg
                if arg == "-":
                    name = "<STDIN>"
                sys.exit("%s:%s: %s" % (name, line_num, str(exc)))
        in_handle.close()
    out_handle.close()