Exemplo n.º 1
0
class AlexBear:
    """
    Checks the markdown file with Alex - Catch insensitive, inconsiderate
    writing.

    Be aware that Alex and this bear only work on English text.
    For more information, consult <https://www.npmjs.com/package/alex>.
    """
    LANGUAGES = {'Natural Language'}
    REQUIREMENTS = {NpmRequirement('alex', '3')}
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL-3.0'

    @classmethod
    def check_prerequisites(cls):
        parent_prereqs = super().check_prerequisites()
        if parent_prereqs is not True:
            return parent_prereqs

        incorrect_pkg_msg = (
            'Please ensure that the package that has been installed is the '
            "one to 'Catch insensitive, inconsiderate writing'. This can be "
            'verified by running `alex --help` and seeing what it does.')
        try:
            output = subprocess.check_output(('alex', '--help'),
                                             stderr=subprocess.STDOUT)
        except (OSError, subprocess.CalledProcessError):
            return ('The `alex` package could not be verified. ' +
                    incorrect_pkg_msg)
        else:
            output = output.decode(sys.getfilesystemencoding())
            if 'Catch insensitive, inconsiderate writing' in output:
                return True
            else:
                return ("The `alex` package that's been installed seems to "
                        'be incorrect. ' + incorrect_pkg_msg)

    @staticmethod
    def create_arguments(filename, file, config_file):
        return filename,
Exemplo n.º 2
0
class DockerfileLintBear:
    """
    Check file syntax as well as arbitrary semantic and best practice
    in Dockerfiles. it also checks LABEL rules against docker images.

    Uses ``dockerfile_lint`` to provide the analysis.
    See <https://github.com/projectatomic/dockerfile_lint#dockerfile-lint> for
    more information .
    """
    LANGUAGES = {'Dockerfile'}
    REQUIREMENTS = {NpmRequirement('dockerfile_lint', '0')}
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL-3.0'
    CAN_DETECT = {'Syntax', 'Smell'}

    severity_map = {
        'error': RESULT_SEVERITY.MAJOR,
        'warn': RESULT_SEVERITY.NORMAL,
        'info': RESULT_SEVERITY.INFO
    }

    @staticmethod
    def create_arguments(filename, file, config_file):
        return '--json', '-f', filename

    def process_output(self, output, filename, file):
        output = json.loads(output)

        for severity in output:
            if severity == 'summary':
                continue
            for issue in output[severity]['data']:
                yield Result.from_values(
                    origin=self,
                    message=issue['message'],
                    file=filename,
                    severity=self.severity_map[issue['level']],
                    line=issue.get('line'))
Exemplo n.º 3
0
class WriteGoodLintBear:
    """
    Lints the text files using ``write-good`` for improving proses.

    See <https://github.com/btford/write-good> for more information.
    """
    LANGUAGES = {'Natural Language'}
    REQUIREMENTS = {NpmRequirement('write-good', '0.9.1')}
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL-3.0'
    ASCIINEMA_URL = 'https://asciinema.org/a/80761'
    CAN_DETECT = {'Formatting', 'Grammar'}

    @staticmethod
    @deprecate_settings(allow_passive_voice=('check_passive_voice', negate),
                        allow_so_beginning=('check_so_beginning', negate),
                        allow_adverbs=('check_adverbs', negate),
                        allow_repeated_words=('check_repeated_words', negate),
                        allow_there_is=('check_there_is', negate),
                        allow_ambiguous_words=('check_ambiguos_words', negate),
                        allow_extra_words=('check_extra_words', negate),
                        allow_cliche_phrases=('check_cliche_exists', negate))
    def create_arguments(filename,
                         file,
                         config_file,
                         allow_passive_voice: bool = True,
                         allow_so_beginning: bool = True,
                         allow_adverbs: bool = True,
                         allow_repeated_words: bool = True,
                         allow_there_is: bool = True,
                         allow_ambiguous_words: bool = True,
                         allow_extra_words: bool = True,
                         allow_cliche_phrases: bool = True):
        """
        Using ``False`` will enable the check.

        :param allow_passive_voice:     Allows passive voice.
        :param allow_so_beginning:      Allows "So" at the beginning of
                                        the sentence.
        :param allow_adverbs:           Allows adverbs that can weaken the
                                        meaning, such as: "really",
                                        "very", "extremely", etc.
        :param allow_repeated_words:    Allows lexical illusions – cases
                                        where a word is repeated.
        :param allow_there_is:          Allows "There is" or "There are"
                                        at the beginning of the sentence.
        :param allow_ambiguous_words:   Allows "weasel words" for example
                                        "often" and "probably".
        :param allow_extra_words:       Allows wordy phrases and unnecessary
                                        words.
        :param allow_cliche_phrases:    Allows common cliche phrases in the
                                        sentence.
        """
        arg_map = {
            'allow_passive_voice': '--passive',
            'allow_so_beginning': '--so',
            'allow_adverbs': '--adverb',
            'allow_repeated_words': '--illusion',
            'allow_there_is': '--thereIs',
            'allow_ambiguous_words': '--weasel',
            'allow_extra_words': '--tooWordy',
            'allow_cliche_phrases': '--cliches'
        }
        arg_values = locals()
        args = tuple(arg for key, arg in arg_map.items()
                     if not arg_values[key])
        return args + (filename, )
Exemplo n.º 4
0
class MarkdownBear:
    """
    Check and correct Markdown style violations automatically.

    See <https://github.com/wooorm/remark-lint> for details about the tool
    below.
    """

    LANGUAGES = {'Markdown'}
    REQUIREMENTS = {NpmRequirement('remark-cli', '2')}
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL-3.0'
    CAN_FIX = {'Formatting'}

    @staticmethod
    def create_arguments(filename, file, config_file,
                         markdown_bullets: str='-',
                         markdown_closed_headings: bool=False,
                         markdown_setext_headings: bool=False,
                         markdown_emphasis: str='*',
                         markdown_strong: str='*',
                         markdown_encode_entities: bool=False,
                         markdown_codefence: str='`',
                         markdown_fences: bool=True,
                         markdown_list_indent: str='1',
                         markdown_loose_tables: bool=False,
                         markdown_spaced_tables: bool=True,
                         markdown_list_increment: bool=True,
                         markdown_horizontal_rule: str='*',
                         markdown_horizontal_rule_spaces: bool=False,
                         markdown_horizontal_rule_repeat: int=3):
        """
        :param markdown_bullets:
            Character to use for bullets in lists. Can be "-", "*" or "+".
        :param markdown_closed_headings:
            Whether to close Atx headings or not. if true, extra # marks will
            be required after the heading. eg: `## Heading ##`.
        :param markdown_setext_headings:
            Whether to use setext headings. A setext heading uses underlines
            instead of # marks.
        :param markdown_emphasis:
            Character to wrap strong emphasis by. Can be "_" or "*".
        :param markdown_strong:
            Character to wrap slight emphasis by. Can be "_" or "*".
        :param markdown_encode_entities:
            Whether to encode symbols that are not ASCII into special HTML
            characters.
        :param markdown_codefence:
            Used to find which characters to use for code fences. Can be "`" or
            "~".
        :param markdown_fences:
            Use fences for code blocks.
        :param markdown_list_indent:
            Used to find spacing after bullet in lists. Can be "1", "tab" or
            "mixed".

            - "1" - 1 space after bullet.
            - "tab" - Use tab stops to begin a sentence after the bullet.
            - "mixed" - Use "1" when the list item is only 1 line, "tab" if it
              spans multiple.
        :param markdown_loose_tables:
            Whether to use pipes for the outermost borders in a table.
        :param markdown_spaced_tables:
            Whether to add space between pipes in a table.
        :param markdown_list_increment:
            Whether an ordered lists numbers should be incremented.
        :param markdown_horizontal_rule:
            The horizontal rule character. Can be '*', '_' or '-'.
        :param markdown_horizontal_rule_spaces:
            Whether spaces should be added between horizontal rule characters.
        :param markdown_horizontal_rule_repeat:
            The number of times the horizontal rule character will be repeated.
        """
        remark_configs = {
            'bullet': markdown_bullets,                         # - or *
            'closeAtx': markdown_closed_headings,               # Bool
            'setext': markdown_setext_headings,                 # Bool
            'emphasis': markdown_emphasis,                      # char (_ or *)
            'strong': markdown_strong,                          # char (_ or *)
            'entities': markdown_encode_entities,               # Bool
            'fence': markdown_codefence,                        # char (~ or `)
            'fences': markdown_fences,                          # Bool
            'listItemIndent': markdown_list_indent,             # int or "tab"
                                                                # or "mixed"
            'looseTable': markdown_loose_tables,                # Bool
            'spacedTable': markdown_spaced_tables,              # Bool
            'incrementListMarker': markdown_list_increment,     # Bool
            'rule': markdown_horizontal_rule,                   # - or * or _
            'ruleSpaces': markdown_horizontal_rule_spaces,      # Bool
            'ruleRepetition': markdown_horizontal_rule_repeat,  # int
        }

        config_json = json.dumps(remark_configs)
        # Remove { and } as remark adds them on its own
        settings = config_json[1:-1]
        return '--no-color', '--quiet', '--setting', settings
Exemplo n.º 5
0
class PugLintBear:
    """
    A configurable linter and style checker for ``Pug`` (formerly ``Jade``)
    that is a clean, whitespace-sensitive template language for writing HTML.
    """

    LANGUAGES = {'Pug'}
    REQUIREMENTS = {NpmRequirement('pug-lint', '2.4.0')}
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL-3.0'
    CAN_DETECT = {'Formatting', 'Syntax', 'Redundancy'}
    SEE_MORE = 'https://github.com/pugjs/pug-lint'

    @staticmethod
    def generate_config(
            filename,
            file,
            prohibit_block_expansion: bool = True,
            prohibit_class_attribute_with_static_value: bool = True,
            prohibit_class_literals_before_attributes: bool = True,
            prohibit_class_literals_before_id_literals: bool = True,
            prohibit_class_literals: bool = True,
            prohibit_duplicate_attributes: bool = True,
            prohibit_html_text: bool = True,
            prohibit_id_attribute_with_static_value: bool = True,
            prohibit_id_literals_before_attributes: bool = True,
            prohibit_id_literals: bool = True,
            prohibit_legacy_mixin_call: bool = True,
            prohibit_multiple_line_breaks: bool = False,
            prohibit_spaces_inside_attribute_brackets: bool = True,
            prohibit_string_interpolation: bool = True,
            prohibit_tag_interpolation: bool = True,
            prohibit_specific_attributes: typed_list(str) = None,
            prohibit_specific_tags: typed_list(str) = None,
            enforce_class_literals_before_attributes: bool = False,
            enforce_class_literals_before_id_literals: bool = False,
            enforce_id_literals_before_attributes: bool = False,
            enforce_lower_case_attributes: bool = True,
            enforce_lower_case_tags: bool = True,
            enforce_spaces_inside_attribute_brackets: bool = False,
            enforce_strict_equality_operators: bool = True,
            validate_div_tags: bool = True,
            validate_extensions: bool = True,
            validate_self_closing_tags: bool = True,
            preferred_quotation: str = "'",
            max_lines_per_file: int = None,
            puglint_config: str = ''):
        """
        :param prohibit_block_expansion:
            When ``True``, disallow any block expansion operators.
            For example: If set to ``True``, this will throw a warning::

                p: strong text
                table: tr: td text

        :param prohibit_class_attribute_with_static_value:
            When ``True``, prefer class literals over class attributes with
            static values.
            For example: If set to ``True``, prefer ``span.foo`` over
            ``span(class='foo')``.
        :param prohibit_class_literals_before_attributes:
            When ``True``, prefer all attribute blocks to be written before
            any class literals.
            For example: If set to ``True``, prefer
            ``input(type='text').class`` over ``input.class(type='text')``.
        :param prohibit_class_literals_before_id_literals:
            When ``True``, prefer all ID literals to be written before any
            class literals.
            For example: If set to ``True``, prefer
            ``input#id.class(type='text')`` over
            ``input.class#id(type='text')``.
        :param prohibit_class_literals:
            When ``True``, disallow any class literals.
            For example: If set to ``True``, prefer ``div(class='class')``
            over ``.class``.
        :param prohibit_duplicate_attributes:
            When ``True``, attribute blocks should not contain any duplicates.
            For example: If set to ``True``, this will throw a warning::

                div(a='a' a='b')
                #id(id='id')

        :param prohibit_html_text:
            When ``True``, disallow any HTML text.
            For example: If set to ``True``, this will throw a warning::

                <strong>html text</strong>
                p this is <strong>html</strong> text

        :param prohibit_id_attribute_with_static_value:
            When ``True``, prefer ID literals over ``id`` attributes with
            static values.
            For example: If set to ``True``, prefer ``span#id`` over
            ``span(id='foo')``.
        :param prohibit_id_literals_before_attributes:
            When ``True``, prefer all attribute blocks to be written before
            any ID literals.
            For example: If set to ``True``, prefer ``input(type='text')#id``
            over ``input#id(type='text')``.
        :param prohibit_id_literals:
            When ``True``, disallow any ID literals.
            For example: If set to ``True``, ``#id`` will throw a warning.
        :param prohibit_legacy_mixin_call:
            When ``True``, disallow any legacy mixin call.
            When ``True``, prefer ``+myMixin(arg)`` over
            ``mixin myMixin(arg)``.
        :param prohibit_multiple_line_breaks:
            When ``True``, disallow multiple blank lines in a row.
        :param prohibit_spaces_inside_attribute_brackets:
            When ``True``, disallow space after opening attribute bracket and
            before closing attribute bracket.
            For example: If set to ``True``, prefer
            ``input(type='text' name='name' value='value')`` over
            ``input( type='text' name='name' value='value' )``.
        :param prohibit_string_interpolation:
            When ``True``, disallow any string interpolation operators.
            For example: If set to ``True``, ``h1 #{title} text`` will throw
            a warning.
        :param prohibit_tag_interpolation:
            When ``True``, disallow any tag interpolation operators.
            For example: If set to ``True``, this will throw a warning::

                | #[strong html] text
                p #[strong html] text

        :param prohibit_specific_attributes:
            Disallow any of the attributes specified.
        :param prohibit_specific_tags:
            Disallow any of the tags specified.
        :param enforce_class_literals_before_attributes:
            When ``True``, all class literals must be written before any
            attribute blocks.
        :param enforce_class_literals_before_id_literals:
            When ``True``, all class literals should be written before any
            ID literals.
        :param enforce_id_literals_before_attributes:
            When ``True``, all ID literals must be written before any
            attribute blocks.
        :param enforce_lower_case_attributes:
            When ``True``, all attributes should be written in lower case.
            For example: If set to ``True``, prefer ``div(class='class')``
            over ``div(Class='class')``.
        :param enforce_lower_case_tags:
            When ``True``, all tags must be written in lower case.
            For example: If set to ``True``, prefer ``div(class='class')``
            over ``Div(class='class')``.
        :param enforce_spaces_inside_attribute_brackets:
            When ``True``, enforce space after opening attribute bracket and
            before closing attribute bracket.
        :param enforce_strict_equality_operators:
            When ``True``, enforce the use of ``===`` and ``!==`` instead of
            ``==`` and ``!=``.
        :param validate_div_tags:
            When ``True``, disallow any unnecessary ``div`` tags.
        :param validate_extensions:
            When ``True``, enforce proper file extensions with inclusion and
            inheritance.
        :param validate_self_closing_tags:
            When ``True``, disallow any unnecessary self closing tags.
        :param preferred_quotation:
            Your preferred quotation character, e.g.``"`` or ``'``.
        :param max_lines_per_file:
            Number of lines allowed per file.
        """
        if puglint_config:
            return None
        else:
            options = {
                'disallowBlockExpansion': prohibit_block_expansion,
                'disallowClassAttributeWithStaticValue':
                prohibit_class_attribute_with_static_value,
                'disallowClassLiteralsBeforeAttributes':
                prohibit_class_literals_before_attributes,
                'disallowClassLiteralsBeforeIdLiterals':
                prohibit_class_literals_before_id_literals,
                'disallowClassLiterals': prohibit_class_literals,
                'disallowDuplicateAttributes': prohibit_duplicate_attributes,
                'disallowHtmlText': prohibit_html_text,
                'disallowIdAttributeWithStaticValue':
                prohibit_id_attribute_with_static_value,
                'disallowIdLiteralsBeforeAttributes':
                prohibit_id_literals_before_attributes,
                'disallowIdLiterals': prohibit_id_literals,
                'disallowLegacyMixinCall': prohibit_legacy_mixin_call,
                'disallowMultipleLineBreaks': prohibit_multiple_line_breaks,
                'disallowSpacesInsideAttributeBrackets':
                prohibit_spaces_inside_attribute_brackets,
                'disallowStringInterpolation': prohibit_string_interpolation,
                'disallowTagInterpolation': prohibit_tag_interpolation,
                'disallowSpecificAttributes': prohibit_specific_attributes,
                'disallowSpecificTags': prohibit_specific_tags,
                'requireClassLiteralsBeforeAttributes':
                enforce_class_literals_before_attributes,
                'requireClassLiteralsBeforeIdLiterals':
                enforce_class_literals_before_id_literals,
                'requireIdLiteralsBeforeAttributes':
                enforce_id_literals_before_attributes,
                'requireLowerCaseAttributes': enforce_lower_case_attributes,
                'requireLowerCaseTags': enforce_lower_case_tags,
                'requireSpacesInsideAttributeBrackets':
                enforce_spaces_inside_attribute_brackets,
                'requireStrictEqualityOperators':
                enforce_strict_equality_operators,
                'validateDivTags': validate_div_tags,
                'validateExtensions': validate_extensions,
                'validateSelfClosingTags': validate_self_closing_tags,
                'validateAttributeQuoteMarks': preferred_quotation,
                'maximumNumberOfLines': max_lines_per_file
            }

            for k, v in options.items():
                options[k] = v if v else None

            return json.dumps(options)

    @staticmethod
    def create_arguments(filename,
                         file,
                         config_file,
                         puglint_config: str = ''):
        """
        :param puglint_config:
            The location of a custom ``.pug-lintrc`` config file.
        """
        return ('--config', puglint_config if puglint_config else config_file,
                '--reporter', 'inline', filename)
Exemplo n.º 6
0
class ESLintBear:
    """
    Check JavaScript and JSX code for style issues and semantic errors.

    Find out more at <http://eslint.org/docs/rules/>.
    """

    LANGUAGES = {'JavaScript', 'JSX'}
    REQUIREMENTS = {
        NpmRequirement('eslint', '3'),
        NpmRequirement('babel-eslint', '8.0'),
        NpmRequirement('eslint-plugin-import', '2')
    }
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL-3.0'
    ASCIINEMA_URL = 'https://asciinema.org/a/38739'
    CAN_DETECT = {'Syntax'}
    CAN_FIX = {'Formatting'}

    severity_map = {
        2: RESULT_SEVERITY.MAJOR,
        1: RESULT_SEVERITY.NORMAL,
        0: RESULT_SEVERITY.INFO
    }

    @staticmethod
    def create_arguments(
        filename,
        file,
        config_file,
        eslint_config: str = '',
    ):
        """
        :param eslint_config: The location of the .eslintrc config file.
        """
        args = (
            '--no-ignore',
            '--no-color',
            '-f=json',
            '--stdin',
            '--stdin-filename=' + filename,
        )

        if eslint_config:
            args += ('--config', eslint_config)
        else:
            args += ('--config', config_file)

        return args

    @staticmethod
    def generate_config(filename, file):
        return '{"extends": "eslint:recommended"}'

    def process_output(self, output, filename, file):
        def warn_issue(message):
            self.warn('While running {0}, some issues were found:'.format(
                self.__class__.__name__))
            self.warn(message)

        # Taking output from stderr for ESLint 2 program errors.
        # ESLint 2 is no longer supported, but it is here so that anyone
        # with ESLint 2 will still see any errors that were emitted.
        if output[1]:  # pragma: no cover
            warn_issue(output[1])

        if not file or not output[0]:
            return

        # Handling program errors
        # such as malformed config file or missing plugin
        # that are not in json format.
        try:
            output = json.loads(output[0])
        except ValueError:
            warn_issue(output[0])
            return

        lines = ''.join(file)

        assert len(output) == 1

        for result in output[0]['messages']:
            if 'fix' not in result:
                diffs = None
            else:
                fix = result['fix']
                start, end = fix['range']
                replacement_text = fix['text']
                new_output = lines[:start] + replacement_text + lines[end:]
                diffs = {
                    filename:
                    Diff.from_string_arrays(lines.splitlines(True),
                                            new_output.splitlines(True))
                }

            origin = ('{class_name} ({rule})'.format(
                class_name=type(self).__name__, rule=result['ruleId'])
                      if result.get('ruleId') is not None else self)
            yield Result.from_values(
                origin=origin,
                message=result['message'],
                file=filename,
                line=result.get('line'),
                diffs=diffs,
                severity=self.severity_map[result['severity']])
class MarkdownBear:
    """
    Check and correct Markdown style violations automatically.

    See <https://github.com/wooorm/remark-lint> for details about the tool
    below.
    """

    LANGUAGES = {'Markdown'}
    REQUIREMENTS = {
        NpmRequirement('remark-cli', '2'),
        NpmRequirement('remark-lint', '5'),
        NpmRequirement('remark-validate-links', '5')
    }
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL-3.0'
    CAN_FIX = {'Formatting'}

    _output_regex = re.compile(
        r'\s*(?P<line>\d+):(?P<column>\d+)'
        r'\s*(?P<severity>warning)\s*(?P<message>.+?)(?:  .*|\n|$)')

    @staticmethod
    @deprecate_settings(bullets='markdown_bullets',
                        closed_headings='markdown_closed_headings',
                        setext_headings='markdown_setext_headings',
                        emphasis='markdown_emphasis',
                        strong='markdown_strong',
                        encode_entities='markdown_encode_entities',
                        codefence='markdown_codefence',
                        fences='markdown_fences',
                        list_indent='markdown_list_indent',
                        loose_tables='markdown_loose_tables',
                        spaced_tables='markdown_spaced_tables',
                        list_increment='markdown_list_increment',
                        horizontal_rule='markdown_horizontal_rule',
                        horizontal_rule_spaces='markdown_horizontal_'
                        'rule_spaces',
                        horizontal_rule_repeat='markdown_horizontal_'
                        'rule_repeat')
    def create_arguments(
            filename,
            file,
            config_file,
            bullets: str = '-',
            closed_headings: bool = False,
            setext_headings: bool = False,
            emphasis: str = '*',
            strong: str = '*',
            encode_entities: bool = False,
            codefence: str = '`',
            fences: bool = True,
            list_indent: str = '1',
            loose_tables: bool = False,
            spaced_tables: bool = True,
            list_increment: bool = True,
            horizontal_rule: str = '*',
            horizontal_rule_spaces: bool = False,
            horizontal_rule_repeat: int = 3,
            max_line_length: int = None,
            check_links: bool = False,
            blockquote_indentation: int = 2,
            enforce_checkbox_content_indentation: bool = True,
            code_block_style: str = 'consistent',
            enforce_labels_at_eof: bool = True,
            first_heading_level: int = None,
            enforce_heading_level_increment: bool = False,
            max_heading_length: int = 60,
            prohibit_duplicate_definitions: bool = True,
            prohibit_duplicate_headings_in_section: bool = True,
            prohibit_duplicate_headings: bool = True,
            prohibit_empty_url: bool = True,
            prohibit_irregular_chars_filename: str = '\\.a-zA-Z0-9-_',
            prohibit_punctuations_in_heading: str = '.,;:!?',
            prohibit_html: bool = True,
            prohibit_shortcut_reference_image: bool = True,
            prohibit_shortcut_reference_link: bool = True,
            use_spaces: bool = True,
            check_undefined_references: bool = True,
            check_unused_definition: bool = True):
        """
        :param bullets:
            Character to use for bullets in lists. Can be "-", "*" or "+".
        :param closed_headings:
            Whether to close Atx headings or not. if true, extra # marks will
            be required after the heading. eg: `## Heading ##`.
        :param setext_headings:
            Whether to use setext headings. A setext heading uses underlines
            instead of # marks.
        :param emphasis:
            Character to wrap strong emphasis by. Can be "_" or "*".
        :param strong:
            Character to wrap slight emphasis by. Can be "_" or "*".
        :param encode_entities:
            Whether to encode symbols that are not ASCII into special HTML
            characters.
        :param codefence:
            Used to find which characters to use for code fences. Can be "`" or
            "~".
        :param fences:
            Use fences for code blocks.
        :param list_indent:
            Used to find spacing after bullet in lists. Can be "1", "tab" or
            "mixed".
            - "1" - 1 space after bullet.
            - "tab" - Use tab stops to begin a sentence after the bullet.
            - "mixed" - Use "1" when the list item is only 1 line, "tab" if it
              spans multiple.
        :param loose_tables:
            Whether to use pipes for the outermost borders in a table.
        :param spaced_tables:
            Whether to add space between pipes in a table.
        :param list_increment:
            Whether an ordered lists numbers should be incremented.
        :param horizontal_rule:
            The horizontal rule character. Can be '*', '_' or '-'.
        :param horizontal_rule_spaces:
            Whether spaces should be added between horizontal rule characters.
        :param horizontal_rule_repeat:
            The number of times the horizontal rule character will be repeated.
        :param max_line_length:
            The maximum line length allowed.
        :param check_links:
            Checks if links to headings and files in markdown are valid.
        :param blockquote_indentation:
            Warn when blockquotes are either indented too much or too little.
        :param enforce_checkbox_content_indentation:
            Warn when list item checkboxes are followed by unnecessary
            whitespace.
        :param code_block_style:
            Warn when code-blocks do not adhere to a given style. Can be
            ``consistent``, ``fenced``, or ``indented``. The default value,
            ``consistent``, detects the first used code-block style, and will
            warn when a subsequent code-block uses a different style.
        :param enforce_labels_at_eof:
            Warn when definitions are not placed at the end of the file.
            For example: If set to ``True``, this will throw a warning::

                Paragraph.
                [example]: http://example.com "Example Domain"
                Another paragraph.

        :param first_heading_level:
            Warn when the first heading has a level other than a specified
            value.
            For example: If set to ``2``, this will throw a warning::

                # Bravo
                Paragraph.

        :param enforce_heading_level_increment:
            Warn when headings increment with more than 1 level at a time.
            For example: If set to ``True``, prefer this::

                # Alpha
                ## Bravo

            over this::

                # Alpha
                ### Bravo

        :param max_heading_length:
            The maximum heading length allowed. Ignores markdown syntax, only
            checks the plain text content.
        :param prohibit_duplicate_definitions:
            Warn when duplicate definitions are found.
            For example: If set to ``True``, this will throw a warning::

                [foo]: bar
                [foo]: qux

        :param prohibit_duplicate_headings_in_section:
            Warn when duplicate headings are found, but only when on the same
            level, “in” the same section.
            For example: If set to ``True``, this will throw a warning::

                ## Foxtrot
                ### Golf
                ### Golf

        :param prohibit_duplicate_headings:
            Warn when duplicate headings are found.
            For example: If set to ``True``, this will throw a warning::

                # Foo
                ## Foo
                ## [Foo](http://foo.com/bar)

        :param prohibit_empty_url:
            Warn for empty URLs in links and images.
            For example: If set to ``True``, this will throw a warning::

                [golf]().
                ![hotel]().

        :param prohibit_irregular_chars_filename:
            Warn when file names contain irregular characters: characters other
             than alpha-numericals, dashes, dots (full-stops) and underscores.
             Can take ``RegExp`` or ``string``. Any match by the given
             expression triggers a warning.
        :param prohibit_punctuations_in_heading:
            Warn when a heading ends with a group of characters. Can take a
            ``string`` that contains the group of characters.
        :param prohibit_html:
            Warn when HTML elements are used. Ignores comments, because they
            are used remark, because markdown doesn’t have native comments.
            For example: If set to ``True``, this will throw a warning::

                <h1>Hello</h1>

        :param prohibit_shortcut_reference_image:
            Warn when shortcut reference images are used.
            For example: If set to ``True``, this will throw a warning::

                ![foo]
                [foo]: http://foo.bar/baz.png

        :param prohibit_shortcut_reference_link:
            Warn when shortcut reference links are used.
            For example: If set to ``True``, this will throw a warning::

                [foo]
                [foo]: http://foo.bar/baz

        :param use_spaces:
            Warn when tabs are used instead of spaces.
        :param check_undefined_references:
            Warn when references to undefined definitions are found.
            For example: If set to ``True``, this will throw a warning::

                [bar][]

        :param check_unused_definition:
            Warn when unused definitions are found.
            For example: If set to ``True``, this will throw a warning::

                [bar]: https://example.com

        """
        remark_configs = {
            'bullet': bullets,  # - or *
            'closeAtx': closed_headings,  # Bool
            'setext': setext_headings,  # Bool
            'emphasis': emphasis,  # char (_ or *)
            'strong': strong,  # char (_ or *)
            'entities': encode_entities,  # Bool
            'fence': codefence,  # char (~ or `)
            'fences': fences,  # Bool
            'listItemIndent': list_indent,  # int or "tab"
            # or "mixed"
            'looseTable': loose_tables,  # Bool
            'spacedTable': spaced_tables,  # Bool
            'incrementListMarker': list_increment,  # Bool
            'rule': horizontal_rule,  # - or * or _
            'ruleSpaces': horizontal_rule_spaces,  # Bool
            'ruleRepetition': horizontal_rule_repeat,  # int
        }
        remark_lint_configs = {
            'blockquoteIndentation': blockquote_indentation,
            'checkboxContentIndent': enforce_checkbox_content_indentation,
            'codeBlockStyle': code_block_style,
            'finalDefinition': enforce_labels_at_eof,
            'firstHeadingLevel': first_heading_level,
            'headingIncrement': enforce_heading_level_increment,
            'maximumHeadingLength': max_heading_length,
            'noDuplicateDefinitions': prohibit_duplicate_definitions,
            'noDuplicateHeadingsInSection':
            prohibit_duplicate_headings_in_section,
            'noDuplicateHeadings': prohibit_duplicate_headings,
            'noEmptyURL': prohibit_empty_url,
            'noFileNameIrregularCharacters': prohibit_irregular_chars_filename,
            'noHeadingPunctuation': prohibit_punctuations_in_heading,
            'noHTML': prohibit_html,
            'noShortcutReferenceImage': prohibit_shortcut_reference_image,
            'noShortcutReferenceLink': prohibit_shortcut_reference_link,
            'noTabs': use_spaces,
            'noUndefinedReferences': check_undefined_references,
            'noUnusedDefinitions': check_unused_definition,
        }

        if max_line_length:
            remark_lint_configs['maximumLineLength'] = max_line_length

        config_json = json.dumps(remark_configs)
        # Remove { and } as remark adds them on its own
        settings = config_json[1:-1]

        args = [filename, '--no-color', '--quiet', '--setting', settings]

        config_json = json.dumps(remark_lint_configs)
        lint = 'lint=' + config_json[1:-1]
        args += ['--use', lint]

        if check_links:
            args += ['--use', 'validate-links']

        return args

    def process_output(self, output, filename, file):
        stdout, stderr = output
        yield from self.process_output_corrected(
            stdout, filename, file, RESULT_SEVERITY.NORMAL,
            'The text does not comply'
            ' to the set style.')
        yield from self.process_output_regex(stderr, filename, file,
                                             self._output_regex)
Exemplo n.º 8
0
class StyleLintBear:
    """
    Checks the code with stylelint. This will run stylelint over each file
    separately.

    Detect errors and potential problems in CSS code and to enforce
    appropriate coding conventions. For example, problems like syntax errors,
    invalid color codes etc can be detected.

    For more information on the analysis visit <http://stylelint.io/>
    """
    LANGUAGES = {'CSS', 'SCSS'}
    REQUIREMENTS = {NpmRequirement('stylelint', '7')}
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL-3.0'
    CAN_DETECT = {'Syntax', 'Unused Code', 'Formatting'}

    @staticmethod
    def generate_config(filename, file):
        # Use standard stylelint rules
        rules = {
            'at-rule-name-case': 'lower',
            'at-rule-name-space-after': 'always-single-line',
            'at-rule-semicolon-newline-after': 'always',
            'block-closing-brace-empty-line-before': 'never',
            'block-closing-brace-newline-after': 'always',
            'block-closing-brace-newline-before': 'always-multi-line',
            'block-closing-brace-space-before': 'always-single-line',
            'block-no-empty': True,
            'block-opening-brace-newline-after': 'always-multi-line',
            'block-opening-brace-space-after': 'always-single-line',
            'block-opening-brace-space-before': 'always',
            'color-hex-case': 'lower',
            'color-hex-length': 'short',
            'color-no-invalid-hex': True,
            'comment-no-empty': True,
            'comment-whitespace-inside': 'always',
            'declaration-bang-space-after': 'never',
            'declaration-bang-space-before': 'always',
            'declaration-block-no-redundant-longhand-properties': True,
            'declaration-block-no-shorthand-property-overrides': True,
            'declaration-block-semicolon-newline-after': 'always-multi-line',
            'declaration-block-semicolon-space-after': 'always-single-line',
            'declaration-block-semicolon-space-before': 'never',
            'declaration-block-single-line-max-declarations': 1,
            'declaration-block-trailing-semicolon': 'always',
            'declaration-colon-newline-after': 'always-multi-line',
            'declaration-colon-space-after': 'always-single-line',
            'declaration-colon-space-before': 'never',
            'font-family-no-duplicate-names': True,
            'function-calc-no-unspaced-operator': True,
            'function-comma-newline-after': 'always-multi-line',
            'function-comma-space-after': 'always-single-line',
            'function-comma-space-before': 'never',
            'function-linear-gradient-no-nonstandard-direction': True,
            'function-max-empty-lines': 0,
            'function-name-case': 'lower',
            'function-parentheses-newline-inside': 'always-multi-line',
            'function-parentheses-space-inside': 'never-single-line',
            'function-whitespace-after': 'always',
            'indentation': 2,
            'keyframe-declaration-no-important': True,
            'length-zero-no-unit': True,
            'max-empty-lines': 1,
            'media-feature-colon-space-after': 'always',
            'media-feature-colon-space-before': 'never',
            'media-feature-name-case': 'lower',
            'media-feature-name-no-unknown': True,
            'media-feature-parentheses-space-inside': 'never',
            'media-feature-range-operator-space-after': 'always',
            'media-feature-range-operator-space-before': 'always',
            'media-query-list-comma-newline-after': 'always-multi-line',
            'media-query-list-comma-space-after': 'always-single-line',
            'media-query-list-comma-space-before': 'never',
            'no-empty-source': True,
            'no-eol-whitespace': True,
            'no-extra-semicolons': True,
            'no-invalid-double-slash-comments': True,
            'no-missing-end-of-source-newline': True,
            'number-leading-zero': 'always',
            'number-no-trailing-zeros': True,
            'property-case': 'lower',
            'property-no-unknown': True,
            'selector-attribute-brackets-space-inside': 'never',
            'selector-attribute-operator-space-after': 'never',
            'selector-attribute-operator-space-before': 'never',
            'selector-combinator-space-after': 'always',
            'selector-combinator-space-before': 'always',
            'selector-descendant-combinator-no-non-space': True,
            'selector-list-comma-newline-after': 'always',
            'selector-list-comma-space-before': 'never',
            'selector-max-empty-lines': 0,
            'selector-pseudo-class-case': 'lower',
            'selector-pseudo-class-no-unknown': True,
            'selector-pseudo-class-parentheses-space-inside': 'never',
            'selector-pseudo-element-case': 'lower',
            'selector-pseudo-element-colon-notation': 'double',
            'selector-pseudo-element-no-unknown': True,
            'selector-type-case': 'lower',
            'selector-type-no-unknown': True,
            'shorthand-property-no-redundant-values': True,
            'string-no-newline': True,
            'unit-case': 'lower',
            'unit-no-unknown': True,
            'value-list-comma-newline-after': 'always-multi-line',
            'value-list-comma-space-after': 'always-single-line',
            'value-list-comma-space-before': 'never',
            'value-list-max-empty-lines': 0
        }

        rules['at-rule-empty-line-before'] = [
            'always', {
                'except':
                ['blockless-after-same-name-blockless', 'first-nested'],
                'ignore': ['after-comment']
            }
        ]

        rules['comment-empty-line-before'] = [
            'always', {
                'except': ['first-nested'],
                'ignore': ['stylelint-commands']
            }
        ]

        rules['custom-property-empty-line-before'] = [
            'always', {
                'except': ['after-custom-property', 'first-nested'],
                'ignore': ['after-comment', 'inside-single-line-block']
            }
        ]

        rules['declaration-block-no-duplicate-properties'] = [
            True, {
                'ignore': ['consecutive-duplicates-with-different-values']
            }
        ]

        rules['declaration-empty-line-before'] = [
            'always', {
                'except': ['after-declaration', 'first-nested'],
                'ignore': ['after-comment', 'inside-single-line-block']
            }
        ]

        rules['rule-nested-empty-line-before'] = [
            'always-multi-line', {
                'except': ['first-nested'],
                'ignore': ['after-comment']
            }
        ]

        rules['rule-non-nested-empty-line-before'] = [
            'always-multi-line', {
                'ignore': ['after-comment']
            }
        ]

        default_config = {'rules': rules}
        return json.dumps(default_config)

    @staticmethod
    def create_arguments(filename, file, config_file):
        return filename, '--config=' + config_file
Exemplo n.º 9
0
class MarkdownBear:
    """
    Check and correct Markdown style violations automatically.

    See <https://github.com/wooorm/remark-lint> for details about the tool
    below.
    """

    LANGUAGES = {'Markdown'}
    REQUIREMENTS = {
        NpmRequirement('remark-cli', '2'),
        NpmRequirement('remark-lint', '5')
    }
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL-3.0'
    CAN_FIX = {'Formatting'}

    _output_regex = re.compile(r'\s*(?P<line>\d+):(?P<column>\d+)'
                               r'\s*(?P<severity>warning)\s*(?P<message>.*)')

    @staticmethod
    @deprecate_settings(bullets='markdown_bullets',
                        closed_headings='markdown_closed_headings',
                        setext_headings='markdown_setext_headings',
                        emphasis='markdown_emphasis',
                        strong='markdown_strong',
                        encode_entities='markdown_encode_entities',
                        codefence='markdown_codefence',
                        fences='markdown_fences',
                        list_indent='markdown_list_indent',
                        loose_tables='markdown_loose_tables',
                        spaced_tables='markdown_spaced_tables',
                        list_increment='markdown_list_increment',
                        horizontal_rule='markdown_horizontal_rule',
                        horizontal_rule_spaces='markdown_horizontal_'
                        'rule_spaces',
                        horizontal_rule_repeat='markdown_horizontal_'
                        'rule_repeat')
    def create_arguments(filename,
                         file,
                         config_file,
                         bullets: str = '-',
                         closed_headings: bool = False,
                         setext_headings: bool = False,
                         emphasis: str = '*',
                         strong: str = '*',
                         encode_entities: bool = False,
                         codefence: str = '`',
                         fences: bool = True,
                         list_indent: str = '1',
                         loose_tables: bool = False,
                         spaced_tables: bool = True,
                         list_increment: bool = True,
                         horizontal_rule: str = '*',
                         horizontal_rule_spaces: bool = False,
                         horizontal_rule_repeat: int = 3,
                         max_line_length: int = None):
        """
        :param bullets:
            Character to use for bullets in lists. Can be "-", "*" or "+".
        :param closed_headings:
            Whether to close Atx headings or not. if true, extra # marks will
            be required after the heading. eg: `## Heading ##`.
        :param setext_headings:
            Whether to use setext headings. A setext heading uses underlines
            instead of # marks.
        :param emphasis:
            Character to wrap strong emphasis by. Can be "_" or "*".
        :param strong:
            Character to wrap slight emphasis by. Can be "_" or "*".
        :param encode_entities:
            Whether to encode symbols that are not ASCII into special HTML
            characters.
        :param codefence:
            Used to find which characters to use for code fences. Can be "`" or
            "~".
        :param fences:
            Use fences for code blocks.
        :param list_indent:
            Used to find spacing after bullet in lists. Can be "1", "tab" or
            "mixed".
            - "1" - 1 space after bullet.
            - "tab" - Use tab stops to begin a sentence after the bullet.
            - "mixed" - Use "1" when the list item is only 1 line, "tab" if it
              spans multiple.
        :param loose_tables:
            Whether to use pipes for the outermost borders in a table.
        :param spaced_tables:
            Whether to add space between pipes in a table.
        :param list_increment:
            Whether an ordered lists numbers should be incremented.
        :param horizontal_rule:
            The horizontal rule character. Can be '*', '_' or '-'.
        :param horizontal_rule_spaces:
            Whether spaces should be added between horizontal rule characters.
        :param horizontal_rule_repeat:
            The number of times the horizontal rule character will be repeated.
        :param max_line_length:
            The maximum line length allowed.
        """
        remark_configs_settings = {
            'bullet': bullets,  # - or *
            'closeAtx': closed_headings,  # Bool
            'setext': setext_headings,  # Bool
            'emphasis': emphasis,  # char (_ or *)
            'strong': strong,  # char (_ or *)
            'entities': encode_entities,  # Bool
            'fence': codefence,  # char (~ or `)
            'fences': fences,  # Bool
            'listItemIndent': list_indent,  # int or "tab"
            # or "mixed"
            'looseTable': loose_tables,  # Bool
            'spacedTable': spaced_tables,  # Bool
            'incrementListMarker': list_increment,  # Bool
            'rule': horizontal_rule,  # - or * or _
            'ruleSpaces': horizontal_rule_spaces,  # Bool
            'ruleRepetition': horizontal_rule_repeat,  # int
        }
        remark_configs_plugins = {}

        if max_line_length:
            remark_configs_plugins['maximumLineLength'] = max_line_length

        config_json = json.dumps(remark_configs_settings)
        # Remove { and } as remark adds them on its own
        settings = config_json[1:-1]

        args = ['--no-color', '--quiet', '--setting', settings]

        if remark_configs_plugins:
            config_json = json.dumps(remark_configs_plugins)
            plugins = 'lint=' + config_json[1:-1]
            args += ['--use', plugins]

        return args

    def process_output(self, output, filename, file):
        stdout, stderr = output
        yield from self.process_output_corrected(
            stdout, filename, file, RESULT_SEVERITY.NORMAL,
            'The text does not comply'
            ' to the set style.')
        yield from self.process_output_regex(stderr, filename, file,
                                             self._output_regex)
Exemplo n.º 10
0
class GherkinLintBear:  # pragma nt: no cover
    """
    Use Gherkin to run linting on feature files
    """

    LANGUAGES = {'Gherkin'}
    REQUIREMENTS = {NpmRequirement('gherkin-lint', '2')}
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL_3.0'
    CAN_DETECT = {'Formatting', 'Syntax'}

    def process_output(self, output, filename, file):
        stderr = json.loads(output)
        for fileErr in stderr:
            filePath = fileErr['filePath']
            for err in fileErr['errors']:
                yield Result.from_values(
                    origin='{} ({})'.format(
                        self.__class__.__name__,
                        err['rule']),
                    message=err['message'],
                    line=int(err['line']),
                    file=filePath)

    @staticmethod
    def generate_config(filename, file,
                        allow_trailing_whitespace: bool = True,
                        allow_dupe_feature_names: bool = True,
                        allow_dupe_scenario_names: bool = True,
                        allow_duplicate_tags: bool = True,
                        allow_empty_file: bool = True,
                        allow_files_without_scenarios: bool = True,
                        allow_homogenous_tags: bool = True,
                        allow_multiple_empty_lines: bool = True,
                        allow_scenario_outlines_without_examples: bool = True,
                        allow_superfluous_tags: bool = True,
                        allow_unnamed_features: bool = True,
                        allow_unnamed_scenarios: bool = True,
                        one_space_between_tags: bool = False,
                        use_and: bool = False):
        """
        :param allow_trailing_whitespace:
            Allow trailing spaces
        :param allow_dupe_feature_names:
            Disallows duplicate Feature names
        :param allow_dupe_scenario_names:
            Disallows duplicate Scenario names
        :param allow_duplicate_tags:
            Disallows duplicate tags on the same Feature or Scenario
        :param allow_empty_file:
            Disllows empty file
        :param allow_files_without_scenarios:
            Disallows files with no scenarios
        :param allow_homogenous_tags:
            Disallows tags present on every Scenario in a Feature,
            rather than on the Feature itself
        :param allow_multiple_empty_lines:
            Disallows/enforces new line at EOF
        :param allow_scenario_outlines_without_examples:
            Disallows scenario outlines without examples
        :param allow_superfluous_tags:
            Disallows tags present on a Feature and a Scenario in
            that Feature
        :param allow_unnamed_features:
            Disallows empty Feature name
        :param allow_unnamed_scenarios:
            Disallows empty Scenario name
        :param one_space_between_tags:
            Tags on the same time must be separated by a single space
        :param use_and:
            Disallows repeated step names requiring use of And instead
        """
        options = {'no-trailing-spaces':
                   _setting_map[not allow_trailing_whitespace],
                   'no-dupe-feature-names':
                   _setting_map[not allow_dupe_feature_names],
                   'no-dupe-scenario-names':
                   _setting_map[not allow_dupe_scenario_names],
                   'no-duplicate-tags': _setting_map[not allow_duplicate_tags],
                   'no-empty-file': _setting_map[not allow_empty_file],
                   'no-files-without-scenarios':
                   _setting_map[not allow_files_without_scenarios],
                   'no-homogenous-tags':
                   _setting_map[not allow_homogenous_tags],
                   'no-multiple-empty-lines':
                   _setting_map[not allow_multiple_empty_lines],
                   'no-scenario-outlines-without-examples':
                   _setting_map[not allow_scenario_outlines_without_examples],
                   'no-superfluous-tags':
                   _setting_map[not allow_superfluous_tags],
                   'no-unnamed-features':
                   _setting_map[not allow_unnamed_features],
                   'no-unnamed-scenarios':
                   _setting_map[not allow_unnamed_scenarios],
                   'one-space-between-tags':
                   _setting_map[one_space_between_tags],
                   'use-and': _setting_map[use_and]}
        return json.dumps(options)

    @staticmethod
    def create_arguments(config_file, gherkin_config: str = ''):
        args = ('-f', 'json', '--config',)
        if gherkin_config:
            args += (gherkin_config,)
        else:
            args += (config_file,)
        return args
class HTMLHintBear:
    """
    Checks HTML code with ``htmlhint`` for possible problems. Attempts to catch
    little mistakes and enforces a code style guide on HTML files.
    """
    LANGUAGES = {'HTML'}
    REQUIREMENTS = {NpmRequirement('htmlhint', '0.9.13')}
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL-3.0'
    CAN_DETECT = {'Syntax', 'Formatting', 'Duplication', 'Code Simplification'}
    SEE_MORE = 'https://github.com/yaniswang/HTMLHint'

    @staticmethod
    def generate_config(filename, file,
                        enforce_lowercase_tagname: bool=True,
                        enforce_lowercase_attribute: bool=True,
                        require_attribute_value_in_double_quotes: bool=False,
                        prohibit_empty_value_for_attribute: bool=False,
                        prohibit_attribute_duplication: bool=True,
                        require_doctype_at_beginning: bool=True,
                        enforce_tag_pair: bool=True,
                        enforce_self_close_empty_tag: bool=True,
                        require_escaped_special_characters: bool=False,
                        require_unique_attribute_id: bool=True,
                        require_title_tag: bool=True,
                        prohibit_script_in_head: bool=False,
                        require_alt_attribute: bool=True,
                        enforce_id_class_naming_convention: str=None,
                        prohibit_inline_style: bool=True,
                        require_relative_links_in_href: bool=None,
                        prohibit_unsafe_characters: bool=True,
                        prohibit_inline_script: bool=False,
                        prohibit_style_tag: bool=False,
                        htmlhint_config: str=''):
        """
        :param enforce_lowercase_tagname:
            Enforce the tagnames to be written in lowercase.
            For example: If set to ``True``, prefer ``<span><div>`` over
            ``<SPAN><BR>``.
        :param enforce_lowercase_attribute:
            Enforce the attribute names to be written in lowercase.
            For example: If set to ``True``, prefer
            ``<img src="test.png" alt="test">`` over
            ``<img SRC="test.png" ALT="test">``.
        :param require_attribute_value_in_double_quotes:
            Allow attribute values to be enclosed in double quotes.
            For example: If set to ``True``, prefer ``<a href="" title="abc">``
            over ``<a href='' title=abc>``.
        :param prohibit_empty_value_for_attribute:
            Disallow empty values for attributes.
            For example: If set to ``True``, prefer
            ``<input type="button" disabled="disabled">`` over
            ``<input type="button" disabled>``.
        :param prohibit_attribute_duplication:
            Disallow defining of the same attribute more than once in
            a tag. For example: If set to ``True``, prefer
            ``<img src="a.png" />`` over ``<img src="a.png" src="b.png" />``.
        :param require_doctype_at_beginning:
            Enforce the ``<!DOCTYPE>`` declaration at the beginning.
            For example: If set to ``True``, prefer ``<!DOCTYPE HTML><html>``
            over ``<!--comment--><!DOCTYPE HTML><html>``.
        :param enforce_tag_pair:
            Enforce the tags to be paired.
        :param enforce_self_close_empty_tag:
            Enforce the empty tag to be closed by self.
            For example: If set to ``True``, prefer ``<br />`` over ``<br>``.
        :param require_escaped_special_characters:
            Require the special characters to be escaped.
            For example: If set to ``True``, prefer
            ``<span>aaa&gt;bbb&lt;ccc</span>`` over
            ``<span>aaa>bbb<ccc</span>``.
        :param require_unique_attribute_id:
            Require the ID attributes to be unique in the document.
            For example: If set to ``True``, prefer
            ``<div id="id1"></div><div id="id2"></div>`` over
            ``<div id="id1"></div><div id="id1"></div>``.
        :param require_title_tag:
            Require the ``<title>`` to be present in the ``<head>`` tag.
        :param prohibit_script_in_head:
            Prohibit the use of the ``<script>`` tag in the ``<head>`` tag.
        :param require_alt_attribute:
            Require ``alt`` attribute when using images (``img`` tag) and links
            (``href`` tag).
            For example: If set to ``True``, prefer this::

                <img src="test.png" alt="test">
                <input type="image" alt="test">

            over this::

                <img src="test.png">
                <input type="image">

        :param enforce_id_class_naming_convention:
            Possible values are ``underline``, ``dash`` and ``hump``.
            Require the ``id`` and ``class`` values to be set according to
            the given rules.
            For example: If set to ``underline``, prefer
            ``<div id="aaa_bbb">``.
            For example: If set to ``dash``, prefer ``<div id="aaa-bbb">``.
        :param prohibit_inline_style:
            Disallow the use of inline ``style`` attribute.
            For example: If set to ``True``, ``<div style="color:red"></div>``
            will raise a warning.
        :param require_relative_links_in_href:
            If ``True``, enforce relative links in the ``href`` attribute and
            if ``False``, enforce absolute links.
        :param prohibit_unsafe_characters:
            Prohibit the use of unsafe characters in attribute values.
            For example: If set to ``True``,
            ``<li><a href="https://vimeo.com//56931059‎\u0009‎">2012</a></li>``
            will raise a warning.
        :param prohibit_inline_script:
            Disallow the use of inline scripts.
            For example: If set to ``True``, this will raise a warning::

                <img src="test.gif" onclick="alert(1);">
                <img src="javascript:alert(1)">
                <a href="javascript:alert(1)">test1</a>

        :param prohibit_style_tag:
            Prohibit the use of ``style`` tag.
            For example: If set to ``True``,
            ``<body><style type="text/css"></style></body>``
            will raise a warning.
        """
        if htmlhint_config:
            return None
        else:
            options = {
                'tagname-lowercase': enforce_lowercase_tagname,
                'attr-lowercase': enforce_lowercase_attribute,
                'attr-value-double-quotes':
                    require_attribute_value_in_double_quotes,
                'attr-value-not_empty': prohibit_empty_value_for_attribute,
                'attr-no-duplication': prohibit_attribute_duplication,
                'doctype-first': require_doctype_at_beginning,
                'tag-pair': enforce_tag_pair,
                'tag-self-close': enforce_self_close_empty_tag,
                'spec-char-escape': require_escaped_special_characters,
                'id-unique': require_unique_attribute_id,
                'title-require': require_title_tag,
                'head-script-disabled': prohibit_script_in_head,
                'alt-require': require_alt_attribute,
                'id-class-value': enforce_id_class_naming_convention,
                'inline-style-disabled': prohibit_inline_style,
                'attr-unsafe-chars': prohibit_unsafe_characters,
                'inline-script-disabled': prohibit_inline_script,
                'style-disabled': prohibit_style_tag,
                'href-abs-or-rel':
                    'false' if require_relative_links_in_href is None
                    else 'rel' if require_relative_links_in_href else 'abs'
            }

            return json.dumps(options)

    @staticmethod
    def create_arguments(filename, file, config_file, htmlhint_config: str=''):
        """
        :param htmlhint_config:
            The path to a custom ``.htmlhintrc`` config file.
        """
        return (filename, '--config',
                htmlhint_config if htmlhint_config else config_file,
                '--format', 'unix')
Exemplo n.º 12
0
class CSSCombBear:
    """
    CSScomb is a coding style formatter for CSS. You can easily write your own
    configuration to make your style sheets beautiful and consistent.
    """

    LANGUAGES = {'CSS'}
    REQUIREMENTS = {NpmRequirement('csscomb', '4.2.0')}
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL-3.0'
    ASCIINEMA_URL = 'https://asciinema.org/a/bxpke7nizyxdf6mlx6ss4h405'
    CAN_FIX = {'Formatting'}
    SEE_MORE = 'https://github.com/csscomb/csscomb.js'

    @staticmethod
    def generate_config(filename, file,
                        enforce_semicolon: bool = True,
                        use_block_indentation: int = 4,
                        use_color_case: str = 'upper',
                        allow_color_shorthand: bool = None,
                        allow_leading_zero_in_dimensions: bool = True,
                        preferred_quotation: str = "'",
                        prohibit_empty_rulesets: bool = True,
                        use_space_after_colon: int = 1,
                        use_space_before_colon: int = 0,
                        use_space_after_combinator: int = 1,
                        use_space_before_combinator: int = 1,
                        use_space_between_declarations: int = None,
                        use_space_after_opening_brace: int = None,
                        use_space_before_opening_brace: int = 1,
                        use_space_before_closing_brace: int = None,
                        use_space_after_selector_delimiter: int = 1,
                        use_space_before_selector_delimiter: int = 1,
                        prohibit_trailing_whitespace: bool = True,
                        prohibit_units_in_zero_valued_dimensions: bool = True,
                        vendor_prefix_align: bool = None,
                        use_lines_between_rulesets: int = 1,
                        csscomb_config: str = '',
                        ):
        """
        :param enforce_semicolon:
            Whether to add a semicolon after the last value/mixin.
            For example: If set to ``True``, prefer this::

                a { color: red; text-decoration: underline; }

            over this::

                a { color: red; text-decoration: underline }

        :param use_block_indentation:
            Set the number of spaces as indent for code inside blocks,
            including media queries and nested rules.
            For example: If set to ``4``, prefer this::

                a {
                    top: 0;
                    p {
                        color: tomato;
                        position: happy;
                        }
                    }

            over this::

                a {
                top: 0;
                  p {
                      color: tomato;
                position: happy;
                 }
                }

        :param use_color_case:
            Unify case of hexadecimal colors. Acceptable values are ``lower``
            and ``upper``.
            For example: If set to ``lower``, prefer this::

                a { color: #fff }

            over this::

                a { color: #FFF }

        :param allow_color_shorthand:
            Whether to expand hexadecimal colors or use shorthands.
            For example: If set to ``True``, prefer this::

                b { color: #fc0 }

            over this::

                b { color: #ffcc00 }

        :param allow_leading_zero_in_dimensions:
            Add/remove leading zero in dimensions.
            For example: If set to ``False``, prefer this::

                p { padding: .5em }

            over this::

                p { padding: 0.5em }

        :param preferred_quotation:
            ``'`` or ``"`` respectively.
        :param prohibit_empty_rulesets:
            Remove all rulesets that contain nothing but spaces.
            For example: If set to ``True``, prefer this::

                a { color: red; } p { /* hey */ }

            over this::

                a { color: red; } p { /* hey */ } b { }

        :param use_space_after_colon:
            Set the number of spaces after ``:`` in declarations.
            For example: If set to ``1``, prefer this::

                a {
                    top: 0;
                    color: tomato;
                }

            over this::

                a {
                    top:0;
                    color:tomato;
                }

        :param use_space_before_colon:
            Set the number of spaces before ``:`` in declarations.
            For example: If set to ``1``, prefer this::

                a {
                    top : 0;
                    color : tomato;
                }

            over this::

                a {
                    top: 0;
                    color: tomato;
                }

        :param use_space_after_combinator:
            Set the number of spaces after the combinator.
            For example: If set to ``1``, prefer this::

                p> a { color: panda; }

            over this::

                p>a { color: panda; }

        :param use_space_before_combinator:
            Set the number of spaces before the combinator.
            For example: If set to ``1``, prefer this::

                p >a { color: panda; }

            over this::

                p>a { color: panda; }

        :param use_space_between_declarations:
            Set the number of spaces between declarations.
        :param use_space_after_opening_brace:
            Set the number of spaces after ``{``.
        :param use_space_before_opening_brace:
            Set the number of spaces before ``{``.
        :param use_space_before_closing_brace:
            Set the number of spaces before ``}``.
        :param use_space_after_selector_delimiter:
            Set the number of spaces after the selector delimiter.
            For example: If set to ``1``, prefer this::

                a, b {
                    color: panda;
                    }

            over this::

                a,b{
                    color: panda;
                    }

        :param use_space_before_selector_delimiter:
            Set the number of spaces before selector delimiter.
        :param prohibit_trailing_whitespace:
            Whether to allow trailing whitespace or not.
        :param prohibit_units_in_zero_valued_dimensions:
            Whether to remove units in zero-valued dimensions.
            For example: If set to ``True``, prefer this::

                img { border: 0 }

            over this::

                img { border: 0px }

        :param vendor_prefix_align:
            Whether to align prefixes in properties and values.
            For example: If set to ``True``, prefer this::

            a
            {
                -webkit-border-radius: 3px;
                   -moz-border-radius: 3px;
                        border-radius: 3px;
                background: -webkit-linear-gradient(top, #fff 0, #eee 100%);
                background:    -moz-linear-gradient(top, #fff 0, #eee 100%);
            }

            over this::

            a
            {
                -webkit-border-radius: 3px;
                -moz-border-radius: 3px;
                border-radius: 3px;
                background: -webkit-linear-gradient(top, #fff 0, #eee 100%);
                background: -moz-linear-gradient(top, #fff 0, #eee 100%);
            }

        :param use_lines_between_rulesets:
            Number of line breaks between rulesets or ``@rules``.
        """
        if csscomb_config:
            return None
        else:
            options = {
                'always-semicolon': enforce_semicolon if enforce_semicolon
                else None,
                'block-indent': use_block_indentation,
                'color-case': use_color_case,
                'color-shorthand': allow_color_shorthand,
                'leading-zero': allow_leading_zero_in_dimensions,
                'quotes': 'single' if preferred_quotation == "'" else 'double',
                'remove-empty-rulesets': prohibit_empty_rulesets if
                prohibit_empty_rulesets else None,
                'space-after-colon': use_space_after_colon,
                'space-before-colon': use_space_before_colon,
                'space-after-combinator': use_space_after_combinator,
                'space-before-combinator': use_space_before_combinator,
                'space-between-declarations': use_space_between_declarations,
                'space-after-opening-brace': use_space_after_opening_brace,
                'space-before-opening-brace': use_space_before_opening_brace,
                'space-before-closing-brace': use_space_before_closing_brace,
                'space-after-selector-delimiter':
                    use_space_after_selector_delimiter,
                'space-before-selector-delimiter':
                    use_space_before_selector_delimiter,
                'strip-spaces': prohibit_trailing_whitespace if
                prohibit_trailing_whitespace else None,
                'unitless-zero': prohibit_units_in_zero_valued_dimensions if
                prohibit_units_in_zero_valued_dimensions else None,
                'vendor-prefix-align': vendor_prefix_align if
                vendor_prefix_align else None,
                'lines-between-rulesets': use_lines_between_rulesets
            }

            return json.dumps(options)

    @staticmethod
    def create_arguments(filename, file, config_file,
                         csscomb_config: str = '',
                         ):
        """
        :param csscomb_config:
            The location of the ``.csscomb.json`` config file.
        """
        return ('--config',
                csscomb_config if csscomb_config else config_file)
Exemplo n.º 13
0
class TextLintBear:
    """
    The pluggable linting tool for text and Markdown. It is similar to ESLint,
    but covers natural language instead.
    """

    LANGUAGES = {'HTML', 'Markdown', 'reStructuredText'}
    REQUIREMENTS = {
        NpmRequirement('textlint', '7.3.0'),
        NpmRequirement('textlint-plugin-asciidoc-loose', '1.0.1'),
        NpmRequirement('textlint-plugin-html', '0.1.5'),
        NpmRequirement('textlint-plugin-review', '0.3.3'),
        NpmRequirement('textlint-plugin-rst', '0.1.1'),
        NpmRequirement('textlint-rule-alex', '1.2.0'),
        NpmRequirement('textlint-rule-common-misspellings', '1.0.1'),
        NpmRequirement('textlint-rule-date-weekday-mismatch', '1.0.5'),
        NpmRequirement('textlint-rule-ginger', '>=2.1.0 <2.1.2'),
        NpmRequirement('textlint-rule-max-comma', '1.0.4'),
        NpmRequirement('textlint-rule-max-number-of-lines', '1.0.3'),
        NpmRequirement('textlint-rule-ng-word', '1.0.0'),
        NpmRequirement('textlint-rule-no-dead-link', '3.1.1'),
        NpmRequirement('textlint-rule-no-empty-section', '1.1.0'),
        NpmRequirement('textlint-rule-no-start-'
                       'duplicated-conjunction', '1.1.3'),
        NpmRequirement('textlint-rule-no-todo', '2.0.0'),
        NpmRequirement('textlint-rule-period-in-list-item', '0.2.0'),
        NpmRequirement('textlint-rule-rousseau', '1.4.5'),
        NpmRequirement('textlint-rule-unexpanded-acronym', '1.2.1'),
        NpmRequirement('textlint-rule-write-good', '1.6.0'),
        # Dependency for textlint-plugin-rst
        PipRequirement('docutils-ast-writer', '0.1.2')
    }
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL-3.0'
    CAN_DETECT = {'Formatting', 'Grammar', 'Spelling'}
    SEE_MORE = 'https://github.com/textlint/textlint'

    @staticmethod
    def generate_config(filename,
                        file,
                        check_todos: bool = None,
                        dont_start_with_duplicated_conjunction: bool = True,
                        no_empty_section: bool = True,
                        check_date_weekday_mismatch: bool = True,
                        check_grammar: bool = True,
                        max_lines_per_file: int = 300,
                        max_comma_per_sentence: int = 4,
                        no_good_words: typed_list(str) = [],
                        period_in_list_item: bool = True,
                        minimum_acronym_length: int = 3,
                        maximum_acronym_length: int = 5,
                        ignore_acronyms: typed_list(str) = [],
                        check_with_rousseau: bool = True,
                        check_with_alex: bool = True,
                        check_common_misspellings: bool = True,
                        allow_passive_voice: bool = True,
                        allow_so_beginning: bool = True,
                        allow_adverbs: bool = True,
                        allow_repeated_words: bool = True,
                        allow_there_is: bool = True,
                        allow_ambiguous_words: bool = True,
                        allow_extra_words: bool = True,
                        allow_cliche_phrases: bool = True,
                        check_relative_links: bool = False,
                        base_uri: str = '',
                        link_ignore_list: typed_list(str) = [],
                        textlint_config: str = ''):
        """
        :param check_todos:
            This rule checks for occurrences of ``- [ ]``
            (so called task lists).
        :param dont_start_with_duplicated_conjunction:
            This rule checks whether your sentence starts with a duplicated
            conjunction.
        :param no_empty_section:
            This rule does not allow to create an empty section.
            For example, there is an empty section ``# Header A`` below::

                # Header A

                # Header B
                Text.

        :param check_date_weekday_mismatch:
            This rule finds a mismatch between a date and the corresponding
            weekday.
        :param check_grammar:
            This rule checks your English grammar with Ginger Proofreading.
        :param max_lines_per_file:
            Number of lines allowed per file.
        :param max_comma_per_sentence:
            Number of commas allowed per sentence.
        :param no_good_words:
            Set of NG (No Good) words to check for.
        :param period_in_list_item:
            Checks whether a sentence in a list item ends with a period.
        :param minimum_acronym_length:
            Minimum length for unexpanded acronyms.
        :param maximum_acronym_length:
            Maximum length for unexpanded acronyms.
        :param ignore_acronyms:
            A list that contains the acronyms to ignore.
        :param check_with_rousseau:
            This rule checks English writing using Rousseau, which is a
            lightweight proofreader written in JavaScript.
            It can check:
            - Passive voice
            - Lexical illusions – cases where a word is repeated
            - 'So' at the beginning of the sentence
            - Adverbs that can weaken meaning: really, very, extremely, etc.
            - Readability of sentences
            - Simpler expressions
            - Weasel words
            - If a sentence is preceded by a space
            - If there is no space between a sentence and its ending
              punctuation
            - If sentences are starting with uppercase letter
        :param check_with_alex:
            This rule helps you find gender favouring, polarising, race
            related, religion inconsiderate, or other unequal phrasing
            and checks for:
            - Gendered work-titles, for example warning about ``garbageman``
              and suggesting ``garbage collector`` instead
            - Gendered proverbs, such as warning about ``like a man`` and
              suggesting ``bravely`` instead, or warning about ``ladylike``
              and suggesting ``courteous``
            - Blunt phrases, such as warning about ``cripple`` and suggesting
              ``person with a limp`` instead
            - Intolerant phrasing, such as warning about using ``master`` and
              ``slave`` together, and suggesting ``primary`` and ``replica``
              instead
        :param check_common_misspellings:
            This rule helps to find common misspellings from Wikipedia's
            list of common misspellings.
        :param allow_passive_voice:
            Allows passive voice.
        :param allow_so_beginning:
            Allows ``So`` at the beginning of a sentence.
        :param allow_adverbs:
            Allows adverbs that can weaken the meaning, such as: ``really``,
            ``very``, ``extremely``, etc.
        :param allow_repeated_words:
            Allows lexical illusions, i.e. cases where a word is repeated.
        :param allow_there_is:
            Allows ``There is`` or ``There are`` at the beginning of a
            sentence.
        :param allow_ambiguous_words:
            Allows "weasel words", for example "often" or "probably".
        :param allow_extra_words:
            Allows wordy phrases and unnecessary words.
        :param allow_cliche_phrases:
            Allows common cliche phrases in the sentence.
            For example: In the sentence
            "Writing specs puts me at loose ends.",
            "at loose ends" is a cliche.
        :param check_relative_links:
            This rule enables dead link checks against relative URIs.
            Note that you also have to specify the ``base_uri`` to make this
            option work.
        :param base_uri:
            The base URI to be used for resolving relative URIs.
        :param link_ignore_list:
            A list of URIs to be ignored, i.e. skipped from availability
            checks.
        """
        if textlint_config:
            return None
        else:
            options = {
                'no-todo': check_todos,
                'no-start-duplicated-conjunction':
                dont_start_with_duplicated_conjunction,
                'no-empty-section': no_empty_section,
                'date-weekday-mismatch': check_date_weekday_mismatch,
                'ginger': check_grammar,
                'max-number-of-lines': {
                    'max': max_lines_per_file
                },
                'max-comma': {
                    'max': max_comma_per_sentence
                },
                'ng-word': {
                    'words': no_good_words
                },
                'period-in-list-item': period_in_list_item,
                'unexpanded-acronym': {
                    'min_acronym_len': minimum_acronym_length,
                    'max_acronym_len': maximum_acronym_length,
                    'ignore_acronyms': ignore_acronyms
                },
                'rousseau': check_with_rousseau,
                'alex': check_with_alex,
                'common-misspellings': check_common_misspellings,
                'write-good': {
                    'passive': allow_passive_voice,
                    'so': allow_so_beginning,
                    'adverb': allow_adverbs,
                    'illusion': allow_repeated_words,
                    'thereIs': allow_there_is,
                    'weasel': allow_ambiguous_words,
                    'tooWordy': allow_extra_words,
                    'cliches': allow_cliche_phrases
                },
                'no-dead-link': {
                    'checkRelative': check_relative_links,
                    'baseURI': base_uri,
                    'ignore': link_ignore_list
                }
            }

            parent_config = {
                'rules': options,
                'plugins': ['asciidoc-loose', 'html', 'review', 'rst']
            }

            return json.dumps(parent_config)

    @staticmethod
    def create_arguments(filename,
                         file,
                         config_file,
                         textlint_config: str = ''):
        """
        :param textlint_config:
            The location of the ``.textlintrc`` config file.
        """
        return ('-c', textlint_config if textlint_config else config_file,
                filename)
class CoffeeLintBear:
    """
    Check CoffeeScript code for a clean and consistent style.

    For more information about coffeelint, visit <http://www.coffeelint.org/>.
    """

    LANGUAGES = {'CoffeeScript'}
    REQUIREMENTS = {NpmRequirement('coffeelint', '1')}
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL-3.0'
    CAN_DETECT = {'Syntax', 'Formatting', 'Smell', 'Complexity', 'Duplication'}

    severity_map = {
        'warn': RESULT_SEVERITY.NORMAL,
        'error': RESULT_SEVERITY.MAJOR,
        'ignore': RESULT_SEVERITY.INFO
    }

    @staticmethod
    def create_arguments(filename, file, config_file):
        return '--reporter=raw', '--stdin', '-f', config_file

    @staticmethod
    @deprecate_settings(
        indent_size='tab_width',
        allow_increment=('no_decr_or_incrementation_operators', negate),
        allow_no_parameters=('no_empty_parameter_list', negate),
        allow_empty_functions=('no_empty_functions', negate),
        allow_this_statements=('no_this', negate),
        allow_implicit_parentheses=('no_implicit_parentheses', negate),
        allow_interpolation_in_single_quotes=(
            'no_interpolation_in_single_quotes', negate),
        allow_stand_alone_at_sign=('no_stand_alone_at_sign', negate),
        allow_throwing_strings=('disable_throwing_strings', negate),
        allow_unnecessary_double_quotes=('no_unnecessary_double_quotes',
                                         negate),
        allow_bitwise_operators=('use_english_operator', negate),
        force_braces='no_implicit_braces')
    def generate_config(
            filename,
            file,
            max_line_length: int = 79,
            max_line_length_affect_comments: bool = True,
            space_before_and_after_arrow: bool = True,
            check_braces_spacing: bool = False,
            braces_spacing_width: int = 1,
            spacing_in_empty_braces: int = 0,
            class_naming_camelCase: bool = True,
            spaces_before_and_after_colon: bool = False,
            spaces_before_colon: int = 0,
            spaces_after_colon: int = 1,
            enforce_newline_at_EOF: bool = True,
            use_spaces: bool = True,
            indent_size: int = 2,
            number_of_newlines_after_classes: int = 2,
            prohibit_embedding_javascript_snippet: bool = True,
            force_braces: bool = False,
            allow_implicit_parentheses: bool = True,
            allow_interpolation_in_single_quotes: bool = True,
            allow_stand_alone_at_sign: bool = False,
            allow_throwing_strings: bool = False,
            allow_trailing_semicolons: bool = False,
            allow_trailing_whitespaces: bool = False,
            allow_unnecessary_double_quotes: bool = True,
            allow_bitwise_operators: bool = True,
            spaces_around_operators: bool = True,
            space_after_comma: bool = True,
            cyclomatic_complexity: int = 0,
            prevent_duplicate_keys: bool = True,
            consistent_line_endings_style: str = '',
            allow_this_statements: bool = True,
            allow_increment: bool = True,
            allow_no_parameters: bool = True,
            allow_empty_functions: bool = False,
            enforce_parentheses_on_non_empty_constructors: bool = True):
        """
        :param max_line_length:
            Maximum number of characters per line.
        :param max_line_length_affect_comments:
            Determines if ``max_line_length`` should also affects comments or
            not.
        :param space_before_and_after_arrow:
            Determines if spaces should be used before and after the arrow.
        :param check_braces_spacing:
            Checks if proper spacing is used inside curly braces.
        :param braces_spacing_width:
            Determines the number of blank spaces after the opening ``{`` and
            before the closing brace ``}`` given that there is something within
            the braces.
        :param spacing_in_empty_braces:
            Determines the number of blank spaces after the opening ``{`` and
            before the closing brace ``}`` given empty content.
        :param class_naming_camelCase:
            Checks whether the classes name should be in camel-case or not.
        :param spaces_before_and_after_colon:
            Checks the number of spaces before and after colon.
        :param spaces_before_colon:
            Determines the number of blank spaces before colon when
            ``spaces_before_and_after_colon == True``.
        :param spaces_after_colon:
            Determines the number of space after colon when
            ``spaces_before_and_after_colon == True``.
        :param enforce_newline_at_EOF:
            Checks if the file ends with a single newline.
        :param use_spaces:
            Forbids tabs in indentation and applies two spaces for this
            purpose.
        :param indent_size:
            Number of spaces per indentation level.
        :param number_of_newlines_after_classes:
            Determines the number of newlines that separate the class
            definition and the rest of the code.
        :param prohibit_embedding_javascript_snippet:
            Prevents some JavaScript elements like ``eval`` to affect
            CoffeeScript.
        :param force_braces:
            Prohibits implicit braces when declaring object literals.

            Example: If ``force_braces = True`` then::

                1:2, 3:4

            is prohibited, whereas::

                {1:2, 3:4}

            is accepted.
        :param allow_implicit_parentheses:
            Allows implicit parentheses.
        :param allow_interpolation_in_single_quotes:
            Allows string interpolation in a single quoted string.

            Example: If ``allow_interpolation_in_single_quotes = False`` then::

                f = '#{bar}'

            is prohibited, whereas::

                f = "#{bar}"

            is correct.
        :param allow_stand_alone_at_sign:
            Allows the use of stand alone  ``@``.

            Example: If ``allow_stand_alone_at_sign = False``::

                @ notok
                not(@).ok
                @::

            are prohibited, whereas::

                @alright
                @(fn)
                @ok()
                @[ok]
                @ok()

            are accepted.
        :param allow_throwing_strings:
            Allows throwing string literals or interpolation.

            Example: If ``allow_throwing_strings = False``::

                throw 'my error'
                throw "#{1234}"

            will not be permitted.
        :param allow_trailing_semicolons:
            Prohibits trailing semicolons when ``False`` since they are
            not useful. The semicolon is meaningful only if there's another
            instruction on the same line.

            Example: If ``allow_trailing_semicolon = False``::

                x = '1234'; console.log(x)

            Here the semicolon is meaningful::

                alert('end of line');

            This semicolon is redundant.
        :param allow_trailing_whitespaces:
            Checks whether to allow trailing whitespacess in the code or not.
        :param allow_unnecessary_double_quotes:
            Allows enclosing strings in double quotes.
        :param allow_bitwise_operators:
            Determines if ``and``, ``or``, ``is`` and ``isnt`` should be used
            instead of ``&&``, ``||``, ``==`` and ``!=``.
        :param spaces_around_operators:
            Enforces that operators have spaces around them.
        :param space_after_comma:
            Checks if there is a blank space after commas.
        :param cyclomatic_complexity:
            Maximum cyclomatic complexity of the file.
        :param prevent_duplicate_keys:
            Prevents defining duplicate keys in object literals and classes.
        :param enforce_parentheses_on_non_empty_constructors:
            Requires constructors with parameters to include parentheses.

            Example::

                class Foo
                # Warn about missing parentheses here
                a = new Foo
                b = new bar.foo.Foo
                # The parentheses make it clear no parameters are intended
                c = new Foo()
                d = new bar.foo.Foo()
                e = new Foo 1, 2
                f = new bar.foo.Foo 1, 2

        :param consistent_line_endings_style:
            The option to ``line_endings``, its value is either ``unix`` or
            ``windows``.
        :param allow_this_statements:
            Allows the use of ``this``. ``@`` should be used if ``False``.
        :param allow_increment:
            Allows the use of increment and decrement arithmetic operators.
        :param allow_no_parameters:
            Allows empty parameter lists in function definitions.
        :param allow_empty_functions:
            Allows declaring empty functions.
        """
        coffee_configs = {
            'max_line_length': {
                'value': max_line_length,
                'level': 'error',
                'limitComments': max_line_length_affect_comments
            }
        }
        coffee_configs['arrow_spacing'] = ({
            'level':
            'error' if space_before_and_after_arrow else 'ignore'
        })
        if check_braces_spacing:
            coffee_configs['braces_spacing'] = ({
                'level':
                'error',
                'spaces':
                braces_spacing_width,
                'empty_object_spaces':
                spacing_in_empty_braces
            })
        if class_naming_camelCase:
            coffee_configs['camel_case_classes'] = {'level': 'error'}
        if spaces_before_and_after_colon:
            coffee_configs['colon_assignment_spacing'] = ({
                'level': 'error',
                'spacing': {
                    'left': spaces_before_colon,
                    'right': spaces_after_colon
                }
            })
        coffee_configs['eol_last'] = ({
            'level':
            'error' if enforce_newline_at_EOF else 'ignore'
        })
        coffee_configs['newlines_after_classes'] = ({
            'value': number_of_newlines_after_classes,
            'level': 'error'
        })
        coffee_configs['no_backticks'] = ({
            'level':
            'error' if prohibit_embedding_javascript_snippet else 'ignore'
        })
        if force_braces:
            coffee_configs['no_implicit_braces'] = ({
                'level': 'error',
                'strict': True
            })
        if not allow_implicit_parentheses:
            coffee_configs['no_implicit_parens'] = ({
                'strict': True,
                'level': 'error'
            })
        coffee_configs['no_interpolation_in_single_quotes'] = ({
            'level':
            'error' if not allow_interpolation_in_single_quotes else 'ignore'
        })
        if not allow_stand_alone_at_sign:
            coffee_configs['no_stand_alone_at'] = {'level': 'error'}
        if use_spaces:
            coffee_configs['no_tabs'] = {'level': 'error'}
        coffee_configs['indentation'] = ({
            'value': indent_size,
            'level': 'error'
        })
        coffee_configs['no_throwing_strings'] = ({
            'level':
            'error' if not allow_throwing_strings else 'ignore'
        })
        coffee_configs['no_trailing_semicolons'] = ({
            'level':
            'error' if not allow_trailing_semicolons else 'ignore'
        })
        if not allow_trailing_whitespaces:
            coffee_configs['no_trailing_whitespace'] = ({
                'level':
                'error',
                'allowed_in_comments':
                True,
                'allowed_in_empty_lines':
                True
            })
        if not allow_unnecessary_double_quotes:
            coffee_configs['no_unnecessary_double_quotes'] = {'level': 'error'}
        if not allow_bitwise_operators:
            coffee_configs['prefer_english_operator'] = ({
                'level':
                'error',
                'doubleNotLevel':
                'ignore'
            })
        if spaces_around_operators:
            coffee_configs['space_operators'] = {'level': 'error'}
        if space_after_comma:
            coffee_configs['spacing_after_comma'] = {'level': 'warn'}
        coffee_configs['cyclomatic_complexity'] = ({
            'value':
            cyclomatic_complexity,
            'level': ('error' if cyclomatic_complexity else 'ignore')
        })
        coffee_configs['duplicate_key'] = ({
            'level':
            'error' if prevent_duplicate_keys else 'ignore'
        })
        if enforce_parentheses_on_non_empty_constructors:
            coffee_configs['non_empty_constructor_needs_parens'] = ({
                'level':
                'error'
            })
        if consistent_line_endings_style:
            coffee_configs['line_endings'] = ({
                'level':
                'error',
                'value':
                consistent_line_endings_style
            })
        if not allow_this_statements:
            coffee_configs['no_this'] = {'level': 'error'}
        if not allow_increment:
            coffee_configs['no_plusplus'] = {'level': 'error'}
        coffee_configs['no_empty_param_list'] = ({
            'level':
            'error' if not allow_no_parameters else 'ignore'
        })
        coffee_configs['no_empty_functions'] = ({
            'level':
            'error' if not allow_empty_functions else 'ignore'
        })

        return json.dumps(coffee_configs)

    def process_output(self, output, filename, file):
        output = json.loads(output)

        assert len(output) == 1, (
            'More than 1 file parsed, something went wrong')
        for item in tuple(output.values())[0]:
            yield Result.from_values(
                origin='{} ({})'.format(self.name, item['rule']),
                message=item['message'],
                file=filename,
                line=item.get('lineNumber', None),
                end_line=item.get('lineNumberEnd', None),
                severity=self.severity_map[item['level']],
                additional_info=item.get('description',
                                         item.get('context', '')))
Exemplo n.º 15
0
class JSHintBear:
    """
    Detect errors and potential problems in JavaScript code and to enforce
    appropriate coding conventions. For example, problems like syntax errors,
    bugs due to implicit type conversion, leaking variables and much more
    can be detected.

    For more information on the analysis visit <http://jshint.com/>
    """

    LANGUAGES = {'JavaScript'}
    REQUIREMENTS = {NpmRequirement('jshint', '2.9.5')}
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL-3.0'
    CAN_DETECT = {'Formatting', 'Syntax', 'Complexity', 'Unused Code'}

    @staticmethod
    @deprecate_settings(
        es_version='use_es6_syntax',
        javascript_strictness=('allow_global_strict', lambda x: 'global'
                               if x else True),
        cyclomatic_complexity='maxcomplexity',
        allow_unused_variables=('prohibit_unused', negate),
        max_parameters='maxparams',
        allow_missing_semicolon='allow_missing_semicol',
        allow_this_statements='allow_this_stmt',
        allow_with_statements='allow_with_stmt',
        allow_bitwise_operators=('prohibit_bitwise', negate),
        max_statements='maxstatements',
        max_depth='maxdepth',
        allow_comma_operator=('prohibit_comma', negate),
        allow_non_breaking_whitespace=('prohibit_non_breaking_whitespace',
                                       negate),
        allow_prototype_overwrite=('prohibit_prototype_overwrite', negate),
        allow_type_coercion=('prohibit_type_coercion', negate),
        allow_future_identifiers=('future_hostile', negate),
        allow_typeof=('prohibit_typeof', negate),
        allow_var_statement=('prohibit_variable_statements', negate),
        allow_grouping_operator=('prohibit_groups', negate),
        allow_variable_shadowing='shadow',
        use_mozilla_extension='using_mozilla',
        allow_constructor_functions=('prohibit_new', negate),
        allow_argument_caller_and_callee=('prohibit_arg', negate),
        allow_iterator_property=('iterator', negate),
        allow_filter_in_forin='force_filter_forin')
    def generate_config(filename,
                        file,
                        allow_bitwise_operators: bool = False,
                        allow_prototype_overwrite: bool = False,
                        force_braces: bool = True,
                        allow_type_coercion: bool = False,
                        allow_future_identifiers: bool = True,
                        allow_typeof: bool = True,
                        allow_filter_in_forin: bool = True,
                        allow_funcscope: bool = False,
                        allow_iterator_property: bool = True,
                        allow_argument_caller_and_callee: bool = False,
                        allow_comma_operator: bool = True,
                        allow_non_breaking_whitespace: bool = False,
                        allow_constructor_functions: bool = True,
                        allow_grouping_operator: bool = True,
                        allow_var_statement: bool = True,
                        allow_missing_semicolon: bool = False,
                        allow_debugger: bool = False,
                        allow_assignment_comparisions: bool = False,
                        allow_eval: bool = False,
                        allow_increment: bool = False,
                        allow_proto: bool = False,
                        allow_scripturls: bool = False,
                        allow_singleton: bool = False,
                        allow_this_statements: bool = False,
                        allow_with_statements: bool = False,
                        use_mozilla_extension: bool = False,
                        javascript_strictness: bool_or_str = True,
                        allow_noyield: bool = False,
                        allow_eqnull: bool = False,
                        allow_last_semicolon: bool = False,
                        allow_func_in_loop: bool = False,
                        allow_expr_in_assignments: bool = False,
                        use_es3_array: bool = False,
                        environment_mootools: bool = False,
                        environment_couch: bool = False,
                        environment_jasmine: bool = False,
                        environment_jquery: bool = False,
                        environment_node: bool = False,
                        environment_qunit: bool = False,
                        environment_rhino: bool = False,
                        environment_shelljs: bool = False,
                        environment_prototypejs: bool = False,
                        environment_yui: bool = False,
                        environment_mocha: bool = True,
                        environment_module: bool = False,
                        environment_wsh: bool = False,
                        environment_worker: bool = False,
                        environment_nonstandard: bool = False,
                        environment_browser: bool = True,
                        environment_browserify: bool = False,
                        environment_devel: bool = True,
                        environment_dojo: bool = False,
                        environment_typed: bool = False,
                        environment_phantom: bool = False,
                        max_statements: bool_or_int = False,
                        max_depth: bool_or_int = False,
                        max_parameters: bool_or_int = False,
                        cyclomatic_complexity: bool_or_int = False,
                        allow_variable_shadowing: bool_or_str = False,
                        allow_unused_variables: bool_or_str = False,
                        allow_latedef: bool_or_str = False,
                        enforce_trailing_comma: bool = False,
                        es_version: bool_or_int = 5,
                        jshint_config: str = ''):
        """
        :param allow_bitwise_operators:
            Allows the use of bitwise operators.
        :param allow_prototype_overwrite:
            This options allows overwriting prototypes of native objects such
            as ``Array``.
        :param force_braces:
            This option requires you to always put curly braces around blocks
            in loops and conditionals.
        :param allow_type_coercion:
            This options allows the use of ``==`` and ``!=``.
        :param allow_future_identifiers:
            This option allows the use of identifiers which are defined in
            future versions of JavaScript.
        :param allow_typeof:
            This option enables warnings about invalid ``typeof`` operator
            values.
        :param allow_filter_in_forin:
            This option requires all ``for in`` loops to filter object's items.
        :param allow_iterator_property:
            This option suppresses warnings about the ``__iterator__``
            property.
        :param allow_funcscope:
            This option suppresses warnings about declaring variables inside of
            control structures while accessing them later from outside.
        :param allow_argument_caller_and_callee:
            This option allows the use of ``arguments.caller`` and
            ``arguments.callee``.
        :param allow_comma_operator:
            This option allows the use of the comma operator.
        :param allow_non_breaking_whitespace:
            Allows "non-breaking whitespace characters".
        :param allow_constructor_functions:
            Allows the use of constructor functions.
        :param allow_grouping_operator:
            This option allows the use of the grouping operator when it is
            not strictly required.
        :param allow_var_statement:
            Allows the use of the ``var`` statement while declaring a variable.
            Should use ``let`` or ``const`` while it is set to ``False``.
        :param allow_missing_semicolon:
            This option suppresses warnings about missing semicolons.
        :param allow_debugger:
            This option suppresses warnings about the ``debugger`` statements.
        :param allow_assignment_comparisions:
            This option suppresses warnings about the use of assignments in
            cases where comparisons are expected.
        :param allow_eval:
            This options suppresses warnings about the use of ``eval``
            function.
        :param allow_increment:
            This option suppresses warnings about the use of unary increment
            and decrement operators.
        :param allow_proto:
            This option suppresses warnings about the ``__proto__`` property.
        :param allow_scripturls:
            This option suppresses warnings about the use of script-targeted
            URLs.
        :param allow_singleton:
            This option suppresses warnings about constructions like
            ``new function () { ... }`` and ``new Object;`` sometimes used to
            produce singletons.
        :param allow_this_statements:
            This option suppresses warnings about possible strict violations
            when the code is running in strict mode and ``this`` is used in a
            non-constructor function.
        :param allow_with_statements:
            This option suppresses warnings about the use of the ``with``
            statement.
        :param use_mozilla_extension:
            This options tells JSHint that your code uses Mozilla JavaScript
            extensions.
        :param javascript_strictness:
            Determines what sort of strictness to use in the JavaScript code.
            The possible options are:

            - "global" - there must be a ``"use strict";`` at global level
            - "implied" - lint the code as if there is a ``"use strict";``
            - "False" - disable warnings about strict mode
            - "True" - there must be a ``"use strict";`` at function level
        :param allow_noyield:
            This option suppresses warnings about generator functions with no
            ``yield`` statement in them.
        :param allow_eqnull:
            This option suppresses warnings about ``== null`` comparisons.
        :param allow_last_semicolon:
            This option suppresses warnings about missing semicolons for the
            last statement.
        :param allow_func_in_loop:
            This option suppresses warnings about functions inside of loops.
        :param allow_expr_in_assignments:
            This option suppresses warnings about the use of expressions where
            normally assignments or function calls are expected.
        :param use_es3_array:
            This option tells JSHintBear ES3 array elision elements, or empty
            elements are used.
        :param environment_mootools:
            This option defines globals exposed by the Mootools.
        :param environment_couch:
            This option defines globals exposed by CouchDB.
        :param environment_jasmine:
            This option defines globals exposed by Jasmine.
        :param environment_jquery:
            This option defines globals exposed by Jquery.
        :param environment_node:
            This option defines globals exposed by Node.
        :param environment_qunit:
            This option defines globals exposed by Qunit.
        :param environment_rhino:
            This option defines globals exposed when the code is running inside
            rhino runtime environment.
        :param environment_shelljs:
            This option defines globals exposed by the ShellJS.
        :param environment_prototypejs:
            This option defines globals exposed by the Prototype.
        :param environment_yui:
            This option defines globals exposed by the YUI JavaScript
            Framework.
        :param environment_mocha:
            This option defines globals exposed by the "BDD" and "TDD" UIs of
            the Mocha unit testing framework.
        :param environment_module:
            This option informs JSHintBear that the input code describes an
            ECMAScript 6 module.
        :param environment_wsh:
            This option defines globals available when the code is running as a
            script for the Windows Script Host.
        :param environment_worker:
            This option defines globals available when the code is running
            inside of a Web Worker.
        :param environment_nonstandard:
            This option defines non- standard but widely adopted globals such
            as ``escape`` and ``unescape``.
        :param environment_browser:
            This option defines globals exposed by modern browsers.
        :param environment_browserify:
            This option defines globals available when using the Browserify.
        :param environment_devel:
            This option defines globals that are usually used for debugging:
            ``console``, ``alert``, etc.
        :param environment_dojo:
            This option defines globals exposed by the Dojo Toolkit.
        :param environment_typed:
            This option defines globals for typed array constructors.
        :param environment_phantom:
            This option defines globals available when your core is running
            inside of the PhantomJS runtime environment.
        :param max_statements:
            Maximum number of statements allowed per function.
        :param max_depth:
            This option lets you control how nested do you want your blocks to
            be.
        :param max_parameters:
            Maximum number of parameters allowed per function.
        :param cyclomatic_complexity:
            Maximum cyclomatic complexity in the code.
        :param allow_variable_shadowing:
            This option suppresses warnings about variable shadowing i.e.
            declaring a variable that had been already declared somewhere in
            the outer scope.

            - "inner" - check for variables defined in the same scope only
            - "outer" - check for variables defined in outer scopes as well
            - False - same as inner
            - True  - allow variable shadowing
        :param allow_unused_variables:
            Allows when variables are defined but never used. This can be set
            to ""vars"" to only check for variables, not function parameters,
            or ""strict"" to check all variables and parameters.
        :param allow_latedef:
            This option allows the use of a variable before it was defined.
            Setting this option to "nofunc" will allow function declarations to
            be ignored.
        :param enforce_trailing_comma:
            This option warns when a comma is not placed after the last element
            in an array or object literal.
        :param es_version:
            This option is used to specify the ECMAScript version to which the
            code must adhere to.
        """
        # Assume that when es_version is bool, it is intended for the
        # deprecated use_es6_version
        if es_version is True:
            es_version = 6
        elif es_version is False:
            es_version = 5
        if not jshint_config:
            options = {
                'bitwise': not allow_bitwise_operators,
                'freeze': not allow_prototype_overwrite,
                'curly': force_braces,
                'eqeqeq': not allow_type_coercion,
                'futurehostile': not allow_future_identifiers,
                'notypeof': not allow_typeof,
                'forin': allow_filter_in_forin,
                'funcscope': allow_funcscope,
                'iterator': not allow_iterator_property,
                'noarg': not allow_argument_caller_and_callee,
                'nocomma': not allow_comma_operator,
                'nonbsp': not allow_non_breaking_whitespace,
                'nonew': not allow_constructor_functions,
                'undef': True,
                'singleGroups': not allow_grouping_operator,
                'varstmt': not allow_var_statement,
                'asi': allow_missing_semicolon,
                'debug': allow_debugger,
                'boss': allow_assignment_comparisions,
                'evil': allow_eval,
                'strict': javascript_strictness,
                'plusplus': allow_increment,
                'proto': allow_proto,
                'scripturl': allow_scripturls,
                'supernew': allow_singleton,
                'validthis': allow_this_statements,
                'withstmt': allow_with_statements,
                'moz': use_mozilla_extension,
                'noyield': allow_noyield,
                'eqnull': allow_eqnull,
                'lastsemic': allow_last_semicolon,
                'loopfunc': allow_func_in_loop,
                'expr': allow_expr_in_assignments,
                'elision': use_es3_array,
                'mootools': environment_mootools,
                'couch': environment_couch,
                'jasmine': environment_jasmine,
                'jquery': environment_jquery,
                'node': environment_node,
                'qunit': environment_qunit,
                'rhino': environment_rhino,
                'shelljs': environment_shelljs,
                'prototypejs': environment_prototypejs,
                'yui': environment_yui,
                'mocha': environment_mocha,
                'module': environment_module,
                'wsh': environment_wsh,
                'worker': environment_worker,
                'nonstandard': environment_nonstandard,
                'browser': environment_browser,
                'browserify': environment_browserify,
                'devel': environment_devel,
                'dojo': environment_dojo,
                'typed': environment_typed,
                'phantom': environment_phantom,
                'maxerr': 99999,
                'maxcomplexity': cyclomatic_complexity,
                'maxdepth': max_depth,
                'maxparams': max_parameters,
                'maxstatements': max_statements,
                'shadow': allow_variable_shadowing,
                'unused': not allow_unused_variables,
                'latedef': allow_latedef,
                'trailingcomma': enforce_trailing_comma,
                'esversion': es_version
            }

            return json.dumps(options)
        else:
            return None

    @staticmethod
    def create_arguments(filename, file, config_file, jshint_config: str = ''):
        """
        :param jshint_config:
            The location of the jshintrc config file. If this option is present
            all the above options are not used. Instead the .jshintrc file is
            used as the configuration file.
        """
        args = ('--verbose', filename, '--config')
        if jshint_config:
            args += (jshint_config, )
        else:
            args += (config_file, )
        return args
Exemplo n.º 16
0
class StylintBear:
    """
    Attempts to catch little mistakes (duplication of rules for instance) and
    enforces a code style guide on Stylus (a dynamic stylesheet language
    with the ``.styl`` extension that is compiled into CSS) files.

    The ``StylintBear`` is able to catch following problems:
    - Duplication of rules
    - Mixed spaces and tabs
    - Unnecessary brackets
    - Missing colon between property and value
    - Naming conventions
    - Trailing whitespace
    - Consistent quotation style
    - Use of extra spaces inside parenthesis
    - Naming convention when declaring classes, ids, and variables
    - Unnecessary leading zeroes on decimal points
    - Checks if a property is valid CSS or HTML
    """

    LANGUAGES = {'Stylus'}
    REQUIREMENTS = {NpmRequirement('stylint', '1.5.9')}
    AUTHORS = {'The coala developers'}
    AUTHORS_EMAILS = {'*****@*****.**'}
    LICENSE = 'AGPL-3.0'
    CAN_DETECT = {'Formatting', 'Syntax', 'Redundancy'}
    SEE_MORE = 'https://github.com/SimenB/stylint'

    @staticmethod
    def generate_config(
        filename,
        file,
        block_keyword: bool = None,
        brackets: bool = False,
        colons_for_property_declaration: bool = True,
        color_variables_for_hex_values: bool = True,
        spaces_after_commas: bool = True,
        spaces_after_comments: bool = True,
        allow_trailing_whitespace: bool = False,
        no_css_literals: bool = False,
        max_selector_depth: bool = False,
        check_duplicates: bool = True,
        efficient_properties: bool = True,
        extend_preference: str = None,
        indent_size: int = 0,
        leading_zero: bool = None,
        max_errors: int = 0,
        max_warnings: int = 0,
        mixed_spaces_and_tabs: bool = False,
        variable_naming_convention: str = None,
        strict_naming_convention: bool = False,
        none_keyword: bool = False,
        check_no_important_keyword: bool = True,
        spaces_inside_parentheses: bool = None,
        placeholder: bool = True,
        prefix_vars_with_dollar: bool = True,
        semicolons: bool = False,
        sort_order: str = 'alphabetical',
        stacked_properties: bool = False,
        check_property_validity: bool = True,
        preferred_quotation: str = None,
        zero_units: bool = False,
        z_index_normalize_base: int = 0,
        stylint_config: str = '',
    ):
        """
        :param block_keyword:
            When ``True`` expect the ``@block`` keyword when defining block
            variables. When ``False``, expect no ``@block`` keyword when
            defining block variables.
        :param brackets:
            When ``True``, expect ``{}`` when declaring a selector. When
            ``False``, expect no brackets when declaring a selector.
        :param colons_for_property_declaration:
            When ``True``, expect ``:`` when declaring a property. When
            ``False``, expect no ``:`` when declaring a property.
        :param color_variables_for_hex_values:
            When ``True``, enforce variables when defining hex values.
        :param spaces_after_commas:
            Enforce or disallow spaces after commas.
        :param spaces_after_comments:
            Enforce or disallow spaces after line comments.
            For example: If set to ``True``, prefer
            ``// comment`` over ``//comment``.
        :param allow_trailing_whitespace:
            If ``True``, ignores trailing whitespace. If ``False``, trailing
            whitespace will throw a warning.
        :param no_css_literals:
            By default Stylint ignores ``@css`` blocks. If set to ``True``
            however, warnings are thrown if ``@css`` is used.
        :param max_selector_depth:
            Set the max selector depth. If set to 4, max selector depth will
            be 4 indents. Pseudo selectors like ``&:first-child`` or
            ``&:hover`` won't count towards the limit.
        :param check_duplicates:
            Checks if selectors or properties are duplicated unnecessarily.
        :param efficient_properties:
            Check for places where properties can be written more efficiently.
        :param extend_preference:
            Pass in either ``@extend`` or ``@extends`` and then enforce that.
            Both are valid in Stylus. It doesn't really matter which one
            you use.
            For example: If set to ``@extends``, prefer
            ``@extends $some-var`` instead of ``@extend $some-var``
            or if set to ``@extend``, prefer
            ``@extend $some-var`` over ``@extends $some-var``.
        :param indent_size:
            This works in conjunction with ``max_selector_depth``. If you
            indent with spaces this is the number of spaces you indent with.
            If you use hard tabs, set this value to ``0``.
            For example: If set to ``2``, prefer
            ``/s/smargin: 0`` over ``/s/s/smargin: 0``.
        :param leading_zero:
            When ``True``, prefer leading zeroes on decimal points. When
            ``False``, disallow leading zeroes on decimal points.
        :param max_errors:
            Set maximum number of errors. If ``0``, all errors will
            be shown without a limit.
        :param max_warnings:
            Set maximum number of warnings. If ``0``, all errors will
            be shown without a limit.
        :param mixed_spaces_and_tabs:
            If a non-negative number is passed to ``indent_size``,
            soft tabs (i.e. spaces) are assumed, and if
            ``0`` is passed to ``indent_size``, hard tabs are assumed.
            For example: If ``indent_size = 4`` and
            ``mixed_spaces_and_tabs = True``, prefer
            ``/s/s/s/smargin 0`` over ``/tmargin 0``
            or if ``indent_size = 0`` and
            ``mixed_spaces_and_tabs = True``, prefer
            ``/tmargin 0`` over ``/s/s/s/smargin 0``.
        :param variable_naming_convention:
            Enforce a particular naming convention when declaring variables.
            Throws a warning if you don't follow the convention.
            Supported values are ``lowercase-dash``, ``lowercase_underscore``,
            ``camelCase`` and ``BEM``.
        :param strict_naming_convention:
            By default, ``variable_naming_convention`` only looks at variable
            names. If ``strict_naming_convention`` is set to ``True``,
            ``variable_naming_convention`` will also look at class and
            ID names.
        :param none_keyword:
            If ``True`` check for places where ``none`` used instead of ``0``.
            If ``False`` check for places where ``0`` could be used
            instead of ``none``.
        :param check_no_important_keyword:
            If ``True``, show warning when ``!important`` is found.
            For example: If set to ``True``, this will throw a warning::

                div
                    color red !important

        :param spaces_inside_parentheses:
            Enforce or disallow use of extra spaces inside parentheses.
            For example: If set to ``True``, prefer
            ``my-mixin( $myParam )`` over ``my-mixin($myParam)``
            or if set to ``False``, prefer
            ``my-mixin($myParam)`` over ``my-mixin( $myParam )``.
        :param placeholder:
            Enforce extending placeholder vars when using ``@extend(s)``.
        :param prefix_vars_with_dollar:
            Enforce use of ``$`` when defining a variable. In Stylus, using a
            ``$`` when defining a variable is optional, but is a good idea
            if you want to prevent ambiguity. Not including the ``$`` sets up
            situations where you wonder: "Is this a variable or a value?"
            For instance: ``padding $default`` is easier to understand than
            ``padding default``.
            For example: If set to ``True``, prefer
            ``$my-var = 0`` over ``my-var = 0``
            or if set to ``False``, prefer
            ``my-var = 0`` over ``$my-var = 0``.
        :param semicolons:
            When ``True``, enforce semicolons. When ``False``, disallow
            semicolons.
        :param sort_order:
            Enforce a particular sort order when declaring properties. Throws
            a warning if you don't follow the order.
            For example: If set to ``alphabetical``, prefer this::

                .some-class
                    display block
                    float left
                    position absolute
                    right 10px
                    top 0

            over this::

                .some-class
                    position absolute
                    top 0
                    right 10px
                    display block
                    float left

            Supported values are ``alphabetical`` and ``grouped``.
        :param stacked_properties:
            No one-liners. Enforce putting properties on new lines.
            For example: If set to ``False``, prefer::

                .className
                    padding 0

            over
            ``.className { padding 0 }``
        :param check_property_validity:
            Check that a property is valid CSS or HTML.
        :param preferred_quotation:
            Your preferred quotation character, e.g. ``double`` or ``single``.
        :param zero_units:
            Looks for instances of ``0px``. You don't need the ``px``.
            Checks all units, not just ``px``.
        :param z_index_normalize_base:
            Enforce some basic z-index sanity. Any number passed in
            will be used as the base for your z-index values.
            Use ``0`` to disable this feature.
            For example: If set to ``5``, prefer
            ``z-index 10`` over ``z-index 9``
            or if set to ``10``, prefer
            ``z-index 20`` over ``z-index 15``.
        """
        if stylint_config:
            return None
        else:
            options = {
                'blocks':
                _setting_map[block_keyword],
                'brackets':
                _setting_map[brackets],
                'colons':
                _setting_map[colons_for_property_declaration],
                'colors':
                _setting_map[color_variables_for_hex_values],
                'commaSpace':
                _setting_map[spaces_after_commas],
                'commentSpace':
                _setting_map[spaces_after_comments],
                'cssLiteral':
                _setting_map[no_css_literals],
                'depthLimit':
                max_selector_depth,
                'duplicates':
                check_duplicates,
                'efficient':
                _setting_map[efficient_properties],
                'extendPref':
                extend_preference,
                'indentPref':
                indent_size,
                'leadingZero':
                _setting_map[leading_zero],
                'maxErrors':
                max_errors,
                'maxWarnings':
                max_warnings,
                'mixed':
                mixed_spaces_and_tabs,
                'namingConvention':
                variable_naming_convention,
                'namingConventionStrict':
                strict_naming_convention,
                'none':
                _setting_map[none_keyword],
                'noImportant':
                check_no_important_keyword,
                'parenSpace':
                _setting_map[spaces_inside_parentheses],
                'placeholders':
                _setting_map[placeholder],
                'prefixVarsWithDollar':
                _setting_map[prefix_vars_with_dollar],
                'quotePref':
                preferred_quotation,
                'semicolons':
                _setting_map[semicolons],
                'sortOrder':
                sort_order,
                'stackedProperties':
                _setting_map[stacked_properties],
                'trailingWhitespace':
                False if allow_trailing_whitespace is True else 'never',
                'valid':
                check_property_validity,
                'zeroUnits':
                _setting_map[zero_units],
                'zIndexNormalize':
                False
                if z_index_normalize_base == 0 else z_index_normalize_base,
                'groupOutputByFile':
                True,
                'reporterOptions': {
                    'columns': ['lineData', 'severity', 'description', 'rule'],
                    'columnSplitter': '  ',
                    'showHeaders': False,
                    'truncate': True
                }
            }

            return json.dumps(options)

    @staticmethod
    def create_arguments(
        filename,
        file,
        config_file,
        stylint_config: str = '',
    ):
        """
        :param stylint_config:
            The location of the ``.stylintrc`` config file.
        """
        return ('--config', stylint_config if stylint_config else config_file,
                filename)