conservancy_beancount/conservancy_beancount/plugin/meta_rt_links.py

66 lines
2.4 KiB
Python

"""meta_rt_links - Check that RT links are valid"""
# Copyright © 2020 Brett Smith
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from . import core
from .. import config as configmod
from .. import data
from .. import errors as errormod
from ..beancount_types import (
MetaKey,
MetaValue,
Posting,
Transaction,
)
from typing import (
MutableMapping,
Optional,
)
class MetaRTLinks(core.TransactionHook):
HOOK_GROUPS = frozenset(['linkcheck', 'network', 'rt'])
def __init__(self, config: configmod.Config) -> None:
rt_wrapper = config.rt_wrapper()
if rt_wrapper is None:
raise errormod.ConfigurationError("can't log in to RT")
self.rt = rt_wrapper
def _check_links(self,
meta: MutableMapping[MetaKey, MetaValue],
txn: Transaction,
post: Optional[Posting]=None,
) -> errormod.Iter:
metadata = data.Metadata(meta)
for key in data.LINK_METADATA:
try:
links = metadata.get_links(key)
except TypeError:
yield errormod.InvalidMetadataError(txn, key, meta[key], post)
else:
for link in links:
if not link.startswith('rt:'):
continue
parsed = self.rt.parse(link)
if parsed is None or not self.rt.exists(*parsed):
yield errormod.BrokenRTLinkError(txn, key, link, parsed)
def run(self, txn: Transaction) -> errormod.Iter:
if self._run_on_txn(txn):
yield from self._check_links(txn.meta, txn)
for post in txn.postings:
if post.meta is not None:
yield from self._check_links(post.meta, txn, post)