From 6fa9cfd4c35566f530fc2a03a4713309f3475db1 Mon Sep 17 00:00:00 2001 From: Joscha Date: Thu, 27 May 2021 13:56:01 +0200 Subject: [PATCH] Fix error when capturing group is None --- CONFIG.md | 4 +++- PFERD/transformer.py | 18 +++++++++++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/CONFIG.md b/CONFIG.md index fcc263a..f31e7f6 100644 --- a/CONFIG.md +++ b/CONFIG.md @@ -258,7 +258,9 @@ are available in `TARGET` for formatting. be referred to as `{g}` (e. g. `{g3}`). `{g0}` refers to the original path. If capturing group *n*'s contents are a valid integer, the integer value is available as `{i}` (e. g. `{i3}`). If capturing group *n*'s contents are a -valid float, the float value is available as `{f}` (e. g. `{f3}`). +valid float, the float value is available as `{f}` (e. g. `{f3}`). If a +capturing group is not present (e. g. when matching the string `cd` with the +regex `(ab)?cd`), the corresponding variables are not defined. Python's format string syntax has rich options for formatting its arguments. For example, to left-pad the capturing group 3 with the digit `0` to width 5, you diff --git a/PFERD/transformer.py b/PFERD/transformer.py index f147fb2..83ffde4 100644 --- a/PFERD/transformer.py +++ b/PFERD/transformer.py @@ -7,7 +7,7 @@ import ast import re from abc import ABC, abstractmethod from pathlib import PurePath -from typing import Dict, Optional, Union +from typing import Dict, Optional, Sequence, Union from .logging import log from .utils import fmt_path @@ -122,8 +122,14 @@ class ReRule(Rule): vars: Dict[str, Union[str, int, float]] = {} - groups = [match[0]] + list(match.groups()) + # For some reason, mypy thinks that "groups" has type List[str]. + # But since elements of "match.groups()" can be None, mypy is + # wrong. + groups: Sequence[Optional[str]] = [match[0]] + list(match.groups()) for i, group in enumerate(groups): + if group is None: + continue + vars[f"g{i}"] = group try: @@ -352,7 +358,13 @@ class Transformer: for i, (line, rule) in enumerate(self._rules): log.explain(f"Testing rule {i+1}: {line}") - result = rule.transform(path) + try: + result = rule.transform(path) + except Exception as e: + log.warn(f"Error while testing rule {i+1}: {line}") + log.warn_contd(str(e)) + continue + if isinstance(result, PurePath): log.explain(f"Match found, transformed path to {fmt_path(result)}") return result