Deduplicate `extend_existing_comment` and `shrink_existing_comment` code
@@ -16,7 +16,7 @@ if MYPY:
Callable, DefaultDict, Dict, Iterable, Iterator, List,
NamedTuple, Optional, Set, TypeVar, Union
)
- from typing_extensions import Final
+ from typing_extensions import Final, Literal
T = TypeVar("T")
S = TypeVar("S")
LintError = persist.LintError
@@ -554,25 +554,16 @@ def read_next_line(view, line):
def extend_existing_comment(search_pattern, joiner, rulenames, line):
# type: (str, str, Set[str], Optional[TextRange]) -> Optional[TextRange]
- if line is None:
- return None
- match = re.search(search_pattern, line.text)
- if match:
- existing_rules = {
- rule.strip()
- for rule in match.group("codes").split(joiner.strip())
- }
- next_rules = sorted(existing_rules | rulenames)
- a, b = match.span("codes")
- return TextRange(
- joiner.join(next_rules),
- sublime.Region(line.range.a + a, line.range.a + b)
- )
- return None
+ return _modify_existing_comment("add", search_pattern, joiner, rulenames, line)
def shrink_existing_comment(search_pattern, joiner, rulenames, line):
# type: (str, str, Set[str], Optional[TextRange]) -> Optional[TextRange]
+ return _modify_existing_comment("remove", search_pattern, joiner, rulenames, line)
+
+
+def _modify_existing_comment(operation, search_pattern, joiner, rulenames, line):
+ # type: (Literal["add", "remove"], str, str, Set[str], Optional[TextRange]) -> Optional[TextRange]
if line is None:
return None
match = re.search(search_pattern, line.text)
@@ -581,7 +572,12 @@ def shrink_existing_comment(search_pattern, joiner, rulenames, line):
rule.strip()
for rule in match.group("codes").split(joiner.strip())
}
+ if operation == "add":
+ next_rules = sorted(existing_rules | rulenames)
+ elif operation == "remove":
next_rules = sorted(existing_rules - rulenames)
+ else:
+ raise RuntimeError("operation '{}' not supported".format(operation))
a, b = match.span("codes")
return TextRange(
joiner.join(next_rules),
