Skip to content

Commit

Permalink
chore: run autoformatters (pyupgrade, isort, black)
Browse files Browse the repository at this point in the history
  • Loading branch information
gforcada committed Oct 8, 2022
1 parent 4c57928 commit 41bf429
Show file tree
Hide file tree
Showing 3 changed files with 118 additions and 132 deletions.
62 changes: 25 additions & 37 deletions flake8_isort.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,20 @@
# -*- coding: utf-8 -*-

import warnings
from contextlib import redirect_stdout
from difflib import Differ
from difflib import unified_diff
from difflib import Differ, unified_diff
from io import StringIO
from pathlib import Path

import isort
import warnings


class Flake8IsortBase(object):
class Flake8IsortBase:
name = 'flake8_isort'
version = '4.2.1'
isort_unsorted = (
'I001 isort found an import in the wrong position'
)
no_config_msg = (
'I002 no configuration found (.isort.cfg or [isort] in configs)'
)
isort_blank_req = (
'I003 isort expected 1 blank line in imports, found 0'
)
isort_blank_unexp = (
'I004 isort found an unexpected blank line in imports'
)
isort_add_unexp = (
'I005 isort found an unexpected missing import'
)
isort_unsorted = 'I001 isort found an import in the wrong position'
no_config_msg = 'I002 no configuration found (.isort.cfg or [isort] in configs)'
isort_blank_req = 'I003 isort expected 1 blank line in imports, found 0'
isort_blank_unexp = 'I004 isort found an unexpected blank line in imports'
isort_add_unexp = 'I005 isort found an unexpected missing import'

show_traceback = False
stdin_display_name = None
Expand All @@ -43,7 +30,7 @@ def add_options(cls, parser):
'--isort-show-traceback',
action='store_true',
parse_from_config=True,
help='Show full traceback with diff from isort'
help='Show full traceback with diff from isort',
)

@classmethod
Expand Down Expand Up @@ -98,9 +85,7 @@ def sortimports_linenum_msg(self, sort_result):
diff = differ.compare(sort_result.in_lines, sort_result.out_lines)

line_num = 0
additions = {
'+ {}'.format(add_import) for add_import in sort_result.add_imports
}
additions = {f'+ {add_import}' for add_import in sort_result.add_imports}
for line in diff:
if line.startswith(' ', 0, 2):
line_num += 1 # Ignore unchanged lines but increment line_num.
Expand Down Expand Up @@ -173,7 +158,8 @@ def _fixup_sortimports_wrapped(sort_imports):
for idx, line in enumerate(sort_imports.out_lines):
if '\n' in line:
for new_idx, new_line in enumerate(
sort_imports.out_lines.pop(idx).splitlines()):
sort_imports.out_lines.pop(idx).splitlines()
):
sort_imports.out_lines.insert(idx + new_idx, new_line)


Expand All @@ -183,12 +169,10 @@ class Flake8Isort5(Flake8IsortBase):
def run(self):
if self.filename is not self.stdin_display_name:
file_path = Path(self.filename)
isort_config = isort.settings.Config(
settings_path=file_path.parent)
isort_config = isort.settings.Config(settings_path=file_path.parent)
else:
file_path = None
isort_config = isort.settings.Config(
settings_path=Path.cwd())
isort_config = isort.settings.Config(settings_path=Path.cwd())
input_string = ''.join(self.lines)
traceback = ''
isort_changed = False
Expand All @@ -201,19 +185,23 @@ def run(self):
input_stream=input_stream,
output_stream=output_stream,
config=isort_config,
file_path=file_path)
file_path=file_path,
)
except isort.exceptions.FileSkipped:
pass
except isort.exceptions.ISortError as e:
warnings.warn(e)
if isort_changed:
outlines = output_stream.getvalue()
diff_delta = "".join(unified_diff(
input_string.splitlines(keepends=True),
outlines.splitlines(keepends=True),
fromfile="{}:before".format(self.filename),
tofile="{}:after".format(self.filename)))
traceback = (isort_stdout.getvalue() + "\n" + diff_delta)
diff_delta = "".join(
unified_diff(
input_string.splitlines(keepends=True),
outlines.splitlines(keepends=True),
fromfile=f"{self.filename}:before",
tofile=f"{self.filename}:after",
)
)
traceback = isort_stdout.getvalue() + "\n" + diff_delta
for line_num, message in self.isort_linenum_msg(diff_delta):
if self.show_traceback:
message += traceback
Expand Down
180 changes: 87 additions & 93 deletions run_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,86 +52,90 @@ def check_isort_ret(ret, ref):


testcases = [
{'name': 'sorted_correctly_default',
'code': ('import os\n'
'from sys import path\n'),
'ref': []},
{'name': 'sorted_correctly_alpha',
'config': 'force_single_line=True\n'
'force_alphabetical_sort=True\n',
'code': 'from sys import path\n'
'\n'
'import os\n',
'ref': []},
{'name': 'eof_blank_lines',
'code': 'import os\n'
'from sys import path\n'
'\n'
'\n'
' \n',
'ref': []},
{'name': 'imports_requires_blank_line',
'code': 'from __future__ import division\n'
'import threading\n'
'from sys import pid\n',
'ref': [(2, 0, 'I003 ')]},
{'name': 'isortcfg_skip_file',
'config': 'skip=test.py',
'code': 'skipped_file',
'ref': []},
{'name': 'file_skipped_with_comment',
'code': '# isort:skip_file',
'ref': []},
{'name': 'imports_unexpected_blank_line',
'code': 'from __future__ import division\n'
'\n'
'import threading\n'
'\n'
'from sys import pid\n',
'ref': [(4, 0, 'I004 ')]},
{'name': 'sorted_incorrectly_multiple',
'code': 'from __future__ import division\n'
'import os\n'
'from sys import pid\n'
'import threading\n'
'\n'
'import isort\n'
'\n\n\n'
'def func()\n',
'ref': [(2, 0, 'I003 '),
(4, 0, 'I001 '),
(9, 0, 'I004 ')]},
{'name': 'sorted_incorrectly',
'config': 'force_single_line=True',
'code': 'from sys import pid\n'
'import threading',
'ref': [(2, 0, 'I001 ')]},
{'name': 'empty_file',
'code': '\n\n',
'ref': []},
{'name': 'wrapped_imports',
'config': 'wrap_length=65',
'code': 'from deluge.common import (fdate, fpcnt, fpeer, fsize, fspeed,\n'
' ftime, get_path_size, is_infohash,\n'
' is_ip, is_magnet, is_url)\n',
'ref': []},
{'name': 'force_single_line_imports',
'config': 'force_alphabetical_sort=True\n'
'force_single_line=True',
'code': 'from plone.app.testing import applyProfile\n'
'from plone.app.testing import FunctionalTesting\n',
'ref': []},
{'name': 'missing_add_imports',
'config': 'add_imports=from __future__ import unicode_literals',
'code': 'import os\n',
'ref': [(1, 0, 'I003'),
(1, 0, 'I005')]},
{
'name': 'sorted_correctly_default',
'code': ('import os\n' 'from sys import path\n'),
'ref': [],
},
{
'name': 'sorted_correctly_alpha',
'config': 'force_single_line=True\n' 'force_alphabetical_sort=True\n',
'code': 'from sys import path\n' '\n' 'import os\n',
'ref': [],
},
{
'name': 'eof_blank_lines',
'code': 'import os\n' 'from sys import path\n' '\n' '\n' ' \n',
'ref': [],
},
{
'name': 'imports_requires_blank_line',
'code': 'from __future__ import division\n'
'import threading\n'
'from sys import pid\n',
'ref': [(2, 0, 'I003 ')],
},
{
'name': 'isortcfg_skip_file',
'config': 'skip=test.py',
'code': 'skipped_file',
'ref': [],
},
{'name': 'file_skipped_with_comment', 'code': '# isort:skip_file', 'ref': []},
{
'name': 'imports_unexpected_blank_line',
'code': 'from __future__ import division\n'
'\n'
'import threading\n'
'\n'
'from sys import pid\n',
'ref': [(4, 0, 'I004 ')],
},
{
'name': 'sorted_incorrectly_multiple',
'code': 'from __future__ import division\n'
'import os\n'
'from sys import pid\n'
'import threading\n'
'\n'
'import isort\n'
'\n\n\n'
'def func()\n',
'ref': [(2, 0, 'I003 '), (4, 0, 'I001 '), (9, 0, 'I004 ')],
},
{
'name': 'sorted_incorrectly',
'config': 'force_single_line=True',
'code': 'from sys import pid\n' 'import threading',
'ref': [(2, 0, 'I001 ')],
},
{'name': 'empty_file', 'code': '\n\n', 'ref': []},
{
'name': 'wrapped_imports',
'config': 'wrap_length=65',
'code': 'from deluge.common import (fdate, fpcnt, fpeer, fsize, fspeed,\n'
' ftime, get_path_size, is_infohash,\n'
' is_ip, is_magnet, is_url)\n',
'ref': [],
},
{
'name': 'force_single_line_imports',
'config': 'force_alphabetical_sort=True\n' 'force_single_line=True',
'code': 'from plone.app.testing import applyProfile\n'
'from plone.app.testing import FunctionalTesting\n',
'ref': [],
},
{
'name': 'missing_add_imports',
'config': 'add_imports=from __future__ import unicode_literals',
'code': 'import os\n',
'ref': [(1, 0, 'I003'), (1, 0, 'I005')],
},
]


@pytest.mark.parametrize('mode', ["file", "code_string"])
@pytest.mark.parametrize('testcase', testcases,
ids=[t['name'] for t in testcases])
@pytest.mark.parametrize('testcase', testcases, ids=[t['name'] for t in testcases])
def test_flake8_isort(tmpdir, testcase, mode):
"""Test the code examples in files and directly from string"""
with tmpdir.as_cwd():
Expand All @@ -151,8 +155,7 @@ def test_flake8_isort(tmpdir, testcase, mode):
def test_isortcfg_found(tmpdir):
(file_path, lines) = write_python_file(
tmpdir,
'from sys import pid\n'
'import threading',
'from sys import pid\n' 'import threading',
)
write_isort_cfg(tmpdir, 'force_single_line=True')
checker = Flake8Isort(None, file_path, lines)
Expand All @@ -162,10 +165,7 @@ def test_isortcfg_found(tmpdir):


def test_isortcfg_not_found(tmpdir):
(file_path, lines) = write_python_file(
tmpdir,
'from sys import pid, path'
)
(file_path, lines) = write_python_file(tmpdir, 'from sys import pid, path')
checker = Flake8Isort(None, file_path, lines)
checker.search_current = False
checker.config_file = True
Expand All @@ -175,18 +175,12 @@ def test_isortcfg_not_found(tmpdir):

def test_isort_formatted_output(tmpdir):
options = collections.namedtuple(
'Options', [
'no_isort_config',
'isort_show_traceback',
'stdin_display_name'
]
'Options', ['no_isort_config', 'isort_show_traceback', 'stdin_display_name']
)

(file_path, lines) = write_python_file(
tmpdir,
'from __future__ import division\n'
'import os\n'
'from sys import pid\n',
'from __future__ import division\n' 'import os\n' 'from sys import pid\n',
)

diff = ' from __future__ import division\n+\n import os'
Expand All @@ -202,12 +196,12 @@ def test_isort_formatted_output(tmpdir):

@pytest.mark.parametrize(
'method_to_write_config',
[write_isort_cfg, write_setup_cfg, write_tox_ini, write_pyproject_toml])
[write_isort_cfg, write_setup_cfg, write_tox_ini, write_pyproject_toml],
)
def test_if_config_file_is_used(tmpdir, method_to_write_config):
(file_path, lines) = write_python_file(
tmpdir,
'import os\n'
'from sys import path\n',
'import os\n' 'from sys import path\n',
)
method_to_write_config(tmpdir, 'lines_between_types=1')

Expand Down
8 changes: 6 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ def read_file(filename):
author_email='gil.gnome@gmail.com',
url='https://github.com/gforcada/flake8-isort',
license='GPL version 2',
py_modules=['flake8_isort', ],
py_modules=[
'flake8_isort',
],
include_package_data=True,
test_suite='run_tests',
zip_safe=False,
Expand All @@ -60,6 +62,8 @@ def read_file(filename):
],
},
entry_points={
'flake8.extension': ['I00 = flake8_isort:Flake8Isort', ],
'flake8.extension': [
'I00 = flake8_isort:Flake8Isort',
],
},
)

0 comments on commit 41bf429

Please sign in to comment.