Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / pigweed / repo / pw_env_setup / py / pw_env_setup / cargo_setup / __init__.py
1 # Copyright 2020 The Pigweed Authors
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 # use this file except in compliance with the License. You may obtain a copy of
5 # the License at
6 #
7 #     https://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, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations under
13 # the License.
14 """Installs rust tools using cargo."""
15
16 import os
17 import subprocess
18 import sys
19 import tempfile
20
21
22 def install(install_dir, package_files, env):
23     """Installs rust tools using cargo."""
24     # Adding to PATH at the beginning to suppress a warning about this not
25     # being in PATH.
26     env.prepend('PATH', os.path.join(install_dir, 'bin'))
27
28     if 'CARGO_TARGET_DIR' not in os.environ:
29         env.set('CARGO_TARGET_DIR', os.path.expanduser('~/.cargo-cache'))
30
31     with env():
32         for package_file in package_files:
33             with open(package_file, 'r') as ins:
34                 for line in ins:
35                     line = line.strip()
36                     if not line or line.startswith('#'):
37                         continue
38
39                     package, version = line.split()
40                     cmd = [
41                         'cargo',
42                         'install',
43                         # If downgrading (which could happen when switching
44                         # branches) '--force' is required.
45                         '--force',
46                         '--root', install_dir,
47                         '--version', version,
48                         package,
49                     ]  # yapf: disable
50
51                     # TODO(pwbug/135) Use function from common utility module.
52                     with tempfile.TemporaryFile(mode='w+') as temp:
53                         try:
54                             subprocess.check_call(cmd,
55                                                   stdout=temp,
56                                                   stderr=subprocess.STDOUT)
57                         except subprocess.CalledProcessError:
58                             temp.seek(0)
59                             sys.stderr.write(temp.read())
60                             raise
61
62     return True