• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# Copyright 2020 The ChromiumOS Authors
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
9
10import collections
11import os
12import subprocess
13
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        )
58        chroot_paths.append(chroot_path.strip())
59
60    return chroot_paths
61
62
63def ConvertChrootPathsToAbsolutePaths(chromeos_root, chroot_paths):
64    """Converts the chroot path(s) to absolute symlink path(s).
65
66    Args:
67      chromeos_root: The absolute path to the chroot.
68      chroot_paths: A list of chroot paths to convert to absolute paths.
69
70    Returns:
71      A list of absolute path(s).
72
73    Raises:
74      ValueError: Invalid prefix for the chroot path or
75      invalid chroot paths were provided.
76    """
77
78    abs_paths = []
79
80    chroot_prefix = "/mnt/host/source/"
81
82    # Iterate through the chroot paths.
83    #
84    # For each chroot file path, remove '/mnt/host/source/' prefix
85    # and combine the chroot path with the result and add it to the list.
86    for chroot_path in chroot_paths:
87        if not chroot_path.startswith(chroot_prefix):
88            raise ValueError(
89                "Invalid prefix for the chroot path: %s" % chroot_path
90            )
91
92        rel_path = chroot_path[len(chroot_prefix) :]
93
94        # combine the chromeos root path + '/src/...'
95        abs_path = os.path.join(chromeos_root, rel_path)
96
97        abs_paths.append(abs_path)
98
99    return abs_paths
100