fix linting errors #297

Merged
cmo merged 15 commits from fix-linting-errors into master 2026-11-12 08:16:09 +00:00
59 changed files with 260 additions and 251 deletions

View file

@ -1,4 +1,4 @@
# 6.X.X (2026-XX-XX)
# 6.8.0 (2026-10-11)
## New features

View file

@ -122,7 +122,7 @@ class CollectionConfig(BaseModel):
schema_location: str = Field(alias='schema')
incoming: PurePosixPath | None = None
backend: RecordDirBackendConfig | SQLiteBackendConfig = RecordDirBackendConfig(
type='record_dir+stl'
type='record_dir+stl',
)
auth_sources: list[ForgejoAuthSpec | ConfigAuthSpec] = [ConfigAuthSpec()]
audit_backends: list[GitAuditBackendConfig] = []
@ -237,7 +237,7 @@ def get_config_backends(
if config_backend is None:
config_backend = RecordDirStore(
config_path, mapping_functions[MappingMethod.digest_md5], 'yaml'
config_path, mapping_functions[MappingMethod.digest_md5], 'yaml',
)
audit_path = store_path / config_audit_path
@ -368,11 +368,11 @@ def check_label(
"""Check that a label exists in a collection configuration or on disk"""
if label not in get_config_labels(
abstract_config, collection
abstract_config, collection,
) and label not in get_on_disk_labels(store_path, abstract_config, collection):
if create_if_missing:
logger.debug(
"Creating incoming label '%' in collection '%'",
"Creating incoming label '%s' in collection '%s'",
label,
collection,
)
@ -557,7 +557,7 @@ def get_conflicting_paths(
# is added.
if collection_config.incoming:
containing_path, _ = _get_containing_path(
collection_config.incoming, collection_config.curated
collection_config.incoming, collection_config.curated,
)
else:
containing_path = None
@ -587,7 +587,7 @@ def get_conflicting_paths(
other_path,
other_collection,
usage_info[other_path],
)
),
)
else:
result.append(
@ -598,7 +598,7 @@ def get_conflicting_paths(
current_path,
current_collection,
usage_info[current_path],
)
),
)
return result
@ -618,4 +618,6 @@ def _get_containing_path(
return container, position
except ValueError:
pass
else:
return container, position
return None, None

View file

@ -154,7 +154,7 @@ class GitAuditBackend(AuditBackend):
filter(
lambda line: not line.startswith('+++') and line.startswith('+'),
log_diff_lines,
)
),
)[1:]
log_entry = json.loads(log_line)
@ -185,7 +185,7 @@ class GitAuditBackend(AuditBackend):
log_entry['author_id'],
yaml_diff,
yaml_content,
)
),
)
changes.sort()
@ -208,7 +208,7 @@ class GitAuditBackend(AuditBackend):
filter(
lambda record_id: matcher.fullmatch(record_id) is not None,
self.index,
)
),
)
return {
record_id: self._locked_get_audit_log(record_id)
@ -223,7 +223,7 @@ class GitAuditBackend(AuditBackend):
author_id: str,
record: dict,
) -> bool:
from dump_things_service.utils import json2yaml # noqa PLC0415 -- global import leads to circular imports
from dump_things_service.utils import json2yaml
existing_record = self._read_record_from_repo_path(location[1])
if existing_record != record:
@ -305,7 +305,7 @@ class GitAuditBackend(AuditBackend):
self,
record_id: str,
) -> tuple[str, Path, Path]:
base = hashlib.sha1(record_id.encode()).hexdigest() # noqa S324 -- hash is not used for security
base = hashlib.sha1(record_id.encode()).hexdigest() # noqa: S324 -- not used for crypto
dir_1, dir_2, _name = base[0:3], base[3:6], base[6:]
location_dir = Path(dir_1) / Path(dir_2)
return (
@ -327,7 +327,7 @@ class GitAuditBackend(AuditBackend):
self.repo = Repo(self.path)
call_git(['config', 'user.name', 'dump-things-service'], cwd=self.path)
call_git(
['config', 'user.email', 'dump-things-service@localhost'], cwd=self.path
['config', 'user.email', 'dump-things-service@localhost'], cwd=self.path,
)
apply_changeset(
self.repo,
@ -341,7 +341,7 @@ class GitAuditBackend(AuditBackend):
if not self.index_path.exists():
self.rebuild_index()
with open(self.index_path) as f:
with self.index_path.open() as f:
self.index = {line.strip() for line in f}
def _add_to_index(
@ -362,7 +362,7 @@ class GitAuditBackend(AuditBackend):
.decode()
.splitlines()
)
with open(self.index_path, 'w') as f:
with self.index_path.open('w') as f:
for line in tree_entries:
if not line.endswith('.yaml'):
continue
@ -372,6 +372,6 @@ class GitAuditBackend(AuditBackend):
['show', object_hash],
cwd=self.path,
capture_output=True,
).decode()
).decode(),
)
f.write(record['pid'] + '\n')

View file

@ -6,10 +6,10 @@ from dump_things_service.audit.gitaudit import GitAuditBackend
def _get_git_log(path: Path) -> list[str]:
result = subprocess.run(
['git', '-C', str(path), 'log', '--oneline'], # noqa S607 -- test run in a controlled environment
['git', '-C', str(path), 'log', '--oneline'],
capture_output=True,
check=True,
)
) # noqa S603, S607 -- environment and input are controlled
return result.stdout.decode().splitlines()

View file

@ -116,7 +116,7 @@ class ForgejoAuthenticationSource(AuthenticationSource, MethodCache):
self.organization = organization
self.team = team
self.label_type = label_type
self.instance_id = instance_id or hashlib.md5(self.api_url.encode()).hexdigest()
self.instance_id = instance_id or hashlib.md5(self.api_url.encode()).hexdigest() # noqa S324 -- not used for crypto
self.repository = repository
def _get_json_from_endpoint(
@ -134,16 +134,16 @@ class ForgejoAuthenticationSource(AuthenticationSource, MethodCache):
},
timeout=_timeout,
)
except Timeout:
except Timeout as e:
logger.info('timeout in request to %s', api_url)
raise RemoteAuthenticationError()
raise RemoteAuthenticationError from e
except requests.exceptions.RequestException as e:
logger.info('could not read from %s: %s', api_url, e)
raise RemoteAuthenticationError()
raise RemoteAuthenticationError from e
if r.status_code >= HTTP_300_MULTIPLE_CHOICES:
logger.info('invalid token: %d', r.status_code)
raise RemoteAuthenticationError()
raise RemoteAuthenticationError
return r.json()
@MethodCache.cache_temporary(duration=120)
@ -216,7 +216,7 @@ class ForgejoAuthenticationSource(AuthenticationSource, MethodCache):
self.team,
self.organization,
)
raise RemoteAuthenticationError()
raise RemoteAuthenticationError
return permissions
@MethodCache.cache_temporary(duration=60)
@ -241,7 +241,7 @@ class ForgejoAuthenticationSource(AuthenticationSource, MethodCache):
'token user is not member of team %s',
self.team,
)
raise RemoteAuthenticationError()
raise RemoteAuthenticationError
organization = self._get_organization(token)
user_info = self._get_user(token)
@ -279,7 +279,7 @@ class ForgejoAuthenticationSource(AuthenticationSource, MethodCache):
self.organization,
self.team,
)
raise RemoteAuthenticationError()
raise RemoteAuthenticationError
# Get the repo.code permissions from the team definition
code_permissions = self._get_unit_content(team, 'repo.code')

View file

@ -70,7 +70,7 @@ class BackendResultList(LazyList):
:return: A JSON object.
"""
return self.generate_result(
index, info.iri, info.class_name, info.sort_key, info.private
index, info.iri, info.class_name, info.sort_key, info.private,
)
def unique_identifier(self, info: ResultListInfo) -> Any:

View file

@ -8,9 +8,7 @@ from __future__ import annotations
import logging
from pathlib import Path
from typing import (
TYPE_CHECKING,
)
from typing import TYPE_CHECKING
import yaml
@ -61,7 +59,7 @@ class RecordDirResultList(BackendResultList):
:param path: The path where the record is stored
:return: A RecordInfo object.
"""
from dump_things_service.utils import order_dict # noqa PLC0415 -- global import leads to circular imports
from dump_things_service.utils import order_dict
with path.open('r') as f:
json_object = yaml.load(f, Loader=yaml.SafeLoader)
@ -113,7 +111,7 @@ class _RecordDirStore(StorageBackend):
class_name: str,
json_object: dict,
):
from dump_things_service.utils import json2yaml # noqa PLC0415 -- global import leads to circular imports
from dump_things_service.utils import json2yaml
pid = json_object['pid']
@ -184,7 +182,7 @@ class _RecordDirStore(StorageBackend):
for index_entry in self.index.get_info_for_class(class_name)
),
key=lambda result_list_info: result_list_info.sort_key,
)
),
)
def get_all_records(
@ -206,7 +204,7 @@ class _RecordDirStore(StorageBackend):
for index_entry in self.index.get_info_for_all_classes()
),
key=lambda result_list_info: result_list_info.sort_key,
)
),
)
def remove_record(
@ -230,7 +228,7 @@ class _RecordDirStore(StorageBackend):
_existing_stores: dict[Path, _RecordDirStore] = {}
def RecordDirStore( # noqa: N802
def RecordDirStore(
root: Path,
pid_mapping_function: Callable,
suffix: str,

View file

@ -128,7 +128,7 @@ class RecordDirIndex:
class_name=class_name,
path=path,
sort_key=sort_key,
)
),
)
def get_info_for_iri(
@ -216,7 +216,7 @@ class RecordDirIndex:
path=str(path),
class_name=class_name,
sort_key=sort_key,
)
),
)
except ValueError as e:
lgr.error('Error during index creation: %s', e)

View file

@ -60,7 +60,7 @@ class SchemaTypeLayerResultList(BackendResultList):
private: Any,
) -> RecordInfo:
origin_element = self.origin_list.generate_result(
index, iri, class_name, sort_key, private
index, iri, class_name, sort_key, private,
)
if 'schema_type' not in origin_element.json_object:
origin_element.json_object = order_dict(
@ -70,7 +70,7 @@ class SchemaTypeLayerResultList(BackendResultList):
origin_element.class_name,
self.schema_model,
),
}
},
)
return origin_element
@ -134,7 +134,7 @@ class _SchemaTypeLayer(StorageBackend):
origin_result.class_name,
self.schema_model,
),
}
},
)
return origin_result
@ -190,7 +190,7 @@ def _get_schema_type(
_existing_layers = {}
def SchemaTypeLayer( # noqa: N802
def SchemaTypeLayer(
backend: StorageBackend,
schema: str,
) -> _SchemaTypeLayer:

View file

@ -36,6 +36,7 @@ from typing import (
from sqlalchemy import (
JSON,
String,
bindparam,
create_engine,
delete,
select,
@ -221,7 +222,7 @@ class _SQLiteBackend(StorageBackend):
class_name=class_name,
object=json_object,
sort_key=sort_key,
)
),
)
def get_record_by_iri(
@ -236,7 +237,7 @@ class _SQLiteBackend(StorageBackend):
thing = session.scalar(statement)
if thing:
thing_policy = thing.object.get('annotations', {}).get(
policy_annotation_tag, default_policy
policy_annotation_tag, default_policy,
)
if (
thing_policy and thing_policy in active_policies
@ -257,7 +258,6 @@ class _SQLiteBackend(StorageBackend):
default_policy: str | None = None,
active_policies: set[str] | None = None,
) -> SQLResultList:
class_list = ', '.join(f"'{cn}'" for cn in class_names)
active_policies = active_policies or set()
policy_clause = self._get_policy_clause(
@ -268,24 +268,31 @@ class _SQLiteBackend(StorageBackend):
if pattern is None:
statement = text(
'select distinct thing.iri, thing.class_name, thing.sort_key, thing.id ' # noqa S608 -- all variables are controlled
'select distinct thing.iri, thing.class_name, thing.sort_key, thing.id '
'from thing '
f'where ({policy_clause}) '
f'and thing.class_name in ({class_list}) '
'ORDER BY thing.sort_key'
f'and thing.class_name in :class_set '
'ORDER BY thing.sort_key',
).bindparams(
bindparam('class_set', expanding=True),
class_set=class_names,
)
else:
statement = text(
'select distinct thing.iri, thing.class_name, thing.sort_key, thing.id ' # noqa S608 -- all variables are controlled
'select distinct thing.iri, thing.class_name, thing.sort_key, thing.id '
'from thing, json_tree(thing.object) '
f'where ({policy_clause}) '
'and lower(json_tree.value) like lower(:pattern) '
f'and thing.class_name in ({class_list}) '
"and json_tree.type = 'text' ORDER BY thing.sort_key"
f'and thing.class_name in :class_set '
"and json_tree.type = 'text' ORDER BY thing.sort_key",
).bindparams(
bindparam('class_set', expanding=True),
pattern=pattern,
class_set=class_names,
)
with self.engine.connect() as connection:
rs = connection.execute(statement, parameters={'pattern': pattern})
rs = connection.execute(statement)
return SQLResultList(self.engine).add_info(
ResultListInfo(
iri=thing.iri,
@ -315,7 +322,7 @@ class _SQLiteBackend(StorageBackend):
'select distinct thing.iri, thing.class_name, thing.sort_key, thing.id '
'from thing '
f'where {policy_clause} '
'ORDER BY thing.sort_key'
'ORDER BY thing.sort_key',
)
else:
statement = text(
@ -324,7 +331,7 @@ class _SQLiteBackend(StorageBackend):
'where lower(json_tree.value) like lower(:pattern) '
"and json_tree.type = 'text' "
f'and ({policy_clause}) '
'ORDER BY thing.sort_key'
'ORDER BY thing.sort_key',
)
with self.engine.connect() as connection:
@ -381,8 +388,8 @@ class _SQLiteBackend(StorageBackend):
_existing_sqlite_backends: dict[Path, _SQLiteBackend] = {}
def SQLiteBackend( # noqa: N802
db_path: Path, *, order_by: Iterable[str] | None = None, echo: bool = False
def SQLiteBackend(
db_path: Path, *, order_by: Iterable[str] | None = None, echo: bool = False,
) -> _SQLiteBackend:
existing_backend = _existing_sqlite_backends.get(db_path)
if not existing_backend:

View file

@ -20,7 +20,7 @@ def test_add_and_delete_record(tmp_path):
record_dir_store.build_index(str(schema_path))
record_dir_store.add_record(
iri=iri, class_name='Object', json_object={'pid': 'some-pid'}
iri=iri, class_name='Object', json_object={'pid': 'some-pid'},
)
record = record_dir_store.get_record_by_iri(iri=iri)

View file

@ -2,10 +2,9 @@ import json
import logging
import os
import shutil
import fsspec
from pathlib import Path
import fsspec
from datalad_core.runners import (
CommandError,
call_git_oneline,
@ -40,7 +39,6 @@ from dump_things_service.instance_state import (
)
from dump_things_service.utils import create_store
logger = logging.getLogger('dump_things_service')
@ -198,7 +196,7 @@ def create_collection(
GitAuditBackend(
path=Path(instance_state.store_path / audit_backend_config.path),
auto_flush_timeout=audit_backend_config.auto_flush_timeout,
)
),
)
@ -397,15 +395,6 @@ def reload_policy(
].policy_annotation_tag = policy_annotation_tag
def refresh_collection_state(
a: int,
) -> tuple[tuple, dict] | None:
print('refresh_collection_state called with argument:', a)
if a % 100 >= 10:
return None
return (), dict(a=a + 1)
def check_recoverable_errors(
abstract_configuration: Configuration,
instance_state: InstanceState,
@ -419,6 +408,6 @@ def check_recoverable_errors(
instance_state=instance_state,
configuration=abstract_configuration,
)
except Exception as e:
except Exception as e: # noqa: BLE001 -- we don't know which errors might occur during recovery, so we catch all exceptions
logger.info(f'Error recovery failed: {e}')
return (abstract_configuration, instance_state), {}

View file

@ -38,7 +38,7 @@ parser.add_argument(
def check_pids_in_stores(stores: Iterable[_ModelStore]) -> int:
result = 0
for store in stores:
print('checking', store.get_uri(), file=sys.stderr) # noqa T201 -- cli result output
print('checking', store.get_uri(), file=sys.stderr)
for record_info in store.get_all_objects():
pid = record_info.json_object['pid']
try:
@ -95,7 +95,7 @@ def main():
arguments = parser.parse_args()
result = check_pids(Path(arguments.store).absolute())
if result > 0:
print(f'found {result} unresolvable pids', file=sys.stderr) # noqa T201 -- cli result output
print(f'found {result} unresolvable pids', file=sys.stderr)
return 1
return 0

View file

@ -14,7 +14,7 @@ parser.add_argument('schema', help='File containing a schema definition')
def update_uris_for_elements(
all_elements: dict, attribute_name: str, prefix_index: dict
all_elements: dict, attribute_name: str, prefix_index: dict,
):
for name, info in all_elements.items():
uri = getattr(info, attribute_name)
@ -64,7 +64,7 @@ def main():
allow_unicode=True,
sort_keys=False,
)
print(text) # noqa T201 -- cli result output
print(text)
return 0

View file

@ -61,7 +61,7 @@ def main():
admin_token = os.environ.get('DTS_ADMIN_TOKEN')
if not admin_token:
print( # noqa T201 -- cli result output
print(
'An admin token must be provided in the environment variable `DTS_ADMIN_TOKEN`',
file=sys.stderr,
flush=True,
@ -75,9 +75,9 @@ def main():
)
if arguments.format == 'json':
print(json.dumps(configuration, indent=2, sort_keys=False)) # noqa T201 -- cli result output
print(json.dumps(configuration, indent=2, sort_keys=False))
elif arguments.format == 'yaml':
print(json2yaml(configuration)) # noqa T201 -- cli result output
print(json2yaml(configuration))
return 0

View file

@ -11,7 +11,7 @@ parser = ArgumentParser(
description='This command rebuilds the index of a `gitaudit`-database.',
)
parser.add_argument(
'audit_store', help='The directory in which the `gitaudit`-database is located.'
'audit_store', help='The directory in which the `gitaudit`-database is located.',
)

View file

@ -32,7 +32,7 @@ def main():
try:
re.compile(arguments.pid)
except re.error as e:
print('Error in PID pattern:', e, file=sys.stderr, flush=True) # noqa T201 -- cli result output
print('Error in PID pattern:', e, file=sys.stderr, flush=True)
return 1
audit_backend = GitAuditBackend(Path(arguments.audit_store))
@ -47,7 +47,7 @@ def main():
'diff': change[2],
'resulting-record': change[3],
}
print(json.dumps(report, ensure_ascii=False), flush=True) # noqa T201 -- cli result output
print(json.dumps(report, ensure_ascii=False), flush=True)
return 0

View file

@ -23,10 +23,10 @@ def main():
token = arguments.token.strip()
if any(s.isspace() for s in token):
print('Whitespace are not allowed in token', file=sys.stderr, flush=True) # noqa T201 -- cli result output
print('Whitespace are not allowed in token', file=sys.stderr, flush=True)
return 1
print(hash_token_representation(token)) # noqa T201 -- cli result output
print(hash_token_representation(token))
return 0

View file

@ -60,7 +60,7 @@ def process_config(arguments) -> tuple[Path, str, str]:
Path(arguments.config) if arguments.config else store / config_file_name
)
config_object = RecordDirConfigFileContent(
**yaml.load(config_path.read_text(), Loader=yaml.SafeLoader)
**yaml.load(config_path.read_text(), Loader=yaml.SafeLoader),
)
return (
store,
@ -70,7 +70,7 @@ def process_config(arguments) -> tuple[Path, str, str]:
def rebuild_index(
store: Path, schema: str, suffix: str, order_by: list[str] | None = None
store: Path, schema: str, suffix: str, order_by: list[str] | None = None,
):
index = RecordDirIndex(
store_dir=store.absolute(),

View file

@ -80,7 +80,7 @@ def main():
elif file_type == 'yaml':
configuration = yaml.safe_load(config_file)
else:
print( # noqa T201 -- cli result output
print(
f'Unknown file type {config_file_path} (use `.json` or `.yaml` suffix, or specify the format with --format <json|yaml>)',
file=sys.stderr,
flush=True,
@ -90,7 +90,7 @@ def main():
if arguments.old_format:
configuration = convert_config_1_to_config_2(configuration, arguments.store)
elif arguments.store:
print( # noqa T201 -- cli result output
print(
'Warning: ignoring `--store` option because `--old-format` '
'is not provided.',
file=sys.stderr,
@ -108,7 +108,7 @@ def main():
if arguments.send_to:
admin_token = os.environ.get('DTS_ADMIN_TOKEN')
if not admin_token:
print( # noqa T201 -- cli result output
print(
'An admin token must be provided in the environment variable `DTS_ADMIN_TOKEN`',
file=sys.stderr,
flush=True,
@ -122,15 +122,15 @@ def main():
admin_token,
)
except RuntimeError as rte:
print(f'{rte.args[0]}', file=sys.stderr, flush=True) # noqa T201 -- cli result output
print(f'{rte.args[0]}', file=sys.stderr, flush=True)
return 2
else:
return 0
if file_type == 'json':
print(json.dumps(configuration, indent=2, sort_keys=False)) # noqa T201 -- cli result output
print(json.dumps(configuration, indent=2, sort_keys=False))
elif file_type == 'yaml':
print(json2yaml(configuration)) # noqa T201 -- cli result output
print(json2yaml(configuration))
return 0
@ -176,7 +176,7 @@ def convert_config_1_to_config_2(
msg = '--store <path> has to be provided to convert collection with record_dir-backends'
raise ValueError(msg)
record_dir_config = get_record_dir_config(
store_path / collection_config['curated']
store_path / collection_config['curated'],
)
collection_config['schema'] = record_dir_config.schema_location
backend = {

Some files were not shown because too many files have changed in this diff Show more