68 lines
2.4 KiB
Python
68 lines
2.4 KiB
Python
"""meta_repo_links - Check that repository 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/>.
|
|
|
|
import re
|
|
|
|
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 MetaRepoLinks(core.TransactionHook):
|
|
HOOK_GROUPS = frozenset(['linkcheck'])
|
|
PATH_PUNCT_RE = re.compile(r'[:/]')
|
|
|
|
def __init__(self, config: configmod.Config) -> None:
|
|
repo_path = config.repository_path()
|
|
if repo_path is None:
|
|
raise errormod.ConfigurationError("no repository configured")
|
|
self.repo_path = repo_path
|
|
|
|
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:
|
|
match = self.PATH_PUNCT_RE.search(link)
|
|
if match and match.group(0) == ':':
|
|
pass
|
|
elif not (self.repo_path / link).exists():
|
|
yield errormod.BrokenLinkError(txn, key, link)
|
|
|
|
def run(self, txn: Transaction) -> errormod.Iter:
|
|
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)
|