|
| 1 | +#!/usr/bin/python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +# Copyright (c) 2017, Christopher Pollok <[email protected]> |
| 5 | +# All rights reserved. |
| 6 | +# |
| 7 | +# Redistribution and use in source and binary forms, with or without |
| 8 | +# modification, are permitted provided that the following conditions are met: |
| 9 | +# |
| 10 | +# * Redistributions of source code must retain the above copyright |
| 11 | +# notice, this list of conditions and the following disclaimer. |
| 12 | +# * Redistributions in binary form must reproduce the above copyright |
| 13 | +# notice, this list of conditions and the following disclaimer in the |
| 14 | +# documentation and/or other materials provided with the distribution. |
| 15 | +# * Neither the name of the Institute for Artificial Intelligence/ |
| 16 | +# Universitaet Bremen nor the names of its contributors may be used to |
| 17 | +# endorse or promote products derived from this software without |
| 18 | +# specific prior written permission. |
| 19 | +# |
| 20 | +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 21 | +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 22 | +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 23 | +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE |
| 24 | +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 25 | +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| 26 | +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 27 | +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| 28 | +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| 29 | +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| 30 | +# POSSIBILITY OF SUCH DAMAGE. |
| 31 | + |
| 32 | +import os |
| 33 | +import sys |
| 34 | +import yaml |
| 35 | +import datetime |
| 36 | +import operator |
| 37 | +import itertools |
| 38 | +import argparse |
| 39 | +import xml.etree.ElementTree as et |
| 40 | + |
| 41 | +MAX_STACK_LIST = 5 |
| 42 | +MAX_PKG_LIST = 20 |
| 43 | + |
| 44 | +FORMAT_1_DEPEND_TAGS = set([ |
| 45 | + # "buildtool_depend", |
| 46 | + "build_depend", |
| 47 | + "run_depend", |
| 48 | + "test_depend" |
| 49 | +]) |
| 50 | + |
| 51 | +FORMAT_2_DEPEND_TAGS = set([ |
| 52 | + "depend", |
| 53 | + # "buildtool_depend", |
| 54 | + "build_depend", |
| 55 | + "exec_depend", |
| 56 | + "test_depend", |
| 57 | + "doc_depend" |
| 58 | +]) |
| 59 | + |
| 60 | + |
| 61 | +# Packages in the source directory being configured, mapped to their path (relative from the cwd when executing) |
| 62 | +pkg_paths = {} |
| 63 | + |
| 64 | +# Packages to be whitelisted by config() |
| 65 | +wl_packages = [] |
| 66 | + |
| 67 | +# White- and blacklist. {path:package} if path is directory containing packages, package is None |
| 68 | +wl_pkg_paths = {} |
| 69 | +bl_pkg_paths = {} |
| 70 | + |
| 71 | + |
| 72 | +inside_cram_src_msg = """The script has to be run inside the top-level directory of the CRAM repository. |
| 73 | +You can only pass packages which are inside the CRAM repository, otherwise the script can't know for which dependencies to configure.""" |
| 74 | + |
| 75 | +################## |
| 76 | +# Help functions # |
| 77 | +################## |
| 78 | + |
| 79 | +def blacklist(dirpath, pkg=None): |
| 80 | + """Add DIRPATH to the blacklist if it's not already CATKIN_IGNOREd.""" |
| 81 | + dir_content = os.listdir(dirpath) |
| 82 | + if 'CATKIN_IGNORE' not in dir_content: |
| 83 | + # open(os.path.join(dirpath, 'CATKIN_IGNORE'), 'w') |
| 84 | + bl_pkg_paths[dirpath] = pkg |
| 85 | + # print "Blacklisted: " + dirpath |
| 86 | + |
| 87 | +def whitelist(dirpath, pkg=None): |
| 88 | + """Add DIRPATH to the whitelist if it's CATKIN_IGNOREd.""" |
| 89 | + dir_content = os.listdir(dirpath) |
| 90 | + if 'CATKIN_IGNORE' in dir_content: |
| 91 | + # os.remove(os.path.join(dirpath, 'CATKIN_IGNORE')) |
| 92 | + wl_pkg_paths[dirpath] = pkg |
| 93 | + # print "Whitelisted: " + dirpath |
| 94 | + |
| 95 | + |
| 96 | +def get_package_name(path): |
| 97 | + """Return the package name stated in the package.xml under PATH.""" |
| 98 | + xml_path = os.path.join(path, 'package.xml') |
| 99 | + e = et.parse(xml_path).getroot() |
| 100 | + return e.find('name').text |
| 101 | + |
| 102 | +def get_dependencies(xml): |
| 103 | + """Return the list of dependencies in the XML as strings.""" |
| 104 | + # Choose the right set of dependency tags |
| 105 | + depend_tags = set() |
| 106 | + if "format" in xml.attrib and xml.attrib["format"] == "2": |
| 107 | + depend_tags.update(FORMAT_2_DEPEND_TAGS) |
| 108 | + else: |
| 109 | + depend_tags.update(FORMAT_1_DEPEND_TAGS) |
| 110 | + |
| 111 | + # Find all elements containing dependencies |
| 112 | + dependency_elements = reduce(lambda x, y: x + xml.findall(y), depend_tags, []) |
| 113 | + |
| 114 | + # Map the elements to their content text, which is the name of the dependency |
| 115 | + dependencies = map(lambda x: x.text, dependency_elements) |
| 116 | + return dependencies |
| 117 | + |
| 118 | +def print_pkg_list(pkg_dict): |
| 119 | + """Print a list of packages in PKG_DICT.""" |
| 120 | + |
| 121 | + # Sort packages and directories in two groups. |
| 122 | + keyfun = lambda x: x[1] == None |
| 123 | + sort = sorted(pkg_dict.items(), key=keyfun) |
| 124 | + groups = [] |
| 125 | + keys = [] |
| 126 | + for k, g in itertools.groupby(sort, keyfun): |
| 127 | + groups.append(list(g)) |
| 128 | + keys.append(k) |
| 129 | + |
| 130 | + pkgs=[] |
| 131 | + dirnames=[] |
| 132 | + if False in keys: |
| 133 | + pkgs = [x[1] for x in groups[keys.index(False)]] |
| 134 | + if True in keys: |
| 135 | + dirnames = [x[0] for x in groups[keys.index(True)]] |
| 136 | + |
| 137 | + # Print the packages. |
| 138 | + step = 5 |
| 139 | + if len(pkgs) != 0: |
| 140 | + for i in range(0, min(MAX_PKG_LIST, len(pkgs)), step): |
| 141 | + print(" " + ("{}," * min(step, len(pkgs)-i)).format(*pkgs[i:i+step])) |
| 142 | + if len(pkgs) > MAX_PKG_LIST: |
| 143 | + print("\n and {} more...".format(len(pkgs) - MAX_PKG_LIST)) |
| 144 | + |
| 145 | + # Print the directories. |
| 146 | + if len(dirnames) != 0: |
| 147 | + print("\n And also in the sub packages of these directories/stacks:") |
| 148 | + for dirname in dirnames[:MAX_STACK_LIST]: |
| 149 | + print(" " + dirname) |
| 150 | + if len(dirnames) > MAX_STACK_LIST: |
| 151 | + print("\n and {} more...".format(len(dirnames) - MAX_STACK_LIST)) |
| 152 | + |
| 153 | + |
| 154 | +################## |
| 155 | +# Main functions # |
| 156 | +################## |
| 157 | + |
| 158 | +def crawl(): |
| 159 | + """Traverse the repository and collect all packages in pkg_paths.""" |
| 160 | + global pkg_paths |
| 161 | + for dirpath, dirnames, filenames in os.walk('.'): |
| 162 | + if '.git' in dirnames: |
| 163 | + # don't look into .git directories |
| 164 | + del dirnames[dirnames.index('.git')] |
| 165 | + |
| 166 | + if 'CMakeLists.txt' in filenames and 'package.xml' in filenames: |
| 167 | + # found a package |
| 168 | + pkg_paths[get_package_name(dirpath)] = dirpath |
| 169 | + dirnames[:] = [] |
| 170 | + |
| 171 | +def check_package_names(): |
| 172 | + """Check if any package name is different from the name of the directory containing it.""" |
| 173 | + for pkg_name, dirpath in pkg_paths.items(): |
| 174 | + dirname = os.path.basename(dirpath) |
| 175 | + if pkg_name != dirname: |
| 176 | + print "WARNING: Package name and name of containing directory differ: Package '{}' in directory '{}'!".format(pkg_name, dirname) |
| 177 | + |
| 178 | +def check_for_high_level_packages(pkgs): |
| 179 | + """Check if the given packages are existent in the repository.""" |
| 180 | + high_lvl_pkgs_in_dir = [x in pkg_paths.keys() for x in pkgs] |
| 181 | + if not all(high_lvl_pkgs_in_dir): |
| 182 | + print("WARNING: Not all packages you passed are existent in the current directory.") |
| 183 | + for pkg_not_found in [x for x in pkgs if not high_lvl_pkgs_in_dir[pkgs.index(x)]]: |
| 184 | + print("WARNING: {} does not designate a package inside {}.".format(pkg_not_found, os.getcwd())) |
| 185 | + return False |
| 186 | + return True |
| 187 | + |
| 188 | +def build_profile(pkgs): |
| 189 | + """Look up the dependecies of the packages in pkgs until reaching the lowest level and thus finding no more dependencies.""" |
| 190 | + global wl_packages |
| 191 | + wl_packages = set() |
| 192 | + wl_packages.update(pkgs) |
| 193 | + deps = set() |
| 194 | + while len(pkgs) != 0: |
| 195 | + deps.clear() |
| 196 | + for pkg in pkgs: |
| 197 | + xml_path = os.path.join(pkg_paths[pkg], 'package.xml') |
| 198 | + pkg_xml = et.parse(xml_path).getroot() |
| 199 | + deps.update(get_dependencies(pkg_xml)) |
| 200 | + wl_packages.update(deps) |
| 201 | + pkgs = set(deps).intersection(pkg_paths.keys()) |
| 202 | + |
| 203 | +def config(): |
| 204 | + """Traverse the repository and black-/whitelist the packages/directories.""" |
| 205 | + for dirpath, dirnames, filenames in os.walk('.'): |
| 206 | + |
| 207 | + pkgs_in_dir = [x for x in pkg_paths.keys() if pkg_paths[x].startswith(dirpath)] |
| 208 | + if 'CMakeLists.txt' in filenames and 'package.xml' in filenames: |
| 209 | + # found a package, don't recurse deeper |
| 210 | + dirnames[:] = [] |
| 211 | + basepath, dirname = os.path.split(dirpath) |
| 212 | + if any(map(lambda x: x == dirname, wl_packages)): |
| 213 | + whitelist(dirpath, pkg=dirname) |
| 214 | + else: |
| 215 | + blacklist(dirpath, pkg=dirname) |
| 216 | + |
| 217 | + elif len(pkgs_in_dir) != 0: |
| 218 | + if not any([x in wl_packages for x in pkgs_in_dir]): |
| 219 | + blacklist(dirpath) |
| 220 | + ## Uncomment this, if you want to remove CATKIN_IGNOREs in the packages when blacklisting the whole dir. Comment the next line then though. |
| 221 | + # wl_packages.update(pkgs_in_dir) |
| 222 | + dirnames[:] = [] |
| 223 | + else: |
| 224 | + whitelist(dirpath) |
| 225 | + |
| 226 | + if '.git' in dirnames: |
| 227 | + # don't look into .git directories |
| 228 | + del dirnames[dirnames.index('.git')] |
| 229 | + |
| 230 | +def ask_permission(): |
| 231 | + """Ask for permission to create and delete CATKIN_IGNORE files.""" |
| 232 | + if len(bl_pkg_paths) != 0: |
| 233 | + print("\nThe script will CREATE CATKIN_IGNOREs in these packages:") |
| 234 | + print_pkg_list(bl_pkg_paths) |
| 235 | + |
| 236 | + if len(wl_pkg_paths) != 0: |
| 237 | + print("\nThe script will DELETE CATKIN_IGNOREs in these packages:") |
| 238 | + print_pkg_list(wl_pkg_paths) |
| 239 | + |
| 240 | + answer = "" |
| 241 | + possibilities = ['Y', 'y', 'N', 'n'] |
| 242 | + while answer not in possibilities: |
| 243 | + if answer != "": |
| 244 | + print("Please type one of '{}', '{}', '{}' or '{}'".format(*possibilities)) |
| 245 | + answer = raw_input("Do you want to proceed? (Y/n)") or "Y" |
| 246 | + if answer in ['N', 'n']: |
| 247 | + return False |
| 248 | + return True |
| 249 | + |
| 250 | +def execute(): |
| 251 | + """Create CATKIN_IGNOREs in the blacklisted paths and delete those in the whitelisted paths.""" |
| 252 | + for dirpath in bl_pkg_paths.keys(): |
| 253 | + open(os.path.join(dirpath, 'CATKIN_IGNORE'), 'w') |
| 254 | + |
| 255 | + for dirpath in wl_pkg_paths.keys(): |
| 256 | + os.remove(os.path.join(dirpath, 'CATKIN_IGNORE')) |
| 257 | + |
| 258 | +def profile_str(): |
| 259 | + """Return the profile of white- and blacklisted packages as a string.""" |
| 260 | + profile = """Latest configuration ({}):""".format(datetime.datetime.now()) |
| 261 | + for pkg, dirpath in sorted(pkg_paths.items(), key=operator.itemgetter(1)): |
| 262 | + profile += "\n * " |
| 263 | + if pkg in wl_packages: |
| 264 | + profile += "Whitelisted: " |
| 265 | + else: |
| 266 | + profile += "Blacklisted: " |
| 267 | + profile += dirpath |
| 268 | + profile += "\n" |
| 269 | + return profile |
| 270 | + |
| 271 | +def parse_args(): |
| 272 | + """Parse the arguments passed to the script.""" |
| 273 | + parser = argparse.ArgumentParser(description="Configure a CRAM repository for a set of given packages.", |
| 274 | + epilog=inside_cram_src_msg) |
| 275 | + |
| 276 | + parser.add_argument("packages", nargs='+', help="The packages to configure for.") |
| 277 | + parser.add_argument("-n3p", "--no_3rdparty", action='store_true', help="This option can be supplied if for some reason not all cram_3rdparty packages should be included in the configuration.") |
| 278 | + return parser.parse_args() |
| 279 | + |
| 280 | +if __name__ == '__main__': |
| 281 | + args = parse_args() |
| 282 | + |
| 283 | + crawl() |
| 284 | + check_package_names() |
| 285 | + |
| 286 | + if not check_for_high_level_packages(args.packages): |
| 287 | + print(inside_cram_src_msg) |
| 288 | + sys.exit() |
| 289 | + |
| 290 | + packages = args.packages |
| 291 | + if not args.no_3rdparty and "cram_3rdparty" not in packages: |
| 292 | + packages.append("cram_3rdparty") |
| 293 | + print("To prevent complications the packages in 'cram_3rdparty' have been included by default.") |
| 294 | + build_profile(packages) |
| 295 | + config() |
| 296 | + if not ask_permission(): |
| 297 | + sys.exit() |
| 298 | + execute() |
| 299 | + |
| 300 | + profile = profile_str() |
| 301 | + |
| 302 | + with open("latest_config", "w") as f: |
| 303 | + f.write(profile) |
0 commit comments