Skip to content

Commit

Permalink
chore(checks): simplify check code
Browse files Browse the repository at this point in the history
- use different code path for counter and list based checking
- normalize strings early
- add type hints
  • Loading branch information
nijel committed May 6, 2024
1 parent 139008f commit 9420cee
Showing 1 changed file with 24 additions and 30 deletions.
54 changes: 24 additions & 30 deletions weblate/checks/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,12 +328,9 @@ def format_string(self, string):
def cleanup_string(self, text):
return text

def normalize(self, matches):
def normalize(self, matches: list[str]) -> list[str]:
if self.normalize_remove is None:
return matches
if isinstance(matches, Counter):
matches.pop(self.normalize_remove, None)
return matches
return [m for m in matches if m != self.normalize_remove]

def extract_matches(self, string: str) -> list[str]:
Expand All @@ -346,37 +343,34 @@ def check_format(self, source, target, ignore_missing, unit):

uses_position = True

# Calculate value
src_matches = self.extract_matches(source)
# Calculate value and ignore mismatch in percent position
src_matches = self.normalize(self.extract_matches(source))
if src_matches:
uses_position = any(self.is_position_based(x) for x in src_matches)

tgt_matches = self.extract_matches(target)
tgt_matches = self.normalize(self.extract_matches(target))

missing: list[str] = []
extra: list[str] = []
if not uses_position:
src_matches = Counter(src_matches)
tgt_matches = Counter(tgt_matches)

if src_matches != tgt_matches:
# Ignore mismatch in percent position
if self.normalize(src_matches) == self.normalize(tgt_matches):
return False
if not uses_position:
missing = sorted(src_matches - tgt_matches)
extra = sorted(tgt_matches - src_matches)
else:
missing = []
extra = []
for i in range(min(len(src_matches), len(tgt_matches))):
if src_matches[i] != tgt_matches[i]:
missing.append(src_matches[i])
extra.append(tgt_matches[i])
missing.extend(src_matches[len(tgt_matches) :])
extra.extend(tgt_matches[len(src_matches) :])
# We can ignore missing format strings
# for first of plurals
if ignore_missing and missing and not extra:
return False
src_counter = Counter(src_matches)
tgt_counter = Counter(tgt_matches)

if src_counter != tgt_counter:
missing = sorted(src_counter - tgt_counter)
extra = sorted(tgt_counter - src_counter)
elif src_matches != tgt_matches:
for i in range(min(len(src_matches), len(tgt_matches))):
if src_matches[i] != tgt_matches[i]:
missing.append(src_matches[i])
extra.append(tgt_matches[i])
missing.extend(src_matches[len(tgt_matches) :])
extra.extend(tgt_matches[len(src_matches) :])

# We can ignore missing format strings for first of plurals
if ignore_missing and missing and not extra:
return False
if missing or extra:
return {"missing": missing, "extra": extra}
return False

Expand Down

0 comments on commit 9420cee

Please sign in to comment.