Skip to content

Commit 206c942

Browse files
committed
Add to linting Configuration:
- adpot changes in dependabot.yml and remove --diff from ruff check. - select pydocstyle, isort, pyflakes, pep8-naming, pycodestyle for ruff and ignore some small issues / add inline comments. - adjust docstring length to 80 in various files Signed-off-by: E3E <ntanzill@purdue.edu>
1 parent cd543c9 commit 206c942

11 files changed

Lines changed: 87 additions & 46 deletions

File tree

.github/dependabot.yml

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,10 @@ updates:
1616
# Python dependencies that are only pinned to ensure test reproducibility
1717
patterns:
1818
- "bandit"
19-
- "black"
2019
- "coverage"
21-
- "isort"
2220
- "mypy"
23-
- "pydocstyle"
2421
- "pylint"
22+
- "ruff"
2523
- "tox"
2624
dependencies:
2725
# Python (developer) runtime dependencies. Also any new dependencies not

examples/repository/_simplerepo.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,9 @@ def _get_verification_result(
112112
)
113113

114114
def open(self, role: str) -> Metadata:
115-
"""Return current Metadata for role from 'storage' (or create a new one)"""
115+
"""Return current Metadata for role from 'storage'
116+
(or create a new one)
117+
"""
116118

117119
if role not in self.role_cache:
118120
signed_init = _signed_init.get(role, Targets)

pyproject.toml

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,11 +81,21 @@ dev-mode-dirs = ["."]
8181
line-length=80
8282

8383
[tool.ruff.lint]
84+
select = [
85+
"D", # pydocstyle
86+
"I", # isort
87+
"F", # pyflakes
88+
"N", # pep8-naming
89+
"E" # pycodestyle
90+
]
8491
ignore = ["D400","D415","D213","D205","D202","D107","D407","D413","D212","D104","D406","D105","D411","D401","D200","D203"]
85-
86-
[tool.ruff.lint.per-file-ignores]
92+
[tool.ruff.lint.per-file-ignores]
93+
"tests/*" = ["D", "E"]
94+
"examples/*/*" = ["D"]
8795
"tuf/repository/__init__.py" = ["F401"]
8896
"tuf/api/exceptions.py" = ["F401"]
97+
"tuf/repository/_repository.py" = ["N818"]
98+
"verify_release" = ["F401", "D103", "E501"]
8999

90100
# Pylint section
91101

tox.ini

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,12 @@ deps =
4747
--editable {toxinidir}
4848
lint_dirs = tuf examples tests verify_release
4949
commands =
50-
ruff check --diff {[testenv:lint]lint_dirs}
50+
ruff check {[testenv:lint]lint_dirs}
5151
ruff format --diff {[testenv:lint]lint_dirs}
5252
pylint -j 0 --rcfile=pyproject.toml {[testenv:lint]lint_dirs}
5353

5454
mypy {[testenv:lint]lint_dirs}
55-
55+
5656
bandit -r tuf
5757

5858
[testenv:docs]

tuf/api/exceptions.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#### Repository errors ####
1212

1313
# pylint: disable=unused-import
14+
# ruff: disable unused-inport
1415
from securesystemslib.exceptions import StorageError
1516

1617

@@ -23,7 +24,9 @@ class RepositoryError(Exception):
2324

2425

2526
class UnsignedMetadataError(RepositoryError):
26-
"""An error about metadata object with insufficient threshold of signatures."""
27+
"""An error about metadata object with insufficient threshold of
28+
signatures.
29+
"""
2730

2831

2932
class BadVersionNumberError(RepositoryError):

tuf/api/metadata.py

Lines changed: 51 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,10 @@
1919
2020
The above principle means that a ``Metadata`` object represents a single
2121
metadata file, and has a ``signed`` attribute that is an instance of one of the
22-
four top level signed classes (``Root``, ``Timestamp``, ``Snapshot`` and ``Targets``).
23-
To make Python type annotations useful ``Metadata`` can be type constrained: e.g. the
24-
signed attribute of ``Metadata[Root]`` is known to be ``Root``.
22+
four top level signed classes (``Root``, ``Timestamp``, ``Snapshot`` and
23+
``Targets``). To make Python type annotations useful ``Metadata`` can be
24+
type constrained: e.g. the signed attribute of ``Metadata[Root]``
25+
is known to be ``Root``.
2526
2627
Currently Metadata API supports JSON as the file format.
2728
@@ -101,8 +102,8 @@ class Metadata(Generic[T]):
101102
102103
Using a type constraint is not required but not doing so means T is not a
103104
specific type so static typing cannot happen. Note that the type constraint
104-
``[Root]`` is not validated at runtime (as pure annotations are not available
105-
then).
105+
``[Root]`` is not validated at runtime (as pure annotations are not
106+
available then).
106107
107108
New Metadata instances can be created from scratch with::
108109
@@ -227,6 +228,7 @@ def from_file(
227228
storage_backend: Object that implements
228229
``securesystemslib.storage.StorageBackendInterface``.
229230
Default is ``FilesystemBackend`` (i.e. a local file).
231+
230232
Raises:
231233
StorageError: The file cannot be read.
232234
tuf.api.serialization.DeserializationError:
@@ -357,9 +359,10 @@ def sign(
357359
"""Create signature over ``signed`` and assigns it to ``signatures``.
358360
359361
Args:
360-
signer: A ``securesystemslib.signer.Signer`` object that provides a private
361-
key and signing implementation to generate the signature. A standard
362-
implementation is available in ``securesystemslib.signer.SSlibSigner``.
362+
signer: A ``securesystemslib.signer.Signer`` object that provides a
363+
private key and signing implementation to generate the signature. A
364+
standard implementation is available in
365+
``securesystemslib.signer.SSlibSigner``.
363366
append: ``True`` if the signature should be appended to
364367
the list of signatures or replace any existing signatures. The
365368
default behavior is to replace signatures.
@@ -403,7 +406,8 @@ def verify_delegate(
403406
threshold of keys for ``delegated_role``.
404407
405408
.. deprecated:: 3.1.0
406-
Please use ``Root.verify_delegate()`` or ``Targets.verify_delegate()``.
409+
Please use ``Root.verify_delegate()`` or
410+
``Targets.verify_delegate()``.
407411
"""
408412

409413
if self.signed.type not in ["root", "targets"]:
@@ -522,7 +526,9 @@ def to_dict(self) -> Dict[str, Any]:
522526
@classmethod
523527
@abc.abstractmethod
524528
def from_dict(cls, signed_dict: Dict[str, Any]) -> "Signed":
525-
"""Deserialization helper, creates object from json/dict representation."""
529+
"""Deserialization helper, creates object from json/dict
530+
representation.
531+
"""
526532
raise NotImplementedError
527533

528534
@classmethod
@@ -533,7 +539,8 @@ def _common_fields_from_dict(
533539
representation, and returns an ordered list to be passed as leading
534540
positional arguments to a subclass constructor.
535541
536-
See ``{Root, Timestamp, Snapshot, Targets}.from_dict`` methods for usage.
542+
See ``{Root, Timestamp, Snapshot, Targets}.from_dict``
543+
methods for usage.
537544
538545
"""
539546
_type = signed_dict.pop("_type")
@@ -551,7 +558,8 @@ def _common_fields_from_dict(
551558
return version, spec_version, expires
552559

553560
def _common_fields_to_dict(self) -> Dict[str, Any]:
554-
"""Return a dict representation of common fields of ``Signed`` instances.
561+
"""Return a dict representation of common fields of
562+
``Signed`` instances.
555563
556564
See ``{Root, Timestamp, Snapshot, Targets}.to_dict`` methods for usage.
557565
@@ -700,19 +708,27 @@ def __bool__(self) -> bool:
700708

701709
@property
702710
def verified(self) -> bool:
703-
"""True if threshold of signatures is met in both underlying VerificationResults."""
711+
"""True if threshold of signatures is met in both underlying
712+
VerificationResults.
713+
"""
704714
return self.first.verified and self.second.verified
705715

706716
@property
707717
def signed(self) -> Dict[str, Key]:
708-
"""Dictionary of all signing keys that have signed, from both VerificationResults"""
709-
# return a union of all signed (in python<3.9 this requires dict unpacking)
718+
"""Dictionary of all signing keys that have signed, from both
719+
VerificationResults.
720+
return a union of all signed (in python<3.9 this requires
721+
dict unpacking)
722+
"""
710723
return {**self.first.signed, **self.second.signed}
711724

712725
@property
713726
def unsigned(self) -> Dict[str, Key]:
714-
"""Dictionary of all signing keys that have not signed, from both VerificationResults"""
715-
# return a union of all unsigned (in python<3.9 this requires dict unpacking)
727+
"""Dictionary of all signing keys that have not signed, from both
728+
VerificationResults.
729+
return a union of all unsigned (in python<3.9 this requires
730+
dict unpacking)
731+
"""
716732
return {**self.first.unsigned, **self.second.unsigned}
717733

718734

@@ -828,8 +844,8 @@ class Root(Signed, _DelegatorMixin):
828844
roles: Dictionary of role names to Roles. Defines which keys are
829845
required to sign the metadata for a specific role. Default is
830846
a dictionary of top level roles without keys and threshold of 1.
831-
consistent_snapshot: ``True`` if repository supports consistent snapshots.
832-
Default is True.
847+
consistent_snapshot: ``True`` if repository supports consistent
848+
snapshots. Default is True.
833849
unrecognized_fields: Dictionary of all attributes that are not managed
834850
by TUF Metadata API
835851
@@ -1191,6 +1207,7 @@ def from_data(
11911207
data: Metadata bytes that the metafile represents.
11921208
hash_algorithms: Hash algorithms to create the hashes with. If not
11931209
specified, the securesystemslib default hash algorithm is used.
1210+
11941211
Raises:
11951212
ValueError: The hash algorithms list contains an unsupported
11961213
algorithm.
@@ -1234,7 +1251,8 @@ class Timestamp(Signed):
12341251
"""A container for the signed part of timestamp metadata.
12351252
12361253
TUF file format uses a dictionary to contain the snapshot information:
1237-
this is not the case with ``Timestamp.snapshot_meta`` which is a ``MetaFile``.
1254+
this is not the case with ``Timestamp.snapshot_meta`` which is a
1255+
``MetaFile``.
12381256
12391257
*All parameters named below are not just constructor arguments but also
12401258
instance attributes.*
@@ -1366,12 +1384,13 @@ class DelegatedRole(Role):
13661384
13671385
A delegation can happen in two ways:
13681386
1369-
- ``paths`` is set: delegates targets matching any path pattern in ``paths``
1370-
- ``path_hash_prefixes`` is set: delegates targets whose target path hash
1371-
starts with any of the prefixes in ``path_hash_prefixes``
1387+
- ``paths`` is set: delegates targets matching any path pattern in
1388+
``paths``
1389+
- ``path_hash_prefixes`` is set: delegates targets whose target path
1390+
hash starts with any of the prefixes in ``path_hash_prefixes``
13721391
1373-
``paths`` and ``path_hash_prefixes`` are mutually exclusive: both cannot be
1374-
set, at least one of them must be set.
1392+
``paths`` and ``path_hash_prefixes`` are mutually exclusive:
1393+
both cannot be set, at least one of them must be set.
13751394
13761395
*All parameters named below are not just constructor arguments but also
13771396
instance attributes.*
@@ -1491,10 +1510,10 @@ def is_delegated_path(self, target_filepath: str) -> bool:
14911510
"""Determine whether the given ``target_filepath`` is in one of
14921511
the paths that ``DelegatedRole`` is trusted to provide.
14931512
1494-
The ``target_filepath`` and the ``DelegatedRole`` paths are expected to be
1495-
in their canonical forms, so e.g. "a/b" instead of "a//b" . Only "/" is
1496-
supported as target path separator. Leading separators are not handled
1497-
as special cases (see `TUF specification on targetpath
1513+
The ``target_filepath`` and the ``DelegatedRole`` paths are expected to
1514+
be in their canonical forms, so e.g. "a/b" instead of "a//b" . Only "/"
1515+
is supported as target path separator. Leading separators are not
1516+
handled as special cases (see `TUF specification on targetpath
14981517
<https://theupdateframework.github.io/specification/latest/#targetpath>`_).
14991518
15001519
Args:
@@ -1613,7 +1632,8 @@ def to_dict(self) -> Dict[str, Any]:
16131632
}
16141633

16151634
def get_role_for_target(self, target_filepath: str) -> str:
1616-
"""Calculate the name of the delegated role responsible for ``target_filepath``.
1635+
"""Calculate the name of the delegated role responsible for
1636+
``target_filepath``.
16171637
16181638
The target at path ``target_filepath`` is assigned to a bin by casting
16191639
the left-most ``bit_length`` of bits of the file path hash digest to
@@ -1897,6 +1917,7 @@ def from_file(
18971917
local_path: Local path to target file content.
18981918
hash_algorithms: Hash algorithms to calculate hashes with. If not
18991919
specified the securesystemslib default hash algorithm is used.
1920+
19001921
Raises:
19011922
FileNotFoundError: The file doesn't exist.
19021923
ValueError: The hash algorithms list contains an unsupported

tuf/ngclient/_internal/requests_fetcher.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
# Copyright 2021, New York University and the TUF contributors
22
# SPDX-License-Identifier: MIT OR Apache-2.0
33

4-
"""Provides an implementation of ``FetcherInterface`` using the Requests HTTP library.
4+
"""Provides an implementation of ``FetcherInterface`` using the Requests HTTP
5+
library.
56
"""
67

78
# requests_fetcher is public but comes from _internal for now (because
@@ -117,7 +118,8 @@ def _chunks(self, response: "requests.Response") -> Iterator[bytes]:
117118
response.close()
118119

119120
def _get_session(self, url: str) -> requests.Session:
120-
"""Return a different customized requests.Session per schema+hostname combination.
121+
"""Return a different customized requests.Session per schema+hostname
122+
combination.
121123
122124
Raises:
123125
exceptions.DownloadError: When there is a problem parsing the url.

tuf/ngclient/_internal/trusted_metadata_set.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,9 +73,10 @@
7373
class TrustedMetadataSet(abc.Mapping):
7474
"""Internal class to keep track of trusted metadata in ``Updater``.
7575
76-
``TrustedMetadataSet`` ensures that the collection of metadata in it is valid
77-
and trusted through the whole client update workflow. It provides easy ways
78-
to update the metadata with the caller making decisions on what is updated.
76+
``TrustedMetadataSet`` ensures that the collection of metadata in it is
77+
valid and trusted through the whole client update workflow. It provides
78+
easy ways to update the metadata with the caller making decisions on
79+
what is updated.
7980
"""
8081

8182
def __init__(self, root_data: bytes):
@@ -107,7 +108,9 @@ def __len__(self) -> int:
107108
return len(self._trusted_set)
108109

109110
def __iter__(self) -> Iterator[Metadata]:
110-
"""Return iterator over ``Metadata`` objects in ``TrustedMetadataSet``."""
111+
"""Return iterator over ``Metadata`` objects in
112+
``TrustedMetadataSet``.
113+
"""
111114
return iter(self._trusted_set.values())
112115

113116
# Helper properties for top level metadata

tuf/repository/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,5 @@
1010
The repository module is not considered part of the stable python-tuf API yet.
1111
"""
1212

13+
# ruff: disable unused-inport
1314
from tuf.repository._repository import AbortEdit, Repository

tuf/repository/_repository.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
logger = logging.getLogger(__name__)
2323

2424

25+
# ruff: ignore N818 `Exception name should have Error suffix`
2526
class AbortEdit(Exception):
2627
"""Raise to exit the edit() contextmanager without saving changes"""
2728

0 commit comments

Comments
 (0)