[RIFT 16413, 16414] Unittest failures fixed for utest_package, utest_publisher_dts
[osm/SO.git] / rwlaunchpad / plugins / rwlaunchpadtasklet / rift / package / icon.py
1
2 #
3 # Copyright 2016 RIFT.IO Inc
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17
18
19 import re
20 import os.path
21
22 from . import package
23
24 class IconExtractionError(Exception):
25 pass
26
27
28 class PackageIconExtractor(object):
29 """ This class extracts icons to a known location for the UI to access """
30
31 DEFAULT_INSTALL_DIR = os.path.join(
32 os.environ["RIFT_INSTALL"],
33 "usr/share/rw.ui/skyquake/plugins/composer/public/assets/logos"
34 )
35
36 ICON_REGEX = "{prefix}/?icons/(?P<icon_name>[^/]+)$"
37
38 def __init__(self, log, install_dir=DEFAULT_INSTALL_DIR):
39 self._log = log
40 self._install_dir = install_dir
41
42 def _get_rel_dest_path(self, descriptor_type, descriptor_id, icon_name):
43 dest_path = os.path.join(self._install_dir, descriptor_type, descriptor_id, icon_name)
44 return dest_path
45
46 @classmethod
47 def package_icon_files(cls, package):
48 icon_file_map = {}
49
50 for file_name in package.files:
51 match = re.match(
52 cls.ICON_REGEX.format(prefix=package.prefix),
53 file_name,
54 )
55 if match is None:
56 continue
57
58 icon_name = match.group("icon_name")
59
60 icon_file_map[icon_name] = file_name
61
62 return icon_file_map
63
64 def get_extracted_icon_path(self, descriptor_type, descriptor_id, icon_name):
65 return os.path.join(
66 self._get_rel_dest_path(descriptor_type, descriptor_id, icon_name),
67 )
68
69 def extract_icons(self, pkg):
70 """ Extract any icons in the package to the UI filesystem location
71
72 Arguments:
73 pkg - A DescriptorPackage
74 """
75 descriptor_id = pkg.descriptor_id
76 icon_files = PackageIconExtractor.package_icon_files(pkg)
77
78 for icon_name, icon_file in icon_files.items():
79 dest_rel_path = self._get_rel_dest_path(pkg.descriptor_type, descriptor_id, icon_name)
80 dest_path = os.path.join(self._install_dir, dest_rel_path)
81
82 dest_dir = os.path.dirname(dest_path)
83 try:
84 os.makedirs(dest_dir, exist_ok=True)
85 except OSError as e:
86 self._log.error("Failed to create icon directory %s: %s", dest_dir, str(e))
87 continue
88
89
90 self._log.debug("Extracting %s icon to %s", icon_name, dest_path)
91 try:
92 pkg.extract_file(icon_file, dest_path)
93 except package.ExtractError as e:
94 self._log.error("Failed to extact icon %s: %s", icon_name, str(e))
95 continue
96