Skip to content

Commit

Permalink
Adopt ruff and address lint (#212)
Browse files Browse the repository at this point in the history
  • Loading branch information
blink1073 committed Dec 7, 2022
1 parent cabeeee commit 0caa08e
Show file tree
Hide file tree
Showing 8 changed files with 118 additions and 77 deletions.
6 changes: 4 additions & 2 deletions .github/dependabot.yml
@@ -1,8 +1,10 @@
version: 2
updates:
# Set update schedule for GitHub Actions
- package-ecosystem: "github-actions"
directory: "/"
schedule:
# Check for updates to GitHub Actions every weekday
interval: "weekly"
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "weekly"
13 changes: 9 additions & 4 deletions .github/workflows/test.yml
Expand Up @@ -111,13 +111,18 @@ jobs:
with:
package_name: jupyter_server_terminals

pre_commit:
name: Run pre-commit hook
test_lint:
name: Test Lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1
- uses: jupyterlab/maintainer-tools/.github/actions/pre-commit@v1
- name: Run Linters
run: |
hatch run typing:test
hatch run lint:style
pipx run 'validate-pyproject[all]' pyproject.toml
pipx run doc8 --max-line-length=200 --ignore-path=doc/index.rst
docs:
runs-on: ubuntu-latest
Expand All @@ -130,7 +135,7 @@ jobs:
if: always()
needs:
- test
- pre_commit
- test_lint
- docs
- check_release
- jupyter_server_terminals
Expand Down
59 changes: 14 additions & 45 deletions .pre-commit-config.yaml
@@ -1,3 +1,6 @@
ci:
autoupdate_schedule: monthly

repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
Expand All @@ -15,59 +18,25 @@ repos:
- id: check-builtin-literals
- id: trailing-whitespace

- repo: https://github.com/psf/black
rev: 22.10.0
hooks:
- id: black
args: ["--line-length", "100"]

- repo: https://github.com/PyCQA/isort
rev: 5.10.1
hooks:
- id: isort
files: \.py$
args: [--profile=black]

- repo: https://github.com/abravalheri/validate-pyproject
rev: v0.10.1
- repo: https://github.com/python-jsonschema/check-jsonschema
rev: 0.19.2
hooks:
- id: validate-pyproject
stages: [manual]
- id: check-github-workflows

- repo: https://github.com/executablebooks/mdformat
rev: 0.7.16
hooks:
- id: mdformat

- repo: https://github.com/asottile/pyupgrade
rev: v3.3.0
hooks:
- id: pyupgrade
args: [--py37-plus]

- repo: https://github.com/PyCQA/doc8
rev: v1.0.0
hooks:
- id: doc8
args: ["--max-line-length=200", "--ignore-path=doc/index.rst"]
stages: [manual]

- repo: https://github.com/john-hen/Flake8-pyproject
rev: 1.2.2
hooks:
- id: Flake8-pyproject
alias: flake8
additional_dependencies:
["flake8-bugbear==22.6.22", "flake8-implicit-str-concat==0.2.0"]
stages: [manual]
[mdformat-gfm, mdformat-frontmatter, mdformat-footnote]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: "v0.991"
- repo: https://github.com/psf/black
rev: 22.10.0
hooks:
- id: mypy
stages: [manual]
- id: black

- repo: https://github.com/python-jsonschema/check-jsonschema
rev: 0.19.2
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.165
hooks:
- id: check-github-workflows
- id: ruff
args: ["--fix"]
2 changes: 1 addition & 1 deletion doc/conf.py
Expand Up @@ -51,7 +51,7 @@
# Get information from _version.py and use it to generate version and release
_version_py = osp.join(HERE, "../terminado/_version.py")
version_ns: dict = {}
exec(compile(open(_version_py).read(), _version_py, "exec"), version_ns)
exec(compile(open(_version_py).read(), _version_py, "exec"), version_ns) # noqa
# The short X.Y version.
version = "%s.%s" % tuple(version_ns["__version__"].split(".")[:2])
# The full version, including alpha/beta/rc tags.
Expand Down
101 changes: 83 additions & 18 deletions pyproject.toml
Expand Up @@ -22,6 +22,13 @@ Homepage = "https://github.com/jupyter/terminado"
[project.optional-dependencies]
test = [ "pytest>=7.0", "pre-commit", "pytest-timeout",]
docs = [ "sphinx", "pydata-sphinx-theme", "myst_parser"]
lint = [
"black>=22.6.0",
"mdformat>0.7",
"mdformat-gfm>=0.3.5",
"ruff>=0.0.156"
]
typing = ["mypy>=0.990"]

[tool.hatch.version]
path = "terminado/_version.py"
Expand All @@ -43,7 +50,25 @@ dependencies = ["coverage", "pytest-cov"]
[tool.hatch.envs.cov.scripts]
test = "python -m pytest -vv --cov terminado --cov-branch --cov-report term-missing:skip-covered {args}"
nowarn = "test -W default {args}"
integration = "test --integration_tests=true {args}"

[tool.hatch.envs.typing]
features = ["typing", "test"]
[tool.hatch.envs.typing.scripts]
test = "mypy --install-types --non-interactive {args:terminado}"

[tool.hatch.envs.lint]
features = ["lint"]
[tool.hatch.envs.lint.scripts]
style = [
"ruff {args:.}",
"black --check --diff {args:.}",
"mdformat --check {args:doc *.md}"
]
fmt = [
"black {args:.}",
"ruff --fix {args:.}",
"mdformat {args:doc *.md}"
]

[tool.pytest.ini_options]
addopts = "-raXs --durations 10 --color=yes --doctest-modules"
Expand Down Expand Up @@ -83,23 +108,63 @@ warn_unused_configs = true
warn_unused_ignores = true
warn_redundant_casts = true

[tool.flake8]
ignore = "E501, W503, E402"
builtins = "c, get_config"
exclude = [
".cache",
".github",
"docs",
"setup.py",

[tool.black]
line-length = 100
skip-string-normalization = true
target-version = ["py38"]
extend-exclude = "^/tests.*ipynb$"

[tool.ruff]
target-version = "py38"
line-length = 100
select = [
"A", "B", "C", "E", "F", "FBT", "I", "N", "Q", "RUF", "S", "T",
"UP", "W", "YTT",
]
enable-extensions = "G"
extend-ignore = [
"G001", "G002", "G004", "G200", "G201", "G202",
# black adds spaces around ':'
"E203",
ignore = [
# Allow non-abstract empty methods in abstract base classes
"B027",
# Ignore McCabe complexity
"C901",
# Allow boolean positional values in function calls, like `dict.get(... True)`
"FBT003",
# Use of `assert` detected
"S101",
# Line too long
"E501",
# Relative imports are banned
"I252",
# Boolean ... in function definition
"FBT001", "FBT002",
# Module level import not at top of file
"E402",
# A001/A002/A003 .. is shadowing a python builtin
"A001", "A002", "A003",
# Possible hardcoded password
"S105", "S106",
# Q000 Single quotes found but double quotes preferred
"Q000",
# N806 Variable `B` in function should be lowercase
"N806",
# T201 `print` found
"T201",
# N802 Function name `CreateWellKnownSid` should be lowercase
"N802", "N803"
]
per-file-ignores = [
# B011: Do not call assert False since python -O removes these calls
# F841 local variable 'foo' is assigned to but never used
"terminado/tests/*: B011", "F841",
unfixable = [
# Don't touch print statements
"T201",
# Don't touch noqa lines
"RUF100",
]

[tool.ruff.per-file-ignores]
# B011 Do not call assert False since python -O removes these calls
# F841 local variable 'foo' is assigned to but never used
# C408 Unnecessary `dict` call
# E402 Module level import not at top of file
# T201 `print` found
# B007 Loop control variable `i` not used within the loop body.
# N802 Function name `assertIn` should be lowercase
"terminado/tests/*" = ["B011", "F841", "C408", "E402", "T201", "B007", "N802"]
10 changes: 5 additions & 5 deletions terminado/management.py
Expand Up @@ -17,14 +17,14 @@
from concurrent import futures

try:
from ptyprocess import PtyProcessUnicode
from ptyprocess import PtyProcessUnicode # type:ignore

def preexec_fn():
signal.signal(signal.SIGPIPE, signal.SIG_DFL)

except ImportError:
try:
from winpty import PtyProcess as PtyProcessUnicode
from winpty import PtyProcess as PtyProcessUnicode # type:ignore
except ImportError:
PtyProcessUnicode = object
preexec_fn = None # type:ignore[assignment]
Expand All @@ -42,7 +42,7 @@ def __init__(self, argv, env=None, cwd=None):
self.clients = []
# Use read_buffer to store historical messages for reconnection
self.read_buffer: deque[list] = deque([], maxlen=1000)
kwargs = dict(argv=argv, env=env or [], cwd=cwd)
kwargs = {"argv": argv, "env": env or [], "cwd": cwd}
if preexec_fn is not None:
kwargs["preexec_fn"] = preexec_fn
self.ptyproc = PtyProcessUnicode.spawn(**kwargs)
Expand Down Expand Up @@ -139,7 +139,7 @@ def _update_removing(target, changes):
def _poll(fd: int, timeout: float = 0.1) -> list:
"""Poll using poll() on posix systems and select() elsewhere (e.g., Windows)"""
if os.name == "posix":
poller = select.poll() # noqa: ignore missing method on Windows
poller = select.poll()
poller.register(
fd, select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR
) # read-only
Expand Down Expand Up @@ -303,7 +303,7 @@ async def kill_all(self):
self.terminal = None


class MaxTerminalsReached(Exception):
class MaxTerminalsReached(Exception): # noqa
def __init__(self, max_terminals):
self.max_terminals = max_terminals

Expand Down
2 changes: 1 addition & 1 deletion terminado/tests/basic_test.py
Expand Up @@ -25,7 +25,7 @@

from terminado import NamedTermManager, SingleTermManager, TermSocket, UniqueTermManager

if sys.version_info[0] == 3 and sys.version_info[1] >= 8 and sys.platform.startswith("win"):
if sys.version_info >= (3, 8) and sys.platform.startswith("win"):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

#
Expand Down
2 changes: 1 addition & 1 deletion terminado/websocket.py
Expand Up @@ -37,7 +37,7 @@ def initialize(self, term_manager):

def origin_check(self, origin=None):
"""Deprecated: backward-compat for terminado <= 0.5."""
return self.check_origin(origin or self.request.headers.get("Origin"))
return self.check_origin(origin or self.request.headers.get("Origin", ""))

def open(self, url_component=None):
"""Websocket connection opened.
Expand Down

0 comments on commit 0caa08e

Please sign in to comment.