示例#1
0
 def __init__(self,
              prefixes=None,
              prompt_func=None,
              popen=None,
              event_handler=None):
     if not event_handler:
         event_handler = Reporter()
     if not popen:
         popen = RosePopener(event_handler=event_handler)
     self.event_handler = event_handler
     self.popen = popen
     self.prompt_func = prompt_func
     self.prefixes = []
     self.unreachable_prefixes = []
     self.auth_managers = {}
     conf = ResourceLocator.default().get_conf()
     conf_rosie_id = conf.get(["rosie-id"], no_ignore=True)
     if conf_rosie_id is None:
         raise RosieWSClientConfError()
     for key, node in conf_rosie_id.value.items():
         if node.is_ignored() or not key.startswith("prefix-ws."):
             continue
         prefix = key.replace("prefix-ws.", "")
         self.auth_managers[prefix] = RosieWSClientAuthManager(
             prefix, popen=self.popen, prompt_func=self.prompt_func)
     if not prefixes:
         prefixes_str = conf_rosie_id.get_value(["prefixes-ws-default"])
         if prefixes_str:
             prefixes = shlex.split(prefixes_str)
         else:
             prefixes = sorted(self.auth_managers.keys())
     self.set_prefixes(prefixes)
示例#2
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)
示例#3
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)
示例#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 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)
示例#6
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)
示例#7
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)
示例#8
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)
示例#9
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)
示例#10
0
def rose_env_cat(args, opts):
    if not args:
        args = ["-"]
    if not opts.output_file or opts.output_file == "-":
        out_handle = sys.stdout
    else:
        out_handle = open(opts.output_file, "w")
    for arg in args:
        if arg == "-":
            in_handle = sys.stdin
        else:
            try:
                in_handle = open(arg)
            except FileNotFoundError as exc:
                Reporter().report(exc)
                if opts.debug_mode:
                    raise exc
                return
        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 __init__(self, event_handler=None, popen=None):
     if event_handler is None:
         event_handler = Reporter()
     self.event_handler = event_handler
     if popen is None:
         popen = RosePopener(self.event_handler)
     self.popen = popen
     self.path = os.path.dirname(
         os.path.dirname(sys.modules["metomi.rosie"].__file__))
示例#13
0
def rose_fileinstall(srcdir=None, opts=None, rundir=None):
    """Call Rose Fileinstall.

    Args:
        srcdir(pathlib.Path):
            Search for a ``rose-suite.conf`` file in this location.
        rundir (pathlib.Path)

    """
    if not rose_config_exists(rundir, opts):
        return False

    # Load the config tree
    config_tree = rose_config_tree_loader(rundir, opts)

    if any(i.startswith('file') for i in config_tree.node.value):
        try:
            startpoint = os.getcwd()
            os.chdir(rundir)
        except FileNotFoundError as exc:
            raise exc
        else:
            # Carry out imports.
            import asyncio
            from metomi.rose.config_processor import ConfigProcessorsManager
            from metomi.rose.popen import RosePopener
            from metomi.rose.reporter import Reporter
            from metomi.rose.fs_util import FileSystemUtil

            # Update config tree with install location
            # NOTE-TO-SELF: value=os.environ["CYLC_WORKFLOW_RUN_DIR"]
            config_tree.node = config_tree.node.set(
                keys=["file-install-root"], value=str(rundir)
            )

            # Artificially set rose to verbose.
            event_handler = Reporter(3)
            fs_util = FileSystemUtil(event_handler)
            popen = RosePopener(event_handler)

            # Get an Asyncio loop if one doesn't exist:
            #   Rose may need an event loop to invoke async interfaces,
            #   doing this here incase we want to go async in cylc-rose.
            # See https://github.com/cylc/cylc-rose/pull/130/files
            try:
                asyncio.get_event_loop()
            except RuntimeError:
                asyncio.set_event_loop(asyncio.new_event_loop())

            # Process fileinstall.
            config_pm = ConfigProcessorsManager(event_handler, popen, fs_util)
            config_pm(config_tree, "file")
        finally:
            os.chdir(startpoint)

    return config_tree.node
示例#14
0
 def __init__(self, event_handler=None, popen=None):
     if event_handler is None:
         event_handler = Reporter()
     self.event_handler = event_handler
     if popen is None:
         popen = RosePopener(self.event_handler)
     self.popen = popen
     path = os.path.dirname(
         os.path.dirname(sys.modules["metomi.rosie"].__file__))
     self.usertools_manager = SchemeHandlersManager([path],
                                                    "rosie.usertools",
                                                    ["get_emails"])
示例#15
0
def main():
    """Launcher for the CLI."""
    opt_parser = metomi.rose.opt_parse.RoseOptionParser()
    opt_parser.add_my_options()
    opts, args = opt_parser.parse_args(sys.argv[1:])
    reporter = Reporter(opts.verbosity - opts.quietness)
    is_top_level = False
    if len(args) > 1:
        reporter.report('Only one argument accepted\n', level=Reporter.FAIL)
        sys.exit(1)
    if len(args) == 0:
        key = ROSE_INSTALL_ROOT / 'etc'
        path = ResourceLocator(paths=[ROSE_INSTALL_ROOT]).locate('etc')
        is_top_level = True
    else:
        key = args[0]
        try:
            path = ResourceLocator().locate(key)
        except ResourceError:
            reporter.report('Resource not found\n', level=Reporter.FAIL)
            sys.exit(1)
    if path.is_file():
        print(path)
    elif path.is_dir():
        print(f'{key}/')
        for item in path.iterdir():
            if is_top_level:
                item = item.relative_to(path)
            else:
                item = item.relative_to(path.parent)
            print(f'  {item}')
示例#16
0
文件: date.py 项目: MartinDix/rose
def upgrade_offset(offset: str) -> str:
    """Convert offset values in the legacy format

    Args:
        offset: offset matching [0-9]+[wdhms]

    Returns: Offset in isodate compatible format.

    URL:
        https://github.com/metomi/rose/issues/2577

    Examples:
        >>> upgrade_offset('1w')
        [WARN] This offset syntax 1w is deprecated: Using P7DT0H0M0S
        'P7DT0H0M0S'
        >>> upgrade_offset('1w1d1h')
        [WARN] This offset syntax 1w1d1h is deprecated: Using P8DT1H0M0S
        'P8DT1H0M0S'
        >>> upgrade_offset('1h1d')
        [WARN] This offset syntax 1h1d is deprecated: Using P1DT1H0M0S
        'P1DT1H0M0S'
    """

    sign = '-' if offset[0] == '-' else ''
    offsets = LEGACY_OFFSET.findall(offset)
    offsets = {unit.upper(): number for number, unit in offsets}

    # Rose 2019 did not make any distinction between 1s1m and 1m1s,
    # so we do an implicit sort here:
    weeks, days, hours, minutes, seconds = [0 for _ in range(5)]
    for unit, value in offsets.items():
        if unit == 'W':
            weeks = int(value)
        if unit == 'D':
            days = int(value)
        if unit == 'H':
            hours = int(value)
        if unit == 'M':
            minutes = int(value)
        if unit == 'S':
            seconds = int(value)

    days = days + weeks * 7

    result = f'{sign}P{days}DT{hours}H{minutes}M{seconds}S'

    Reporter().report(
        f'This offset syntax {offset} is deprecated: Using {result}',
        prefix=Reporter.PREFIX_WARN,
        level=Reporter.WARN)

    return result
示例#17
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)
示例#18
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)
示例#19
0
def main():
    """Launcher for the CLI."""
    opt_parser = metomi.rose.opt_parse.RoseOptionParser(
        usage='rose resource RESOURCE_PATH',
        description='''
Display the path of resources in the Rose Python installation.

* If the requested resource exists and is a file its path is printed.
* If the requested resource exists and is a directory it is listed.

Provide no arguments to see a list of top-level resources.

EXAMPLES
    # List top-level resources:
    $ rose resource

    # List the contents of the "syntax" directory:
    $ rose resource syntax

    # Extract the Rose syntax file for the Vim text editor:
    $ rose resource syntax/rose-conf.vim
        ''',
        epilog='''
ARGUMENTS
    RESOURCE_PATH
        Path of the resource to extract.

        Run `rose resource` to see the list of resources.
        ''',
    )
    opt_parser.add_my_options()
    opts, args = opt_parser.parse_args()
    reporter = Reporter(opts.verbosity - opts.quietness)
    is_top_level = False
    if len(args) > 1:
        reporter.report('Only one argument accepted\n', level=Reporter.FAIL)
        sys.exit(1)
    if len(args) == 0:
        key = ROSE_INSTALL_ROOT / 'etc'
        path = ResourceLocator(paths=[ROSE_INSTALL_ROOT]).locate('etc')
        is_top_level = True
    else:
        key = args[0]
        try:
            path = ResourceLocator().locate(key)
        except ResourceError:
            reporter.report('Resource not found\n', level=Reporter.FAIL)
            sys.exit(1)
    if path.is_file():
        print(path)
    elif path.is_dir():
        print(f'{key}/')
        for item in path.iterdir():
            if is_top_level:
                item = item.relative_to(path)
            else:
                item = item.relative_to(path.parent)
            print(f'  {item}')
示例#20
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)
示例#21
0
文件: db_create.py 项目: wxtim/rose
def main():
    """rosa db-create."""
    db_conf = ResourceLocator.default().get_conf().get(["rosie-db"])
    if db_conf is not None:
        opts = RoseOptionParser().parse_args()[0]
        reporter = Reporter(opts.verbosity - opts.quietness)
        init = RosieDatabaseInitiator(event_handler=reporter)
        conf = ResourceLocator.default().get_conf()
        for key in db_conf.value:
            if key.startswith("db."):
                prefix = key.replace("db.", "", 1)
                db_url = conf.get_value(["rosie-db", "db." + prefix])
                repos_path = conf.get_value(["rosie-db", "repos." + prefix])
                init(db_url, repos_path)
示例#22
0
 def __init__(self,
              event_handler=None,
              host_selector=None,
              suite_engine_proc=None):
     if event_handler is None:
         event_handler = Reporter()
     self.event_handler = event_handler
     if host_selector is None:
         host_selector = HostSelector(event_handler=event_handler)
     self.host_selector = host_selector
     if suite_engine_proc is None:
         suite_engine_proc = SuiteEngineProcessor.get_processor(
             event_handler=event_handler)
     self.suite_engine_proc = suite_engine_proc
示例#23
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)
示例#24
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)
示例#25
0
 def __init__(self, opts, reporter=None, popen=None, fs_util=None):
     self.opts = opts
     if reporter is None:
         self.reporter = Reporter(opts.verbosity - opts.quietness)
     else:
         self.reporter = reporter
     if popen is None:
         self.popen = RosePopener(event_handler=self.reporter)
     else:
         self.popen = popen
     if fs_util is None:
         self.fs_util = FileSystemUtil(event_handler=self.reporter)
     else:
         self.fs_util = fs_util
     self.host_selector = HostSelector(event_handler=self.reporter,
                                       popen=self.popen)
示例#26
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)
示例#27
0
def rose_fileinstall(srcdir=None, opts=None, rundir=None):
    """Call Rose Fileinstall.

    Args:
        srcdir(pathlib.Path):
            Search for a ``rose-suite.conf`` file in this location.
        rundir (pathlib.Path)

    """
    if not rose_config_exists(rundir, opts):
        return False

    # Load the config tree
    config_tree = rose_config_tree_loader(rundir, opts)

    if any(i.startswith('file') for i in config_tree.node.value):
        try:
            startpoint = os.getcwd()
            os.chdir(rundir)
        except FileNotFoundError as exc:
            raise exc
        else:
            # Carry out imports.
            from metomi.rose.config_processor import ConfigProcessorsManager
            from metomi.rose.popen import RosePopener
            from metomi.rose.reporter import Reporter
            from metomi.rose.fs_util import FileSystemUtil

            # Update config tree with install location
            # NOTE-TO-SELF: value=os.environ["CYLC_WORKFLOW_RUN_DIR"]
            config_tree.node = config_tree.node.set(
                keys=["file-install-root"], value=str(rundir)
            )

            # Artificially set rose to verbose.
            event_handler = Reporter(3)
            fs_util = FileSystemUtil(event_handler)
            popen = RosePopener(event_handler)

            # Process files
            config_pm = ConfigProcessorsManager(event_handler, popen, fs_util)
            config_pm(config_tree, "file")
        finally:
            os.chdir(startpoint)

    return config_tree.node
示例#28
0
    def __init__(
        self, prefix, popen=None, prompt_func=None, event_handler=None
    ):
        self.prefix = prefix
        root = self._get_conf_value("ws")
        if root is None:
            raise UndefinedRosiePrefixWS(self.prefix)
        if not root.endswith("/"):
            root += "/"
        self.root = root
        urlparse_res = urlparse(self.root)
        self.scheme = urlparse_res[0]
        self.host = urlparse_res[1]
        self.password_orig = None
        self.username_orig = None
        self.password = None
        self.username = None
        if popen is None:
            popen = RosePopener()
        self.popen = popen
        self.prompt_func = prompt_func
        if event_handler is None:
            self.event_handler = Reporter()
        else:
            self.event_handler = event_handler
        res_loc = ResourceLocator.default()
        password_stores_str = (
            res_loc.default()
            .get_conf()
            .get_value(
                keys=["rosie-id", "prefix-password-store." + self.prefix],
                default=self.PASSWORD_STORES_STR,
            )
        )
        for password_store_name in shlex.split(password_stores_str):
            password_store_cls = self.PASSWORD_STORE_CLASSES.get(
                password_store_name
            )
            if password_store_cls is not None and password_store_cls.usable():
                self.password_store = password_store_cls()
                break
        else:
            self.password_store = None

        self.requests_kwargs = {}
        self._init_https_params()
示例#29
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)
示例#30
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))