Skip to content

Commit 81f9652

Browse files
authored
Enable more of ruff (#1246)
1 parent 1605a74 commit 81f9652

File tree

12 files changed

+123
-105
lines changed

12 files changed

+123
-105
lines changed

doc/conf.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
#
32
# pyOpenSSL documentation build configuration file, created by
43
# sphinx-quickstart on Sat Jul 16 07:12:22 2011.
@@ -16,7 +15,6 @@
1615
import re
1716
import sys
1817

19-
2018
HERE = os.path.abspath(os.path.dirname(__file__))
2119

2220

pyproject.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,9 @@
22
line-length = 79
33
target-version = ["py37"]
44

5+
[tool.ruff]
6+
select = ['E', 'F', 'I', 'W', 'UP', 'RUF']
7+
line-length = 79
8+
9+
[tool.ruff.isort]
10+
known-first-party = ["OpenSSL", "tests"]

setup.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
32
#
43
# Copyright (C) Jean-Paul Calderone 2008-2015, All rights reserved
54
#
@@ -13,7 +12,6 @@
1312

1413
from setuptools import find_packages, setup
1514

16-
1715
HERE = os.path.abspath(os.path.dirname(__file__))
1816
META_PATH = os.path.join("src", "OpenSSL", "version.py")
1917

@@ -23,9 +21,7 @@ def read_file(*parts):
2321
Build an absolute path from *parts* and return the contents of the
2422
resulting file. Assume UTF-8 encoding.
2523
"""
26-
with open(
27-
os.path.join(HERE, *parts), "r", encoding="utf-8", newline=None
28-
) as f:
24+
with open(os.path.join(HERE, *parts), encoding="utf-8", newline=None) as f:
2925
return f.read()
3026

3127

@@ -37,11 +33,11 @@ def find_meta(meta):
3733
Extract __*meta*__ from META_FILE.
3834
"""
3935
meta_match = re.search(
40-
r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M
36+
rf"^__{meta}__ = ['\"]([^'\"]*)['\"]", META_FILE, re.M
4137
)
4238
if meta_match:
4339
return meta_match.group(1)
44-
raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta))
40+
raise RuntimeError(f"Unable to find __{meta}__ string.")
4541

4642

4743
URI = find_meta("uri")

src/OpenSSL/SSL.py

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import socket
3+
import typing
34
from errno import errorcode
45
from functools import partial, wraps
56
from itertools import chain, count
@@ -8,18 +9,32 @@
89

910
from OpenSSL._util import (
1011
UNSPECIFIED as _UNSPECIFIED,
12+
)
13+
from OpenSSL._util import (
1114
exception_from_error_queue as _exception_from_error_queue,
15+
)
16+
from OpenSSL._util import (
1217
ffi as _ffi,
18+
)
19+
from OpenSSL._util import (
1320
lib as _lib,
21+
)
22+
from OpenSSL._util import (
1423
make_assert as _make_assert,
24+
)
25+
from OpenSSL._util import (
1526
no_zero_allocator as _no_zero_allocator,
27+
)
28+
from OpenSSL._util import (
1629
path_bytes as _path_bytes,
30+
)
31+
from OpenSSL._util import (
1732
text_to_bytes_and_warn as _text_to_bytes_and_warn,
1833
)
1934
from OpenSSL.crypto import (
2035
FILETYPE_PEM,
21-
PKey,
2236
X509,
37+
PKey,
2338
X509Name,
2439
X509Store,
2540
_PassphraseHelper,
@@ -803,7 +818,7 @@ class Context:
803818
not be used.
804819
"""
805820

806-
_methods = {
821+
_methods: typing.ClassVar[typing.Dict] = {
807822
SSLv23_METHOD: (_lib.TLS_method, None),
808823
TLSv1_METHOD: (_lib.TLS_method, TLS1_VERSION),
809824
TLSv1_1_METHOD: (_lib.TLS_method, TLS1_1_VERSION),
@@ -1373,8 +1388,8 @@ def set_client_ca_list(self, certificate_authorities):
13731388
for ca_name in certificate_authorities:
13741389
if not isinstance(ca_name, X509Name):
13751390
raise TypeError(
1376-
"client CAs must be X509Name objects, not %s "
1377-
"objects" % (type(ca_name).__name__,)
1391+
"client CAs must be X509Name objects, not {} "
1392+
"objects".format(type(ca_name).__name__)
13781393
)
13791394
copy = _lib.X509_NAME_dup(ca_name._name)
13801395
_openssl_assert(copy != _ffi.NULL)
@@ -1777,8 +1792,7 @@ def __getattr__(self, name):
17771792
"""
17781793
if self._socket is None:
17791794
raise AttributeError(
1780-
"'%s' object has no attribute '%s'"
1781-
% (self.__class__.__name__, name)
1795+
f"'{self.__class__.__name__}' object has no attribute '{name}'"
17821796
)
17831797
else:
17841798
return getattr(self._socket, name)

src/OpenSSL/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
__version__,
1818
)
1919

20-
2120
__all__ = [
2221
"SSL",
2322
"crypto",

src/OpenSSL/crypto.py

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import calendar
22
import datetime
33
import functools
4+
import typing
45
from base64 import b16encode
56
from functools import partial
67
from os import PathLike
@@ -22,23 +23,36 @@
2223
from cryptography.hazmat.primitives.asymmetric import (
2324
dsa,
2425
ec,
25-
ed25519,
2626
ed448,
27+
ed25519,
2728
rsa,
2829
)
2930

3031
from OpenSSL._util import (
3132
UNSPECIFIED as _UNSPECIFIED,
33+
)
34+
from OpenSSL._util import (
3235
byte_string as _byte_string,
36+
)
37+
from OpenSSL._util import (
3338
exception_from_error_queue as _exception_from_error_queue,
39+
)
40+
from OpenSSL._util import (
3441
ffi as _ffi,
42+
)
43+
from OpenSSL._util import (
3544
lib as _lib,
45+
)
46+
from OpenSSL._util import (
3647
make_assert as _make_assert,
48+
)
49+
from OpenSSL._util import (
3750
path_bytes as _path_bytes,
51+
)
52+
from OpenSSL._util import (
3853
text_to_bytes_and_warn as _text_to_bytes_and_warn,
3954
)
4055

41-
4256
__all__ = [
4357
"FILETYPE_PEM",
4458
"FILETYPE_ASN1",
@@ -111,7 +125,7 @@ def _untested_error(where: str) -> NoReturn:
111125
encountered isn't one that's exercised by the test suite so future behavior
112126
of pyOpenSSL is now somewhat less predictable.
113127
"""
114-
raise RuntimeError("Unknown %s failure" % (where,))
128+
raise RuntimeError(f"Unknown {where} failure")
115129

116130

117131
def _new_mem_buf(buffer: Optional[bytes] = None) -> Any:
@@ -448,7 +462,7 @@ def __ne__(self, other: Any) -> bool:
448462
circumstance.
449463
"""
450464
if isinstance(other, _EllipticCurve):
451-
return super(_EllipticCurve, self).__ne__(other)
465+
return super().__ne__(other)
452466
return NotImplemented
453467

454468
@classmethod
@@ -518,7 +532,7 @@ def __init__(self, lib: Any, nid: int, name: str) -> None:
518532
self.name = name
519533

520534
def __repr__(self) -> str:
521-
return "<Curve %r>" % (self.name,)
535+
return f"<Curve {self.name!r}>"
522536

523537
def _to_EC_KEY(self) -> Any:
524538
"""
@@ -602,14 +616,15 @@ def __init__(self, name: "X509Name") -> None:
602616

603617
def __setattr__(self, name: str, value: Any) -> None:
604618
if name.startswith("_"):
605-
return super(X509Name, self).__setattr__(name, value)
619+
return super().__setattr__(name, value)
606620

607621
# Note: we really do not want str subclasses here, so we do not use
608622
# isinstance.
609623
if type(name) is not str: # noqa: E721
610624
raise TypeError(
611-
"attribute name must be string, not '%.200s'"
612-
% (type(value).__name__,)
625+
"attribute name must be string, not '{:.200}'".format(
626+
type(value).__name__
627+
)
613628
)
614629

615630
nid = _lib.OBJ_txt2nid(_byte_string(name))
@@ -701,7 +716,7 @@ def __repr__(self) -> str:
701716
)
702717
_openssl_assert(format_result != _ffi.NULL)
703718

704-
return "<X509Name object '%s'>" % (
719+
return "<X509Name object '{}'>".format(
705720
_ffi.string(result_buffer).decode("utf-8"),
706721
)
707722

@@ -839,7 +854,7 @@ def _nid(self) -> Any:
839854
_lib.X509_EXTENSION_get_object(self._extension)
840855
)
841856

842-
_prefixes = {
857+
_prefixes: typing.ClassVar[typing.Dict[int, str]] = {
843858
_lib.GEN_EMAIL: "email",
844859
_lib.GEN_DNS: "DNS",
845860
_lib.GEN_URI: "URI",
@@ -1814,7 +1829,7 @@ class X509StoreContextError(Exception):
18141829
def __init__(
18151830
self, message: str, errors: List[Any], certificate: X509
18161831
) -> None:
1817-
super(X509StoreContextError, self).__init__(message)
1832+
super().__init__(message)
18181833
self.errors = errors
18191834
self.certificate = certificate
18201835

@@ -2166,7 +2181,7 @@ class Revoked:
21662181
# which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
21672182
# OCSP_crl_reason_str. We use the latter, just like the command line
21682183
# program.
2169-
_crl_reasons = [
2184+
_crl_reasons: typing.ClassVar[typing.List[bytes]] = [
21702185
b"unspecified",
21712186
b"keyCompromise",
21722187
b"CACompromise",
@@ -2667,7 +2682,7 @@ def set_friendlyname(self, name: Optional[bytes]) -> None:
26672682
self._friendlyname = None
26682683
elif not isinstance(name, bytes):
26692684
raise TypeError(
2670-
"name must be a byte string or None (not %r)" % (name,)
2685+
f"name must be a byte string or None (not {name!r})"
26712686
)
26722687
self._friendlyname = name
26732688

src/OpenSSL/debug.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,13 @@
1-
from __future__ import print_function
2-
31
import ssl
42
import sys
53

64
import cffi
7-
85
import cryptography
96

107
import OpenSSL.SSL
118

129
from . import version
1310

14-
1511
_env_info = """\
1612
pyOpenSSL: {pyopenssl}
1713
cryptography: {cryptography}

src/OpenSSL/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,4 @@
2525
__author__ = "The pyOpenSSL developers"
2626
__email__ = "[email protected]"
2727
__license__ = "Apache License, Version 2.0"
28-
__copyright__ = "Copyright 2001-2023 {0}".format(__author__)
28+
__copyright__ = f"Copyright 2001-2023 {__author__}"

tests/conftest.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@
77

88

99
def pytest_report_header(config):
10-
import OpenSSL.SSL
1110
import cryptography
1211

12+
import OpenSSL.SSL
13+
1314
return "OpenSSL: {openssl}\ncryptography: {cryptography}".format(
1415
openssl=OpenSSL.SSL.SSLeay_version(OpenSSL.SSL.SSLEAY_VERSION),
1516
cryptography=cryptography.__version__,

tests/memdbg.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44
from cffi import api as _api
55

6-
76
sys.modules["ssl"] = None
87
sys.modules["_hashlib"] = None
98

@@ -22,7 +21,7 @@
2221
char **backtrace_symbols(void *const *buffer, int size);
2322
void backtrace_symbols_fd(void *const *buffer, int size, int fd);
2423
"""
25-
) # noqa
24+
)
2625
_api = _ffi.verify(
2726
"""
2827
#include <openssl/crypto.h>
@@ -79,7 +78,7 @@ def free(p):
7978
if p != _ffi.NULL:
8079
C.free(p)
8180
del heap[p]
82-
log("free(0x%x)" % (int(_ffi.cast("int", p)),))
81+
log("free(0x{:x})".format(int(_ffi.cast("int", p))))
8382

8483

8584
if _api.CRYPTO_set_mem_functions(malloc, realloc, free):

0 commit comments

Comments
 (0)