blob: 1505a471434988134949535cbe955d1f104a1f94 [file] [log] [blame]
Allen Webb65ed16f2020-08-06 21:25:55 -05001#!/usr/bin/env python3
2# Copyright 2020 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Find ebuilds for rust crates that have been replaced by newer versions.
7
8Aids the process of removing unused rust ebuilds that have been replaced
9by newer versions:
10
11 1) Get the list of dev-rust ebuilds.
12 2) Exclude the newest version of each ebuild.
13 3) Generate a list of ebuilds that are installed for typical configurations.
14 4) List the dev-rust ebuilds that aren't included.
15
16For example:
17 ./cleanup_crates.py -c --log-level=debug
18"""
19
20import distutils.version # pylint: disable=no-name-in-module,import-error
21import logging
22import os
23import pickle
24import sys
25
26from chromite.lib import build_target_lib
Allen Webba0c3ad42021-05-10 12:02:44 -050027from chromite.lib import chroot_util
Allen Webb65ed16f2020-08-06 21:25:55 -050028from chromite.lib import commandline
29from chromite.lib import constants
Allen Webb65ed16f2020-08-06 21:25:55 -050030from chromite.lib import osutils
31from chromite.lib import portage_util
Allen Webb65ed16f2020-08-06 21:25:55 -050032
33# The path of the cache.
34DEFAULT_CACHE_PATH = os.path.join(osutils.GetGlobalTempDir(),
35 'cleanup_crates.py')
36
37# build targets to include for the host.
38HOST_CONFIGURATIONS = {
39 'virtual/target-sdk',
40 'virtual/target-sdk-post-cross',
41}
42# build targets to include for each board.
43BOARD_CONFIGURATIONS = {
44 'virtual/target-os',
45 'virtual/target-os-dev',
46 'virtual/target-os-test',
47}
48
49# The set of boards to check. This only needs to be a representative set.
Allen Webba0c3ad42021-05-10 12:02:44 -050050BOARDS = {'eve', 'tatl'} | (
Allen Webb65ed16f2020-08-06 21:25:55 -050051 set() if not os.path.isdir(os.path.join(constants.SOURCE_ROOT, 'src',
52 'private-overlays')) else
53 {'lasilla-ground', 'mistral'}
54)
55
56_GEN_CONFIG = lambda boards, configs: [(b, c) for b in boards for c in configs]
57# A tuple of (board, ebuild) pairs used to generate the set of installed
58# packages.
59CONFIGURATIONS = (
60 _GEN_CONFIG((None,), HOST_CONFIGURATIONS) +
61 _GEN_CONFIG(BOARDS, BOARD_CONFIGURATIONS)
62)
63
64
65def main(argv):
66 """List ebuilds for rust crates replaced by newer versions."""
67 opts = get_opts(argv)
68
69 cln = CachedPackageLists(use_cache=opts.cache,
70 clear_cache=opts.clear_cache,
71 cache_dir=opts.cache_dir)
72
73 ebuilds = exclude_latest_version(get_dev_rust_ebuilds())
74 used = cln.get_used_packages(CONFIGURATIONS)
75
76 unused_ebuilds = sorted(x.cpv for x in ebuilds if x.cpv not in used)
77 print('\n'.join(unused_ebuilds))
78 return 0
79
80
81def get_opts(argv):
82 """Parse the command-line options."""
83 parser = commandline.ArgumentParser(description=__doc__)
84 parser.add_argument(
85 '-c', '--cache', action='store_true',
86 help='Enables caching of the results of GetPackageDependencies.')
87 parser.add_argument(
88 '-x', '--clear-cache', action='store_true',
89 help='Clears the contents of the cache before executing.')
90 parser.add_argument(
91 '-C', '--cache-dir', action='store', default=DEFAULT_CACHE_PATH,
92 type='path',
93 help='The path to store the cache (default: %(default)s)')
94 opts = parser.parse_args(argv)
95 opts.Freeze()
96 return opts
97
98
99def get_dev_rust_ebuilds():
100 """Return a list of dev-rust ebuilds."""
101 return portage_util.FindPackageNameMatches('dev-rust/*')
102
103
104def exclude_latest_version(packages):
105 """Return a list of ebuilds that aren't the latest version."""
106 latest = {}
107 results = []
108 lv = distutils.version.LooseVersion
109 for pkg in packages:
110 name = pkg.cp
111 if name not in latest:
112 latest[name] = pkg
113 continue
114
115 version = lv(pkg.version_no_rev)
116 other_version = lv(latest[name].version_no_rev)
117 if version > other_version:
118 results.append(latest[name])
119 latest[name] = pkg
120 elif version != other_version:
121 results.append(pkg)
122 return results
123
124
125def _get_package_dependencies(board, package):
126 """List the ebuild-version dependencies for a specific board & package."""
Allen Webba0c3ad42021-05-10 12:02:44 -0500127 if board and not os.path.isdir(
128 build_target_lib.get_default_sysroot_path(board)):
129 chroot_util.SetupBoard(board, update_chroot=False,
130 update_host_packages=False,)
Allen Webb65ed16f2020-08-06 21:25:55 -0500131 return portage_util.GetPackageDependencies(board, package)
132
133
134class CachedPackageLists:
135 """Lists used packages with the specified cache configuration."""
136
137 def __init__(self, use_cache=False, clear_cache=False,
138 cache_dir=DEFAULT_CACHE_PATH):
139 """Initialize the cache if it is enabled."""
140 self.use_cache = bool(use_cache)
141 self.clear_cache = bool(clear_cache)
142 self.cache_dir = cache_dir
143 if self.clear_cache:
144 osutils.RmDir(self.cache_dir, ignore_missing=True)
145 if self.use_cache:
146 osutils.SafeMakedirs(self.cache_dir)
147
148 def _try_cache(self, name, fn):
149 """Caches the return value of a function."""
150 if not self.use_cache:
151 return fn()
152
153 try:
154 with open(os.path.join(self.cache_dir, name), 'rb') as fp:
155 logging.info('cache hit: %s', name)
156 return pickle.load(fp)
157 except FileNotFoundError:
158 pass
159
160 logging.info('cache miss: %s', name)
161 result = fn()
162
163 with open(os.path.join(self.cache_dir, name), 'wb+') as fp:
164 pickle.dump(result, fp)
165
166 return result
167
168 def get_used_packages(self, configurations):
169 """Return the packages installed in the specified configurations."""
170
171 def get_deps(board, package):
172 filename_package = package.replace('/', ':')
173 return self._try_cache(
174 f'deps:{board}:{filename_package}',
175 lambda: _get_package_dependencies(board, package))
176
177 used = set()
178 for board, package in configurations:
179 deps = get_deps(board, package)
180 if deps:
181 used.update(deps)
182 else:
183 logging.warning('No depts for (%s, %s)', board, package)
184 return used
185
186
187if __name__ == '__main__':
188 sys.exit(main(sys.argv[1:]))