Skip to content

Commit d5dd9a6

Browse files
committed
replace assert statements with exceptions
1 parent 540122b commit d5dd9a6

13 files changed

Lines changed: 78 additions & 37 deletions

File tree

colrev/env/language_service.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@ def __init__(self) -> None:
4040
# pylint: disable=too-many-return-statements
4141
# pylint: disable=too-many-branches
4242
def _determine_alphabet(self, str_to_check: str) -> str:
43-
assert len(str_to_check) != 0
43+
if len(str_to_check) == 0:
44+
raise ValueError("str_to_check must not be empty")
4445

4546
str_to_check = re.sub(r"[\s\d\.\:]*", "", str_to_check)
4647

@@ -116,7 +117,10 @@ def compute_language_confidence_values(self, *, text: str) -> list:
116117

117118
def validate_iso_639_3_language_codes(self, *, lang_code_list: list) -> None:
118119
"""Validates whether a list of language codes complies with the ISO 639-3 standard."""
119-
assert isinstance(lang_code_list, list)
120+
if not isinstance(lang_code_list, list):
121+
raise TypeError(
122+
f"Expected lang_code_list to be a list, got {type(lang_code_list).__name__}"
123+
)
120124

121125
invalid_language_codes = [x for x in lang_code_list if 3 != len(x)]
122126
if invalid_language_codes:

colrev/env/tei_parser.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@ def __init__(
5959
- tei_path: read TEI from file.
6060
"""
6161
# pylint: disable=consider-using-with
62-
assert pdf_path is not None or tei_path is not None
62+
if pdf_path is None and tei_path is None:
63+
raise ValueError("Either pdf_path or tei_path must be provided")
6364
if pdf_path is not None:
6465
pdf_path = Path(pdf_path)
6566
if pdf_path.is_symlink(): # pragma: no cover

colrev/git_repo.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,8 @@ def has_record_changes(self, *, change_type: str = "all") -> bool:
5858

5959
def has_changes(self, relative_path: Path, *, change_type: str = "all") -> bool:
6060
"""Check whether the relative path (or the git repository) has changes."""
61-
assert change_type in [
62-
"all",
63-
"staged",
64-
"unstaged",
65-
], "Invalid change_type specified"
61+
if change_type not in ["all", "staged", "unstaged"]:
62+
raise ValueError(f"Invalid change_type specified: {change_type!r}")
6663
try:
6764
bool(self.repo.head.commit)
6865
except ValueError:
@@ -179,11 +176,10 @@ def file_in_history(self, filepath: Path) -> bool:
179176
def get_commit_message(self, *, commit_nr: int) -> str:
180177
"""Get the commit message for commit #."""
181178
master = self.repo.head.reference
182-
assert commit_nr == 0 # extension : implement other cases
183-
if commit_nr == 0:
184-
cmsg = master.commit.message
185-
return cmsg
186-
return ""
179+
if commit_nr != 0:
180+
raise NotImplementedError("Only commit_nr == 0 is currently supported")
181+
cmsg = master.commit.message
182+
return cmsg
187183

188184
def add_setting_changes(self) -> None:
189185
"""Add changes in settings to git."""

colrev/loader/loader.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,10 @@ def __init__(
2929
"""Initialize the instance."""
3030
self.filename = filename
3131
self.unique_id_field = unique_id_field
32-
assert id_labeler is not None or unique_id_field != ""
32+
if id_labeler is None and unique_id_field == "":
33+
raise ValueError(
34+
"Either id_labeler must be provided or unique_id_field must be set"
35+
)
3336
self.id_labeler = id_labeler
3437
self.entrytype_setter = entrytype_setter
3538
self.field_mapper = field_mapper
@@ -48,23 +51,22 @@ def _set_ids(self, records_list: list) -> None:
4851
else:
4952
self.id_labeler(records_list) # type: ignore
5053

51-
assert all(
52-
Fields.ID in record_dict for record_dict in records_list
53-
), "ID not set in all records"
54+
if not all(Fields.ID in record_dict for record_dict in records_list):
55+
raise ValueError("ID not set in all records")
5456
unique_ids = {record_dict[Fields.ID] for record_dict in records_list}
5557
non_unique_ids = [
5658
id
5759
for id in unique_ids
5860
if sum(1 for r in records_list if r[Fields.ID] == id) > 1
5961
]
60-
assert not non_unique_ids, f"ID is not unique in records: {non_unique_ids}"
62+
if non_unique_ids:
63+
raise ValueError(f"ID is not unique in records: {non_unique_ids}")
6164

6265
def _set_entrytypes(self, records_dict: dict) -> None:
6366
for r_dict_val in records_dict.values():
6467
self.entrytype_setter(r_dict_val)
65-
assert all(
66-
Fields.ENTRYTYPE in r for r in records_dict.values()
67-
), "ENTRYTYPE not set in all records"
68+
if not all(Fields.ENTRYTYPE in r for r in records_dict.values()):
69+
raise ValueError("ENTRYTYPE not set in all records")
6870

6971
for r in records_dict.values():
7072
if r[Fields.ENTRYTYPE] in ENTRYTYPES.get_all():

colrev/ops/merge.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,8 @@ def main(self, *, branch: str) -> None:
9898
remote.fetch()
9999

100100
branches = git_repo.heads
101-
assert branch in [b.name for b in branches]
101+
if branch not in [b.name for b in branches]:
102+
raise ValueError(f"Branch does not exist: {branch!r}")
102103

103104
git_branch = [b for b in branches if b.name == branch][0]
104105
merging_branch_author = git_branch.commit.author
@@ -114,7 +115,10 @@ def main(self, *, branch: str) -> None:
114115
unmerged_blobs = git_repo.index.unmerged_blobs()
115116

116117
# Note : only two-way merges supported for now.
117-
assert all(len(v) == 3 for k, v in unmerged_blobs.items())
118+
if not all(len(v) == 3 for _, v in unmerged_blobs.items()):
119+
raise RuntimeError(
120+
"Only two-way merges with three blob stages are supported"
121+
)
118122

119123
# Ensure the path uses forward slashes, which is compatible with Git's path handling
120124
if self.review_manager.paths.RECORDS_FILE_GIT in unmerged_blobs:

colrev/ops/search.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,12 @@ def _get_search_sources(
5454
if s.search_results_path.name in selected_filenames
5555
]
5656

57-
assert len(sources_selected) != 0
57+
if len(sources_selected) == 0:
58+
raise colrev_exceptions.ParameterError(
59+
parameter="select",
60+
value=selection_str,
61+
options=[str(s.search_results_path) for s in self.sources],
62+
)
5863
return sources_selected
5964

6065
def _remove_forthcoming(

colrev/packages/export_man_prep/src/prep_man_export.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,10 @@ def __init__(
8181
self.logger = logger or logging.getLogger(__name__)
8282
if "pdf_handling_mode" not in settings:
8383
settings["pdf_handling_mode"] = "symlink"
84-
assert settings["pdf_handling_mode"] in ["symlink", "copy_first_page"]
84+
if settings["pdf_handling_mode"] not in ["symlink", "copy_first_page"]:
85+
raise ValueError(
86+
"pdf_handling_mode must be one of ['symlink', 'copy_first_page']"
87+
)
8588

8689
self.settings = self.settings_class(**settings)
8790

colrev/packages/importer/src/importer.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,10 @@ def _import_records(
239239
continue
240240
original_id = duplicate_id_set[0]
241241
other_id = duplicate_id_set[1]
242-
assert other_id.startswith("other_")
242+
if not other_id.startswith("other_"):
243+
raise ValueError(
244+
f"Expected other_id to start with 'other_', got {other_id!r}"
245+
)
243246
print(f"{original_id} <-- {other_id}")
244247

245248
# merge

colrev/packages/open_citations_forward_search/src/open_citations_forward_search.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,10 @@ def _validate_source(self) -> None:
8282

8383
self.logger.debug(f"Validate SearchSource {source.search_results_path}")
8484

85-
assert source.search_type == SearchType.FORWARD_SEARCH
85+
if source.search_type != SearchType.FORWARD_SEARCH:
86+
raise ValueError(
87+
f"Expected search_type {SearchType.FORWARD_SEARCH}, got {source.search_type}"
88+
)
8689

8790
if "scope" not in source.search_parameters:
8891
raise colrev_exceptions.InvalidQueryException(

colrev/packages/pdf_backward_search/src/pdf_backward_search.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,10 @@ def _validate_source(self) -> None:
101101
source = self.search_source
102102
self.logger.debug(f"Validate SearchSource {source.search_results_path}")
103103

104-
assert source.search_type == SearchType.BACKWARD_SEARCH
104+
if source.search_type != SearchType.BACKWARD_SEARCH:
105+
raise ValueError(
106+
f"Expected search_type {SearchType.BACKWARD_SEARCH}, got {source.search_type}"
107+
)
105108

106109
if "scope" not in source.search_parameters:
107110
raise colrev_exceptions.InvalidQueryException(
@@ -576,8 +579,14 @@ def add_endpoint(
576579
if "min_intext_citations" not in params_dict:
577580
cls._get_params_from_ui(params=params_dict, path=path)
578581
else:
579-
assert params_dict["min_intext_citations"].isdigit()
580-
assert params_dict["min_ref_freq"].isdigit()
582+
if not params_dict["min_intext_citations"].isdigit():
583+
raise ValueError(
584+
f"min_intext_citations must be numeric, got {params_dict['min_intext_citations']!r}"
585+
)
586+
if not params_dict["min_ref_freq"].isdigit():
587+
raise ValueError(
588+
f"min_ref_freq must be numeric, got {params_dict['min_ref_freq']!r}"
589+
)
581590

582591
search_source = cls.get_default_source()
583592
if "min_intext_citations" in params_dict:

0 commit comments

Comments
 (0)