Example #1
0
def test_markup_detection_tty_no(mocker: MockFixture) -> None:
    """Assures that if no tty is reported we disable markup."""
    mocker.patch("os.environ", {})
    mocker.patch("sys.stdout.isatty", return_value=False)
    assert not should_do_markup()
    mocker.resetall()
    mocker.stopall()
Example #2
0
def initialize_options(arguments: Optional[List[str]] = None) -> None:
    """Load config options and store them inside options module."""
    new_options = cli.get_config(arguments or [])
    new_options.cwd = pathlib.Path.cwd()

    if new_options.version:
        ansible_version, err = check_ansible_presence()
        print('ansible-lint {ver!s} using ansible {ansible_ver!s}'.format(
            ver=__version__, ansible_ver=ansible_version))
        if err:
            _logger.error(err)
            sys.exit(ANSIBLE_MISSING_RC)
        sys.exit(0)

    if new_options.colored is None:
        new_options.colored = should_do_markup()

    # persist loaded configuration inside options module
    for k, v in new_options.__dict__.items():
        setattr(options, k, v)

    # rename deprecated ids/tags to newer names
    options.tags = [normalize_tag(tag) for tag in options.tags]
    options.skip_list = [normalize_tag(tag) for tag in options.skip_list]
    options.warn_list = [normalize_tag(tag) for tag in options.warn_list]

    options.configured = True
    # 6 chars of entropy should be enough
    cache_key = hashlib.sha256(os.path.abspath(
        options.project_dir).encode()).hexdigest()[:6]
    options.cache_dir = "%s/ansible-lint/%s" % (
        os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache")),
        cache_key,
    )
Example #3
0
def initialize_options(arguments: List[str]):
    """Load config options and store them inside options module."""
    new_options = cli.get_config(arguments)
    new_options.cwd = pathlib.Path.cwd()

    if new_options.version:
        ansible_version, err = check_ansible_presence()
        print('ansible-lint {ver!s} using ansible {ansible_ver!s}'.format(
            ver=__version__, ansible_ver=ansible_version))
        if err:
            print(err, file=sys.stderr)
            sys.exit(ANSIBLE_MISSING_RC)
        sys.exit(0)

    if new_options.colored is None:
        new_options.colored = should_do_markup()

    # persist loaded configuration inside options module
    for k, v in new_options.__dict__.items():
        setattr(options, k, v)

    # rename deprecated ids/tags to newer names
    options.tags = [normalize_tag(tag) for tag in options.tags]
    options.skip_list = [normalize_tag(tag) for tag in options.skip_list]
    options.warn_list = [normalize_tag(tag) for tag in options.warn_list]
Example #4
0
def test_markup_detection_tty_yes(mocker: MockFixture) -> None:
    """Assures TERM=xterm enables markup."""
    mocker.patch("sys.stdout.isatty", return_value=True)
    mocker.patch("os.environ", {"TERM": "xterm"})
    assert should_do_markup()
    mocker.resetall()
    mocker.stopall()
Example #5
0
def initialize_options(arguments: List[str]):
    """Load config options and store them inside options module."""
    new_options = cli.get_config(arguments)
    new_options.cwd = pathlib.Path.cwd()

    if new_options.version:
        print('ansible-lint {ver!s}'.format(ver=__version__))
        # assure we fail if ansible is missing, even for version printing
        check_ansible_presence()
        sys.exit(0)

    if new_options.colored is None:
        new_options.colored = should_do_markup()

    # persist loaded configuration inside options module
    for k, v in new_options.__dict__.items():
        setattr(options, k, v)

    # rename deprecated ids/tags to newer names
    options.tags = [normalize_tag(tag) for tag in options.tags]
    options.skip_list = [normalize_tag(tag) for tag in options.skip_list]
    options.warn_list = [normalize_tag(tag) for tag in options.warn_list]
Example #6
0
def test_markup_detection_pycolors1() -> None:
    """Assure PY_COLORS=1 enables markup."""
    with pytest.MonkeyPatch.context() as monkeypatch:
        monkeypatch.setenv("PY_COLORS", "1")
        assert should_do_markup()
Example #7
0
def test_markup_detection_pycolors1(monkeypatch):
    """Assure PY_COLORS=1 enables markup."""
    monkeypatch.setenv("PY_COLORS", "1")
    assert should_do_markup()
Example #8
0
def test_markup_detection_pycolors0(monkeypatch):
    """Assure PY_COLORS=0 disables markup."""
    monkeypatch.setenv("PY_COLORS", "0")
    assert not should_do_markup()
Example #9
0
def main(argv: List[str] = None) -> int:
    """Linter CLI entry point."""
    if argv is None:
        argv = sys.argv

    options = cli.get_config(argv[1:])
    options.cwd = pathlib.Path.cwd()

    if options.version:
        print('ansible-lint {ver!s}'.format(ver=__version__))
        # assure we fail if ansible is missing, even for version printing
        check_ansible_presence()
        sys.exit(0)

    if options.colored is None:
        options.colored = should_do_markup()
    console_options["force_terminal"] = options.colored
    reconfigure(console_options)

    initialize_logger(options.verbosity)
    _logger.debug("Options: %s", options)

    app = App(options=options)

    prepare_environment()
    check_ansible_presence()

    # On purpose lazy-imports to avoid pre-loading Ansible
    # pylint: disable=import-outside-toplevel
    from ansiblelint.generate_docs import rules_as_rich, rules_as_rst
    from ansiblelint.rules import RulesCollection

    rules = RulesCollection(options.rulesdirs)

    if options.listrules:

        _rule_format_map = {
            'plain': str,
            'rich': rules_as_rich,
            'rst': rules_as_rst
        }

        console.print(_rule_format_map[options.format](rules), highlight=False)
        return 0

    if options.listtags:
        console.print(render_yaml(rules.listtags()))
        return 0

    if isinstance(options.tags, str):
        options.tags = options.tags.split(',')

    from ansiblelint.runner import _get_matches
    result = _get_matches(rules, options)

    mark_as_success = False
    if result.matches and options.progressive:
        _logger.info(
            "Matches found, running again on previous revision in order to detect regressions"
        )
        with _previous_revision():
            old_result = _get_matches(rules, options)
            # remove old matches from current list
            matches_delta = list(set(result.matches) - set(old_result.matches))
            if len(matches_delta) == 0:
                _logger.warning(
                    "Total violations not increased since previous "
                    "commit, will mark result as success. (%s -> %s)",
                    len(old_result.matches), len(matches_delta))
                mark_as_success = True

            ignored = 0
            for match in result.matches:
                # if match is not new, mark is as ignored
                if match not in matches_delta:
                    match.ignored = True
                    ignored += 1
            if ignored:
                _logger.warning(
                    "Marked %s previously known violation(s) as ignored due to"
                    " progressive mode.", ignored)

    app.render_matches(result.matches)

    return report_outcome(result,
                          mark_as_success=mark_as_success,
                          options=options)