Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drop old code #122

Merged
merged 1 commit into from
Aug 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,10 @@ repos:
rev: 5.0.4
hooks:
- id: flake8

- repo: https://github.com/asottile/pyupgrade
rev: v2.37.3
hooks:
- id: pyupgrade
args:
- --py37-plus
49 changes: 13 additions & 36 deletions autoflake.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,22 +48,10 @@
ATOMS = frozenset([tokenize.NAME, tokenize.NUMBER, tokenize.STRING])

EXCEPT_REGEX = re.compile(r'^\s*except [\s,()\w]+ as \w+:$')
PYTHON_SHEBANG_REGEX = re.compile(r'^#!.*\bpython[23]?\b\s*$')
PYTHON_SHEBANG_REGEX = re.compile(r'^#!.*\bpython[3]?\b\s*$')

MAX_PYTHON_FILE_DETECTION_BYTES = 1024

try:
unicode
except NameError:
unicode = str


try:
RecursionError
except NameError:
# Python before 3.5.
RecursionError = RuntimeError


def standard_paths():
"""Yield paths to standard modules."""
Expand All @@ -72,14 +60,12 @@ def standard_paths():
# Yield lib paths.
path = distutils.sysconfig.get_python_lib(standard_lib=True,
plat_specific=is_plat_spec)
for name in os.listdir(path):
yield name
yield from os.listdir(path)

# Yield lib-dynload paths.
dynload_path = os.path.join(path, 'lib-dynload')
if os.path.isdir(dynload_path):
for name in os.listdir(dynload_path):
yield name
yield from os.listdir(dynload_path)


def standard_package_names():
Expand Down Expand Up @@ -118,8 +104,8 @@ def unused_import_module_name(messages):
for message in messages:
if isinstance(message, pyflakes.messages.UnusedImport):
module_name = re.search(pattern, str(message))
module_name = module_name.group()[1:-1]
if module_name:
module_name = module_name.group()[1:-1]
yield (message.lineno, module_name)


Expand Down Expand Up @@ -184,15 +170,6 @@ def create_key_to_messages_dict(messages):

def check(source):
"""Return messages from pyflakes."""
if sys.version_info[0] == 2 and isinstance(source, unicode):
# Convert back to original byte string encoding, otherwise pyflakes
# call to compile() will complain. See PEP 263. This only affects
# Python 2.
try:
source = source.encode('utf-8')
except UnicodeError: # pragma: no cover
return []

reporter = ListReporter()
try:
pyflakes.api.check(source, filename='<string>', reporter=reporter)
Expand All @@ -201,7 +178,7 @@ def check(source):
return reporter.messages


class StubFile(object):
class StubFile:
"""Stub out file for pyflakes."""

def write(self, *_):
Expand Down Expand Up @@ -267,7 +244,7 @@ def multiline_statement(line, previous_line=''):
return True


class PendingFix(object):
class PendingFix:
"""Allows a rewrite operation to span multiple lines.

In the main rewrite loop, every time a helper function returns a
Expand Down Expand Up @@ -835,8 +812,8 @@ def _fix_file(input_file, filename, args, write_to_stdout, standard_out,
if original_source != filtered_source:
if args.check:
standard_out.write(
'{filename}: Unused imports/variables detected\n'.format(
filename=filename))
f'{filename}: Unused imports/variables detected\n',
)
sys.exit(1)
if write_to_stdout:
standard_out.write(filtered_source)
Expand Down Expand Up @@ -866,8 +843,8 @@ def open_with_encoding(filename, encoding, mode='r',
if not encoding:
encoding = detect_encoding(filename, limit_byte_check=limit_byte_check)

return io.open(filename, mode=mode, encoding=encoding,
newline='') # Preserve line endings
return open(filename, mode=mode, encoding=encoding,
newline='') # Preserve line endings


def detect_encoding(filename, limit_byte_check=-1):
Expand Down Expand Up @@ -934,7 +911,7 @@ def is_python_file(filename):
if not text:
return False
first_line = text.splitlines()[0]
except (IOError, IndexError):
except (OSError, IndexError):
return False

if not PYTHON_SHEBANG_REGEX.match(first_line):
Expand Down Expand Up @@ -1075,8 +1052,8 @@ def _main(argv, standard_out, standard_error, standard_input=None):
else:
try:
fix_file(name, args=args, standard_out=standard_out)
except IOError as exception:
_LOGGER.error(unicode(exception))
except OSError as exception:
_LOGGER.error(str(exception))
failure = True

return 1 if failure else 0
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ def version():
license='Expat License',
author='Steven Myint',
url='https://github.com/myint/autoflake',
python_requires='>=3.7',
classifiers=['Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
Expand Down
5 changes: 2 additions & 3 deletions test_autoflake.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# coding: utf-8
"""Test suite for autoflake."""
import contextlib
import functools
Expand Down Expand Up @@ -2007,7 +2006,7 @@ def test_fix_without_from(self):
'\n'
)

self.unused = ['lib{}.x.y.z'.format(x) for x in (1, 3, 4)]
self.unused = [f'lib{x}.x.y.z' for x in (1, 3, 4)]
self.assert_fix([
'import \\\n',
' lib1.x.y.z \\',
Expand Down Expand Up @@ -2201,7 +2200,7 @@ def temporary_directory(directory='.', prefix='tmp.'):
shutil.rmtree(temp_directory)


class StubFile(object):
class StubFile:

"""Fake file that ignores everything."""

Expand Down
10 changes: 2 additions & 8 deletions test_fuzz.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,6 @@
END = ''


try:
unicode
except NameError:
unicode = str


def colored(text, color):
"""Return color coded text."""
return color + text + END
Expand Down Expand Up @@ -106,7 +100,7 @@ def run(filename, command, verbose=False, options=None):
if file_diff and after_count > before_count:
sys.stderr.write('autoflake made ' + filename + ' worse\n')
return False
except IOError as exception:
except OSError as exception:
sys.stderr.write(str(exception) + '\n')

return True
Expand Down Expand Up @@ -209,7 +203,7 @@ def check(args):
completed_filenames.update(name)

if os.path.isdir(name):
for root, directories, children in os.walk(unicode(name)):
for root, directories, children in os.walk(name):
filenames += [os.path.join(root, f) for f in children
if f.endswith('.py') and
not f.startswith('.')]
Expand Down
8 changes: 4 additions & 4 deletions test_fuzz_pypi.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
def latest_packages(last_hours):
"""Return names of latest released packages on PyPI."""
process = subprocess.Popen(
['yolk', '--latest-releases={hours}'.format(hours=last_hours)],
['yolk', f'--latest-releases={last_hours}'],
stdout=subprocess.PIPE)

for line in process.communicate()[0].decode('utf-8').split('\n'):
Expand All @@ -29,7 +29,7 @@ def download_package(name, output_directory):

Raise CalledProcessError on failure.
"""
subprocess.check_call(['yolk', '--fetch-package={name}'.format(name=name)],
subprocess.check_call(['yolk', f'--fetch-package={name}'],
cwd=output_directory)


Expand All @@ -41,14 +41,14 @@ def extract_package(path, output_directory):
tar.extractall(path=output_directory)
tar.close()
return True
except (tarfile.ReadError, IOError):
except (tarfile.ReadError, OSError):
return False
elif path.lower().endswith('.zip'):
try:
archive = zipfile.ZipFile(path)
archive.extractall(path=output_directory)
archive.close()
except (zipfile.BadZipfile, IOError):
except (zipfile.BadZipfile, OSError):
return False
return True

Expand Down