Skip to content

Commit

Permalink
Autosort all Python files using black and isort
Browse files Browse the repository at this point in the history
  • Loading branch information
lafrenierejm committed Feb 6, 2022
1 parent 16c9b78 commit ce6d238
Show file tree
Hide file tree
Showing 35 changed files with 2,460 additions and 1,708 deletions.
1 change: 0 additions & 1 deletion .isort.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
[settings]
line_length = 88
profile = black
py_version = 39
skip_gitignore = true
src_paths = hy,tests
3 changes: 1 addition & 2 deletions bin/py2ast
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#!/usr/bin/env python

import sys
import ast

import sys

print(ast.dump(ast.parse(open(sys.argv[1], 'r').read())))
24 changes: 15 additions & 9 deletions conftest.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import sys
import os
import importlib
from operator import or_
import os
import sys
from functools import reduce
from operator import or_

import pytest

import hy
from hy._compat import PY3_8, PY3_10

Expand All @@ -21,16 +22,21 @@ def pytest_ignore_collect(path, config):
(PY3_10, "py3_10_only"),
]

return reduce(
or_,
(name in path.basename and not condition for condition, name in versions),
) or None
return (
reduce(
or_,
(name in path.basename and not condition for condition, name in versions),
)
or None
)


def pytest_collect_file(parent, path):
if (path.ext == ".hy"
if (
path.ext == ".hy"
and NATIVE_TESTS in path.dirname + os.sep
and path.basename != "__init__.hy"):
and path.basename != "__init__.hy"
):

if hasattr(pytest.Module, "from_parent"):
pytest_mod = pytest.Module.from_parent(parent, fspath=path)
Expand Down
121 changes: 64 additions & 57 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,34 @@
# This file is execfile()d with the current directory set to its containing dir.

import re, os, sys, time, html
import html
import os
import re
import sys
import time

sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath(".."))

extensions = [
'sphinx.ext.napoleon',
'sphinx.ext.intersphinx',
'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
'sphinxcontrib.hydomain',
"sphinx.ext.napoleon",
"sphinx.ext.intersphinx",
"sphinx.ext.autodoc",
"sphinx.ext.viewcode",
"sphinxcontrib.hydomain",
]

from get_version import __version__ as hy_version

# Read the Docs might dirty its checkout, so strip the dirty flag.
hy_version = re.sub(r'[+.]dirty\Z', '', hy_version)
hy_version = re.sub(r"[+.]dirty\Z", "", hy_version)

templates_path = ['_templates']
source_suffix = '.rst'
templates_path = ["_templates"]
source_suffix = ".rst"

master_doc = 'index'
master_doc = "index"

# General information about the project.
project = 'hy'
copyright = '%s the authors' % time.strftime('%Y')
project = "hy"
copyright = "%s the authors" % time.strftime("%Y")

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
Expand All @@ -38,104 +42,107 @@
if "+" in hy_version:
hy_descriptive_version += " <strong style='color: red;'>(unstable)</strong>"

exclude_patterns = ['_build', 'coreteam.rst']
exclude_patterns = ["_build", "coreteam.rst"]
add_module_names = True

pygments_style = 'sphinx'
pygments_style = "sphinx"

import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'

html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_static_path = ["_static"]

html_use_smartypants = False
html_show_sphinx = False

html_context = dict(
hy_descriptive_version = hy_descriptive_version,
has_active_alpha = True,
hy_descriptive_version=hy_descriptive_version,
has_active_alpha=True,
)

highlight_language = 'clojure'
highlight_language = "clojure"

intersphinx_mapping = dict(
py = ('https://docs.python.org/3/', None),
py3_10 = ('https://docs.python.org/3.10/', None),
hyrule = ('https://hyrule.readthedocs.io/en/master/', None))
py=("https://docs.python.org/3/", None),
py3_10=("https://docs.python.org/3.10/", None),
hyrule=("https://hyrule.readthedocs.io/en/master/", None),
)
# ** Generate Cheatsheet
import json
from pathlib import Path
from itertools import zip_longest
from pathlib import Path


def refize(spec):
role = ':hy:func:'
role = ":hy:func:"
if isinstance(spec, dict):
_name = spec['name']
uri = spec['uri']
if spec.get('internal'):
role = ':ref:'
_name = spec["name"]
uri = spec["uri"]
if spec.get("internal"):
role = ":ref:"
else:
uri = spec
_name = str.split(uri, '.')[-1]
return '{}`{} <{}>`'.format(role, _name, uri)
_name = str.split(uri, ".")[-1]
return "{}`{} <{}>`".format(role, _name, uri)


def format_refs(refs, indent):
args = [iter(map(refize, refs))]
ref_groups = zip_longest(*args, fillvalue="")
return str.join(
' \\\n' + ' ' * (indent + 3),
[str.join(' ', ref_group) for ref_group in ref_groups],
" \\\n" + " " * (indent + 3),
[str.join(" ", ref_group) for ref_group in ref_groups],
)


def format_row(category, divider_loc):
return '{title: <{width}} | {methods}'.format(
return "{title: <{width}} | {methods}".format(
width=divider_loc,
title=category['name'],
methods=format_refs(category['methods'], divider_loc)
title=category["name"],
methods=format_refs(category["methods"], divider_loc),
)


def format_table(table_spec):
table_name = table_spec['name']
categories = table_spec['categories']
longest_cat_name = max(len(category['name']) for category in categories)
table_name = table_spec["name"]
categories = table_spec["categories"]
longest_cat_name = max(len(category["name"]) for category in categories)
table = [
table_name,
'-' * len(table_name),
'',
'=' * longest_cat_name + ' ' + '=' * 25,
"-" * len(table_name),
"",
"=" * longest_cat_name + " " + "=" * 25,
*(format_row(category, longest_cat_name) for category in categories),
'=' * longest_cat_name + ' ' + '=' * 25,
''
"=" * longest_cat_name + " " + "=" * 25,
"",
]
return '\n'.join(table)
return "\n".join(table)


# Modifications to the cheatsheet should be added in `cheatsheet.json`
cheatsheet_spec = json.loads(Path('./docs/cheatsheet.json').read_text())
cheatsheet_spec = json.loads(Path("./docs/cheatsheet.json").read_text())
cheatsheet = [
'..',
' DO NOT MODIFY THIS FILE. IT IS AUTO GENERATED BY ``conf.py``',
' If you need to change or add methods, modify ``cheatsheet_spec`` in ``conf.py``',
'',
'.. _cheatsheet:',
'',
'Cheatsheet',
'==========',
'',
"..",
" DO NOT MODIFY THIS FILE. IT IS AUTO GENERATED BY ``conf.py``",
" If you need to change or add methods, modify ``cheatsheet_spec`` in ``conf.py``",
"",
".. _cheatsheet:",
"",
"Cheatsheet",
"==========",
"",
*map(format_table, cheatsheet_spec),
]
Path('./docs/cheatsheet.rst').write_text('\n'.join(cheatsheet))
Path("./docs/cheatsheet.rst").write_text("\n".join(cheatsheet))


# ** Sphinx App Setup


def setup(app):
app.add_css_file('overrides.css')
app.add_css_file("overrides.css")
46 changes: 25 additions & 21 deletions fastentrypoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
"""
Monkey patch setuptools to write faster console_scripts with this format:
import sys
Expand All @@ -35,10 +35,12 @@
(c) 2016, Aaron Christianson
http://github.com/ninjaaron/fast-entry_points
'''
from setuptools.command import easy_install
"""
import re
TEMPLATE = '''\

from setuptools.command import easy_install

TEMPLATE = """\
# -*- coding: utf-8 -*-
# EASY-INSTALL-ENTRY-SCRIPT: '{3}','{4}','{5}'
__requires__ = '{3}'
Expand All @@ -49,7 +51,7 @@
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit({2}())'''
sys.exit({2}())"""


@classmethod
Expand All @@ -62,15 +64,15 @@ def get_args(cls, dist, header=None): # noqa: D205,D400
# pylint: disable=E1101
header = cls.get_header()
spec = str(dist.as_requirement())
for type_ in 'console', 'gui':
group = type_ + '_scripts'
for type_ in "console", "gui":
group = type_ + "_scripts"
for name, ep in dist.get_entry_map(group).items():
# ensure_safe_name
if re.search(r'[\\/]', name):
if re.search(r"[\\/]", name):
raise ValueError("Path separators not allowed in script names")
script_text = TEMPLATE.format(
ep.module_name, ep.attrs[0], '.'.join(ep.attrs),
spec, group, name)
ep.module_name, ep.attrs[0], ".".join(ep.attrs), spec, group, name
)
# pylint: disable=E1101
args = cls._get_script_args(type_, name, header, script_text)
for res in args:
Expand All @@ -86,27 +88,29 @@ def main():
import re
import shutil
import sys
dests = sys.argv[1:] or ['.']
filename = re.sub('\.pyc$', '.py', __file__)

dests = sys.argv[1:] or ["."]
filename = re.sub("\.pyc$", ".py", __file__)

for dst in dests:
shutil.copy(filename, dst)
manifest_path = os.path.join(dst, 'MANIFEST.in')
setup_path = os.path.join(dst, 'setup.py')
manifest_path = os.path.join(dst, "MANIFEST.in")
setup_path = os.path.join(dst, "setup.py")

# Insert the include statement to MANIFEST.in if not present
with open(manifest_path, 'a+') as manifest:
with open(manifest_path, "a+") as manifest:
manifest.seek(0)
manifest_content = manifest.read()
if 'include fastentrypoints.py' not in manifest_content:
manifest.write(('\n' if manifest_content else '') +
'include fastentrypoints.py')
if "include fastentrypoints.py" not in manifest_content:
manifest.write(
("\n" if manifest_content else "") + "include fastentrypoints.py"
)

# Insert the import statement to setup.py if not present
with open(setup_path, 'a+') as setup:
with open(setup_path, "a+") as setup:
setup.seek(0)
setup_content = setup.read()
if 'import fastentrypoints' not in setup_content:
if "import fastentrypoints" not in setup_content:
setup.seek(0)
setup.truncate()
setup.write('import fastentrypoints\n' + setup_content)
setup.write("import fastentrypoints\n" + setup_content)
17 changes: 11 additions & 6 deletions get_version.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import os, subprocess, runpy
import os
import runpy
import subprocess

# Try to get and update the version.

Expand All @@ -9,16 +11,19 @@
if "HY_VERSION" in os.environ:
__version__ = os.environ["HY_VERSION"]
else:
__version__ = (subprocess.check_output
(["git", "describe", "--tags", "--dirty"])
.decode('ASCII').strip()
.replace('-', '+', 1).replace('-', '.'))
__version__ = (
subprocess.check_output(["git", "describe", "--tags", "--dirty"])
.decode("ASCII")
.strip()
.replace("-", "+", 1)
.replace("-", ".")
)

with open(VERSIONFILE, "wt") as o:
o.write("__version__ = {!r}\n".format(__version__))

except (subprocess.CalledProcessError, OSError):
if os.path.exists(VERSIONFILE):
__version__ = runpy.run_path(VERSIONFILE)['__version__']
__version__ = runpy.run_path(VERSIONFILE)["__version__"]
else:
__version__ = "unknown"
Loading

0 comments on commit ce6d238

Please sign in to comment.