1#!/usr/bin/env python3
2"""Install all the required Python packages, with the minimum Python version.
3"""
4
5# Copyright The Mbed TLS Contributors
6# SPDX-License-Identifier: Apache-2.0
7#
8# Licensed under the Apache License, Version 2.0 (the "License"); you may
9# not use this file except in compliance with the License.
10# You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17# See the License for the specific language governing permissions and
18# limitations under the License.
19
20import argparse
21import os
22import re
23import subprocess
24import sys
25import tempfile
26import typing
27
28from typing import List, Optional
29from mbedtls_dev import typing_util
30
31def pylint_doesn_t_notice_that_certain_types_are_used_in_annotations(
32        _list: List[typing.Any],
33) -> None:
34    pass
35
36
37class Requirements:
38    """Collect and massage Python requirements."""
39
40    def __init__(self) -> None:
41        self.requirements = [] #type: List[str]
42
43    def adjust_requirement(self, req: str) -> str:
44        """Adjust a requirement to the minimum specified version."""
45        # allow inheritance #pylint: disable=no-self-use
46        # If a requirement specifies a minimum version, impose that version.
47        split_req = req.split(';', 1)
48        split_req[0] = re.sub(r'>=|~=', r'==', split_req[0])
49        return ';'.join(split_req)
50
51    def add_file(self, filename: str) -> None:
52        """Add requirements from the specified file.
53
54        This method supports a subset of pip's requirement file syntax:
55        * One requirement specifier per line, which is passed to
56          `adjust_requirement`.
57        * Comments (``#`` at the beginning of the line or after whitespace).
58        * ``-r FILENAME`` to include another file.
59        """
60        for line in open(filename):
61            line = line.strip()
62            line = re.sub(r'(\A|\s+)#.*', r'', line)
63            if not line:
64                continue
65            m = re.match(r'-r\s+', line)
66            if m:
67                nested_file = os.path.join(os.path.dirname(filename),
68                                           line[m.end(0):])
69                self.add_file(nested_file)
70                continue
71            self.requirements.append(self.adjust_requirement(line))
72
73    def write(self, out: typing_util.Writable) -> None:
74        """List the gathered requirements."""
75        for req in self.requirements:
76            out.write(req + '\n')
77
78    def install(
79            self,
80            pip_general_options: Optional[List[str]] = None,
81            pip_install_options: Optional[List[str]] = None,
82    ) -> None:
83        """Call pip to install the requirements."""
84        if pip_general_options is None:
85            pip_general_options = []
86        if pip_install_options is None:
87            pip_install_options = []
88        with tempfile.TemporaryDirectory() as temp_dir:
89            # This is more complicated than it needs to be for the sake
90            # of Windows. Use a temporary file rather than the command line
91            # to avoid quoting issues. Use a temporary directory rather
92            # than NamedTemporaryFile because with a NamedTemporaryFile on
93            # Windows, the subprocess can't open the file because this process
94            # has an exclusive lock on it.
95            req_file_name = os.path.join(temp_dir, 'requirements.txt')
96            with open(req_file_name, 'w') as req_file:
97                self.write(req_file)
98            subprocess.check_call([sys.executable, '-m', 'pip'] +
99                                  pip_general_options +
100                                  ['install'] + pip_install_options +
101                                  ['-r', req_file_name])
102
103DEFAULT_REQUIREMENTS_FILE = 'ci.requirements.txt'
104
105def main() -> None:
106    """Command line entry point."""
107    parser = argparse.ArgumentParser(description=__doc__)
108    parser.add_argument('--no-act', '-n',
109                        action='store_true',
110                        help="Don't act, just print what will be done")
111    parser.add_argument('--pip-install-option',
112                        action='append', dest='pip_install_options',
113                        help="Pass this option to pip install")
114    parser.add_argument('--pip-option',
115                        action='append', dest='pip_general_options',
116                        help="Pass this general option to pip")
117    parser.add_argument('--user',
118                        action='append_const', dest='pip_install_options',
119                        const='--user',
120                        help="Install to the Python user install directory"
121                             " (short for --pip-install-option --user)")
122    parser.add_argument('files', nargs='*', metavar='FILE',
123                        help="Requirement files"
124                             " (default: {} in the script's directory)" \
125                             .format(DEFAULT_REQUIREMENTS_FILE))
126    options = parser.parse_args()
127    if not options.files:
128        options.files = [os.path.join(os.path.dirname(__file__),
129                                      DEFAULT_REQUIREMENTS_FILE)]
130    reqs = Requirements()
131    for filename in options.files:
132        reqs.add_file(filename)
133    reqs.write(sys.stdout)
134    if not options.no_act:
135        reqs.install(pip_general_options=options.pip_general_options,
136                     pip_install_options=options.pip_install_options)
137
138if __name__ == '__main__':
139    main()
140