Function cli_help

Synopsis

def cli_help(config_obj)

Description

Returns string for config's cli-arguments with corresponding comments

Source

Lines 8-65 in anyfig/print_utils.py.

def cli_help(config_obj):
  ''' Returns string for config's cli-arguments with corresponding comments '''
  comments = extract_config_obj_comments(config_obj)

  indent_width = 4  # In spaces
  comment_indents = {}  # attribute-name=indent. key = '' for main config class
  formated_comments = []

  # Calculate comment indents
  for attribute_name, comment in comments.items():
    # Access nested value -> config.attribute.value
    attribute_names = attribute_name.split('.')
    attribute_value = functools.reduce(getattr, attribute_names, config_obj)

    # Formats the attribute string
    attribute_type = type(attribute_value).__name__
    if isinstance(attribute_value, InputField):
      attribute_type = str(attribute_value.type_pattern.__name__)
    elif isinstance(attribute_value, InterfaceField):
      attribute_type = type(attribute_value.value).__name__

    nested_level = attribute_name.count('.')
    nested_indent = ' ' * (indent_width * nested_level)
    attr_string = f"{nested_indent}--{attribute_name} ({attribute_type}):"

    # Save strings for further formating
    attribute_chain = '.'.join(attribute_names[:-1])
    formated_comments.append((attribute_chain, attr_string, comment))

    # Calculate even indention width
    n_spaces = len(attr_string) + indent_width
    if n_spaces > comment_indents.get(attribute_chain, -1):
      comment_indents[attribute_chain] = n_spaces

  # Adds indention based on which config class
  help_strings = []
  for attribute_chain, attr_string, comment in formated_comments:
    n_spaces = comment_indents[attribute_chain]
    comment = (' ' * n_spaces).join(comment.splitlines(True)).rstrip('\n')
    help_string = f"{attr_string}{' ' * (n_spaces - len(attr_string))}{comment}"
    help_strings.append(help_string)

  # Add header info
  cli_help_header = []
  config_classes = list(figutils.get_config_classes())
  if len(config_classes) > 1:
    header = (
      f"Current config is '{type(config_obj).__name__}'. Available config classes {config_classes}. "
      "Set config with --config=OtherConfigClass")
    cli_help_header.append(header)

  if help_strings:
    cli_help_header.append("{}The available input arguments are".format(
      '\n' if cli_help_header else ''))

  return '\n'.join(cli_help_header + help_strings)







Add Discussion as Guest

Log in