Skip to content

Commit

Permalink
v0.1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
Author myslak71 committed Aug 2, 2019
0 parents commit 3101c7a
Show file tree
Hide file tree
Showing 16 changed files with 995 additions and 0 deletions.
108 changes: 108 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# Byte-compiled / optimized / DLL files
__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
MANIFEST

# 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/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# 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/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/

# PyCharm projects config
.idea

15 changes: 15 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
language: python
sudo: required
dist: xenial
python: "3.7"
cache: pip
install:
- pip install -r requirements-dev.txt
script:
- make flake8
- make mypy
- make yamllint
- pip install .
- make unittests
after_success: coveralls
1 change: 1 addition & 0 deletions CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* @myslak71 @kedod
19 changes: 19 additions & 0 deletions LICENSE.TXT
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
MIT License

Copyright (c) 2019 Kornel Szurek

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.
23 changes: 23 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
mypy: ## run mypy
mypy flake8_koles

flake8: ## run flake8
flake8 flake8_koles/

yamllint: # run yamllint
yamllint .

lint: mypy flake8 yamllint # run all linters

unittests: ## run pytest with coverage and -s flag for debugging
pytest --cov=flake8_koles.checker tests/ --cov-branch

coverage_report: ## display pytest coverage report
coverage report

coverage_html: ## create html coverage report and open it in the default browser
coverage html
xdg-open htmlcov/index.html



36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# flake8-koles

[![Build Status](https://travis-ci.org/myslak71/flake8-koles.svg?branch=master)](https://travis-ci.org/myslak71/flake8-koles)
[![Coverage Status](https://coveralls.io/repos/github/myslak71/flake8-koles/badge.svg?branch=master)](https://coveralls.io/github/myslak71/flake8-koles?branch=master)
![image](https://img.shields.io/badge/python-3.7-blue.svg)
![image](https://img.shields.io/badge/version-0.0.1-yellow)

Watch your language young pal!

Flake8 extension for checking bad language occurrences. Lists all swears found in the code and their location.
For now only english language is supported.

## Installation
flake8 is required for the installation.
```
pip install flake8-koles
```

## Usage
```
flake8 --ignore-shorties 4 --censor-msg
```
`--ignore-shorties <number>` - ignores bad words shorter or equal to `<number>`

`--censor-msg` - replaces bad words not leading letters with `*` in error messages

## Development notes
`make lint` - runs all linters

`make flake8` - runs flake8

`make unittests` - runs unittests with coverage report and -s flag

`make mypy` - runs mypy

`make yamllint` - runs yamllint
12 changes: 12 additions & 0 deletions flake8_koles/__about__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"""Package information module."""

__title__ = 'flake8-koles'
__description__ = 'Watch your language young lad! Swears nad curses linter.'
__version__ = 'v0.0.1'
__author__ = 'myslak71'
__author_email__ = 'myslak@protonmail.com'
__url__ = 'https://github.com/myslak71/flake8-koles'
__license__ = 'MIT'
__copyright__ = 'Copyright 2019 myslak71'
__keywords__ = ['linter', 'flake8', 'swears', 'curses']
__download_url__ = 'https://github.com/myslak71/flake8-koles/archive/v0.0.1.tar.gz'
13 changes: 13 additions & 0 deletions flake8_koles/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"""flake8-koles package."""
from flake8_koles.__about__ import ( # noqa
__version__,
__license__,
__url__,
__author_email__,
__author__,
__description__,
__title__,
__copyright__,
__download_url__,
__keywords__
)
104 changes: 104 additions & 0 deletions flake8_koles/checker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
"""Koles checker module."""
import os
import re
import optparse
from typing import Generator, List, Tuple
import pkg_resources
from flake8.options.manager import OptionManager

from flake8.utils import stdin_get_value
from pycodestyle import readlines

from flake8_koles import __version__


class KolesChecker:
"""Bad language checker class."""

name = "flake8-koles"
version = __version__
swear_list_file = "/data/swear_list/english.dat"

def __init__(self, tree, filename):
"""Initialize class values."""
self.filename = filename
self.tree = tree
self._pattern = "|".join(self._get_bad_words())

def _check_row(self, string: str) -> List[Tuple[int, str]]:
"""Return a list containing bad words and their positions."""
if self._pattern == "":
return []

regex = re.compile(f"(?=({self._pattern}))", flags=re.IGNORECASE)

return [(match.start(), match.group(1)) for match in regex.finditer(string)]

def _get_bad_words(self) -> Generator[str, None, None]:
"""Get a generator of bad words."""
data = pkg_resources.resource_string(__name__, self.swear_list_file)
return (
word
for word in data.decode().strip().split("\n")
if len(word) > self.options.ignore_shorties # type: ignore
)

def _get_file_content(self) -> List[str]:
"""Return file content as a list of lines."""
if self.filename in ("stdin", "-", None):
return stdin_get_value().splitlines(True)
else:
return readlines(self.filename)

def _censor_word(self, word: str) -> str:
"""Replace all letters but first with `*` if censor_msg option is True."""
if self.options.censor_msg: # type: ignore
return word[0] + '*' * (len(word) - 1)
return word

def _get_filename_errors(self) -> Generator[Tuple[int, int, str, type], None, None]:
"""Get filename errors if exist."""
filename_errors = self._check_row(os.path.basename(self.filename))
if filename_errors:
for column, word in filename_errors:
yield (
0,
column,
f"KOL002 Filename contains bad language: {self._censor_word(word)}",
KolesChecker,
)

def run(self) -> Generator[Tuple[int, int, str, type], None, None]:
"""Run the linter and return a generator of errors."""
content = self._get_file_content()
yield from self._get_filename_errors()
yield from self._get_content_errors(content)

def _get_content_errors(
self, content
) -> Generator[Tuple[int, int, str, type], None, None]:
"""Get file content errors if exist."""
for row_number, row in enumerate(content, 1):
errors = self._check_row(row)
for column, word in errors:
yield (
row_number,
column,
f"KOL001 Bad language found: {self._censor_word(word)}",
KolesChecker,
)

@classmethod
def add_options(cls, parser: OptionManager) -> None:
"""Add koles linter options to the flake8 parser."""
parser.add_option(
"--ignore-shorties", default=0, type="int", parse_from_config=True
)
parser.add_option(
"--censor-msg", default=0, parse_from_config=True, action='store_true'
)

@classmethod
def parse_options(cls, options: optparse.Values) -> None:
"""Get parser options from flake8."""
cls.options = options # type: ignore

0 comments on commit 3101c7a

Please sign in to comment.