1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# Copyright 2020 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Chroot helper functions."""
8
9from __future__ import print_function
10
11import os
12import subprocess
13import collections
14
15CommitContents = collections.namedtuple('CommitContents', ['url', 'cl_number'])
16
17
18def InChroot():
19  """Returns True if currently in the chroot."""
20  return 'CROS_WORKON_SRCROOT' in os.environ
21
22
23def VerifyOutsideChroot():
24  """Checks whether the script invoked was executed in the chroot.
25
26  Raises:
27    AssertionError: The script was run inside the chroot.
28  """
29
30  assert not InChroot(), 'Script should be run outside the chroot.'
31
32
33def GetChrootEbuildPaths(chromeos_root, packages):
34  """Gets the chroot path(s) of the package(s).
35
36  Args:
37    chromeos_root: The absolute path to the chroot to
38    use for executing chroot commands.
39    packages: A list of a package/packages to
40    be used to find their chroot path.
41
42  Returns:
43    A list of chroot paths of the packages' ebuild files.
44
45  Raises:
46    ValueError: Failed to get the chroot path of a package.
47  """
48
49  chroot_paths = []
50
51  # Find the chroot path for each package's ebuild.
52  for package in packages:
53    chroot_path = subprocess.check_output(
54        ['cros_sdk', '--', 'equery', 'w', package],
55        cwd=chromeos_root,
56        encoding='utf-8')
57    chroot_paths.append(chroot_path.strip())
58
59  return chroot_paths
60
61
62def ConvertChrootPathsToAbsolutePaths(chromeos_root, chroot_paths):
63  """Converts the chroot path(s) to absolute symlink path(s).
64
65  Args:
66    chromeos_root: The absolute path to the chroot.
67    chroot_paths: A list of chroot paths to convert to absolute paths.
68
69  Returns:
70    A list of absolute path(s).
71
72  Raises:
73    ValueError: Invalid prefix for the chroot path or
74    invalid chroot paths were provided.
75  """
76
77  abs_paths = []
78
79  chroot_prefix = '/mnt/host/source/'
80
81  # Iterate through the chroot paths.
82  #
83  # For each chroot file path, remove '/mnt/host/source/' prefix
84  # and combine the chroot path with the result and add it to the list.
85  for chroot_path in chroot_paths:
86    if not chroot_path.startswith(chroot_prefix):
87      raise ValueError('Invalid prefix for the chroot path: %s' % chroot_path)
88
89    rel_path = chroot_path[len(chroot_prefix):]
90
91    # combine the chromeos root path + '/src/...'
92    abs_path = os.path.join(chromeos_root, rel_path)
93
94    abs_paths.append(abs_path)
95
96  return abs_paths
97