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