blob: 23634ee9069333a81ea4687a158eb54b0799a35a [file] [log] [blame]
Alex Kleineb77ffa2019-05-28 14:47:44 -06001# -*- coding: utf-8 -*-
2# Copyright 2019 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"""Package utility functionality."""
7
8from __future__ import print_function
9
Yaakov Shaul730814a2019-09-10 13:58:25 -060010import collections
Yaakov Shaulcb1cfc32019-09-16 13:51:19 -060011import fileinput
Alex Klein87531182019-08-12 15:23:37 -060012import functools
Yaakov Shaul395ae832019-09-09 14:45:32 -060013import json
Evan Hernandezb51f1522019-08-15 11:29:40 -060014import os
Michael Mortensenb70e8a82019-10-10 18:43:41 -060015import re
Yaakov Shaulcb1cfc32019-09-16 13:51:19 -060016import sys
Alex Klein87531182019-08-12 15:23:37 -060017
Andrew Lamb2bde9e42019-11-04 13:24:09 -070018from google.protobuf import json_format
Yaakov Shaul730814a2019-09-10 13:58:25 -060019
Andrew Lamb2bde9e42019-11-04 13:24:09 -070020from chromite.api.gen.config import replication_config_pb2
Michael Mortensen9fdb14b2019-10-17 11:17:30 -060021from chromite.cbuildbot import manifest_version
Alex Kleineb77ffa2019-05-28 14:47:44 -060022from chromite.lib import constants
Evan Hernandezb51f1522019-08-15 11:29:40 -060023from chromite.lib import cros_build_lib
Alex Klein4de25e82019-08-05 15:58:39 -060024from chromite.lib import cros_logging as logging
Alex Kleineb77ffa2019-05-28 14:47:44 -060025from chromite.lib import git
Michael Mortensenb70e8a82019-10-10 18:43:41 -060026from chromite.lib import osutils
Alex Kleineb77ffa2019-05-28 14:47:44 -060027from chromite.lib import portage_util
Andrew Lamb2bde9e42019-11-04 13:24:09 -070028from chromite.lib import replication_lib
Alex Kleind6195b62019-08-06 16:01:16 -060029from chromite.lib import uprev_lib
Alex Kleineb77ffa2019-05-28 14:47:44 -060030
Alex Klein36b117f2019-09-30 15:13:46 -060031if cros_build_lib.IsInsideChroot():
32 from chromite.service import dependency
33
Alex Klein87531182019-08-12 15:23:37 -060034# Registered handlers for uprevving versioned packages.
35_UPREV_FUNCS = {}
36
Alex Kleineb77ffa2019-05-28 14:47:44 -060037
38class Error(Exception):
39 """Module's base error class."""
40
41
Alex Klein4de25e82019-08-05 15:58:39 -060042class UnknownPackageError(Error):
43 """Uprev attempted for a package without a registered handler."""
44
45
Alex Kleineb77ffa2019-05-28 14:47:44 -060046class UprevError(Error):
47 """An error occurred while uprevving packages."""
48
49
Michael Mortensenb70e8a82019-10-10 18:43:41 -060050class NoAndroidVersionError(Error):
51 """An error occurred while trying to determine the android version."""
52
53
54class NoAndroidBranchError(Error):
55 """An error occurred while trying to determine the android branch."""
56
57
58class NoAndroidTargetError(Error):
59 """An error occurred while trying to determine the android target."""
60
61
Alex Klein4de25e82019-08-05 15:58:39 -060062class AndroidIsPinnedUprevError(UprevError):
63 """Raised when we try to uprev while Android is pinned."""
64
65 def __init__(self, new_android_atom):
66 """Initialize a AndroidIsPinnedUprevError.
67
68 Args:
69 new_android_atom: The Android atom that we failed to
70 uprev to, due to Android being pinned.
71 """
72 assert new_android_atom
73 msg = ('Failed up uprev to Android version %s as Android was pinned.' %
74 new_android_atom)
75 super(AndroidIsPinnedUprevError, self).__init__(msg)
76 self.new_android_atom = new_android_atom
Alex Klein87531182019-08-12 15:23:37 -060077
78
Yaakov Shaul1eafe832019-09-10 16:50:26 -060079class EbuildManifestError(Error):
80 """Error when running ebuild manifest."""
81
82
Yaakov Shaul730814a2019-09-10 13:58:25 -060083UprevVersionedPackageModifications = collections.namedtuple(
84 'UprevVersionedPackageModifications', ('new_version', 'files'))
Alex Klein34afcbc2019-08-22 16:14:31 -060085
Yaakov Shaul730814a2019-09-10 13:58:25 -060086
87class UprevVersionedPackageResult(object):
88 """Data object for uprev_versioned_package."""
89
90 def __init__(self):
91 self.modified = []
92
93 def add_result(self, new_version, modified_files):
94 """Adds version/ebuilds tuple to result.
95
96 Args:
97 new_version: New version number of package.
98 modified_files: List of files modified for the given version.
99 """
100 result = UprevVersionedPackageModifications(new_version, modified_files)
101 self.modified.append(result)
102 return self
Alex Klein34afcbc2019-08-22 16:14:31 -0600103
104 @property
105 def uprevved(self):
Yaakov Shaul730814a2019-09-10 13:58:25 -0600106 return bool(self.modified)
Alex Klein34afcbc2019-08-22 16:14:31 -0600107
108
Yaakov Shaulcb1cfc32019-09-16 13:51:19 -0600109def patch_ebuild_vars(ebuild_path, variables):
110 """Updates variables in ebuild.
111
112 Use this function rather than portage_util.EBuild.UpdateEBuild when you
113 want to preserve the variable position and quotes within the ebuild.
114
115 Args:
116 ebuild_path: The path of the ebuild.
117 variables: Dictionary of variables to update in ebuild.
118 """
119 try:
120 for line in fileinput.input(ebuild_path, inplace=1):
121 varname, eq, _ = line.partition('=')
122 if eq == '=' and varname.strip() in variables:
123 value = variables[varname]
124 sys.stdout.write('%s="%s"\n' % (varname, value))
125 else:
126 sys.stdout.write(line)
127 finally:
128 fileinput.close()
129
130
Alex Klein87531182019-08-12 15:23:37 -0600131def uprevs_versioned_package(package):
132 """Decorator to register package uprev handlers."""
133 assert package
134
135 def register(func):
136 """Registers |func| as a handler for |package|."""
137 _UPREV_FUNCS[package] = func
138
139 @functools.wraps(func)
140 def pass_through(*args, **kwargs):
141 return func(*args, **kwargs)
142
143 return pass_through
144
145 return register
146
147
Alex Klein4de25e82019-08-05 15:58:39 -0600148def uprev_android(tracking_branch, android_package, android_build_branch,
149 chroot, build_targets=None, android_version=None,
150 android_gts_build_branch=None):
151 """Returns the portage atom for the revved Android ebuild - see man emerge."""
152 command = ['cros_mark_android_as_stable',
153 '--tracking_branch=%s' % tracking_branch,
154 '--android_package=%s' % android_package,
155 '--android_build_branch=%s' % android_build_branch]
156 if build_targets:
157 command.append('--boards=%s' % ':'.join(bt.name for bt in build_targets))
158 if android_version:
159 command.append('--force_version=%s' % android_version)
160 if android_gts_build_branch:
161 command.append('--android_gts_build_branch=%s' % android_gts_build_branch)
162
Mike Frysinger45602c72019-09-22 02:15:11 -0400163 result = cros_build_lib.run(command, redirect_stdout=True,
164 enter_chroot=True,
165 chroot_args=chroot.get_enter_args())
Alex Klein4de25e82019-08-05 15:58:39 -0600166
167 android_atom = _parse_android_atom(result)
168 if not android_atom:
169 logging.info('Found nothing to rev.')
170 return None
171
172 for target in build_targets or []:
173 # Sanity check: We should always be able to merge the version of
174 # Android we just unmasked.
175 command = ['emerge-%s' % target.name, '-p', '--quiet',
176 '=%s' % android_atom]
177 try:
Mike Frysinger45602c72019-09-22 02:15:11 -0400178 cros_build_lib.run(command, enter_chroot=True,
179 chroot_args=chroot.get_enter_args())
Alex Klein4de25e82019-08-05 15:58:39 -0600180 except cros_build_lib.RunCommandError:
181 logging.error(
182 'Cannot emerge-%s =%s\nIs Android pinned to an older '
183 'version?', target, android_atom)
184 raise AndroidIsPinnedUprevError(android_atom)
185
186 return android_atom
187
188
189def _parse_android_atom(result):
190 """Helper to parse the atom from the cros_mark_android_as_stable output.
191
192 This function is largely just intended to make testing easier.
193
194 Args:
195 result (cros_build_lib.CommandResult): The cros_mark_android_as_stable
196 command result.
197 """
198 portage_atom_string = result.output.strip()
199
200 android_atom = None
201 if portage_atom_string:
202 android_atom = portage_atom_string.splitlines()[-1].partition('=')[-1]
203
204 return android_atom
205
206
Alex Kleineb77ffa2019-05-28 14:47:44 -0600207def uprev_build_targets(build_targets, overlay_type, chroot=None,
208 output_dir=None):
209 """Uprev the set provided build targets, or all if not specified.
210
211 Args:
212 build_targets (list[build_target_util.BuildTarget]|None): The build targets
213 whose overlays should be uprevved, empty or None for all.
214 overlay_type (str): One of the valid overlay types except None (see
215 constants.VALID_OVERLAYS).
216 chroot (chroot_lib.Chroot|None): The chroot to clean, if desired.
217 output_dir (str|None): The path to optionally dump result files.
218 """
219 # Need a valid overlay, but exclude None.
220 assert overlay_type and overlay_type in constants.VALID_OVERLAYS
221
222 if build_targets:
223 overlays = portage_util.FindOverlaysForBoards(
224 overlay_type, boards=[t.name for t in build_targets])
225 else:
226 overlays = portage_util.FindOverlays(overlay_type)
227
228 return uprev_overlays(overlays, build_targets=build_targets, chroot=chroot,
229 output_dir=output_dir)
230
231
232def uprev_overlays(overlays, build_targets=None, chroot=None, output_dir=None):
233 """Uprev the given overlays.
234
235 Args:
236 overlays (list[str]): The list of overlay paths.
237 build_targets (list[build_target_util.BuildTarget]|None): The build targets
238 to clean in |chroot|, if desired. No effect unless |chroot| is provided.
239 chroot (chroot_lib.Chroot|None): The chroot to clean, if desired.
240 output_dir (str|None): The path to optionally dump result files.
241
242 Returns:
243 list[str] - The paths to all of the modified ebuild files. This includes the
244 new files that were added (i.e. the new versions) and all of the removed
245 files (i.e. the old versions).
246 """
247 assert overlays
248
249 manifest = git.ManifestCheckout.Cached(constants.SOURCE_ROOT)
250
Alex Kleind6195b62019-08-06 16:01:16 -0600251 uprev_manager = uprev_lib.UprevOverlayManager(overlays, manifest,
252 build_targets=build_targets,
253 chroot=chroot,
254 output_dir=output_dir)
Alex Kleineb77ffa2019-05-28 14:47:44 -0600255 uprev_manager.uprev()
256
257 return uprev_manager.modified_ebuilds
258
259
Alex Klein87531182019-08-12 15:23:37 -0600260def uprev_versioned_package(package, build_targets, refs, chroot):
261 """Call registered uprev handler function for the package.
262
263 Args:
264 package (portage_util.CPV): The package being uprevved.
265 build_targets (list[build_target_util.BuildTarget]): The build targets to
266 clean on a successful uprev.
267 refs (list[uprev_lib.GitRef]):
268 chroot (chroot_lib.Chroot): The chroot to enter for cleaning.
269
270 Returns:
Alex Klein34afcbc2019-08-22 16:14:31 -0600271 UprevVersionedPackageResult: The result.
Alex Klein87531182019-08-12 15:23:37 -0600272 """
273 assert package
274
275 if package.cp not in _UPREV_FUNCS:
276 raise UnknownPackageError(
277 'Package "%s" does not have a registered handler.' % package.cp)
278
279 return _UPREV_FUNCS[package.cp](build_targets, refs, chroot)
280
281
Evan Hernandezb51f1522019-08-15 11:29:40 -0600282# TODO(evanhernandez): Remove this. Only a quick hack for testing.
283@uprevs_versioned_package('sample/sample')
284def uprev_sample(*_args, **_kwargs):
285 """Mimics an uprev by changing files in sandbox repos.
286
287 See: uprev_versioned_package.
288 """
289 paths = [
290 os.path.join(constants.SOURCE_ROOT, 'infra/dummies', repo, 'sample.txt')
291 for repo in ('general-sandbox', 'merge-sandbox')
292 ]
293
Yaakov Shaul730814a2019-09-10 13:58:25 -0600294 return UprevVersionedPackageResult().add_result('1.2.3', paths)
Evan Hernandezb51f1522019-08-15 11:29:40 -0600295
296
Yaakov Shaul395ae832019-09-09 14:45:32 -0600297@uprevs_versioned_package('afdo/kernel-profiles')
298def uprev_kernel_afdo(*_args, **_kwargs):
David Burger92485342019-09-10 17:52:45 -0600299 """Updates kernel ebuilds with versions from kernel_afdo.json.
Yaakov Shaul395ae832019-09-09 14:45:32 -0600300
301 See: uprev_versioned_package.
Yaakov Shaul1eafe832019-09-10 16:50:26 -0600302
303 Raises:
304 EbuildManifestError: When ebuild manifest does not complete successfuly.
Yaakov Shaul395ae832019-09-09 14:45:32 -0600305 """
306 path = os.path.join(constants.SOURCE_ROOT, 'src', 'third_party',
307 'toolchain-utils', 'afdo_metadata', 'kernel_afdo.json')
308
David Burger92485342019-09-10 17:52:45 -0600309 with open(path, 'r') as f:
310 versions = json.load(f)
Yaakov Shaul395ae832019-09-09 14:45:32 -0600311
Yaakov Shaul730814a2019-09-10 13:58:25 -0600312 result = UprevVersionedPackageResult()
Yaakov Shaul395ae832019-09-09 14:45:32 -0600313 for version, version_info in versions.items():
Yaakov Shauldd8b4112019-09-11 11:44:03 -0600314 path = os.path.join('src', 'third_party', 'chromiumos-overlay',
315 'sys-kernel', version)
316 ebuild_path = os.path.join(constants.SOURCE_ROOT, path,
317 '%s-9999.ebuild' % version)
Yaakov Shaula187b152019-09-11 12:41:32 -0600318 chroot_ebuild_path = os.path.join(constants.CHROOT_SOURCE_ROOT, path,
319 '%s-9999.ebuild' % version)
Yaakov Shaul730814a2019-09-10 13:58:25 -0600320 afdo_profile_version = version_info['name']
Yaakov Shaulcb1cfc32019-09-16 13:51:19 -0600321 patch_ebuild_vars(ebuild_path,
322 dict(AFDO_PROFILE_VERSION=afdo_profile_version))
Yaakov Shaul1eafe832019-09-10 16:50:26 -0600323
324 try:
Yaakov Shaul730814a2019-09-10 13:58:25 -0600325 cmd = ['ebuild', chroot_ebuild_path, 'manifest', '--force']
Mike Frysinger45602c72019-09-22 02:15:11 -0400326 cros_build_lib.run(cmd, enter_chroot=True)
Yaakov Shaul1eafe832019-09-10 16:50:26 -0600327 except cros_build_lib.RunCommandError as e:
328 raise EbuildManifestError(
329 'Error encountered when regenerating the manifest for ebuild: %s\n%s'
Yaakov Shaula187b152019-09-11 12:41:32 -0600330 % (chroot_ebuild_path, e), e)
Yaakov Shaul1eafe832019-09-10 16:50:26 -0600331
Yaakov Shauldd8b4112019-09-11 11:44:03 -0600332 manifest_path = os.path.join(constants.SOURCE_ROOT, path, 'Manifest')
Yaakov Shaul1eafe832019-09-10 16:50:26 -0600333
Yaakov Shaul730814a2019-09-10 13:58:25 -0600334 result.add_result(afdo_profile_version, [ebuild_path, manifest_path])
335
336 return result
Yaakov Shaul395ae832019-09-09 14:45:32 -0600337
338
Alex Klein87531182019-08-12 15:23:37 -0600339@uprevs_versioned_package(constants.CHROME_CP)
340def uprev_chrome(build_targets, refs, chroot):
341 """Uprev chrome and its related packages.
342
343 See: uprev_versioned_package.
344 """
345 # Determine the version from the refs (tags), i.e. the chrome versions are the
346 # tag names.
347 chrome_version = uprev_lib.get_chrome_version_from_refs(refs)
348
349 uprev_manager = uprev_lib.UprevChromeManager(
350 chrome_version, build_targets=build_targets, chroot=chroot)
David Burger37f48672019-09-18 17:07:56 -0600351 result = UprevVersionedPackageResult()
Alex Klein87531182019-08-12 15:23:37 -0600352 # Start with chrome itself, as we can't do anything else unless chrome
353 # uprevs successfully.
354 if not uprev_manager.uprev(constants.CHROME_CP):
David Burger37f48672019-09-18 17:07:56 -0600355 return result
Alex Klein87531182019-08-12 15:23:37 -0600356
357 # With a successful chrome rev, also uprev related packages.
358 for package in constants.OTHER_CHROME_PACKAGES:
359 uprev_manager.uprev(package)
360
David Burger37f48672019-09-18 17:07:56 -0600361 return result.add_result(chrome_version, uprev_manager.modified_ebuilds)
Alex Klein87531182019-08-12 15:23:37 -0600362
363
Andrew Lamb2bde9e42019-11-04 13:24:09 -0700364@uprevs_versioned_package('chromeos-base/chromeos-config-bsp-coral-private')
365def replicate_private_config(_build_targets, refs, _chroot):
366 """Replicate a private cros_config change to the corresponding public config.
367
368 See uprev_versioned_package for args
369 """
370 # TODO(crbug.com/1020262): Generalize this to other packages.
371 package = 'chromeos-base/chromeos-config-bsp-coral-private'
372
373 if len(refs) != 1:
374 raise ValueError('Expected exactly one ref, actual %s' % refs)
375
376 # Expect a replication_config.jsonpb in the package root.
377 package_root = os.path.join(constants.SOURCE_ROOT, refs[0].path, package)
378 replication_config_path = os.path.join(package_root,
379 'replication_config.jsonpb')
380
381 try:
382 replication_config = json_format.Parse(
383 osutils.ReadFile(replication_config_path),
384 replication_config_pb2.ReplicationConfig())
385 except IOError:
386 raise ValueError('Expected ReplicationConfig missing at %s' %
387 replication_config_path)
388
389 replication_lib.Replicate(replication_config)
390
391 modified_files = [
392 rule.destination_path
393 for rule in replication_config.file_replication_rules
394 ]
395
396 # TODO(crbug.com/1021241): Use cros_config_schema to generate platform JSON
397 # and C files.
398
399 # Use the private repo's commit hash as the new version.
400 new_private_version = refs[0].revision
401
402 return UprevVersionedPackageResult().add_result(new_private_version,
403 modified_files)
404
405
Alex Kleinbbef2b32019-08-27 10:38:50 -0600406def get_best_visible(atom, build_target=None):
407 """Returns the best visible CPV for the given atom.
408
409 Args:
410 atom (str): The atom to look up.
411 build_target (build_target_util.BuildTarget): The build target whose
Alex Kleinda39c6d2019-09-16 14:36:36 -0600412 sysroot should be searched, or the SDK if not provided.
Alex Kleinbbef2b32019-08-27 10:38:50 -0600413 """
David Burger1e0fe232019-07-01 14:52:07 -0600414 assert atom
Alex Kleinbbef2b32019-08-27 10:38:50 -0600415
416 board = build_target.name if build_target else None
417 return portage_util.PortageqBestVisible(atom, board=board)
Alex Kleinda39c6d2019-09-16 14:36:36 -0600418
419
420def has_prebuilt(atom, build_target=None):
421 """Check if a prebuilt exists.
422
423 Args:
424 atom (str): The package whose prebuilt is being queried.
425 build_target (build_target_util.BuildTarget): The build target whose
426 sysroot should be searched, or the SDK if not provided.
427 """
428 assert atom
429
430 board = build_target.name if build_target else None
431 return portage_util.HasPrebuilt(atom, board=board)
Alex Klein36b117f2019-09-30 15:13:46 -0600432
433
David Burger0f9dd4e2019-10-08 12:33:42 -0600434def builds(atom, build_target, packages=None):
Alex Klein36b117f2019-09-30 15:13:46 -0600435 """Check if |build_target| builds |atom| (has it in its depgraph)."""
436 cros_build_lib.AssertInsideChroot()
437
David Burger0f9dd4e2019-10-08 12:33:42 -0600438 graph = dependency.GetBuildDependency(build_target.name, packages)
Alex Klein36b117f2019-09-30 15:13:46 -0600439 return any(atom in package for package in graph['package_deps'])
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600440
441
Michael Mortensenb51a1f02019-10-16 13:28:20 -0600442def determine_chrome_version(build_target):
Michael Mortensenc2615b72019-10-15 08:12:24 -0600443 """Returns the current Chrome version for the board (or in buildroot).
444
445 Args:
Michael Mortensenb51a1f02019-10-16 13:28:20 -0600446 build_target (build_target_util.BuildTarget): The board build target.
Michael Mortensenc2615b72019-10-15 08:12:24 -0600447 """
Michael Mortensen9fe740c2019-10-29 14:42:48 -0600448 # TODO(crbug/1019770): Long term we should not need the try/catch here once
449 # the builds function above only returns True for chrome when
450 # determine_chrome_version will succeed.
451 try:
452 cpv = portage_util.PortageqBestVisible(constants.CHROME_CP,
453 build_target.name,
454 cwd=constants.SOURCE_ROOT)
455 except cros_build_lib.RunCommandError as e:
456 # Return None because portage failed when trying to determine the chrome
457 # version.
458 logging.warning('Caught exception in determine_chrome_package: %s', e)
459 return None
Michael Mortensenc2615b72019-10-15 08:12:24 -0600460 # Something like 78.0.3877.4_rc -> 78.0.3877.4
461 return cpv.version_no_rev.partition('_')[0]
462
463
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600464def determine_android_package(board):
465 """Returns the active Android container package in use by the board.
466
467 Args:
468 board: The board name this is specific to.
469 """
Michael Mortensene0f4b542019-10-24 15:30:23 -0600470 try:
471 packages = portage_util.GetPackageDependencies(board, 'virtual/target-os')
472 # We assume there is only one Android package in the depgraph.
473 for package in packages:
474 if package.startswith('chromeos-base/android-container-') or \
475 package.startswith('chromeos-base/android-vm-'):
476 return package
477 return None
478 except cros_build_lib.RunCommandError as e:
479 # Return None because a command (likely portage) failed when trying to
480 # determine the package.
481 logging.warning('Caught exception in determine_android_package: %s', e)
482 return None
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600483
484
485def determine_android_version(boards=None):
486 """Determine the current Android version in buildroot now and return it.
487
488 This uses the typical portage logic to determine which version of Android
489 is active right now in the buildroot.
490
491 Args:
492 boards: List of boards to check version of.
493
494 Returns:
495 The Android build ID of the container for the boards.
496
497 Raises:
498 NoAndroidVersionError: if no unique Android version can be determined.
499 """
500 if not boards:
501 return None
502 # Verify that all boards have the same version.
503 version = None
504 for board in boards:
505 package = determine_android_package(board)
506 if not package:
Michael Mortensenedf76532019-10-16 14:22:37 -0600507 return None
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600508 cpv = portage_util.SplitCPV(package)
509 if not cpv:
510 raise NoAndroidVersionError(
511 'Android version could not be determined for %s' % board)
512 if not version:
513 version = cpv.version_no_rev
514 elif version != cpv.version_no_rev:
515 raise NoAndroidVersionError(
516 'Different Android versions (%s vs %s) for %s' %
517 (version, cpv.version_no_rev, boards))
518 return version
519
520def determine_android_branch(board):
521 """Returns the Android branch in use by the active container ebuild."""
522 try:
523 android_package = determine_android_package(board)
524 except cros_build_lib.RunCommandError:
525 raise NoAndroidBranchError(
526 'Android branch could not be determined for %s' % board)
527 if not android_package:
Michael Mortensenedf76532019-10-16 14:22:37 -0600528 return None
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600529 ebuild_path = portage_util.FindEbuildForBoardPackage(android_package, board)
530 # We assume all targets pull from the same branch and that we always
531 # have an ARM_TARGET, ARM_USERDEBUG_TARGET, or an X86_USERDEBUG_TARGET.
532 targets = ['ARM_TARGET', 'ARM_USERDEBUG_TARGET', 'X86_USERDEBUG_TARGET']
533 ebuild_content = osutils.SourceEnvironment(ebuild_path, targets)
534 for target in targets:
535 if target in ebuild_content:
536 branch = re.search(r'(.*?)-linux-', ebuild_content[target])
537 if branch is not None:
538 return branch.group(1)
539 raise NoAndroidBranchError(
540 'Android branch could not be determined for %s (ebuild empty?)' % board)
541
542
543def determine_android_target(board):
Michael Mortensen14960d02019-10-18 07:53:59 -0600544 """Returns the Android target in use by the active container ebuild."""
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600545 try:
546 android_package = determine_android_package(board)
547 except cros_build_lib.RunCommandError:
548 raise NoAndroidTargetError(
549 'Android Target could not be determined for %s' % board)
550 if not android_package:
Michael Mortensenedf76532019-10-16 14:22:37 -0600551 return None
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600552 if android_package.startswith('chromeos-base/android-vm-'):
553 return 'bertha'
554 elif android_package.startswith('chromeos-base/android-container-'):
555 return 'cheets'
556
557 raise NoAndroidTargetError(
558 'Android Target cannot be determined for the package: %s' %
559 android_package)
Michael Mortensen9fdb14b2019-10-17 11:17:30 -0600560
561
562def determine_platform_version():
563 """Returns the platform version from the source root."""
Michael Mortensen009cb662019-10-21 11:38:43 -0600564 # Platform version is something like '12575.0.0'.
Michael Mortensen9fdb14b2019-10-17 11:17:30 -0600565 version = manifest_version.VersionInfo.from_repo(constants.SOURCE_ROOT)
566 return version.VersionString()
Michael Mortensen009cb662019-10-21 11:38:43 -0600567
568
569def determine_milestone_version():
570 """Returns the platform version from the source root."""
571 # Milestone version is something like '79'.
572 version = manifest_version.VersionInfo.from_repo(constants.SOURCE_ROOT)
573 return version.chrome_branch
574
575def determine_full_version():
576 """Returns the full version from the source root."""
577 # Full version is something like 'R79-12575.0.0'.
578 milestone_version = determine_milestone_version()
579 platform_version = determine_platform_version()
580 full_version = ('R%s-%s' % (milestone_version, platform_version))
581 return full_version