Added prefix filtering to TagLine.tags() and Message.tags_from_file()

This commit is contained in:
2023-08-26 12:50:47 +02:00
parent 9aafdf9421
commit 71f6613aca
4 changed files with 36 additions and 10 deletions
+10 -4
View File
@@ -219,9 +219,12 @@ class Message():
file_path=data.get(cls.file_yaml_key, None))
@classmethod
def tags_from_file(cls: Type[MessageInst], file_path: pathlib.Path) -> set[Tag]:
def tags_from_file(cls: Type[MessageInst],
file_path: pathlib.Path,
prefix: Optional[str] = None) -> set[Tag]:
"""
Return only the tags from the given Message file.
Return only the tags from the given Message file,
optionally filtered based on prefix.
"""
if not file_path.exists():
raise MessageError(f"Message file '{file_path}' does not exist")
@@ -229,11 +232,14 @@ class Message():
raise MessageError(f"File type '{file_path.suffix}' is not supported")
if file_path.suffix == '.txt':
with open(file_path, "r") as fd:
tags = TagLine(fd.readline()).tags()
tags = TagLine(fd.readline()).tags(prefix)
else: # '.yaml'
with open(file_path, "r") as fd:
data = yaml.load(fd, Loader=yaml.FullLoader)
tags = set(sorted(data[cls.tags_yaml_key]))
if prefix and len(prefix) > 0:
tags = set(sorted([t.strip() for t in data[cls.tags_yaml_key] if t.startswith(prefix)]))
else:
tags = set(sorted(data[cls.tags_yaml_key]))
return tags
@classmethod
+7 -3
View File
@@ -118,9 +118,10 @@ class TagLine(str):
"""
return cls(' '.join([cls.prefix] + sorted([t for t in tags])))
def tags(self) -> set[Tag]:
def tags(self, prefix: Optional[str] = None) -> set[Tag]:
"""
Returns all tags contained in this line as a set.
Returns all tags contained in this line as a set, optionally
filtered based on prefix.
"""
tagstr = self[len(self.prefix):].strip()
separator = Tag.default_separator
@@ -130,7 +131,10 @@ class TagLine(str):
if s in tagstr:
separator = s
break
return set(sorted([Tag(t.strip()) for t in tagstr.split(separator)]))
if prefix and len(prefix) > 0:
return set(sorted([Tag(t.strip()) for t in tagstr.split(separator) if t.startswith(prefix)]))
else:
return set(sorted([Tag(t.strip()) for t in tagstr.split(separator)]))
def merge(self, taglines: set['TagLine']) -> 'TagLine':
"""