coalib.settings package¶
Submodules¶
coalib.settings.Annotations module¶
-
coalib.settings.Annotations.
typechain
(*args)[source]¶ 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.
aspectize_sections
(sections)[source]¶ Search for aspects related setting in a section, initialize it, and then embed the aspects information as AspectList object into the section itself.
Parameters: sections – List of section that potentially contain aspects setting. Returns: The new sections.
-
coalib.settings.ConfigurationGathering.
find_user_config
(file_path, max_trials=10)[source]¶ 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=None, arg_list=None, arg_parser=None, args=None)[source]¶ 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.
- args – Alternative pre-parsed CLI 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
- Reads and merges all settings in sections from
-
coalib.settings.ConfigurationGathering.
get_all_bears
(log_printer=None, arg_parser=None, silent=True, bear_globs=('**', ))[source]¶ Parameters: - log_printer – The log_printer to handle logging.
- arg_parser – An
ArgParser
object. - silent – Whether or not to display warnings.
- bear_globs – List of glob patterns.
Returns: Tuple containing dictionaries of local bears and global bears.
-
coalib.settings.ConfigurationGathering.
get_config_directory
(section)[source]¶ 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. - the
-
coalib.settings.ConfigurationGathering.
get_filtered_bears
(languages, log_printer=None, arg_parser=None, silent=True)[source]¶ Parameters: - languages – List of languages.
- log_printer – The log_printer to handle logging.
- arg_parser – An
ArgParser
object. - silent – Whether or not to display warnings.
Returns: Tuple containing dictionaries of local bears and global bears.
-
coalib.settings.ConfigurationGathering.
load_config_file
(filename, log_printer=None, silent=False)[source]¶ 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
isFalse
.
-
coalib.settings.ConfigurationGathering.
load_configuration
(arg_list, log_printer=None, arg_parser=None, args=None, silent=False)[source]¶ 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 CLI arguments.
- log_printer – The LogPrinter object for logging.
- arg_parser – An
argparse.ArgumentParser
instance used for parsing the CLI arguments. - args – Alternative pre-parsed CLI arguments.
- silent – Whether or not to display warnings, ignored if
save
is enabled.
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)[source]¶ 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)[source]¶ Saves the given sections if they are to be saved.
Parameters: sections – A section dict.
-
coalib.settings.ConfigurationGathering.
validate_aspect_config
(section)[source]¶ Validate if a section contain required setting to run in aspects mode.
Parameters: section – The section that potentially contain aspect setting. Returns: The validity of section.
-
coalib.settings.ConfigurationGathering.
warn_config_absent
(sections, argument, log_printer=None)[source]¶ Checks if at least 1 of the given arguments 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 – An argument OR a list of arguments that at least 1 should present.
- log_printer – A log printer to emit the warning to.
Returns: Returns a boolean False if the given argument is present in the sections, else returns True.
-
coalib.settings.ConfigurationGathering.
warn_nonexistent_targets
(targets, sections, log_printer=None)[source]¶ 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¶
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())[source]¶ Bases:
object
-
add_deprecated_param
(original, alias)[source]¶ 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)[source]¶ 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)[source]¶ 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())[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ Adds the value of the setting to an existing setting if there is already a setting with the key. Otherwise creates a new setting.
-
get
(key, default='', ignore_defaults=False)[source]¶ 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)[source]¶ 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)[source]¶ 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'
This works case insensitive. The key of the sections dict is expected to be lowered though!
>>> sections = {'c': Section('C'), 'cpp': Section('Cpp'), ... 'c.something': Section('C.something')} >>> section = Section('C.something') >>> section.set_default_section(sections) >>> section.defaults.name 'C' >>> section = Section('C.SOMETHING.else') >>> section.set_default_section(sections) >>> section.defaults.name 'C.something' >>> section = Section('Cpp.SOMETHING.else') >>> section.set_default_section(sections) >>> section.defaults.name 'Cpp'
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)[source]¶ 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
-
-
coalib.settings.Section.
append_to_sections
(sections, key, value, origin, section_name=None, from_cli=False, to_append=False)[source]¶ 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.Section.
extract_aspects_from_section
(section)[source]¶ Extract aspects settings from a section into an AspectList.
Note that the section is assumed to already have valid and complete aspects related setting. This checking could be done by
coalib.settings.ConfigurationGathering.validate_aspect_config()
.Parameters: section – Section object. Returns: AspectList containing aspectclass instance with user-defined tastes.
coalib.settings.SectionFilling module¶
-
coalib.settings.SectionFilling.
fill_section
(section, acquire_settings, log_printer, bears)[source]¶ 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, targets, acquire_settings, log_printer=None, fill_section_method=<function fill_section>, **kwargs)[source]¶ 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.
- targets – List of section names to be executed which are passed from cli.
- 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.
- fill_section_method – Method to be used to fill the section settings.
- kwargs – Any other arguments for the fill_section_method can be supplied via kwargs, which are passed directly to the fill_section_method.
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: str = '', strip_whitespaces: bool = True, list_delimiters: collections.abc.Iterable = (', ', ';'), from_cli: bool = False, remove_empty_iter_elements: bool = True, to_append: bool = False)[source]¶ 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)[source]¶ 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)[source]¶ 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.
language
(name)[source]¶ Convert a string into
Language
object.Parameters: name – String containing language name. Returns: Language
object.Raises: ValueError – If the name
contain invalid language name.
-
coalib.settings.Setting.
typed_dict
(key_type, value_type, default)[source]¶ Creates a class 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: An instance of the created conversion class.
-
coalib.settings.Setting.
typed_list
(conversion_func)[source]¶ Creates a class 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: An instance of the created conversion class.
-
coalib.settings.Setting.
typed_ordered_dict
(key_type, value_type, default)[source]¶ Creates a class 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: An instance of the created conversion class.