Skip to content

Commit

Permalink
General cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
LilSpazJoekp committed Dec 7, 2022
1 parent 8edcd93 commit fad201d
Show file tree
Hide file tree
Showing 14 changed files with 107 additions and 109 deletions.
1 change: 0 additions & 1 deletion .pre-commit-config.yaml
Expand Up @@ -32,7 +32,6 @@ repos:
- repo: https://github.com/LilSpazJoekp/docstrfmt
hooks:
- id: docstrfmt
require_serial: true
rev: v1.5.1

- repo: https://github.com/pycqa/flake8
Expand Down
3 changes: 2 additions & 1 deletion .readthedocs.yml
@@ -1,10 +1,11 @@
formats:
- htmlzip
- pdf
python:
install:
- method: pip
extra_requirements:
- readthedocs
path: .
version: 3.8
version: '3.8'
version: 2
4 changes: 0 additions & 4 deletions MANIFEST.in
@@ -1,7 +1,3 @@
include CHANGES.rst LICENSE.txt README.rst praw_license.txt
include asyncpraw/praw.ini
include "asyncpraw/images/PRAW logo.png"
include docs/Makefile
recursive-include docs *.png *.py *.rst
recursive-include tests *.json *.py
recursive-include tests/files *
164 changes: 91 additions & 73 deletions pre_push.py
@@ -1,104 +1,122 @@
#!/usr/bin/env python3
"""Run static analysis on the project."""

import argparse
import enum
import sys
from contextlib import contextmanager
from subprocess import CalledProcessError, check_call
from tempfile import TemporaryDirectory
from typing import List

import click

def do_process(args, shell=False):
"""Run program provided by args.
Return ``True`` on success.

Output failed message on non-zero exit and return False.
class Stage(enum.IntFlag):
"""Enum to represent the different stages of linting."""

Exit if command is not found.
BUILD_DOCS = enum.auto()
PRE_COMMIT = enum.auto()
UNIT_TESTS = enum.auto()
ALL = BUILD_DOCS | PRE_COMMIT | UNIT_TESTS

"""
print(f"Running: {' '.join(args)}")
try:
check_call(args, shell=shell)
except CalledProcessError:
print(f"\nFailed: {' '.join(args)}")
return False
except Exception as exc:
sys.stderr.write(f"{str(exc)}\n")
sys.exit(1)
return True
@contextmanager
def get_commands(self) -> List[List[str]]:
"""Return the commands to run for the given stage."""
commands = []
with TemporaryDirectory() as tmp_dir:
if self & Stage.PRE_COMMIT:
commands.append(["pre-commit", "run", "--all-files"])
if self & Stage.BUILD_DOCS:
commands.append(["sphinx-build", "-W", "--keep-going", "docs", tmp_dir])
if self & Stage.UNIT_TESTS:
commands.append(["pytest"])
yield commands


def run_static():
"""Runs the static tests.
def execute_check(check: List[str]) -> int:
"""Runs the checks in the given list.
Returns a statuscode of 0 if everything ran correctly. Otherwise, it will return
statuscode 1
status code 1
"""
success = True
success &= do_process(["pre-commit", "run", "--all-files"])

with TemporaryDirectory() as tmp_dir:
success &= do_process(["sphinx-build", "-W", "--keep-going", "docs", tmp_dir])

click.echo(f"Running: {' '.join(check)}")
try:
check_call(check, shell=False)
except CalledProcessError:
click.echo(f"\nFailed: {' '.join(check)}", err=True)
success = False
except Exception as exc:
click.echo(f"{str(exc)}\n", err=True)
sys.exit(1)
return success


def run_unit():
"""Runs the unit-tests.
Follows the behavior of the static tests, where any failed tests cause pre_push.py
to fail.
"""
return do_process(["pytest"])


def main():
"""Runs the main function.
usage: pre_push.py [-h] [-n] [-u] [-a]
Run static and/or unit-tests
@click.command()
@click.option(
"-a",
"--all",
"all_checks",
default=False,
help="Run all the checks (building docs, linting, and unit tests). If this is"
" provided, all other parameters are ignored.",
is_flag=True,
)
@click.option(
"-s",
"--skip-build-docs",
"skip_build_docs",
default=False,
help="Skip building the docs.",
is_flag=True,
)
@click.option(
"-n",
"--skip-linting",
"skip_linting",
default=False,
help="Skip static pre-commit linting checks and formatters.",
is_flag=True,
)
@click.option(
"-u",
"--unit",
"--unit-tests",
"unit_tests",
default=False,
help="Run the unit tests.",
is_flag=True,
)
def main(all_checks, skip_build_docs, skip_linting, unit_tests):
"""Run the main function.
Runs the linting, unit tests, and building of the docs.
"""
parser = argparse.ArgumentParser(description="Run static and/or unit-tests")
parser.add_argument(
"-n",
"--unstatic",
action="store_true",
help="Do not run static tests (black/flake8/pydocstyle/sphinx-build)",
default=False,
)
parser.add_argument(
"-u",
"--unit-tests",
"--unit",
action="store_true",
default=False,
help="Run the unit tests",
)
parser.add_argument(
"-a",
"--all",
action="store_true",
default=False,
help="Run all the tests (static and unit). Overrides the unstatic argument.",
)
args = parser.parse_args()
success = True
try:
if not args.unstatic or args.all:
success &= run_static()
if args.all or args.unit_tests:
success &= run_unit()
if all_checks:
checks = Stage.ALL
else:
checks = Stage(0) # 0 means no checks
if not skip_linting:
checks |= Stage.PRE_COMMIT
if not skip_build_docs:
checks |= Stage.BUILD_DOCS
if unit_tests:
checks |= Stage.UNIT_TESTS
with checks.get_commands() as commands:
success = True
for command in commands:
success &= execute_check(command)
except KeyboardInterrupt:
return int(not False)
return int(not success)


if __name__ == "__main__":
exit_code = main()
print("\npre_push.py: Success!" if not exit_code else "\npre_push.py: Fail")
click.echo(
"\npre_push.py: Success!" if not exit_code else "\npre_push.py: Fail",
err=not exit_code,
)
sys.exit(exit_code)
5 changes: 5 additions & 0 deletions pyproject.toml
Expand Up @@ -8,3 +8,8 @@ extend_exclude = ['./docs/examples/']
[tool.isort]
profile = 'black'
skip_glob = '.venv*'

[tool.pytest.ini_options]
asyncio_mode = "auto"
filterwarnings = "ignore::DeprecationWarning"
testpaths = "tests"
5 changes: 0 additions & 5 deletions pytest.ini

This file was deleted.

2 changes: 0 additions & 2 deletions setup.cfg

This file was deleted.

4 changes: 2 additions & 2 deletions setup.py
Expand Up @@ -10,11 +10,11 @@
with open(path.join(HERE, "README.rst"), encoding="utf-8") as fp:
README = fp.read()
with open(path.join(HERE, PACKAGE_NAME, "const.py"), encoding="utf-8") as fp:
VERSION = re.search('__version__ = "([^"]+)"', fp.read()).group(1)
VERSION = re.search(r'__version__ = "([^"]+)"', fp.read()).group(1)

extras = {
"ci": ["coveralls"],
"dev": ["packaging"],
"dev": ["click", "packaging"],
"lint": ["pre-commit"],
"readthedocs": [
"readthedocs-sphinx-search",
Expand Down
2 changes: 1 addition & 1 deletion tools/bump_version.py
Expand Up @@ -8,7 +8,7 @@ def main():
line = sys.stdin.readline()
if not line.startswith(COMMIT_PREFIX):
sys.stderr.write(
f"Commit message does not begin with `{COMMIT_PREFIX}`.\nMessage:\n\n{line}"
f"Commit message does not begin with '{COMMIT_PREFIX}'.\nMessage:\n\n{line}"
)
return 1
print(line[len(COMMIT_PREFIX) : -1])
Expand Down
2 changes: 1 addition & 1 deletion tools/check_documentation.py
Expand Up @@ -27,7 +27,7 @@ class DocumentationChecker:
ModmailObject, # is never publicly accessed
}
HAS_CODE_BLOCK = re.compile(r".. code-block::")
HAS_ATTRIBUTE_TABLE = re.compile(r"Attribute[ ]+Description")
HAS_ATTRIBUTE_TABLE = re.compile(r"Attribute +Description")
METHOD_EXCEPTIONS = {"from_data", "id_from_url", "parse", "sluggify", "gild"}
subclasses = set()

Expand Down
Empty file removed tools/generate_award_table.py
Empty file.
2 changes: 1 addition & 1 deletion tools/set_version.py
Expand Up @@ -7,7 +7,7 @@

CHANGELOG_HEADER = (
"Change Log\n==========\n\n"
"Async PRAW follows `semantic versioning <http://semver.org/>`_.\n\n"
"Async PRAW follows `semantic versioning <https://semver.org/>`_.\n\n"
)
UNRELEASED_HEADER = "Unreleased\n----------\n\n"

Expand Down
2 changes: 1 addition & 1 deletion tools/static_word_checks.py
Expand Up @@ -10,7 +10,7 @@ class StaticChecker:
def __init__(self, replace: bool):
"""Initialize a :class:`.StaticChecker` instance.
:param replace: Whether or not to make replacements.
:param replace: Whether to make replacements.
"""
self.full_file_checks = [
Expand Down
20 changes: 3 additions & 17 deletions tox.ini
@@ -1,22 +1,8 @@
[tox]
envlist = py36,py37,py38
skip_missing_interpreters = true
skipsdist = true
envlist = py37,py38,py39,py310
skip_missing_interpreters = false

[testenv]
deps =
betamax >=0.8, <0.9
betamax-matchers >=0.3.0, <0.5
pytest >=2.7.3
flake8
commands =
pytest
flake8 --exclude=.eggs,build,docs
passenv =
prawtest_client_id
prawtest_client_secret
prawtest_password
prawtest_refresh_token
prawtest_test_subreddit
prawtest_username
prawtest_user_agent
extras = dev

0 comments on commit fad201d

Please sign in to comment.