Skip to content

Commit

Permalink
enhancement: make ansible-lint find custom rules from rules/custom/*/
Browse files Browse the repository at this point in the history
Make ansible-lint to find custom rules in rules/custom/*/ automatically
by default. Found custom rules will have higher priority than the
default rules.

This is an alternative way to accomplish the issue ansible#755.
  • Loading branch information
ssato committed Jul 28, 2020
1 parent edf8aaa commit f946a89
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
24 changes: 19 additions & 5 deletions lib/ansiblelint/__main__.py
Expand Up @@ -21,13 +21,18 @@
"""Command line implementation."""

import errno
import glob
import logging
import os.path
import pathlib
import sys
from typing import Any, Set

from ansiblelint import cli, formatters
from ansiblelint.constants import DEFAULT_RULESDIR
from ansiblelint.constants import (
DEFAULT_RULESDIR,
DEFAULT_CUSTOM_RULESDIR
)
from ansiblelint.generate_docs import rules_as_rst
from ansiblelint.rules import RulesCollection
from ansiblelint.runner import Runner
Expand Down Expand Up @@ -56,6 +61,18 @@ def initialize_logger(level: int = 0) -> None:
_logger.debug("Logging initialized to level %s", logging_level)


def get_rules_dirs(rulesdir, use_default):
"""Return a list of rules dirs."""
custom_rules_dirs = (
rdir for rdir in glob.glob(os.path.join(DEFAULT_CUSTOM_RULESDIR, '*'))
if os.path.isdir(rdir) and os.path.exists(os.path.join(rdir, "__init__.py"))
)
if use_default:
return rulesdir + sorted(custom_rules_dirs) + [DEFAULT_RULESDIR]

return rulesdir or sorted(custom_rules_dirs) + [DEFAULT_RULESDIR]


def main() -> int:
"""Linter CLI entry point."""
cwd = pathlib.Path.cwd()
Expand All @@ -77,10 +94,7 @@ def main() -> int:

formatter = formatter_factory(cwd, options.display_relative_path)

if options.use_default_rules:
rulesdirs = options.rulesdir + [DEFAULT_RULESDIR]
else:
rulesdirs = options.rulesdir or [DEFAULT_RULESDIR]
rulesdirs = get_rules_dirs(options.rulesdir, options.use_default_rules)
rules = RulesCollection(rulesdirs)

if options.listrules:
Expand Down
1 change: 1 addition & 0 deletions lib/ansiblelint/constants.py
Expand Up @@ -10,6 +10,7 @@
from typing_extensions import Literal

DEFAULT_RULESDIR = os.path.join(os.path.dirname(__file__), 'rules')
DEFAULT_CUSTOM_RULESDIR = os.path.join(DEFAULT_RULESDIR, "custom")

INVALID_CONFIG_RC = 2
ANSIBLE_FAILURE_RC = 3
Expand Down

0 comments on commit f946a89

Please sign in to comment.