coalib.settings package — coala 0.11.0.rc1 documentation

# coalib.settings package

## Submodules

## coalib.settings.Annotations module

`coalib.settings.Annotations.` `typechain`(*args)

  Returns function which applies the first transformation it can from args and returns transformed value, or the value itself if it is in args.

      >>> function = typechain(int, 'a', ord, None)
      >>> function("10")
      10
      >>> function("b")
      98
      >>> function("a")
      'a'
      >>> function(int)
      <class 'int'>
      >>> function(None) is None
      True
      >>> function("str")
      Traceback (most recent call last):
          ...
      ValueError: Couldn't convert value 'str' to any specified type or find it in specified values.

  Raises: | TypeError – Raises when either no functions are specified for checking.

## coalib.settings.ConfigurationGathering module

`coalib.settings.ConfigurationGathering.` `find_user_config`(file_path, max_trials=10)

  Uses the filepath to find the most suitable user config file for the file by going down one directory at a time and finding config files there.

  Parameters: | file_path – The path of the file whose user config needs to be found max_trials – The maximum number of directories to go down to.
  Returns: | The config file’s path, empty string if none was found

`coalib.settings.ConfigurationGathering.` `gather_configuration`(acquire_settings, log_printer, arg_list=None, arg_parser=None)

  Loads all configuration files, retrieves bears and all needed settings, saves back if needed and warns about non-existent targets.

  This function:

  - Reads and merges all settings in sections from
    - Default config
    - User config
    - Configuration file
    - CLI
  - Collects all the bears
  - Fills up all needed settings
  - Writes back the new sections to the configuration file if needed
  - Gives all information back to caller

  Parameters: | acquire_settings – The method to use for requesting settings. It will get a parameter which is a dictionary with the settings name as key and a list containing a description in [0] and the names of the bears who need this setting in all following indexes. log_printer – The log printer to use for logging. The log level will be adjusted to the one given by the section. arg_list – CLI args to use arg_parser – Instance of ArgParser that is used to parse none-setting arguments.
  Returns: | A tuple with the following contents: A dictionary with the sections Dictionary of list of local bears for each section Dictionary of list of global bears for each section The targets list

`coalib.settings.ConfigurationGathering.` `get_config_directory`(section)

  Retrieves the configuration directory for the given section.

  Given an empty section:

      >>> section = Section("name")

  The configuration directory is not defined and will therefore fallback to the current directory:

      >>> get_config_directory(section) == os.path.abspath(".")
      True

  If the `files` setting is given with an originating coafile, the directory of the coafile will be assumed the configuration directory:

      >>> section.append(Setting("files", "**", origin="/tmp/.coafile"))
      >>> get_config_directory(section) == os.path.abspath('/tmp/')
      True

  However if its origin is already a directory this will be preserved:

      >>> files = section['files']
      >>> files.origin = os.path.abspath('/tmp/dir/')
      >>> section.append(files)
      >>> os.makedirs(section['files'].origin, exist_ok=True)
      >>> get_config_directory(section) == section['files'].origin
      True

  The user can manually set a project directory with the `project_dir` setting:

      >>> section.append(Setting('project_dir', os.path.abspath('/tmp'), '/'))
      >>> get_config_directory(section) == os.path.abspath('/tmp')
      True

  If no section is given, the current directory is returned:

      >>> get_config_directory(None) == os.path.abspath(".")
      True

  To summarize, the config directory will be chosen by the following priorities if possible in that order:

  - the `project_dir` setting
  - the origin of the `files` setting, if it’s a directory
  - the directory of the origin of the `files` setting
  - the current directory

  Parameters: | section – The section to inspect.
  Returns: | The directory where the project is lying.

`coalib.settings.ConfigurationGathering.` `get_filtered_bears`(languages, log_printer, arg_parser=None)

  Fetch bears and filter them based on given list of languages.

  Parameters: | languages – List of languages. log_printer – The log_printer to handle logging. arg_parser – An `ArgParser` object.
  Returns: | Tuple containing dictionaries of local bears and global bears.

`coalib.settings.ConfigurationGathering.` `load_config_file`(filename, log_printer, silent=False)

  Loads sections from a config file. Prints an appropriate warning if it doesn’t exist and returns a section dict containing an empty default section in that case.

  It assumes that the cli_sections are available.

  Parameters: | filename – The file to load settings from. log_printer – The log printer to log the warning/error to (in case). silent – Whether or not to warn the user/exit if the file doesn’t exist.
  Raises: | SystemExit – Exits when the given filename is invalid and is not the default coafile. Only raised when `silent` is `False`.

`coalib.settings.ConfigurationGathering.` `load_configuration`(arg_list, log_printer, arg_parser=None)

  Parses the CLI args and loads the config file accordingly, taking default_coafile and the users .coarc into account.

  Parameters: | arg_list – The list of command line arguments. log_printer – The LogPrinter object for logging.
  Returns: | A tuple holding (log_printer: LogPrinter, sections: dict(str, Section), targets: list(str)). (Types indicated after colon.)

`coalib.settings.ConfigurationGathering.` `merge_section_dicts`(lower, higher)

  Merges the section dictionaries. The values of higher will take precedence over the ones of lower. Lower will hold the modified dict in the end.

  Parameters: | lower – A section. higher – A section which values will take precedence over the ones from the other.
  Returns: | The merged dict.

`coalib.settings.ConfigurationGathering.` `save_sections`(sections)

  Saves the given sections if they are to be saved.

  Parameters: | sections – A section dict.

`coalib.settings.ConfigurationGathering.` `warn_config_absent`(sections, argument, log_printer)

  Checks if the given argument is present somewhere in the sections and emits a warning that code analysis can not be run without it.

  Parameters: | sections – A dictionary of sections. argument – The argument to check for, e.g. “files”. log_printer – A log printer to emit the warning to.

`coalib.settings.ConfigurationGathering.` `warn_nonexistent_targets`(targets, sections, log_printer)

  Prints out a warning on the given log printer for all targets that are not existent within the given sections.

  Parameters: | targets – The targets to check. sections – The sections to search. (Dict.) log_printer – The log printer to warn to.

## coalib.settings.DocstringMetadata module

class `coalib.settings.DocstringMetadata.` `DocstringMetadata`(desc, param_dict, retval_desc)

  Bases: `object`

  classmethod `from_docstring`(docstring)

    Parses a python docstring. Usable attributes are: :param @param :return @return

## coalib.settings.FunctionMetadata module

class `coalib.settings.FunctionMetadata.` `FunctionMetadata`(name: str, desc: str = '', retval_desc: str = '', non_optional_params: (<class 'dict'>, None) = None, optional_params: (<class 'dict'>, None) = None, omit: (<class 'set'>, <class 'tuple'>, <class 'list'>, <class 'frozenset'>) = frozenset(), deprecated_params: (<class 'set'>, <class 'tuple'>, <class 'list'>, <class 'frozenset'>) = frozenset())

  Bases: `object`

  `add_deprecated_param`(original, alias)

    Adds an alias for the original setting. The alias setting will have the same metadata as the original one. If the original setting is not optional, the alias will default to `None`.

    Parameters: | original – The name of the original setting. alias – The name of the alias for the original.
    Raises: | KeyError – If the new setting doesn’t exist in the metadata.

  `create_params_from_section`(section)

    Create a params dictionary for this function that holds all values the function needs plus optional ones that are available.

    Parameters: | section – The section to retrieve the values from.
    Returns: | The params dictionary.

  `desc`

    Returns description of the function.

  `filter_parameters`(dct)

    Filters the given dict for keys that are declared as parameters inside this metadata (either optional or non-optional).

    You can use this function to safely pass parameters from a given dictionary:

        >>> def multiply(a, b=2, c=0):
        ...     return a * b + c
        >>> metadata = FunctionMetadata.from_function(multiply)
        >>> args = metadata.filter_parameters({'a': 10, 'b': 20, 'd': 30})

    You can safely pass the arguments to the function now:

        >>> multiply(**args)  # 10 * 20
        200

    Parameters: | dct – The dict to filter.
    Returns: | A new dict containing the filtered items.

  classmethod `from_function`(func, omit=frozenset())

    Creates a FunctionMetadata object from a function. Please note that any variable argument lists are not supported. If you do not want the first (usual named ‘self’) argument to appear please pass the method of an actual INSTANCE of a class; passing the method of the class isn’t enough. Alternatively you can add “self” to the omit set.

    Parameters: | func – The function. If __metadata__ of the unbound function is present it will be copied and used, otherwise it will be generated. omit – A set of parameter names that are to be ignored.
    Returns: | The FunctionMetadata object corresponding to the given function.

  classmethod `merge`(*metadatas)

    Merges signatures of `FunctionMetadata` objects.

    Parameter (either optional or non-optional) and non-parameter descriptions are merged from left to right, meaning the right hand metadata overrides the left hand one.

        >>> def a(x, y):
        ...     '''
        ...     desc of *a*
        ...     :param x: x of a
        ...     :param y: y of a
        ...     :return:  5*x*y
        ...     '''
        ...     return 5 * x * y
        >>> def b(x):
        ...     '''
        ...     desc of *b*
        ...     :param x: x of b
        ...     :return:  100*x
        ...     '''
        ...     return 100 * x
        >>> metadata1 = FunctionMetadata.from_function(a)
        >>> metadata2 = FunctionMetadata.from_function(b)
        >>> merged = FunctionMetadata.merge(metadata1, metadata2)
        >>> merged.name
        "<Merged signature of 'a', 'b'>"
        >>> merged.desc
        'desc of *b*'
        >>> merged.retval_desc
        '100*x'
        >>> merged.non_optional_params['x'][0]
        'x of b'
        >>> merged.non_optional_params['y'][0]
        'y of a'

    Parameters: | metadatas – The sequence of metadatas to merge.
    Returns: | A `FunctionMetadata` object containing the merged signature of all given metadatas.

  `non_optional_params`

    Retrieves a dict containing the name of non optional parameters as the key and a tuple of a description and the python annotation. Values that are present in self.omit will be omitted.

  `optional_params`

    Retrieves a dict containing the name of optional parameters as the key and a tuple of a description, the python annotation and the default value. Values that are present in self.omit will be omitted.

  `str_nodesc` = 'No description given.'
  `str_optional` = "Optional, defaults to '{}'."

## coalib.settings.Section module

class `coalib.settings.Section.` `Section`(name, defaults=None)

  Bases: `object`

  This class holds a set of settings.

  To add settings and sections to a dictionary of sections we can use `append_to_sections`:

      >>> sections = {}
      >>> append_to_sections(sections,
      ...                    'test1',
      ...                    'val',
      ...                    'origin',
      ...                    section_name='all')
      >>> 'all' in sections
      True
      >>> len(sections)
      1
      >>> str(sections)
      "{'all': <Section object(contents=OrderedDict([('test1', ..."

  We can also add settings that can be appended to other settings. Basically it takes the default value of the setting which resides in the defaults of the section and appends the value of the setting in the second and returns the value of the setting:

      >>> append_to_sections(sections,
      ...                    'test1',
      ...                    'val2',
      ...                    'origin',
      ...                    section_name='all.python',
      ...                    to_append=True)

  When the section has no defaults:

      >>> str(sections['all.python']['test1'])
      'val2'

  After assigning defaults:

      >>> sections['all.python'].set_default_section(sections)
      >>> str(sections['all.python']['test1'])
      'val, val2'

  `add_or_create_setting`(setting, custom_key=None, allow_appending=True)

    Adds the value of the setting to an existing setting if there is already a setting with the key. Otherwise creates a new setting.

  `append`(setting, custom_key=None)
  `bear_dirs`()
  `copy`()

    Returns: | a deep copy of this object

  `delete_setting`(key)

    Delete a setting :param key: The key of the setting to be deleted

  `get`(key, default='', ignore_defaults=False)

    Retrieves the item without raising an exception. If the item is not available an appropriate Setting will be generated from your provided default value.

    Parameters: | key – The key of the setting to return. default – The default value ignore_defaults – Whether or not to ignore the default section.
    Returns: | The setting.

  `is_enabled`(targets)

    Checks if this section is enabled or, if targets is not empty, if it is included in the targets list.

    Parameters: | targets – List of target section names, all lower case.
    Returns: | True or False

  `set_default_section`(sections, section_name=None)

    Find and set the defaults of a section from a dictionary of sections. The defaults are found on the basis of ‘.’ in section names:

        >>> sections = {'all': Section('all')}
        >>> section = Section('all.python')
        >>> section.set_default_section(sections)
        >>> section.defaults.name
        'all'
        >>> section = Section('all.python.syntax')
        >>> section.set_default_section(sections)
        >>> section.defaults.name
        'all'

    Parameters: | sections – A dictionary of sections. section_name – Optional section name argument to find the default section for. If not given then use member section name.

  `update`(other_section, ignore_defaults=False)

    Incorporates all keys and values from the other section into this one. Values from the other section override the ones from this one.

    Default values from the other section override the default values from this only.

    Parameters: | other_section – Another Section ignore_defaults – If set to true, do not take default values from other
    Returns: | self

  `update_setting`(key, new_key=None, new_value=None)

    Updates a setting with new values. :param key: The old key string. :param new_key: The new key string. :param new_value: The new value for the setting

`coalib.settings.Section.` `append_to_sections`(sections, key, value, origin, section_name=None, from_cli=False, to_append=False)

  Appends the given data as a Setting to a Section with the given name. If the Section does not exist before it will be created empty.

  Parameters: | sections – The sections dictionary to add to. key – The key of the setting to add. value – The value of the setting to add. origin – The origin value of the setting to add. section_name – The name of the section to add to. from_cli – Whether or not this data comes from the CLI. to_append – The boolean value if setting value needs to be appended to a setting in the defaults of a section.

## coalib.settings.SectionFilling module

`coalib.settings.SectionFilling.` `fill_section`(section, acquire_settings, log_printer, bears)

  Retrieves needed settings from given bears and asks the user for missing values.

  If a setting is requested by several bears, the help text from the latest bear will be taken.

  Parameters: | section – A section containing available settings. Settings will be added if some are missing. acquire_settings – The method to use for requesting settings. It will get a parameter which is a dictionary with the settings name as key and a list containing a description in [0] and the names of the bears who need this setting in all following indexes. log_printer – The log printer for logging. bears – All bear classes or instances.
  Returns: | The new section.

`coalib.settings.SectionFilling.` `fill_settings`(sections, acquire_settings, log_printer)

  Retrieves all bears and requests missing settings via the given acquire_settings method.

  This will retrieve all bears and their dependencies.

  Parameters: | sections – The sections to fill up, modified in place. acquire_settings – The method to use for requesting settings. It will get a parameter which is a dictionary with the settings name as key and a list containing a description in [0] and the names of the bears who need this setting in all following indexes. log_printer – The log printer to use for logging.
  Returns: | A tuple containing (local_bears, global_bears), each of them being a dictionary with the section name as key and as value the bears as a list.

## coalib.settings.Setting module

class `coalib.settings.Setting.` `Setting`(key, value, origin='', strip_whitespaces=True, list_delimiters=(', ', ';'), from_cli=False, remove_empty_iter_elements=True, to_append=False)

  Bases: `coala_utils.string_processing.StringConverter.StringConverter`

  A Setting consists mainly of a key and a value. It mainly offers many conversions into common data types.

  `key`
  `value`

`coalib.settings.Setting.` `glob`(obj, *args, **kwargs)

  Creates a path in which all special glob characters in all the parent directories in the given setting are properly escaped.

  Parameters: | obj – The `Setting` object from which the key is obtained.
  Returns: | Returns a path in which special glob characters are escaped.

`coalib.settings.Setting.` `glob_list`(obj, *args, **kwargs)

  Creates a list of paths in which all special glob characters in all the parent directories of all paths in the given setting are properly escaped.

  Parameters: | obj – The `Setting` object from which the key is obtained.
  Returns: | Returns a list of paths in which special glob characters are escaped.

`coalib.settings.Setting.` `path`(obj, *args, **kwargs)

`coalib.settings.Setting.` `path_list`(obj, *args, **kwargs)

`coalib.settings.Setting.` `typed_dict`(key_type, value_type, default)

  Creates a function that converts a setting into a dict with the given types.

  Parameters: | key_type – The type conversion function for the keys. value_type – The type conversion function for the values. default – The default value to use if no one is given by the user.
  Returns: | A conversion function.

`coalib.settings.Setting.` `typed_list`(conversion_func)

  Creates a function that converts a setting into a list of elements each converted with the given conversion function.

  Parameters: | conversion_func – The conversion function that converts a string into your desired list item object.
  Returns: | A conversion function.

`coalib.settings.Setting.` `typed_ordered_dict`(key_type, value_type, default)

  Creates a function that converts a setting into an ordered dict with the given types.

  Parameters: | key_type – The type conversion function for the keys. value_type – The type conversion function for the values. default – The default value to use if no one is given by the user.
  Returns: | A conversion function.

`coalib.settings.Setting.` `url`(obj, *args, **kwargs)

## Module contents