master 28f3cd0d5a97 cached
17 files
27.1 KB
7.4k tokens
24 symbols
1 requests
Download .txt
Repository: wemake-services/flake8-eradicate
Branch: master
Commit: 28f3cd0d5a97
Files: 17
Total size: 27.1 KB

Directory structure:
gitextract_1672ojvl/

├── .editorconfig
├── .github/
│   ├── dependabot.yml
│   └── workflows/
│       └── test.yml
├── .gitignore
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── flake8_eradicate.py
├── pyproject.toml
├── setup.cfg
└── tests/
    ├── conftest.py
    ├── fixtures/
    │   ├── correct.py
    │   ├── correct_no_comment.py
    │   └── incorrect.py
    ├── test_comments.py
    └── test_version.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .editorconfig
================================================
# Check http://editorconfig.org for more information
# This is the main config file for this project:
root = true

[*]
charset = utf-8
trim_trailing_whitespace = true
end_of_line = lf
indent_style = space
insert_final_newline = true
indent_size = 2

[*.py]
indent_size = 4


================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
- package-ecosystem: pip
  directory: "/"
  schedule:
    interval: daily
    time: "02:00"
  open-pull-requests-limit: 10
- package-ecosystem: github-actions
  directory: "/"
  schedule:
    interval: daily
    time: "02:00"


================================================
FILE: .github/workflows/test.yml
================================================
name: test

on:
  push:
    branches:
      - master
  pull_request:
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ['3.8', '3.9', '3.10', '3.11', '3.12']

    steps:
    - uses: actions/checkout@v4
    - name: Set up Python ${{ matrix.python-version }}
      uses: actions/setup-python@v5
      with:
        python-version: ${{ matrix.python-version }}

    - name: Install poetry
      run: |
        curl -sSL "https://install.python-poetry.org" | python

        # Adding `poetry` to `$PATH`:
        echo "$HOME/.poetry/bin" >> $GITHUB_PATH

    - name: Install dependencies
      run: |
        poetry config virtualenvs.in-project true
        poetry run pip install -U pip
        poetry install

    - name: Run tests
      run: |
        poetry run flake8 .
        poetry run mypy flake8_eradicate.py
        poetry run pytest
        poetry check
        poetry run pip check

    - name: Upload coverage to Codecov
      if: matrix.python-version == 3.12
      uses: codecov/codecov-action@v5
      with:
        file: ./coverage.xml


================================================
FILE: .gitignore
================================================
#### joe made this: http://goel.io/joe
#### python ####
# Byte-compiled / optimized / DLL files
.pytest_cache
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
#### macos ####
# General
*.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon


# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
#### windows ####
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db

# Dump file
*.stackdump

# Folder config file
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msm
*.msp

# Windows shortcuts
*.lnk
#### linux ####
*~

# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*

# KDE directory preferences
.directory

# Linux trash folder which might appear on any partition or disk
.Trash-*

# .nfs files are created when an open file is removed but is still being accessed
.nfs*
#### jetbrains ####
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff:
.idea/

## File-based project format:
*.iws

## Plugin-specific files:

# IntelliJ
/out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Cursive Clojure plugin
.idea/replstate.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties


================================================
FILE: CHANGELOG.md
================================================
# Version history

We follow Semantic Versions since the `0.1.0` release.


## 1.5.0

### Features

- Drops `python3.7` support, because it has almost reached its EOL
- Adds `flake8@6` support and drops support of `flake8<5`

### Misc

- Updates many dependencies


## 1.4.0

### Features

- Drops `python3.6` support
- Switches from `pkg_resources` to `importlib_metadata`

### Misc

- Uses `poetry@1.2`


## 1.3.0

### Features

- Adds `flake8@5.0` support


## 1.2.1

### Bugfixes

- Adds `setuptools` in the dependencies


## 1.2.0

### Features

- Adds `flake8@4.0.0` support
- Adds `python3.10` support


## 1.1.0

### Features

- Improves performance on long files #210


## 1.0.0

### Features

- Adds `python3.9` support
- Now using new `eradicate` API
- Adds `--eradicate-whitelist` and `--eradicate-whitelist-append` options

### Misc

- Moves to Github Actions


## 0.4.0

### Features

- Adds `python3.5` support


## 0.3.0

### Features

- Adds `python3.8` support


## 0.2.4

### Bugfixes

- Fixes that some lines inside the docstrings were marked as commented out code


## 0.2.3

### Bugfixes

- Fixed `argparse` bug, see [#76](https://github.com/sobolevn/flake8-eradicate/issues/76)


## 0.2.2

### Bugfixes

- Now `eradicate-aggressive` is parsed from config


## 0.2.1

### Features

- Updates to `flake8 >= 3.7`
- Updates `attrs < 20`
- Fixes plugin to work with `stdin`

### Misc

- Changes how we use `flake8`, moves from `pytest-flake8` to native CLI


## Version 0.2.0

### Features

- Adds `aggressive` configuration option
- Upgrades `eradicate` to `1.0`


## Version 0.1.2

### Misc

- Improves readme
- Improves tests


## Version 0.1.1

### Bugfixes

- Relies on `attrs` explicitly, see [#2](https://github.com/sobolevn/flake8-eradicate/issues/2)

### Misc

- Improves readme
- Improves tests


## Version 0.1.0

- Initial release


================================================
FILE: CONTRIBUTING.md
================================================
# How to contribute

If you want to start working on this project,
you will need to get familiar with these APIs:

- [Writing a `flake8` plugin](http://flake8.pycqa.org/en/latest/plugin-development/)
- [Using `ast` module](https://docs.python.org/3/library/ast.html)

It is also recommended to take a look at these resources:

- [Missing `ast` guide](https://greentreesnakes.readthedocs.io/en/latest/)


## Dependencies

We use [`poetry`](https://github.com/sdispater/poetry) to manage the dependencies.

To install them you would need to run two commands:

```bash
poetry install
poetry develop
```

To activate your `virtualenv` run `poetry shell`.


## Tests

We use `pytest` and `flake8` for quality control.
We also use `wemake_python_styleguide` itself
to develop `wemake_python_styleguide`.

To run all tests:

```bash
pytest
```

This step is mandatory during the CI.


## Type checks

We use `mypy` to run type checks on our code.
To use it:

```bash
mypy flake8_eradicate.py
```

This step is mandatory during the CI.


## Before submitting

Before submitting your code please do the following steps:

1. Run `pytest` to make sure everything was working before
2. Add any changes you want
3. Adds tests for the new changes
4. Edit documentation if you have changed something significant
5. Run `pytest` again to make sure it is still working
6. Run `mypy` to ensure that types are correct


## Other help

You can contribute by spreading a word about this library.
It would also be a huge contribution to write
a short article on how you are using this project.
What are your best-practices?


================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2018 Nikita Sobolev

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: README.md
================================================
# flake8-eradicate

[![wemake.services](https://img.shields.io/badge/-wemake.services-green.svg?label=%20&logo=data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC%2FxhBQAAAAFzUkdCAK7OHOkAAAAbUExURQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP%2F%2F%2F5TvxDIAAAAIdFJOUwAjRA8xXANAL%2Bv0SAAAADNJREFUGNNjYCAIOJjRBdBFWMkVQeGzcHAwksJnAPPZGOGAASzPzAEHEGVsLExQwE7YswCb7AFZSF3bbAAAAABJRU5ErkJggg%3D%3D)](https://wemake-services.github.io)
[![Build Status](https://github.com/wemake-services/flake8-eradicate/workflows/test/badge.svg?branch=master&event=push)](https://github.com/wemake-services/flake8-eradicate/actions?query=workflow%3Atest)
[![codecov](https://codecov.io/gh/wemake-services/flake8-eradicate/branch/master/graph/badge.svg)](https://codecov.io/gh/wemake-services/flake8-eradicate)
[![Python Version](https://img.shields.io/pypi/pyversions/flake8-eradicate.svg)](https://pypi.org/project/flake8-eradicate/)
[![PyPI version](https://badge.fury.io/py/flake8-eradicate.svg)](https://pypi.org/project/flake8-eradicate/)
[![wemake-python-styleguide](https://img.shields.io/badge/style-wemake-000000.svg)](https://github.com/wemake-services/wemake-python-styleguide)

`flake8` plugin to find commented out (or so called "dead") code.

This is quite important for the project in a long run.
Based on [`eradicate`](https://github.com/myint/eradicate) project.


## Installation

```bash
pip install flake8-eradicate
```

It is also a valuable part of [`wemake-python-styleguide`](https://github.com/wemake-services/wemake-python-styleguide).


## Usage

Run your `flake8` checker [as usual](http://flake8.pycqa.org/en/latest/user/invocation.html).
Commented code should raise an error.

Example:

```bash
flake8 your_module.py
```


## Options

- `--eradicate-aggressive` to enable aggressive mode from `eradicate`, can lead to false positives
- `--eradicate-whitelist` to overwrite the whitelist from `eradicate` (`#` separated list)
- `--eradicate-whitelist-extend` to extend the whitelist from `eradicate` (`#` separated list)


## Error codes

| Error code |        Description       |
|:----------:|:------------------------:|
|    E800    | Found commented out code |


## Output example

Here's how output looks like (we are using [`wemake` formatter](https://wemake-python-styleguide.rtfd.io/en/latest/pages/usage/formatter.html)):



![flake8-eradicate output](https://raw.githubusercontent.com/wemake-services/flake8-eradicate/master/eradicate.png)


## License

MIT.


================================================
FILE: flake8_eradicate.py
================================================
import tokenize
from importlib import metadata as importlib_metadata
from typing import (
    Any,
    ClassVar,
    Dict,
    Iterable,
    Iterator,
    List,
    Optional,
    Sequence,
    Tuple,
    Type,
)

from eradicate import Eradicator
from flake8.options.manager import OptionManager

#: This is a name that we use to install this library:
pkg_name = 'flake8-eradicate'

#: We store the version number inside the `pyproject.toml`:
pkg_version = importlib_metadata.version(pkg_name)


class Checker(object):
    """Flake8 plugin to find commented out code."""

    name = pkg_name
    version = pkg_version

    _error_template = 'E800 Found commented out code'

    options: ClassVar[Optional[Dict[str, Any]]] = None  # type: ignore

    def __init__(
        self,
        tree,  # that's the hack we use to trigger this check
        file_tokens: List[tokenize.TokenInfo],
        lines: Sequence[str],
    ) -> None:
        """
        ``flake8`` plugin constructor.

        Arguments:
            file_tokens: all tokens for this file.
            lines: all file lines.

        """
        self._file_tokens = file_tokens
        self._lines = lines
        self._options = {
            'aggressive': self.options.eradicate_aggressive,  # type: ignore
        }

        self._eradicator = Eradicator()

        whitelist = self.options.eradicate_whitelist  # type: ignore
        whitelist_ext = self.options.eradicate_whitelist_extend  # type: ignore

        if whitelist_ext:
            self._eradicator.update_whitelist(
                whitelist_ext.split('#'),
                extend_default=True,
            )
        elif whitelist:
            self._eradicator.update_whitelist(
                whitelist.split('#'),
                extend_default=False,
            )

    @classmethod
    def add_options(cls, parser: OptionManager) -> None:
        """
        ``flake8`` api method to register new plugin options.

        See :class:`.Configuration` docs for detailed options reference.

        Arguments:
            parser: ``flake8`` option parser instance.

        """
        parser.add_option(
            '--eradicate-aggressive',
            default=False,
            help=(
                'Enables aggressive mode for eradicate; '
                'this may result in false positives'
            ),
            action='store_true',
            parse_from_config=True,
        )
        parser.add_option(
            '--eradicate-whitelist',
            default=False,
            help=(
                'String of "#" separated comment beginnings to whitelist '
                'for eradicate. '
                'Single parts are interpreted as regex. '
                'OVERWRITING the default whitelist: {0}'
            ).format(Eradicator.DEFAULT_WHITELIST),
            action='store',
            parse_from_config=True,
        )
        parser.add_option(
            '--eradicate-whitelist-extend',
            default=False,
            help=(
                'String of "#" separated comment beginnings to whitelist '
                'for eradicate. '
                'Single parts are interpreted as regex. '
                'Overwrites --eradicate-whitelist. '
                'EXTENDING the default whitelist: {0} '
            ).format(Eradicator.DEFAULT_WHITELIST),
            action='store',
            parse_from_config=True,
        )

    @classmethod
    def parse_options(cls, options) -> None:
        """Parses registered options for providing them to each visitor."""
        cls.options = options

    def run(self) -> Iterator[Tuple[int, int, str, Type['Checker']]]:
        """Runs on each step of flake8."""
        for line_no in self._lines_with_commented_out_code():
            yield line_no, 0, self._error_template, type(self)

    def _lines_with_commented_out_code(self) -> Iterable[int]:
        """
        Yield the physical line number that contain commented out code.

        This test relies on eradicate function to remove commented out code
        from a physical line.

        Physical lines might appear like commented code although they are part
        of a multi-line docstring (e.g. a `# noqa: DAR201` comment to suppress
        flake8 warning about missing returns in the docstring).
        To prevent this false-positive, the tokens of the physical line are
        checked for a comment. The eradicate function is only invokes,
        when the tokens indicate a comment in the physical line.
        """
        comment_in_file = any(
            token.type == tokenize.COMMENT
            for token in self._file_tokens
        )

        if comment_in_file:
            for line_no, line in enumerate(self._lines):
                filtered_source = ''.join(
                    self._eradicator.filter_commented_out_code(
                        line,
                        aggressive=self._options['aggressive'],
                    ),
                )
                if line != filtered_source:
                    yield line_no + 1


================================================
FILE: pyproject.toml
================================================
[tool.poetry]
name = "flake8-eradicate"
version = "1.5.0"
description = "Flake8 plugin to find commented out code"

license = "MIT"

authors = [
  "Nikita Sobolev <mail@sobolevn.me>"
]

readme = "README.md"

repository = "https://github.com/wemake-services/flake8-eradicate"
homepage = "https://github.com/wemake-services/flake8-eradicate"

keywords = [
  "flake8",
  "plugin",
  "linting",
  "wemake.services",
  "code quality"
]

classifiers = [
  "Development Status :: 5 - Production/Stable",
  "Environment :: Console",
  "Framework :: Flake8",
  "Intended Audience :: Developers",
  "Operating System :: OS Independent",
  "Topic :: Software Development :: Libraries :: Python Modules",
  "Topic :: Software Development :: Quality Assurance",
]

[tool.poetry.urls]
"Funding" = "https://opencollective.com/wemake-python-styleguide"

[tool.poetry.dependencies]
python = "^3.8"

flake8 = ">5"
eradicate = "^2.0"
attrs = "*"

[tool.poetry.group.test.dependencies]
pytest = ">=7.3,<9.0"
pytest-cov = ">=4,<6"
pytest-randomly = "^3.12"

mypy = "^1.3"
safety = ">=2.3,<4.0"

[tool.poetry.plugins."flake8.extension"]
E8 = "flake8_eradicate:Checker"


[build-system]
requires = ["poetry-core>=1.6.0"]
build-backend = "poetry.core.masonry.api"


================================================
FILE: setup.cfg
================================================
# All configuration for plugins and other utils is defined here.
# Read more about `setup.cfg`:
# https://docs.python.org/3/distutils/configfile.html


[flake8]
show-source = True
statistics = False
doctests = True

# Flake plugins:
max-complexity = 6
max-line-length = 80
inline-quotes = single
eradicate-aggressive = True

exclude =
  .git
  __pycache__
  .venv
  .eggs
  *.egg
  tests/fixtures

ignore =
  # Disable some pydocstyle checks:
  D100 D104 D106 D401


[tool:pytest]
# py.test options:
norecursedirs = tests/fixtures *.egg .eggs dist build docs .tox .git __pycache__

# You will need to measure your tests speed with `-n auto` and without it,
# so you can see whether it gives you any performance gain, or just gives
# you an overhead. See `docs/template/development-process.rst`.
addopts =
  --doctest-modules
  --cov=flake8_eradicate
  --cov-branch
  --cov-report=term:skip-covered
  --cov-report=html
  --cov-report=xml
  --cov-fail-under=100


[isort]
# isort configuration:
# https://github.com/timothycrosley/isort/wiki/isort-Settings
profile = wemake


[mypy]
# The mypy configurations: http://bit.ly/2zEl9WI
enable_error_code = truthy-bool, redundant-expr, unused-awaitable

allow_redefinition = false
check_untyped_defs = true
disallow_untyped_decorators = true
disallow_any_explicit = true
disallow_any_generics = true
disallow_untyped_calls = true
ignore_errors = false
ignore_missing_imports = true
implicit_reexport = false
local_partial_types = true
strict_optional = true
strict_equality = true
no_implicit_optional = true
# We use `type: ignore` to get `importlib.metadata` version.
warn_unused_ignores = false
warn_redundant_casts = true
warn_unused_configs = true
warn_unreachable = true
warn_no_return = true


================================================
FILE: tests/conftest.py
================================================
import os
import tokenize
from typing import List

import pytest


@pytest.fixture(scope='session')
def absolute_path():
    """Fixture to create full path relative to `contest.py` inside tests."""
    def factory(*files):
        dirname = os.path.dirname(__file__)
        return os.path.join(dirname, *files)
    return factory


@pytest.fixture(scope='session')
def get_file_tokens():
    """Fixture to generate tokens for a given filename."""
    def factory(filename: str) -> List[tokenize.TokenInfo]:
        with open(filename) as file_obj:
            return list(tokenize.generate_tokens(file_obj.readline))
    return factory


@pytest.fixture(scope='session')
def get_file_lines():
    """Fixture to read file into a sequence of lines for a given filename."""
    def factory(filename: str) -> List[str]:
        with open(filename) as file_obj:
            return file_obj.readlines()
    return factory


================================================
FILE: tests/fixtures/correct.py
================================================
# -*- coding: utf-8 -*-

"""
Some docs string in a module.

Some code example here:

>>> x = (1 / 2) * 2
>>> min(x, 0)
0

"""

class Some(object):
    """
    Docstring inside a class.

    Contains some code:

        instance = Some()
        print('Test', instance.other_property)

    """

    #: Doc comment with some code: property_name = 1
    property_name = 1

    # Regular comment with some code: other_property: int = 2
    other_property: int = 2

    def some_method(self) -> None:
        """Comment inside a method."""
        print('not True and not False')

        # Some logics: count(numbers) or print(False)
        print(12 + 23 / 3)


def some_function():
    """
    Test for noqa comments in docstrings.

    This function has a multi-line doc string, but no return value is
    stipulated, while the function defines a return. This would raise DAR201
    flake8 violation. To suppress this raise violation the following noqa
    comment is defined in the docstring.

    # noqa: DAR201

    This noqa comment should not be detected as commented out code. `eradicate`
    itself does not raise this as a violation.

    """
    return "something"


================================================
FILE: tests/fixtures/correct_no_comment.py
================================================
class Some(object):

    property_name = 1

    other_property: int = 2

    def some_method(self) -> None:
        print('not True and not False')

        print(12 + 23 / 3)


def some_function():
    return "something"


================================================
FILE: tests/fixtures/incorrect.py
================================================

class Some(object):
    # property_name = 1
    # typed_property: int = 10
    other_property = 2

# fmt: on

# def function_name():
#     return None

# fmt: off

# class CommentedClass(object):
#     def __init__(self, prop: int) -> None:
#         self.property = prop

#     def __str__(self) -> str:
#         return self.__class__.__name__

#    def set_prop(self, prop: int):
#        self.prop = prop

#    def get_prop(self):
#        return self.prop


================================================
FILE: tests/test_comments.py
================================================
import subprocess
from collections import namedtuple

from flake8_eradicate import Checker


def test_correct_fixture(absolute_path):
    """End-to-End test to check that correct code works."""
    filename = absolute_path('fixtures', 'correct.py')
    process = subprocess.Popen(
        [
            'flake8',
            '--isolated',
            '--show-source',
            '--select',
            'E8',
            filename,
        ],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    stdout, _ = process.communicate()

    assert stdout.count(b'E800') == 0


def test_incorrect_fixture(absolute_path):
    """End-to-End test to check that incorrect code raises warning."""
    filename = absolute_path('fixtures', 'incorrect.py')
    process = subprocess.Popen(
        [
            'flake8',
            '--isolated',
            '--show-source',
            '--select',
            'E8',
            filename,
        ],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    stdout, _ = process.communicate()

    assert stdout.count(b'E800') == 7
    assert b'# property_name = 1' in stdout
    assert b'# typed_property: int = 10' in stdout


def test_incorrect_fixture_aggressive(absolute_path):
    """End-to-End test to check that incorrect code raises warning."""
    filename = absolute_path('fixtures', 'incorrect.py')
    process = subprocess.Popen(
        [
            'flake8',
            '--eradicate-aggressive',
            '--isolated',
            '--show-source',
            '--select',
            'E8',
            filename,
        ],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    stdout, _ = process.communicate()
    assert stdout.count(b'E800') == 13
    assert b'# property_name = 1' in stdout
    assert b'# typed_property: int = 10' in stdout
    assert b'# def function_name():' in stdout
    assert b'# class CommentedClass(object):' in stdout


def test_incorrect_fixture_whitelist(absolute_path):
    """End-to-End test to check that incorrect code raises warning."""
    filename = absolute_path('fixtures', 'incorrect.py')
    process = subprocess.Popen(
        [
            'flake8',
            '--eradicate-whitelist',
            'just#overwrite',
            '--isolated',
            '--show-source',
            '--select',
            'E8',
            filename,
        ],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    stdout, _ = process.communicate()

    assert stdout.count(b'E800') == 9
    assert b'# property_name = 1' in stdout
    assert b'# typed_property: int = 10' in stdout
    assert b'# fmt: on' in stdout
    assert b'# fmt: off' in stdout


def test_incorrect_fixture_whitelist_extend(absolute_path):
    """End-to-End test to check that incorrect code raises warning."""
    filename = absolute_path('fixtures', 'incorrect.py')
    process = subprocess.Popen(
        [
            'flake8',
            '--eradicate-whitelist-extend',
            'return',
            '--isolated',
            '--show-source',
            '--select',
            'E8',
            filename,
        ],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    stdout, _ = process.communicate()

    assert stdout.count(b'E800') == 4
    assert b'# property_name = 1' in stdout
    assert b'return' not in stdout
    assert b'# typed_property: int = 10' in stdout


def test_lines_with_commented_out_code_incorrect_fixture_output(
    absolute_path,
    get_file_lines,
    get_file_tokens,
):
    """Verify central underlying method is returning correct output."""
    filename = absolute_path('fixtures', 'incorrect.py')

    OptionsStub = namedtuple(
        'Options',
        'eradicate_aggressive eradicate_whitelist eradicate_whitelist_extend',
    )
    Checker.options = OptionsStub(
        eradicate_aggressive=True,
        eradicate_whitelist=False,
        eradicate_whitelist_extend=False,
    )

    checker = Checker(
        tree=None,
        lines=get_file_lines(filename),
        file_tokens=get_file_tokens(filename),
    )
    output = list(checker._lines_with_commented_out_code())
    assert output == [3, 4, 9, 10, 14, 15, 16, 18, 19, 21, 22, 24, 25]


def test_lines_with_commented_out_code_file_no_comment(
    absolute_path,
    get_file_tokens,
    get_file_lines,
):
    """Make sure file without comment are ignored."""
    filename = absolute_path('fixtures', 'correct_no_comment.py')

    OptionsStub = namedtuple(
        'Options',
        'eradicate_aggressive eradicate_whitelist eradicate_whitelist_extend',
    )
    Checker.options = OptionsStub(
        eradicate_aggressive=True,
        eradicate_whitelist=False,
        eradicate_whitelist_extend=False,
    )

    checker = Checker(
        tree=None,
        lines=get_file_lines(filename),
        file_tokens=get_file_tokens(filename),
    )
    output = list(checker._lines_with_commented_out_code())
    assert output == []


================================================
FILE: tests/test_version.py
================================================
import subprocess

from flake8_eradicate import pkg_name, pkg_version


def test_call_flake8_version():
    """Checks that module is registered and visible in the meta data."""
    output = subprocess.check_output(
        ['flake8', '--version'],
        stderr=subprocess.STDOUT,
    )

    output_text = output.decode('utf-8')
    assert pkg_name in output_text
    assert pkg_version in output_text
Download .txt
gitextract_1672ojvl/

├── .editorconfig
├── .github/
│   ├── dependabot.yml
│   └── workflows/
│       └── test.yml
├── .gitignore
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── flake8_eradicate.py
├── pyproject.toml
├── setup.cfg
└── tests/
    ├── conftest.py
    ├── fixtures/
    │   ├── correct.py
    │   ├── correct_no_comment.py
    │   └── incorrect.py
    ├── test_comments.py
    └── test_version.py
Download .txt
SYMBOL INDEX (24 symbols across 7 files)

FILE: flake8_eradicate.py
  class Checker (line 26) | class Checker(object):
    method __init__ (line 36) | def __init__(
    method add_options (line 73) | def add_options(cls, parser: OptionManager) -> None:
    method parse_options (line 120) | def parse_options(cls, options) -> None:
    method run (line 124) | def run(self) -> Iterator[Tuple[int, int, str, Type['Checker']]]:
    method _lines_with_commented_out_code (line 129) | def _lines_with_commented_out_code(self) -> Iterable[int]:

FILE: tests/conftest.py
  function absolute_path (line 9) | def absolute_path():
  function get_file_tokens (line 18) | def get_file_tokens():
  function get_file_lines (line 27) | def get_file_lines():

FILE: tests/fixtures/correct.py
  class Some (line 14) | class Some(object):
    method some_method (line 31) | def some_method(self) -> None:
  function some_function (line 39) | def some_function():

FILE: tests/fixtures/correct_no_comment.py
  class Some (line 1) | class Some(object):
    method some_method (line 7) | def some_method(self) -> None:
  function some_function (line 13) | def some_function():

FILE: tests/fixtures/incorrect.py
  class Some (line 2) | class Some(object):

FILE: tests/test_comments.py
  function test_correct_fixture (line 7) | def test_correct_fixture(absolute_path):
  function test_incorrect_fixture (line 27) | def test_incorrect_fixture(absolute_path):
  function test_incorrect_fixture_aggressive (line 49) | def test_incorrect_fixture_aggressive(absolute_path):
  function test_incorrect_fixture_whitelist (line 73) | def test_incorrect_fixture_whitelist(absolute_path):
  function test_incorrect_fixture_whitelist_extend (line 99) | def test_incorrect_fixture_whitelist_extend(absolute_path):
  function test_lines_with_commented_out_code_incorrect_fixture_output (line 124) | def test_lines_with_commented_out_code_incorrect_fixture_output(
  function test_lines_with_commented_out_code_file_no_comment (line 151) | def test_lines_with_commented_out_code_file_no_comment(

FILE: tests/test_version.py
  function test_call_flake8_version (line 6) | def test_call_flake8_version():
Condensed preview — 17 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (30K chars).
[
  {
    "path": ".editorconfig",
    "chars": 273,
    "preview": "# Check http://editorconfig.org for more information\n# This is the main config file for this project:\nroot = true\n\n[*]\nc"
  },
  {
    "path": ".github/dependabot.yml",
    "chars": 246,
    "preview": "version: 2\nupdates:\n- package-ecosystem: pip\n  directory: \"/\"\n  schedule:\n    interval: daily\n    time: \"02:00\"\n  open-p"
  },
  {
    "path": ".github/workflows/test.yml",
    "chars": 1117,
    "preview": "name: test\n\non:\n  push:\n    branches:\n      - master\n  pull_request:\n  workflow_dispatch:\n\njobs:\n  build:\n    runs-on: u"
  },
  {
    "path": ".gitignore",
    "chars": 2857,
    "preview": "#### joe made this: http://goel.io/joe\n#### python ####\n# Byte-compiled / optimized / DLL files\n.pytest_cache\n__pycache_"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 1861,
    "preview": "# Version history\n\nWe follow Semantic Versions since the `0.1.0` release.\n\n\n## 1.5.0\n\n### Features\n\n- Drops `python3.7` "
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 1602,
    "preview": "# How to contribute\n\nIf you want to start working on this project,\nyou will need to get familiar with these APIs:\n\n- [Wr"
  },
  {
    "path": "LICENSE",
    "chars": 1071,
    "preview": "MIT License\n\nCopyright (c) 2018 Nikita Sobolev\n\nPermission is hereby granted, free of charge, to any person obtaining a "
  },
  {
    "path": "README.md",
    "chars": 2504,
    "preview": "# flake8-eradicate\n\n[![wemake.services](https://img.shields.io/badge/-wemake.services-green.svg?label=%20&logo=data%3Aim"
  },
  {
    "path": "flake8_eradicate.py",
    "chars": 5054,
    "preview": "import tokenize\nfrom importlib import metadata as importlib_metadata\nfrom typing import (\n    Any,\n    ClassVar,\n    Dic"
  },
  {
    "path": "pyproject.toml",
    "chars": 1240,
    "preview": "[tool.poetry]\nname = \"flake8-eradicate\"\nversion = \"1.5.0\"\ndescription = \"Flake8 plugin to find commented out code\"\n\nlice"
  },
  {
    "path": "setup.cfg",
    "chars": 1742,
    "preview": "# All configuration for plugins and other utils is defined here.\n# Read more about `setup.cfg`:\n# https://docs.python.or"
  },
  {
    "path": "tests/conftest.py",
    "chars": 917,
    "preview": "import os\nimport tokenize\nfrom typing import List\n\nimport pytest\n\n\n@pytest.fixture(scope='session')\ndef absolute_path():"
  },
  {
    "path": "tests/fixtures/correct.py",
    "chars": 1173,
    "preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nSome docs string in a module.\n\nSome code example here:\n\n>>> x = (1 / 2) * 2\n>>> min(x, 0)\n0"
  },
  {
    "path": "tests/fixtures/correct_no_comment.py",
    "chars": 222,
    "preview": "class Some(object):\n\n    property_name = 1\n\n    other_property: int = 2\n\n    def some_method(self) -> None:\n        prin"
  },
  {
    "path": "tests/fixtures/incorrect.py",
    "chars": 462,
    "preview": "\nclass Some(object):\n    # property_name = 1\n    # typed_property: int = 10\n    other_property = 2\n\n# fmt: on\n\n# def fun"
  },
  {
    "path": "tests/test_comments.py",
    "chars": 5005,
    "preview": "import subprocess\nfrom collections import namedtuple\n\nfrom flake8_eradicate import Checker\n\n\ndef test_correct_fixture(ab"
  },
  {
    "path": "tests/test_version.py",
    "chars": 403,
    "preview": "import subprocess\n\nfrom flake8_eradicate import pkg_name, pkg_version\n\n\ndef test_call_flake8_version():\n    \"\"\"Checks th"
  }
]

About this extraction

This page contains the full source code of the wemake-services/flake8-eradicate GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 17 files (27.1 KB), approximately 7.4k tokens, and a symbol index with 24 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!