Alex Klein | a9d500b | 2019-04-22 15:37:51 -0600 | [diff] [blame^] | 1 | # -*- 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 | """Utility functions that are useful for controllers.""" |
| 7 | |
| 8 | from __future__ import print_function |
| 9 | |
| 10 | from chromite.lib import portage_util |
| 11 | |
| 12 | |
| 13 | def CPVToPackageInfo(cpv, package_info): |
| 14 | """Helper to translate CPVs into a PackageInfo message.""" |
| 15 | package_info.package_name = cpv.package |
| 16 | if cpv.category: |
| 17 | package_info.category = cpv.category |
| 18 | if cpv.version: |
| 19 | package_info.version = cpv.version |
| 20 | |
| 21 | |
| 22 | def PackageInfoToCPV(package_info): |
| 23 | """Helper to translate a PackageInfo message into a CPV.""" |
| 24 | if not package_info or not package_info.package_name: |
| 25 | return None |
| 26 | |
| 27 | return portage_util.SplitCPV(PackageInfoToString(package_info), strict=False) |
| 28 | |
| 29 | |
| 30 | def PackageInfoToString(package_info): |
| 31 | # Combine the components into the full CPV string that SplitCPV parses. |
| 32 | # TODO: Turn portage_util.CPV into a class that can handle building out an |
| 33 | # instance from components. |
| 34 | if not package_info.package_name: |
| 35 | raise ValueError('Invalid package_info.') |
| 36 | |
| 37 | c = ('%s/' % package_info.category) if package_info.category else '' |
| 38 | p = package_info.package_name |
| 39 | v = ('-%s' % package_info.version) if package_info.version else '' |
| 40 | return '%s%s%s' % (c, p, v) |
| 41 | |
| 42 | |
| 43 | def CPVToString(cpv): |
| 44 | """Get the most useful string representation from a CPV. |
| 45 | |
| 46 | Args: |
| 47 | cpv (portage_util.CPV): The CPV object. |
| 48 | |
| 49 | Returns: |
| 50 | str |
| 51 | |
| 52 | Raises: |
| 53 | ValueError - when the CPV has no useful fields set. |
| 54 | """ |
| 55 | if cpv.cpf: |
| 56 | return cpv.cpf |
| 57 | elif cpv.cpv: |
| 58 | return cpv.cpv |
| 59 | elif cpv.cp: |
| 60 | return cpv.cp |
| 61 | elif cpv.package: |
| 62 | return cpv.package |
| 63 | else: |
| 64 | raise ValueError('Invalid CPV provided.') |