Exemplo n.º 1
0
def set_no_wrap_on_formatters(no_wrap, formatters):
    """
       Purpose of this function is to temporarily force
       the no_wrap setting for the formatters parameter.
       returns orig_no_wrap_settings defined for each formatter
       Use unset_no_wrap_on_formatters(orig_no_wrap_settings) to undo what
       this function does
    """
    # handle easy case:
    if not formatters:
        return {}

    formatter_no_wrap_settings = {}

    global_orig_no_wrap = is_nowrap_set()
    set_no_wrap(no_wrap)

    for k, f in formatters.iteritems():
        if WrapperFormatter.is_wrapper_formatter(f):
            formatter_no_wrap_settings[k] = (f.wrapper_formatter.no_wrap,
                                             f.wrapper_formatter)
            f.wrapper_formatter.no_wrap = no_wrap

    return {
        "global_orig_no_wrap": global_orig_no_wrap,
        "formatter_no_wrap_settings": formatter_no_wrap_settings
    }
Exemplo n.º 2
0
def _simpleTestHarness(no_wrap):

    import utils

    def testFormatter(event):
        return "*{}".format(event["state"])

    def buildFormatter(field, width):
        def f(dict):
            if field == 'number':
                return dict[field]
            return "{}".format(dict[field]).replace("_", " ")
        return {"formatter": f, "wrapperFormatter": width}

    set_no_wrap(no_wrap)

    field_labels = ['Time Stamp', 'State', 'Event Log ID', 'Reason Text',
                    'Entity Instance ID', 'Severity', 'Number']
    fields = ['timestamp', 'state', 'event_log_id', 'reason_text',
              'entity_instance_id', 'severity', 'number']

    formatterSpecX = {"timestamp": 10,
                      "state": 8,
                      "event_log_id": 70,
                      "reason_text": 30,
                      "entity_instance_id": 30,
                      "severity": 12,
                      "number": 4}

    formatterSpec = {}
    for f in fields:
        formatterSpec[f] = buildFormatter(f, formatterSpecX[f])

    logs = []
    for i in range(0, 30):
        log = {}
        for f in fields:
            if f == 'number':
                log[f] = i
            else:
                log[f] = "{}{}".format(f, i)
        logs.append(utils.objectify(log))

    formatterSpec = formatterSpecX

    formatters = build_wrapping_formatters(logs, fields, field_labels, formatterSpec)

    utils.print_list(logs, fields, field_labels, formatters=formatters, sortby=6,
                     reversesort=True, no_wrap_fields=['entity_instance_id'])

    print("nowrap = {}".format(is_nowrap_set()))
Exemplo n.º 3
0
def unset_no_wrap_on_formatters(orig_no_wrap_settings):
    """
        It only makes sense to call this function with the return value
        from the last call to set_no_wrap_on_formatters(no_wrap, formatters).
        It effectively undoes what set_no_wrap_on_formatters() does
    """
    if not orig_no_wrap_settings:
        return {}

    global_orig_no_wrap = orig_no_wrap_settings["global_orig_no_wrap"]
    formatter_no_wrap_settings = orig_no_wrap_settings["formatter_no_wrap_settings"]

    formatters = {}

    for k, v in formatter_no_wrap_settings.iteritems():
        formatters[k] = v[1]
        formatters[k].no_wrap = v[0]

    set_no_wrap(global_orig_no_wrap)

    return formatters
Exemplo n.º 4
0
def build_wrapping_formatters(objs,
                              fields,
                              field_labels,
                              format_spec,
                              add_blank_line=True,
                              no_wrap=None,
                              use_max=False):
    """
      A convenience function for building all wrapper formatters that will be used to
      format a CLI's output when its rendered in a prettyTable object.

      It iterates through the keys of format_spec and calls wrapperFormatterFactory to build
       wrapperFormatter objects for each column.

       Its best to show by example parameters:

        field_labels = ['UUID', 'Time Stamp', 'State', 'Event Log ID', 'Reason Text',
                        'Entity Instance ID', 'Severity']
        fields = ['uuid', 'timestamp', 'state', 'event_log_id', 'reason_text',
                  'entity_instance_id', 'severity']
        format_spec =  {
                            "uuid"                       : .10,  # float = so display as 10% of terminal width
                            "timestamp"                  : .08,
                            "state"                      : .08,
                            "event_log_id"               : .07,
                            "reason_text"                : .42,
                            "entity_instance_id"         : .13,
                            "severity"                   : {"formatter" : captializeFunction,
                                                            "wrapperFormatter":  .12}
                          }

    :param objs: the actual celldata that will get word wrapped
    :param fields:  fields (attributes of the celldata) that will be  displayed in the table
    :param field_labels: column (field headers)
    :param format_spec:  dict specify formatter for each column (field)
    :param add_blank_line: default True, when tru adds blank line to column if it wraps, aids readability
    :param no_wrap:  default False, when True turns wrapping off but does not suppress other custom formatters
    :param use_max
    :return: wrapping formatters as functions
    """

    no_wrap = set_no_wrap(no_wrap)

    if objs is None or len(objs) == 0:
        return {}

    biggest_word_pattern = re.compile("[\.:,;\!\?\\ =-\_]")

    def get_biggest_word(s):
        return max(biggest_word_pattern.split(s), key=len)

    wrapping_formatters_as_functions = {}

    if len(fields) != len(field_labels):
        raise Exception("Error in buildWrappingFormatters: "
                        "len(fields) = {}, len(field_labels) = {},"
                        " they must be the same length!".format(
                            len(fields), len(field_labels)))
    field_to_label = {}

    for i in range(0, len(fields)):
        field_to_label[fields[i]] = field_labels[i]

    ctx = WrapperContext()
    ctx.set_num_columns(len(fields))

    if not format_spec:
        if use_max:
            format_spec = build_best_guess_formatters_using_max_widths(
                objs, fields, field_labels)
        else:
            format_spec = build_best_guess_formatters_using_average_widths(
                objs, fields, field_labels)

    for k in format_spec.keys():
        if k not in fields:
            raise Exception("Error in buildWrappingFormatters: format_spec "
                            "specifies a field {} that is not specified "
                            "in fields : {}".format(k, fields))

        format_spec_for_k = copy.deepcopy(format_spec[k])
        if callable(format_spec_for_k):
            format_spec_for_k = {"formatter": format_spec_for_k}
        wrapper_formatter = wrapper_formatter_factory(ctx, k,
                                                      format_spec_for_k)
        if wrapper_formatter.min_width <= 0:
            # need to specify min-width so that
            # column is not unnecessarily squashed
            if is_uuid_field(k):  # special case
                wrapper_formatter.set_min_width(UUID_MIN_LENGTH)
            else:
                # column width cannot be smaller than the widest word
                column_data = [
                    str(wrapper_formatter.get_unwrapped_field_value(data))
                    for data in objs
                ]
                widest_word_in_column = max([
                    get_biggest_word(d) + " "
                    for d in column_data + [field_to_label[k]]
                ],
                                            key=len)
                wrapper_formatter.set_min_width(len(widest_word_in_column))
                wrapper_formatter.header_width = get_width(field_to_label[k])

        wrapper_formatter.add_blank_line = add_blank_line
        wrapper_formatter.no_wrap = no_wrap
        wrapping_formatters_as_functions[k] = wrapper_formatter.as_function()
        ctx.add_column_formatter(k, wrapper_formatter)

    return wrapping_formatters_as_functions