diff --git a/helpers/create-abi-bump.py b/helpers/create-abi-bump.py new file mode 100644 --- /dev/null +++ b/helpers/create-abi-bump.py @@ -0,0 +1,239 @@ +#!/usr/bin/python3 + +import argparse +from collections import defaultdict +import os +import pathlib +import re +import subprocess +import tempfile +from typing import Dict, List, Union + +from helperslib import Packages + +import logging +logging.basicConfig(level=logging.DEBUG) + +# Parse the command line arguments we've been given +parser = argparse.ArgumentParser(description='Utility to create abi checker tarballs.') +parser.add_argument('--buildlog', type=str, required=True) +parser.add_argument('--environment', type=str, required=True) +arguments = parser.parse_args() + +def cmake_parser(lines: List) -> Dict: + """A small cmake parser, if you search for a better solution think about using + a propper one based on ply. + see https://salsa.debian.org/qt-kde-team/pkg-kde-jenkins/blob/master/hooks/prepare/cmake_update_deps + + But in our case we are only interessed in two keywords and do not need many features. + we return a dictonary with keywords and targets. + set(VAR "123") + -> variables["VAR"]="123" + set_target_properties(TARGET PROPERTIES PROP1 A B PROP2 C D) + -> targets = { + "PROP1":["A","B"], + "PROP2":["C","D"], + } + """ + + variables = {} # type: Dict[str,str] + targets = defaultdict(lambda:defaultdict(list)) # type: Dict[str, Dict[str, List[str]]] + + ret = { + "variable": variables, + "targets": targets, + } + + def parse_set(args: str) -> None: + """process set lines and updates the variables directory: + set(VAR 1.2.3) -> args = ["VAR", "1.2.3"] + and we set variable["VAR"] = "1.2.3" + """ + _args = args.split() + if len(_args) == 2: + name, value = _args + variables[name] = value + + def parse_set_target_properties(args: str) -> None: + """process set_target_properties cmake lines and update the targets directory + all argiments of set_target_properties are given in the args parameter as list. + as cmake using keyword val1 val2 we need to save the keyword so long we detect + a next keyword. + + args[0] is the target we want to update + args[1] must be PROPERTIES + """ + name, properties, values = args.split() + target = targets[name] + if not properties == "PROPERTIES": + logging.warning("unknown line: %s"%(args)) + + # Known set_target_properties keywords + keywords = [ + "IMPORTED_LINK_DEPENDENT_LIBRARIES_DEBUG", + "IMPORTED_LOCATION_DEBUG", + "IMPORTED_SONAME_DEBUG", + "INTERFACE_INCLUDE_DIRECTORIES", + "INTERFACE_LINK_LIBRARIES", + "INTERFACE_COMPILE_OPTIONS", + ] + + tmpKeyword = None + for arg in values: + if arg in keywords: + tmpKeyword = target[arg] + continue + tmpKeyword.append(arg) + + #Keywords we want to react on + keywords = { + "set": parse_set, + "set_target_properties": parse_set_target_properties, + } + + RELINE = re.compile("^\s*(?P[^(]+)\s*\(\s*(?P.*)\s*\)\s*$") + for line in lines: + m = RELINE.match(line) + if m and m.group('keyword') in keywords: + keywords[m.group('keyword')](m.group('args')) + + return ret + + +class Library: + def __init__(self, name: str) -> None: + + # name of the library + self.name = name # type: str + + # The raw cmake Parser output, available for debug porpuse + # see cmake_parser function for the return value + self.__parser_output = None # type: Union[Dict, None] + + # version of the library + # created/documented within runCMake function + + # targets the targets of the libary ( existing so files) + # created/documented within runCMake function + + + def __repr__(self) -> str: + return "".format(self=self) # replace with f-String in python 3.6 + + def runCMake(self) -> None: + """Create a CMakeLists.txt to detect the headers, version and library path""" + with tempfile.TemporaryDirectory() as d: + + # Create a CMakeLists.txt that depends on the requested library + cmakeFile = (pathlib.Path(d)/"CMakeLists.txt") + cmakeFile.write_text("find_package({self.name} CONFIG REQUIRED)\n".format(self=self)) # replace with f-String in python 3.6 + + proc = subprocess.Popen(['cmake', '.', '--trace-expand'], cwd=d, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, check=True) + + # search only for lines that are the output of the specifc cmake files + self.__mlines = [] # type: List[str] + # cmake prefixes outout with the name of the file, filter only lines with interessting files + retarget=re.compile('.*/{self.name}(Targets[^/]*|Config[^/]*)\.cmake\(\d+\):\s*(.*)$'.format(self=self)) # replace with f-String in python 3.6 + for line in proc.stderr: + theLine = line.decode("utf-8") + m = retarget.match(theLine) + if m: + mline = m.group(2) + self.__mlines.append(mline) + + self.__parser_output = cmake_parser(self.__mlines) + + # version of the library + self.version = self.__parser_output["variables"]["PACKAGE_VERSION"] # type: str + + # targets the targets of the libary ( existing so files) + # a dict with keys, SONAME = the SONAME of the lib + # path = path of the library + # include_dirs = the header files for the library + self.targets = {} # type: Dict + + def inclDirs(args: List[str]) -> List[str]: + """ cmake using ";" to seperate different paths + split the paths and make a unique list of all paths (do not add paths multiple times) + """ + d = [] # type: List[str] + for arg in args: + d += arg.split(";") + return d + + for t,value in self.__parser_output["targets"].items(): + target = { + "SONAME": re.search("\.([\d]*)$",value["IMPORTED_SONAME_DEBUG"][0]).group(1), + "path": value["IMPORTED_LOCATION_DEBUG"][0], + "include_dirs": inclDirs(value["INTERFACE_INCLUDE_DIRECTORIES"]), + } + self.targets[t]=target + + def createABIDump(self) -> None: + """run abi-compliance-checker (acc) to create a ABIDump tar gz + + First we need to construct a input file for acc, see xml variable. + After that we can run acc with the constructed file. + """ + if not self.__parser_output: + self.runCMake() + + version = self.version + headers = [] # type: List[str] + libs = [] # type: List[str] + for target in self.targets.values(): + for i in target['include_dirs']: + # ignore general folders, as there are no lib specific headers are placed + if i == '/usr/include' or i.endswith("/KF5"): + continue + if not i in headers: + headers.append(i) + if not target['path'] in libs: + libs.append(target['path']) + + xml = """ +{version} + +{headers} + + +{libs} + +""".format(version=version, headers="\n".join(headers), libs="\n".join(libs)) # replace with f-String in Python 3.6 + with open("{version}.xml".format(version=version),"w") as f: # replace with f-String in python 3.6 + f.write(xml) + + # acc is compatible for C/C++ as Qt using C++11 and -fPic we need to set the gcc settings explitly + subprocess.check_call(["abi-compliance-checker", "-gcc-options", "-std=c++11 -fPIC", "-l", self.name, "--dump",f.name]) + + +# search in buildlog for the Installing/Up-to-date lines where we installnig the Config.cmake files. +# with this we get a complete List of installed libraries. + +#List of all libraries +libs = [] +reline = re.compile("^-- (Installing|Up-to-date): .*/([^/]*)Config\.cmake$") +with open(arguments.buildlog) as f: + for line in f.readlines(): + m = reline.match(line) + if m: + lib = Library(m.group(2)) + libs.append(lib) + +# Initialize the archive manager +ourArchive = Packages.Archive(arguments.environment, 'ABIReference', usingCache = False) + +# Determine which SCM revision we are storing +# This will be embedded into the package metadata which might help someone doing some debugging +# GIT_COMMIT is set by Jenkins Git plugin, so we can rely on that for most of our builds +scmRevision = '' +if os.getenv('GIT_COMMIT') != '': + scmRevision = os.getenv('GIT_COMMIT') + +for lib in libs: + lib.createABIDump() + + fileName = "abi_dumps/{name}/{name}_{version}.abi.tar.gz".format(name=lib.name,version=lib.version) # can replaced with f-String in python 3.6 + scmRevision = max([t['SONAME'] for t in lib.targets.values()]) # a more hackish way, to save the SONAME in the metadata + packageName = "{name}_{scmRevision}".format(name=lib.name, scmRevision=scmRevision) + ourArchive.storePackage(packageName, fileName, scmRevision)