Ejemplo n.º 1
0
def bashcomplete(cli, prog_name, complete_var, complete_instr):
    if complete_instr == 'source':
        echo(get_completion_script(prog_name, complete_var))
        return True
    elif complete_instr == 'complete':
        return do_complete(cli, prog_name)
    return False
Ejemplo n.º 2
0
 def render_finish(self):
     if self.is_hidden:
         return
     # display a new line after the 'dots' IFF we do not have a show func
     nl = not bool(self.item_show_func)
     echo(None, file=self.file, nl=nl, color=self.color)
     self.show_finish()
Ejemplo n.º 3
0
def do_complete(cli, prog_name):
    cwords = split_arg_string(os.environ['COMP_WORDS'])
    cword = int(os.environ['COMP_CWORD'])
    args = cwords[1:cword]
    try:
        incomplete = cwords[cword]
    except IndexError:
        incomplete = ''

    ctx = resolve_ctx(cli, prog_name, args)
    if ctx is None:
        return True

    choices = []
    if incomplete and not incomplete[:1].isalnum():
        for param in ctx.command.params:
            if not isinstance(param, Option):
                continue
            choices.extend(param.opts)
            choices.extend(param.secondary_opts)
    elif isinstance(ctx.command, MultiCommand):
        choices.extend(ctx.command.list_commands(ctx))

    for item in choices:
        if item.startswith(incomplete):
            echo(item)

    return True
Ejemplo n.º 4
0
 def render_progress(self):
     line = self.format_progress_line()
     if line:
         # only add new lines if there is an item_show_func
         nl = bool(self.item_show_func)
         echo(line, file=self.file, nl=nl, color=self.color)
         self.file.flush()
Ejemplo n.º 5
0
 def render_progress(self):
     line = self.format_progress_line()
     if line:
         # only add new lines if there is an item_show_func
         nl = bool(self.item_show_func)
         echo(line, file=self.file, nl=nl, color=self.color)
         self.file.flush()
Ejemplo n.º 6
0
 def render_start(self):
     if self.is_hidden:
         return
     if self.start_show_func is not None:
         text = self.start_show_func()
         if text:
             echo(text, file=self.file, color=self.color)
             self.file.flush()
Ejemplo n.º 7
0
 def show(self, file=None):
     import sys
     if file is None:
         file = get_text_stderr()
     if self.ctx is not None:
         color = self.ctx.color
         echo(self.ctx.get_usage() + '\n', file=file, color=color)
     echo_error(self.format_message(), file=file)
     sys.argv = [sys.argv[0]]
Ejemplo n.º 8
0
 def show(self, file=None):
     import sys
     if file is None:
         file = get_text_stderr()
     color = None
     if self.ctx is not None:
         color = self.ctx.color
         echo(self.ctx.get_usage() + '\n', file=file, color=color)
     echo('Error: %s\n' % self.format_message(), file=file, color=color)
     sys.argv = [sys.argv[0]]
     main_command()
Ejemplo n.º 9
0
 def show(self, file=None):
     if file is None:
         file = get_text_stderr()
     if "--no-color" in sys.argv or "-nc" in sys.argv:
         echo(click.style("[x]") +
              click.style(u' %s' % text(self.format_message())),
              file=file)
     else:
         echo(click.style("[x]", bg="red") +
              click.style(u' %s' % text(self.format_message()), fg="red"),
              file=file)
Ejemplo n.º 10
0
 def prompt_func(text):
     f = hidden_prompt_func if hide_input else visible_prompt_func
     try:
         # Write the prompt separately so that we get nice
         # coloring through colorama on Windows
         echo(f"{text}{_ansi_reset_all}", nl=False, err=err)
         return f("")
     except (KeyboardInterrupt, EOFError):
         # getpass doesn't print a newline if the user aborts input with ^C.
         # Allegedly this behavior is inherited from getpass(3).
         # A doc bug has been filed at https://bugs.python.org/issue24711
         if hide_input:
             echo(None, err=err)
         raise Abort()
Ejemplo n.º 11
0
def confirm(
    text,
    default=False,
    abort=False,
    prompt_suffix=": ",
    show_default=True,
    err=False,
) -> bool:
    """Prompts for confirmation (yes/no question).

    If the user aborts the input by sending a interrupt signal this
    function will catch it and raise a :exc:`Abort` exception.

    .. versionadded:: 4.0
       Added the `err` parameter.

    :param text: the question to ask.
    :param default: the default for the prompt.
    :param abort: if this is set to `True` a negative answer aborts the
                  exception by raising :exc:`Abort`.
    :param prompt_suffix: a suffix that should be added to the prompt.
    :param show_default: shows or hides the default value in the prompt.
    :param err: if set to true the file defaults to ``stderr`` instead of
                ``stdout``, the same as with echo.
    :return: User's decision.
    """
    prompt_ = _build_prompt(text, prompt_suffix, show_default,
                            "Y/n" if default else "y/N")
    while 1:
        try:
            # Write the prompt separately so that we get nice
            # coloring through colorama on Windows
            echo(f"{prompt_}{_ansi_reset_all}", nl=False, err=err)
            value = visible_prompt_func("").lower().strip()
        except (KeyboardInterrupt, EOFError):
            raise Abort()
        if value in ("y", "yes"):
            rv = True
        elif value in ("n", "no"):
            rv = False
        elif value == "":
            rv = default
        else:
            echo("Error: invalid input", err=err)
            continue
        break
    if abort and not rv:
        raise Abort()
    return rv
Ejemplo n.º 12
0
    def show(self, file=None):

        tcfcli.common.operation_msg.Operation(self.format_message(),
                                              level="ERROR").no_output()

        if file is None:
            file = get_text_stderr()
        if "--no-color" in sys.argv or "-nc" in sys.argv:
            echo(click.style("[x]") +
                 click.style(u' %s' % text(self.format_message())),
                 file=file)
        else:
            echo(click.style("[x] [ERROR] ", bg="red") +
                 click.style(u' %s' % text(self.format_message()), fg="red"),
                 file=file)
Ejemplo n.º 13
0
def do_complete(cli, prog_name):
    commandline = os.environ['COMMANDLINE']
    args = split_arg_string(commandline)[1:]
    if args and not commandline.endswith(' '):
        incomplete = args[-1]
        args = args[:-1]
    else:
        incomplete = ''

    for item, help in get_choices(cli, prog_name, args, incomplete):
        if help:
            echo("%s\t%s" % (item, help))
        else:
            echo(item)

    return True
def _show_usage_error(self, file=None):
    if file is None:
        file = get_text_stderr()
    color = None
    echo('Error: %s' % self.format_message(), file=file, color=color)
    if self.ctx is not None:
        echo('', file=file)
        color = self.ctx.color
        echo(self.ctx.get_help() + '\n', file=file, color=color)
Ejemplo n.º 15
0
def submit(ctx, file, annotation, large, public, private):
    """
    For uploading submission files to evalai:
        - Invoked by running 'evalai challenge CHALLENGE phase PHASE submit --file FILE'
        - For large files, add a '--large' option at the end of the command

    For uploading test annotation files to evalai:
        - Invoked by running "evalai challenge CHALLENGE phase PHASE submit --file FILE --annotation"

    Arguments:
        ctx (class click.Context) --  The context object which holds state of the invocation
        file (str) -- the path of the file to be uploaded
        annotations (boolean) -- flag to denote if file is a test annotation file
        large (boolean) -- flag to denote if submission file is large (if large, presigned urls are used for uploads)
        public (boolean) -- flag to denote if submission is public
        private (boolean) -- flag to denote if submission is private
    Returns:
        None
    """
    if public and private:
        message = "\nError: Submission can't be public and private.\nPlease select either --public or --private"
        notify_user(message, color="red")
    else:
        if annotation:
            upload_file_using_presigned_url(ctx.phase_id, file, "annotation")
        else:
            submission_metadata = {}
            if public:
                submission_metadata["is_public"] = json.dumps(True)
            elif private:
                submission_metadata["is_public"] = json.dumps(False)
            else:
                submission_metadata["is_public"] = None
            if click.confirm("Do you want to include the Submission Details?"):
                submission_metadata["method_name"] = click.prompt(style(
                    "Method Name", fg="yellow"),
                                                                  type=str,
                                                                  default="")
                submission_metadata["method_description"] = click.prompt(
                    style("Method Description", fg="yellow"),
                    type=str,
                    default="",
                )
                submission_metadata["project_url"] = click.prompt(style(
                    "Project URL", fg="yellow"),
                                                                  type=str,
                                                                  default="")
                submission_metadata["publication_url"] = click.prompt(
                    style("Publication URL", fg="yellow"),
                    type=str,
                    default="")
            submission_meta_attributes = get_submission_meta_attributes(
                ctx.challenge_id, ctx.phase_id)
            submission_attribute_metadata = []
            if (submission_meta_attributes
                    and len(submission_meta_attributes) > 0):
                if click.confirm(
                        "Do you want to include the Submission Metadata?"):
                    for attribute in submission_meta_attributes:
                        attribute_type = attribute["type"]
                        attribute_name = attribute["name"]
                        attribute_description = attribute["description"]
                        attribute_required = attribute.get("required")
                        if attribute_required:
                            attribute_name = attribute_name + '*'
                        value = None
                        message = "{} ({})".format(attribute_name,
                                                   attribute_description)
                        if attribute_type == "text":
                            while True:
                                value = click.prompt(
                                    style(message, fg="yellow"),
                                    type=str,
                                    default="",
                                )
                                if not attribute_required or value != "":
                                    break
                                echo("Error: {} is a required field".format(
                                    attribute["name"]))
                        if attribute_type == "boolean":
                            while True:
                                value = click.prompt(style(message,
                                                           fg="yellow"),
                                                     type=bool,
                                                     default="")
                                if not attribute_required or value != "":
                                    break
                                echo("Error: {} is a required field".format(
                                    attribute["name"]))
                        if attribute_type == "radio":
                            while True:
                                value = click.prompt(style(
                                    "{}:\nChoices:{}".format(
                                        message, attribute["options"]),
                                    fg="yellow",
                                ),
                                                     type=click.Choice(
                                                         attribute["options"]),
                                                     default="")
                                if not attribute_required or value != "":
                                    break
                                echo("Error: {} is a required field".format(
                                    attribute["name"]))
                        if attribute_type == "checkbox":
                            option_chosen = True
                            while option_chosen:
                                value = []
                                choices = click.prompt(style(
                                    "{}:\nChoices(separated by comma):{}".
                                    format(message, attribute["options"]),
                                    fg="yellow",
                                ),
                                                       type=str,
                                                       show_default=False,
                                                       default="")
                                if choices != "":
                                    choices = [
                                        choice.strip(" ")
                                        for choice in choices.split(",")
                                    ]
                                else:
                                    choices = []
                                    option_chosen = False
                                if attribute_required and len(choices) == 0:
                                    echo(
                                        "Error: {} is a required field. Please select atleast one option"
                                        .format(attribute["name"]))
                                    option_chosen = True
                                for choice in choices:
                                    if choice in attribute["options"]:
                                        value.append(choice)
                                        option_chosen = False
                                    else:
                                        echo(
                                            "Error: Choose correct value(s) from the given options only"
                                        )
                                        option_chosen = True
                                        break
                        submission_attribute_metadata.append(
                            {attribute_name: value})
            if large:
                upload_file_using_presigned_url(ctx.phase_id, file,
                                                "submission",
                                                submission_metadata)
            else:
                make_submission(
                    ctx.challenge_id,
                    ctx.phase_id,
                    file,
                    submission_metadata,
                    submission_attribute_metadata,
                )
Ejemplo n.º 16
0
    def show(self, file: t.Optional[t.IO] = None) -> None:
        if file is None:
            file = get_text_stderr()

        message = _build_message(self)
        echo(_("Error: {message}").format(message=message), file=file)
Ejemplo n.º 17
0
 def show(self, file=None):
     if file is None:
         file = get_text_stderr()
     echo(click.style("[x]", bg="red") +
          click.style(u' %s' % text(self.format_message()), fg="red"),
          file=file)
Ejemplo n.º 18
0
 def show_finish(self):
     if self.finish_show_func is not None:
         text = self.finish_show_func()
         if text:
             echo(text, file=self.file, color=self.color)
             self.file.flush()
Ejemplo n.º 19
0
def prompt(
    text,
    default=None,
    hide_input=False,
    confirmation_prompt=False,
    type=None,
    value_proc=None,
    prompt_suffix=": ",
    show_default=True,
    err=False,
    show_choices=True,
) -> None:
    """Prompts a user for input.  This is a convenience function that can \
    be used to prompt a user for input later.

    If the user aborts the input by sending a interrupt signal, this
    function will catch it and raise a :exc:`Abort` exception.

    .. versionadded:: 7.0
       Added the show_choices parameter.

    .. versionadded:: 6.0
       Added unicode support for cmd.exe on Windows.

    .. versionadded:: 4.0
       Added the `err` parameter.

    :param text: the text to show for the prompt.
    :param default: the default value to use if no input happens.  If this
                    is not given it will prompt until it's aborted.
    :param hide_input: if this is set to true then the input value will
                       be hidden.
    :param confirmation_prompt: asks for confirmation for the value.
    :param type: the type to use to check the value against.
    :param value_proc: if this parameter is provided it's a function that
                       is invoked instead of the type conversion to
                       convert a value.
    :param prompt_suffix: a suffix that should be added to the prompt.
    :param show_default: shows or hides the default value in the prompt.
    :param err: if set to true the file defaults to ``stderr`` instead of
                ``stdout``, the same as with echo.
    :param show_choices: Show or hide choices if the passed type is a Choice.
                         For example if type is a Choice of either day or week,
                         show_choices is true and text is "Group by" then the
                         prompt will be "Group by (day, week): ".
    :return: None
    """
    result = None

    def prompt_func(text):
        f = hidden_prompt_func if hide_input else visible_prompt_func
        try:
            # Write the prompt separately so that we get nice
            # coloring through colorama on Windows
            echo(f"{text}{_ansi_reset_all}", nl=False, err=err)
            return f("")
        except (KeyboardInterrupt, EOFError):
            # getpass doesn't print a newline if the user aborts input with ^C.
            # Allegedly this behavior is inherited from getpass(3).
            # A doc bug has been filed at https://bugs.python.org/issue24711
            if hide_input:
                echo(None, err=err)
            raise Abort()

    if value_proc is None:
        value_proc = convert_type(type, default)

    prompt_ = _build_prompt(text, prompt_suffix, show_default, default,
                            show_choices, type)

    while 1:
        while 1:
            value = prompt_func(prompt_)
            if value:
                break
            elif default is not None:
                value = default
                break
        try:
            result = value_proc(value)
        except UsageError as e:
            if hide_input:
                echo("Error: the value you entered was invalid", err=err)
            else:
                echo(f"Error: {e.message}", err=err)  # noqa: B306
            continue
        if not confirmation_prompt:
            return result
        while 1:
            value2 = prompt_func("Repeat for confirmation: ")
            if value2:
                break
        if value == value2:
            return result
        echo("Error: the two entered values do not match", err=err)
Ejemplo n.º 20
0
    def _do_deploy_core(self, func, func_name, func_ns, region, forced, success_list, faild_list, skip_event=False):
        # check role exit
        try:
            role = func.get(tsmacro.Properties, {}).get(tsmacro.Role)
            if role:
                rolelist = list_scf_role(region)
                if rolelist == None:
                    Operation("Get Role list error").warning()
                    func[tsmacro.Properties][tsmacro.Role] = None
                elif role not in rolelist:
                    Operation("%s not exists in remote scf role list" % (role)).warning()
                    if len(rolelist):
                        Operation("You can choose from %s " % (str(rolelist))).warning()
                    func[tsmacro.Properties][tsmacro.Role] = None
            # check namespace exit, create namespace
            if self.namespace and self.namespace != func_ns:
                func_ns = self.namespace

            function_data = Function(region, func_ns, func_name, self.resources).get_function_trigger()
            trigger_release = None
            if function_data:
                now_runtime = function_data[0]
                trigger_release = function_data[1]

                if func['Properties']['Runtime'] != now_runtime:
                    err_msg = "RUNTIME in YAML does not match RUNTIME on the RELEASE (release: %s)" % now_runtime
                    echo(
                        Operation("[x]", bg="red").style() + Operation(u' %s' % text(err_msg), fg="red").style(),
                        file=get_text_stderr()
                    )
                    exit(1)
                    # raise DeployException(err_msg)

            rep = ScfClient(region).get_ns(func_ns)
            if not rep:
                Operation("{ns} not exists, create it now".format(ns=func_ns)).process()
                err = ScfClient(region).create_ns(func_ns)
                if err is not None:
                    if sys.version_info[0] == 3:
                        s = err.get_message()
                    else:
                        s = err.get_message().encode("UTF-8")
                    err_msg = "Create namespace '{name}' failure. Error: {e}.".format(name=func_ns, e=s)
                    echo(
                        Operation("[x]", bg="red").style() + Operation(u' %s' % text(err_msg), fg="red").style(),
                        file=get_text_stderr()
                    )
                    exit(1)
                    # raise NamespaceException()

            deploy_result = ScfClient(region).deploy_func(func, func_name, func_ns, forced)

            if deploy_result == 1:
                Operation("{ns} {name} already exists, update it now".format(ns=func_ns, name=func_name)).process()
                deploy_result = ScfClient(region).update_config(func, func_name, func_ns)
                if deploy_result == True:
                    deploy_result = ScfClient(region).update_code(func, func_name, func_ns)
                    deploy_result = 0 if deploy_result == True else deploy_result

            if deploy_result == 0:
                Operation("Deploy function '{name}' success".format(name=func_name)).success()
                if not skip_event:
                    self._do_deploy_trigger(func, func_name, func_ns, region, trigger_release)
                success_list.append(func_name)
                return

            elif deploy_result == 2:
                faild_list.append(func_name)
                Operation(
                    "%s %s: You can add -f to update the function when it already exists. Example : scf deploy -f" % (
                        func_ns, func_name)).warning()
                err_msg = "%s %s: The function already exists." % (func_ns, func_name)
                echo(
                    Operation("[x]", bg="red").style() + Operation(u' %s' % text(err_msg), fg="red").style(),
                    file=get_text_stderr()
                )

                exit(1)
                # raise CloudAPIException("The function already exists.")

            if deploy_result != None:
                faild_list.append(func_name)
                err = deploy_result
                s = err.get_message()
                if sys.version_info[0] == 2 and isinstance(s, str):
                    s = s.encode("utf8")
                err_msg = u"Deploy function '{name}' failure, {e}.".format(name=func_name, e=s)

                if err.get_request_id():
                    err_msg += (u" RequestId: {}".format(err.get_request_id()))
                echo(
                    Operation("[x]", bg="red").style() + Operation(u' %s' % text(err_msg), fg="red").style(),
                    file=get_text_stderr()
                )
                exit(1)
                # raise CloudAPIException(err_msg)
        except Exception as e:
            faild_list.append(func_name)
            echo(
                Operation("[x]", bg="red").style() + Operation(u' %s' % text(str(e)), fg="red").style(),
                file=get_text_stderr()
            )
            exit(1)
Ejemplo n.º 21
0
 def echo(message=None, file=None, nl=True, err=False, color=None):
     utils.echo(message, file, nl, err, color)