coalib.bearlib.abstractions package


coalib.bearlib.abstractions.ExternalBearWrap module

coalib.bearlib.abstractions.ExternalBearWrap.external_bear_wrap(executable: str, **options)[source]

coalib.bearlib.abstractions.Linter module

coalib.bearlib.abstractions.Linter.linter(executable: str, global_bear: bool = False, use_stdin: bool = False, use_stdout: bool = True, use_stderr: bool = False, normalize_line_numbers: bool = False, normalize_column_numbers: bool = False, config_suffix: str = '', executable_check_fail_info: str = '', prerequisite_check_command: tuple = (), output_format: (<class 'str'>, None) = None, strip_ansi: bool = False, **options)[source]

Decorator that creates a Bear that is able to process results from an external linter tool. Depending on the value of global_bear this can either be a LocalBear or a GlobalBear.

The main functionality is achieved through the create_arguments() function that constructs the command-line-arguments that get passed to your executable.

>>> @linter('xlint', output_format='regex', output_regex='...')
... class XLintBear:
...     @staticmethod
...     def create_arguments(filename, file, config_file):
...         return '--lint', filename

Or for a GlobalBear without the filename and file:

>>> @linter('ylint',
...         global_bear=True,
...         output_format='regex',
...         output_regex='...')
... class YLintBear:
...     def create_arguments(self, config_file):
...         return '--lint', self.file_dict.keys()

Requiring settings is possible like in with supplying additional keyword arguments (and if needed with defaults).

>>> @linter('xlint', output_format='regex', output_regex='...')
... class XLintBear:
...     @staticmethod
...     def create_arguments(filename,
...                          file,
...                          config_file,
...                          lintmode: str,
...                          enable_aggressive_lints: bool=False):
...         arguments = ('--lint', filename, '--mode=' + lintmode)
...         if enable_aggressive_lints:
...             arguments += ('--aggressive',)
...         return arguments

Sometimes your tool requires an actual file that contains configuration. linter allows you to just define the contents the configuration shall contain via generate_config() and handles everything else for you.

>>> @linter('xlint', output_format='regex', output_regex='...')
... class XLintBear:
...     @staticmethod
...     def generate_config(filename,
...                         file,
...                         lintmode,
...                         enable_aggressive_lints):
...         modestring = ('aggressive'
...                       if enable_aggressive_lints else
...                       'non-aggressive')
...         contents = ('<xlint>',
...                     '    <mode>' + lintmode + '</mode>',
...                     '    <aggressive>' + modestring + '</aggressive>',
...                     '</xlint>')
...         return '\n'.join(contents)
...     @staticmethod
...     def create_arguments(filename,
...                          file,
...                          config_file):
...         return '--lint', filename, '--config', config_file

As you can see you don’t need to copy additional keyword-arguments you introduced from create_arguments() to generate_config() and vice-versa. linter takes care of forwarding the right arguments to the right place, so you are able to avoid signature duplication.

If you override process_output, you have the same feature like above (auto-forwarding of the right arguments defined in your function signature).

Note when overriding process_output: Providing a single output stream (via use_stdout or use_stderr) puts the according string attained from the stream into parameter output, providing both output streams inputs a tuple with (stdout, stderr). Providing use_stdout=False and use_stderr=False raises a ValueError. By default use_stdout is True and use_stderr is False.

Every linter is also a subclass of the LinterClass class.

>>> issubclass(XLintBear, LinterClass)

Documentation: Bear description shall be provided at class level. If you document your additional parameters inside create_arguments, generate_config and process_output, beware that conflicting documentation between them may be overridden. Document duplicated parameters inside create_arguments first, then in generate_config and after that inside process_output.

For the tutorial see:

  • executable – The linter tool.
  • use_stdin – Whether the input file is sent via stdin instead of passing it over the command-line-interface.
  • use_stdout – Whether to use the stdout output stream. Incompatible with global_bear=True.
  • use_stderr – Whether to use the stderr output stream.
  • normalize_line_numbers – Whether to normalize line numbers (increase by one) to fit coala’s one-based convention.
  • normalize_column_numbers – Whether to normalize column numbers (increase by one) to fit coala’s one-based convention.
  • config_suffix – The suffix-string to append to the filename of the configuration file created when generate_config is supplied. Useful if your executable expects getting a specific file-type with specific file-ending for the configuration file.
  • executable_check_fail_info – Information that is provided together with the fail message from the normal executable check. By default no additional info is printed.
  • prerequisite_check_command – A custom command to check for when check_prerequisites gets invoked (via subprocess.check_call()). Must be an Iterable.
  • prerequisite_check_fail_message – A custom message that gets displayed when check_prerequisites fails while invoking prerequisite_check_command. Can only be provided together with prerequisite_check_command.
  • global_bear – Whether the created bear should be a GlobalBear or not. Global bears will be run once on the whole project, instead of once per file. Incompatible with use_stdin=True.
  • output_format

    The output format of the underlying executable. Valid values are

    • None: Define your own format by overriding process_output. Overriding process_output is then mandatory, not specifying it raises a ValueError.
    • 'regex': Parse output using a regex. See parameter output_regex.
    • 'corrected': The output is the corrected of the given file. Diffs are then generated to supply patches for results.
    • 'unified-diff': The output is the unified diff of the corrections. Patches are then supplied for results using this output.

    Passing something else raises a ValueError.

  • output_regex

    The regex expression as a string that is used to parse the output generated by the underlying executable. It should use as many of the following named groups (via (?P<name>...)) to provide a good result:

    • filename - The name of the linted file. This is relevant for
      global bears only.
    • line - The line where the issue starts.
    • column - The column where the issue starts.
    • end_line - The line where the issue ends.
    • end_column - The column where the issue ends.
    • severity - The severity of the issue.
    • message - The message of the result.
    • origin - The origin of the issue.
    • additional_info - Additional info provided by the issue.

    The groups line, column, end_line and end_column don’t have to match numbers only, they can also match nothing, the generated Result is filled automatically with None then for the appropriate properties.

    Needs to be provided if output_format is 'regex'.

  • severity_map

    A dict used to map a severity string (captured from the output_regex with the named group severity) to an actual coalib.results.RESULT_SEVERITY for a result. Severity strings are mapped case-insensitive!

    • RESULT_SEVERITY.MAJOR: Mapped by critical, c, fatal, fail, f, error, err or e.
    • RESULT_SEVERITY.NORMAL: Mapped by warning, warn or w.
    • RESULT_SEVERITY.INFO: Mapped by information, info, i, note or suggestion.

    A ValueError is raised when the named group severity is not used inside output_regex and this parameter is given.

  • diff_severity – The severity to use for all results if output_format is 'corrected' or 'unified-diff'. By default this value is coalib.results.RESULT_SEVERITY.NORMAL. The given value needs to be defined inside coalib.results.RESULT_SEVERITY.
  • result_message – The message-string to use for all results. Can be used only together with corrected or unified-diff or regex output format. When using corrected or unified-diff, the default value is 'Inconsistency found.', while for regex this static message is disabled and the message matched by output_regex is used instead.
  • diff_distance – Number of unchanged lines that are allowed in between two changed lines so they get yielded as one diff if corrected or unified-diff output-format is given. If a negative distance is given, every change will be yielded as an own diff, even if they are right beneath each other. By default this value is 1.
  • strip_ansi – Supresses colored output from linters when enabled by stripping the ascii characters around the text.
  • ValueError – Raised when invalid options are supplied.
  • TypeError – Raised when incompatible types are supplied. See parameter documentations for allowed types.

A LocalBear derivation that lints code using an external tool.

coalib.bearlib.abstractions.LinterClass module

class coalib.bearlib.abstractions.LinterClass.LinterClass[source]

Bases: object

Every linter is also a subclass of the LinterClass class.

coalib.bearlib.abstractions.SectionCreatable module

class coalib.bearlib.abstractions.SectionCreatable.SectionCreatable[source]

Bases: object

A SectionCreatable is an object that is creatable out of a section object. Thus this is the class for many helper objects provided by the bearlib.

If you want to use an object that inherits from this class the following approach is recommended: Instantiate it via the from_section method. You can provide default arguments via the lower case keyword arguments.


SpacingHelper.from_section(section, tabwidth=8)

creates a SpacingHelper and if the “tabwidth” setting is needed and not contained in section, 8 will be taken.

It is recommended to write the prototype of the __init__ method according to this example:

def __init__(self, setting_one: int, setting_two: bool=False):
    pass  # Implementation

This way the get_optional_settings and the get_non_optional_settings method will extract automatically that:

  • setting_one should be an integer
  • setting_two should be a bool and defaults to False

If you write a documentation comment, you can use :param to add descriptions to your parameters. These will be available too automatically.

classmethod from_section(section, **kwargs)[source]

Creates the object from a section object.

  • section – A section object containing at least the settings specified by get_non_optional_settings()
  • kwargs – Additional keyword arguments
classmethod get_metadata()[source]
classmethod get_non_optional_settings()[source]

Retrieves the minimal set of settings that need to be defined in order to use this object.

Returns:a dictionary of needed settings as keys and help texts as values
classmethod get_optional_settings()[source]

Retrieves the settings needed IN ADDITION to the ones of get_non_optional_settings to use this object without internal defaults.

Returns:a dictionary of needed settings as keys and help texts as values

Module contents

The abstractions package contains classes that serve as interfaces for helper classes in the bearlib.