Support substitution of version strings

This commit is contained in:
Yen Chi Hsuan 2017-10-10 00:39:24 +08:00
parent f3653c79c8
commit 3628505ea7
1 changed files with 34 additions and 1 deletions

View File

@ -2,6 +2,7 @@
# Copyright (c) 2013-2017 lilydjwg <lilydjwg@gmail.com>, et al. # Copyright (c) 2013-2017 lilydjwg <lilydjwg@gmail.com>, et al.
import logging import logging
import re
from importlib import import_module from importlib import import_module
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -13,13 +14,45 @@ handler_precedence = (
'anitya', 'anitya',
) )
def substitute_version(version, name, conf):
'''
Substitute the version string via defined rules in the configuration file.
Accepted rules are:
* from_pattern, to_pattern: Both should be Python regular expressions.
`from_pattern` found in the version string will be substituted to
`to_pattern`.
* prefix: If the version string starts with `prefix`, the prefix is removed.
Otherwise the version string is returned as-is.
If both prefix and from_pattern/to_pattern are used, from_pattern/to_pattern
are ignored.
'''
prefix = conf.get('prefix')
if prefix:
if version.startswith(prefix):
version = version[len(prefix):]
return version
from_pattern = conf.get('from_pattern')
if from_pattern:
to_pattern = conf.get('to_pattern')
if not to_pattern:
raise ValueError('%s: from_pattern exists but to_pattern doesn\'t', name)
return re.sub(from_pattern, to_pattern, version)
# No substitution rules found. Just return the original version string.
return version
async def get_version(name, conf): async def get_version(name, conf):
for key in handler_precedence: for key in handler_precedence:
if key in conf: if key in conf:
func = import_module('.source.' + key, __package__).get_version func = import_module('.source.' + key, __package__).get_version
version = await func(name, conf) version = await func(name, conf)
if version: if version:
version.replace('\n', ' ') version = version.replace('\n', ' ')
version = substitute_version(version, name, conf)
return version return version
else: else:
logger.error('%s: no idea to get version info.', name) logger.error('%s: no idea to get version info.', name)