coalib.bearlib.abstractions package¶
Submodules¶
coalib.bearlib.abstractions.ExternalBearWrap module¶
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 ofglobal_bear
this can either be aLocalBear
or aGlobalBear
.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 thefilename
andfile
:>>> @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
Bear.run()
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 viagenerate_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()
togenerate_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 (viause_stdout
oruse_stderr
) puts the according string attained from the stream into parameteroutput
, providing both output streams inputs a tuple with(stdout, stderr)
. Providinguse_stdout=False
anduse_stderr=False
raises aValueError
. By defaultuse_stdout
isTrue
anduse_stderr
isFalse
.Every
linter
is also a subclass of theLinterClass
class.>>> issubclass(XLintBear, LinterClass) True
Documentation: Bear description shall be provided at class level. If you document your additional parameters inside
create_arguments
,generate_config
andprocess_output
, beware that conflicting documentation between them may be overridden. Document duplicated parameters insidecreate_arguments
first, then ingenerate_config
and after that insideprocess_output
.For the tutorial see: http://api.coala.io/en/latest/Developers/Writing_Linter_Bears.html
Parameters: - 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 (viasubprocess.check_call()
). Must be anIterable
. - prerequisite_check_fail_message – A custom message that gets displayed when
check_prerequisites
fails while invokingprerequisite_check_command
. Can only be provided together withprerequisite_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 withuse_stdin=True
. - output_format –
The output format of the underlying executable. Valid values are
None
: Define your own format by overridingprocess_output
. Overridingprocess_output
is then mandatory, not specifying it raises aValueError
.'regex'
: Parse output using a regex. See parameteroutput_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
andend_column
don’t have to match numbers only, they can also match nothing, the generatedResult
is filled automatically withNone
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 groupseverity
) to an actualcoalib.results.RESULT_SEVERITY
for a result. Severity strings are mapped case-insensitive!RESULT_SEVERITY.MAJOR
: Mapped bycritical
,c
,fatal
,fail
,f
,error
,err
ore
.RESULT_SEVERITY.NORMAL
: Mapped bywarning
,warn
orw
.RESULT_SEVERITY.INFO
: Mapped byinformation
,info
,i
,note
orsuggestion
.
A
ValueError
is raised when the named groupseverity
is not used insideoutput_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 iscoalib.results.RESULT_SEVERITY.NORMAL
. The given value needs to be defined insidecoalib.results.RESULT_SEVERITY
. - result_message – The message-string to use for all results. Can be used only together
with
corrected
orunified-diff
orregex
output format. When usingcorrected
orunified-diff
, the default value is'Inconsistency found.'
, while forregex
this static message is disabled and the message matched byoutput_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
orunified-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 is1
. - strip_ansi – Supresses colored output from linters when enabled by stripping the ascii characters around the text.
Raises: - ValueError – Raised when invalid options are supplied.
- TypeError – Raised when incompatible types are supplied. See parameter documentations for allowed types.
Returns: A
LocalBear
derivation that lints code using an external tool.
coalib.bearlib.abstractions.LinterClass module¶
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.
Example:
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.
Parameters: - section – A section object containing at least the settings specified by get_non_optional_settings()
- kwargs – Additional keyword arguments
Module contents¶
The abstractions package contains classes that serve as interfaces for helper classes in the bearlib.