Example #1
0
def ask(prompt, default=None, color='cyan'):
    """Ask a question, waits for user input.

    Replacement for "input". Updates the same line by replacing "default".

    .. code-block:: python

        >>> my_name = ask('Say my name: %s ', 'Heisenberg')
        # Wait for user input
        Say my name: (Heisenberg) Walter
        # Updates *the same* line with 'Walter' in green
        Say my name: Walter
        >>> print(my_name)
        Walter

    Inspired by 'bower_ init' which confirms user input by replacing the
    default option in line (ref_).

    Args:
        prompt (str): Question to print, '%s' will be replaced by default
        default (str, optional): Default option unless replaced by user
        color (str, optional): Some common color like 'red', 'green', 'yellow'

    Returns:
        str: User input or default

    .. _bower: http://bower.io/
    .. _ref: http://stackoverflow.com/questions/12586601
    """
    # helper variables
    MOVE_CURSOR_UP = '\x1b[1A'
    ERASE_LINE = '\x1b[2K'

    # determine if a default was submitted
    if default:
        # prepare the default-part of the prompt
        default_string = "(%s)" % default
    else:
        # not relevant since ``promt`` shouldn't include a '%s'
        default_string = ''

    # pass question to user and wait for response
    # write default option in parentheses, use it as response if nothing
    # was submitted by user.
    response = input(build_prompt(prompt, default_string)) or default
    if isinstance(default, list) and isinstance(response, str):
        sep = ',' if ',' in response else None
        response = [int(item) for item in response.split(sep)]

    # print the updated confirmation line by replacing the previous
    echo(MOVE_CURSOR_UP + ERASE_LINE +
         build_prompt(prompt, style(str(response) or '', fg=color)))

    return response
Example #2
0
def ask(prompt, default=None, color='cyan'):
    """Ask a question, waits for user input.

    Replacement for "input". Updates the same line by replacing "default".

    .. code-block:: python

        >>> my_name = ask('Say my name: %s ', 'Heisenberg')
        # Wait for user input
        Say my name: (Heisenberg) Walter
        # Updates *the same* line with 'Walter' in green
        Say my name: Walter
        >>> print(my_name)
        Walter

    Inspired by 'bower_ init' which confirms user input by replacing the
    default option in line (ref_).

    Args:
        prompt (str): Question to print, '%s' will be replaced by default
        default (str, optional): Default option unless replaced by user
        color (str, optional): Some common color like 'red', 'green', 'yellow'

    Returns:
        str: User input or default

    .. _bower: http://bower.io/
    .. _ref: http://stackoverflow.com/questions/12586601
    """
    # helper variables
    MOVE_CURSOR_UP = '\x1b[1A'
    ERASE_LINE = '\x1b[2K'

    # determine if a default was submitted
    if default:
        # prepare the default-part of the prompt
        default_string = "(%s)" % default
    else:
        # not relevant since ``promt`` shouldn't include a '%s'
        default_string = ''

    # pass question to user and wait for response
    # write default option in parentheses, use it as response if nothing
    # was submitted by user.
    response = input(build_prompt(prompt, default_string)) or default
    if isinstance(default, list) and isinstance(response, str):
        sep = ',' if ',' in response else None
        response = [int(item) for item in response.split(sep)]

    # print the updated confirmation line by replacing the previous
    echo(MOVE_CURSOR_UP + ERASE_LINE
         + build_prompt(prompt, style(str(response) or '', fg=color)))

    return response
Example #3
0
def init_pipeline(program, config, questions):
    """Initializes a config object by interactively asking questions."""
    if config.user_data:
        # Some existing user settings were found, warn about overwriting them
        message = "{program} {note}\tThe existing {file} will be updated"
        segments = dict(program=program, note=style('existing', fg='yellow'),
                        file=style(config.config_path.basename(), fg='white'))
        echo(message.format(**segments))

    # Launch questionnaire
    user_defaults = questionnaire(questions)
    # Set the selected user defaults
    for dot_key, value in user_defaults.items():
        config.set(dot_key, value, scope=config.user_data)
Example #4
0
def init_pipeline(program, config, questions):
    """Initializes a config object by interactively asking questions."""
    if config.user_data:
        # Some existing user settings were found, warn about overwriting them
        message = "{program} {note}\tThe existing {file} will be updated"
        segments = dict(program=program,
                        note=style('existing', fg='yellow'),
                        file=style(config.config_path.basename(), fg='white'))
        echo(message.format(**segments))

    # Launch questionnaire
    user_defaults = questionnaire(questions)
    # Set the selected user defaults
    for dot_key, value in user_defaults.items():
        config.set(dot_key, value, scope=config.user_data)
Example #5
0
def _org_reports_help(ctx,
                      value,
                      header,
                      synopsis,
                      discussion=None,
                      paged=True):
    """Print a nicely formatted help message.

    :param ctx click.Context: The current click Context instance
    :param header str: Heading for this help page
    :param synopsis str: A brief description of this command
    :param discussion str: A discussion of this command of arbitrary length

    Print a help page in a nicer format using ANSI escape codes.
    """
    from click.formatting import HelpFormatter
    from click.termui import echo, echo_via_pager

    if not value or ctx.resilient_parsing:
        return

    fmt = HelpFormatter()
    fmt.write_text('' + header + '')
    fmt.write_paragraph()
    pieces = ctx.command.collect_usage_pieces(ctx)
    fmt.write_usage(ctx.command_path, ' '.join(pieces), 'Usage\n\n')
    fmt.write_paragraph()
    with fmt.indentation():
        fmt.write_text(synopsis)
    ctx.command.format_options(ctx, fmt)
    fmt.write_paragraph()
    if discussion:
        fmt.write_text('Discussion')
        fmt.write_paragraph()
        with fmt.indentation():
            fmt.write_text(discussion)

    if paged:
        echo_via_pager(fmt.getvalue(), ctx.color)
    else:
        echo(fmt.getvalue(), ctx.color)

    ctx.exit()