pax_global_header00006660000000000000000000000064140141671470014517gustar00rootroot0000000000000052 comment=9c82d04b5ddaf60f738fa3193cb6590d2f369a7a Melevir-cognitive_complexity-9c82d04/000077500000000000000000000000001401416714700177235ustar00rootroot00000000000000Melevir-cognitive_complexity-9c82d04/.editorconfig000066400000000000000000000004231401416714700223770ustar00rootroot00000000000000# http://editorconfig.org # Inspired by Django .editorconfig file root = true [*] indent_style = space indent_size = 4 insert_final_newline = true trim_trailing_whitespace = true end_of_line = lf charset = utf-8 [*.py] max_line_length = 100 [Makefile] indent_style = tab Melevir-cognitive_complexity-9c82d04/.flake_master000066400000000000000000000002241401416714700223570ustar00rootroot00000000000000{"name": "rose", "revision": "4", "url": "https://raw.githubusercontent.com/Melevir/flake_master_presets/master/presets/rose.cfg", "filepath": null}Melevir-cognitive_complexity-9c82d04/.gitignore000066400000000000000000000023151401416714700217140ustar00rootroot00000000000000# 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/ # VS code .vscode .idea Melevir-cognitive_complexity-9c82d04/.travis.yml000066400000000000000000000007171401416714700220410ustar00rootroot00000000000000language: python python: - "3.6" - "3.7" - "3.8" install: - pip install -r requirements_dev.txt before_script: - gem install chef-utils -v 16.6.14 - gem install mdl - curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter - chmod +x ./cc-test-reporter - ./cc-test-reporter before-build script: - make check after_script: - ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT Melevir-cognitive_complexity-9c82d04/LICENSE000066400000000000000000000020551401416714700207320ustar00rootroot00000000000000MIT License Copyright (c) 2020 Ilya Lebedev 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. Melevir-cognitive_complexity-9c82d04/Makefile000066400000000000000000000002241401416714700213610ustar00rootroot00000000000000check: flake8 . mypy . make test check_readme test: python -m pytest --cov=cognitive_complexity --cov-report=xml check_readme: mdl README.md Melevir-cognitive_complexity-9c82d04/README.md000066400000000000000000000054531401416714700212110ustar00rootroot00000000000000# congnitive-complexity [![Build Status](https://travis-ci.org/Melevir/cognitive_complexity.svg?branch=master)](https://travis-ci.org/Melevir/cognitive_complexity) [![Maintainability](https://api.codeclimate.com/v1/badges/853d47d353e7becc9f09/maintainability)](https://codeclimate.com/github/Melevir/cognitive_complexity/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/853d47d353e7becc9f09/test_coverage)](https://codeclimate.com/github/Melevir/cognitive_complexity/test_coverage) [![PyPI version](https://badge.fury.io/py/cognitive-complexity.svg)](https://badge.fury.io/py/cognitive-complexity) ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/cognitive-complexity) Library to calculate Python functions cognitive complexity via code. ## Installation ```bash pip install cognitive_complexity ``` ## Usage ```python >>> import ast >>> funcdef = ast.parse(""" ... def f(a): ... return a * f(a - 1) # +1 for recursion ... """).body[0] >>> from cognitive_complexity.api import get_cognitive_complexity >>> get_cognitive_complexity(funcdef) 1 ``` ## What is cognitive complexity Here are some readings about cognitive complexity: - [Cognitive Complexity, Because Testability != Understandability](https://blog.sonarsource.com/cognitive-complexity-because-testability-understandability); - [Cognitive Complexity: A new way of measuring understandability](https://www.sonarsource.com/docs/CognitiveComplexity.pdf), white paper by G. Ann Campbell; - [Cognitive Complexity: the New Guide to Refactoring for Maintainable Code](https://www.youtube.com/watch?v=5C6AGTlKSjY); - [Cognitive Complexity](https://docs.codeclimate.com/docs/cognitive-complexity) from CodeClimate docs; - [Is Your Code Readable By Humans? Cognitive Complexity Tells You](https://www.tomasvotruba.cz/blog/2018/05/21/is-your-code-readable-by-humans-cognitive-complexity-tells-you/). ## Realization details This is not precise realization of original algorithm proposed by [G. Ann Campbell](https://github.com/ganncamp), but it gives rather similar results. The algorithm gives complexity points for breaking control flow, nesting, recursion, stacks logic operation etc. ## Contributing We would love you to contribute to our project. It's simple: - Create an issue with bug you found or proposal you have. Wait for approve from maintainer. - Create a pull request. Make sure all checks are green. - Fix review comments if any. - Be awesome. Here are useful tips: - You can run all checks and tests with `make check`. Please do it before TravisCI does. - We use [BestDoctor python styleguide](https://github.com/best-doctor/guides/blob/master/guides/python_styleguide.md). Sorry, styleguide is available only in Russian for now. - We respect [Django CoC](https://www.djangoproject.com/conduct/). Make soft, not bullshit. Melevir-cognitive_complexity-9c82d04/cognitive_complexity/000077500000000000000000000000001401416714700241675ustar00rootroot00000000000000Melevir-cognitive_complexity-9c82d04/cognitive_complexity/__init__.py000066400000000000000000000000261401416714700262760ustar00rootroot00000000000000__version__ = '1.2.0' Melevir-cognitive_complexity-9c82d04/cognitive_complexity/api.py000066400000000000000000000023761401416714700253220ustar00rootroot00000000000000import ast from cognitive_complexity.common_types import AnyFuncdef from cognitive_complexity.utils.ast import ( has_recursive_calls, is_decorator, process_child_nodes, process_node_itself, ) def get_cognitive_complexity(funcdef: AnyFuncdef) -> int: if is_decorator(funcdef): return get_cognitive_complexity(funcdef.body[0]) # type: ignore complexity = 0 for node in funcdef.body: complexity += get_cognitive_complexity_for_node(node) if has_recursive_calls(funcdef): complexity += 1 return complexity def get_cognitive_complexity_for_node( node: ast.AST, increment_by: int = 0, verbose: bool = False, ) -> int: increment_by, base_complexity, should_iter_children = process_node_itself(node, increment_by) child_complexity = 0 if should_iter_children: child_complexity += process_child_nodes( node, increment_by, verbose, get_cognitive_complexity_for_node, ) complexity = base_complexity + child_complexity if verbose: print( # noqa f'Complexity for {node} is {complexity} ({base_complexity} + {child_complexity})' f' (increment {increment_by})', ) return complexity Melevir-cognitive_complexity-9c82d04/cognitive_complexity/common_types.py000066400000000000000000000001401401416714700272500ustar00rootroot00000000000000import ast from typing import Union AnyFuncdef = Union[ast.FunctionDef, ast.AsyncFunctionDef] Melevir-cognitive_complexity-9c82d04/cognitive_complexity/utils/000077500000000000000000000000001401416714700253275ustar00rootroot00000000000000Melevir-cognitive_complexity-9c82d04/cognitive_complexity/utils/__init__.py000066400000000000000000000000001401416714700274260ustar00rootroot00000000000000Melevir-cognitive_complexity-9c82d04/cognitive_complexity/utils/ast.py000066400000000000000000000055041401416714700264740ustar00rootroot00000000000000import ast from typing import Callable, Tuple, Union from cognitive_complexity.common_types import AnyFuncdef def has_recursive_calls(funcdef: AnyFuncdef) -> bool: return bool([ n for n in ast.walk(funcdef) if ( isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id == funcdef.name ) ]) def is_decorator(funcdef: AnyFuncdef) -> bool: return ( isinstance(funcdef, ast.FunctionDef) and len(funcdef.body) == 2 and isinstance(funcdef.body[0], ast.FunctionDef) and isinstance(funcdef.body[1], ast.Return) ) def process_child_nodes( node: ast.AST, increment_by: int, verbose: bool, complexity_calculator: Callable, ) -> int: child_complexity = 0 child_nodes = ast.iter_child_nodes(node) for node_num, child_node in enumerate(child_nodes): if isinstance(node, ast.Try): if node_num == 1: # add +1 for all try nodes except body increment_by += 1 if node_num: child_complexity += max(1, increment_by) child_complexity += complexity_calculator( child_node, increment_by=increment_by, verbose=verbose, ) return child_complexity def process_control_flow_breaker( node: Union[ast.If, ast.For, ast.While, ast.IfExp], increment_by: int, ) -> Tuple[int, int, bool]: if isinstance(node, ast.IfExp): # C if A else B; ternary operator equivalent increment = 0 increment_by += 1 elif isinstance(node, ast.If) and len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If): # node is an elif; the increment will be counted on the ast.If increment = 0 elif node.orelse: # +1 for the else and add a nesting level increment = 1 increment_by += 1 else: # no 'else' to count, just add a nesting level increment = 0 increment_by += 1 return increment_by, max(1, increment_by) + increment, True def process_node_itself( node: ast.AST, increment_by: int, ) -> Tuple[int, int, bool]: control_flow_breakers = ( ast.If, ast.For, ast.While, ast.IfExp, ) incrementers_nodes = ( ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ) if isinstance(node, control_flow_breakers): return process_control_flow_breaker(node, increment_by) elif isinstance(node, incrementers_nodes): increment_by += 1 return increment_by, 0, True elif isinstance(node, ast.BoolOp): inner_boolops_amount = len([n for n in ast.walk(node) if isinstance(n, ast.BoolOp)]) base_complexity = inner_boolops_amount return increment_by, base_complexity, False return increment_by, 0, True Melevir-cognitive_complexity-9c82d04/requirements_dev.txt000066400000000000000000000015031401416714700240440ustar00rootroot00000000000000mypy==0.770 mypy-extensions==0.4.3 typing==3.6.4 typing-extensions==3.7.4 flake8==3.7.9 flake8-annotations-complexity==0.0.4 flake8-blind-except==0.1.1 flake8-broken-line==0.2.0 flake8-bugbear==20.1.4 flake8-builtins==1.5.2 flake8-commas==2.0.0 flake8-comprehensions==3.2.2 flake8-debugger==3.2.1 flake8-docstrings==1.5.0 flake8-functions==0.0.4 flake8-polyfill==1.0.2 flake8-print==3.1.4 flake8-quotes==3.0.0 flake8-string-format==0.3.0 flake8-todo==0.7 flake8-variables-names==0.0.3 pytest==6.2.2 pytest-cov==2.6.1 attrs==20.3.0 astpretty==1.6.0 pydocstyle==5.0.2 flake8-2020==1.6.0 flake8-eradicate==0.3.0 flake8-fixme==1.1.1 flake8-class-attributes-order==0.1.0 flake8-tidy-imports==4.1.0 flake8-typing-imports==1.9.0 dlint==0.10.3 flake8-if-statements==0.1.0 flake8-annotations-coverage==0.0.4 flake8-expression-complexity==0.0.7 Melevir-cognitive_complexity-9c82d04/setup.cfg000066400000000000000000000010371401416714700215450ustar00rootroot00000000000000[flake8] ignore = W503, P103, D max-line-length = 120 use_class_attributes_order_strict_mode = True max_function_length = 50 max-complexity = 6 max-annotations-complexity = 4 exclude = node_modules,env,venv,venv36 var_names_exclude_pathes = node_modules,env,venv,venv36 assert_allowed_in_pathes = tests,migrations,env,venv,venv36 adjustable-default-max-complexity = 8 per-file-ignores = __init__.py: F401 tests/*: TAE001 ban-relative-imports = True min-coverage-percents = 100 [mypy] ignore_missing_imports = True allow_redefinition = True Melevir-cognitive_complexity-9c82d04/setup.py000066400000000000000000000030161401416714700214350ustar00rootroot00000000000000from typing import Optional from setuptools import setup, find_packages package_name = 'cognitive_complexity' def get_version() -> Optional[str]: with open('cognitive_complexity/__init__.py', 'r') as f: lines = f.readlines() for line in lines: if line.startswith('__version__'): return line.split('=')[-1].strip().strip("'") return None def get_long_description() -> str: with open('README.md') as f: return f.read() setup( name=package_name, description='Library to calculate Python functions cognitive complexity via code', classifiers=[ 'Environment :: Console', 'Operating System :: OS Independent', 'Topic :: Software Development :: Documentation', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Quality Assurance', 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], long_description=get_long_description(), long_description_content_type='text/markdown', packages=find_packages(), python_requires='>=3.6', include_package_data=True, keywords='flake8', version=get_version(), author='Ilya Lebedev', author_email='melevir@gmail.com', install_requires=['setuptools'], url='https://github.com/Melevir/cognitive_complexity', license='MIT', py_modules=[package_name], zip_safe=False, ) Melevir-cognitive_complexity-9c82d04/tests/000077500000000000000000000000001401416714700210655ustar00rootroot00000000000000Melevir-cognitive_complexity-9c82d04/tests/conftest.py000066400000000000000000000003271401416714700232660ustar00rootroot00000000000000import ast from cognitive_complexity.api import get_cognitive_complexity def get_code_snippet_compexity(src: str) -> int: funcdef = ast.parse(src.strip()).body[0] return get_cognitive_complexity(funcdef) Melevir-cognitive_complexity-9c82d04/tests/test_cognitive_complexity.py000066400000000000000000000140041401416714700267410ustar00rootroot00000000000000from conftest import get_code_snippet_compexity def test_simple_if_simple_condition_complexity(): assert get_code_snippet_compexity(""" def f(a, b): if a: # +1 return 1 """) == 1 def test_simple_if_serial_condition_complexity(): assert get_code_snippet_compexity(""" def f(a, b): if a and b and True: # +2 return 1 """) == 2 def test_simple_if_serial_heterogenious_condition_complexity(): assert get_code_snippet_compexity(""" def f(a, b): if a and b or True: # +3 return 1 """) == 3 def test_simple_if_complex_condition_complexity(): assert get_code_snippet_compexity(""" def f(a, b): if ( # +1 a and b and # +1 (c or d) # +1 ): return 1 """) == 3 def test_simple_structure_condition_complexity(): assert get_code_snippet_compexity(""" def f(a, b): if (a): # +1 return 1 if (b): # +1 return 2 """) == 2 def test_simple_elif_condition_complexity(): assert get_code_snippet_compexity(""" def f(a, b): if (a): # +1 return 1 elif (b): # +1 return 2 else: # +1 return 3 """) == 3 def test_simple_else_condition_complexity(): assert get_code_snippet_compexity(""" def f(a): if (a): # +1 return 1 else: # +1 return 3 """) == 2 def test_nested_structure_condition_complexity(): assert get_code_snippet_compexity(""" def f(a, b): if a: # +1 for i in range(b): # +2 return 1 """) == 3 def test_very_nested_structure_condition_complexity(): assert get_code_snippet_compexity(""" def f(a, b): if a: # +1 for i in range(b): # +2 if b: # +3 return 1 """) == 6 def test_try_condition_complexity(): assert get_code_snippet_compexity(""" def f(a, b): try: for foo in bar: # +1 return a except Exception: # +1 if a < 0: # +2 return a """) == 4 def test_recursion_complexity(): assert get_code_snippet_compexity(""" def f(a): return a * f(a - 1) # +1 for recursion """) == 1 def test_real_function(): assert get_code_snippet_compexity(""" def process_raw_constant(constant, min_word_length): processed_words = [] raw_camelcase_words = [] for raw_word in re.findall(r'[a-z]+', constant): # +1 word = raw_word.strip() if ( # +2 (nesting = 1) len(word) >= min_word_length # +2 (2 bool operator sequences) and not (word.startswith('-') or word.endswith('-')) ): if is_camel_case_word(word): # +3 (nesting=2) raw_camelcase_words.append(word) else: # +1 processed_words.append(word.lower()) return processed_words, raw_camelcase_words """) == 9 def test_break_and_continue(): assert get_code_snippet_compexity(""" def f(a): for a in range(10): # +1 if a % 2: # +2 continue if a == 8: # +2 break """) == 5 def test_nested_functions(): assert get_code_snippet_compexity(""" def f(a): def foo(a): if a: # +2 return 1 bar = lambda a: lambda b: b or 2 # +1 return bar(foo(a))(a) """) == 3 def test_ternary_operator(): assert get_code_snippet_compexity(""" def f(a): if a % 2: # +1 return 'c' if a else 'd' # +2 return 'a' if a else 'b' # +1 """) == 4 def test_nested_if_condition_complexity(): assert get_code_snippet_compexity(""" def f(a, b): if a == b: # +1 if (a): # +2 (nesting=1) return 1 return 0 """) == 3 def test_nested_else_condition_complexity(): assert get_code_snippet_compexity(""" def f(a, b): if a == b: # +1 if (a): # +2 (nesting=1) return 1 else: # +1 return 3 return 0 """) == 4 def test_nested_elif_condition_complexity(): assert get_code_snippet_compexity(""" def f(a, b): if a == b: # +1 if (a): # +2 (nesting=1) return 1 elif (b): # +1 return 2 else: # +1 return 3 return 0 """) == 5 def test_for_else_complexity(): assert get_code_snippet_compexity(""" def f(a): for a in range(10): # +1 if a % 2: # +2 continue if a == 8: # +2 break else: # +1 return 5 """) == 6 def test_while_else_complexity(): assert get_code_snippet_compexity(""" def f(a): a = 0 while a < 10: # +1 if a % 2: # +2 continue if a == 8: # +2 break a += 1 else: # +1 return 5 """) == 6 def test_a_decorator_complexity(): assert get_code_snippet_compexity(""" def a_decorator(a, b): def inner(func): # nesting = 0 if condition: # +1 print(b) func() return inner """) == 1 def test_not_a_decorator_complexity(): assert get_code_snippet_compexity(""" def not_a_decorator(a, b): my_var = a*b def inner(func): # nesting = 1 if condition: # +1 structure, +1 nesting print(b) func() return inner """) == 2 def test_decorator_generator_complexity(): assert get_code_snippet_compexity(""" def decorator_generator(a): def generator(func): def decorator(func): # nesting = 0 if condition: # +1 print(b) return func() return decorator return generator """) == 1