1# Copyright (C) 2018 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Helper functions for updaters."""
15
16import os
17import re
18import subprocess
19import sys
20from pathlib import Path
21from typing import List, Tuple, Type
22
23from base_updater import Updater
24# pylint: disable=import-error
25import metadata_pb2  # type: ignore
26
27
28def create_updater(metadata: metadata_pb2.MetaData, proj_path: Path,
29                   updaters: List[Type[Updater]]) -> Updater:
30    """Creates corresponding updater object for a project.
31
32    Args:
33      metadata: Parsed proto for METADATA file.
34      proj_path: Absolute path for the project.
35
36    Returns:
37      An updater object.
38
39    Raises:
40      ValueError: Occurred when there's no updater for all urls.
41    """
42    for url in metadata.third_party.url:
43        for updater_cls in updaters:
44            updater = updater_cls(proj_path, url, metadata.third_party.version)
45            if updater.is_supported_url():
46                return updater
47
48    raise ValueError('No supported URL.')
49
50
51def replace_package(source_dir, target_dir) -> None:
52    """Invokes a shell script to prepare and update a project.
53
54    Args:
55      source_dir: Path to the new downloaded and extracted package.
56      target_dir: The path to the project in Android source tree.
57    """
58
59    print('Updating {} using {}.'.format(target_dir, source_dir))
60    script_path = os.path.join(os.path.dirname(sys.argv[0]),
61                               'update_package.sh')
62    subprocess.check_call(['bash', script_path, source_dir, target_dir])
63
64
65VERSION_SPLITTER_PATTERN: str = r'[\.\-_]'
66VERSION_PATTERN: str = (r'^(?P<prefix>[^\d]*)' + r'(?P<version>\d+(' +
67                        VERSION_SPLITTER_PATTERN + r'\d+)*)' +
68                        r'(?P<suffix>.*)$')
69VERSION_RE: re.Pattern = re.compile(VERSION_PATTERN)
70VERSION_SPLITTER_RE: re.Pattern = re.compile(VERSION_SPLITTER_PATTERN)
71
72ParsedVersion = Tuple[List[int], str, str]
73
74
75def _parse_version(version: str) -> ParsedVersion:
76    match = VERSION_RE.match(version)
77    if match is None:
78        raise ValueError('Invalid version.')
79    try:
80        prefix, version, suffix = match.group('prefix', 'version', 'suffix')
81        versions = [int(v) for v in VERSION_SPLITTER_RE.split(version)]
82        return (versions, str(prefix), str(suffix))
83    except IndexError:
84        # pylint: disable=raise-missing-from
85        raise ValueError('Invalid version.')
86
87
88def _match_and_get_version(old_ver: ParsedVersion,
89                           version: str) -> Tuple[bool, bool, List[int]]:
90    try:
91        new_ver = _parse_version(version)
92    except ValueError:
93        return (False, False, [])
94
95    right_format = (new_ver[1:] == old_ver[1:])
96    right_length = len(new_ver[0]) == len(old_ver[0])
97
98    return (right_format, right_length, new_ver[0])
99
100
101def get_latest_version(current_version: str, version_list: List[str]) -> str:
102    """Gets the latest version name from a list of versions.
103
104    The new version must have the same prefix and suffix with old version.
105    If no matched version is newer, current version name will be returned.
106    """
107    parsed_current_ver = _parse_version(current_version)
108
109    latest = max(
110        version_list,
111        key=lambda ver: _match_and_get_version(parsed_current_ver, ver),
112        default=None)
113    if not latest:
114        raise ValueError('No matching version.')
115    return latest
116