project_manifest.py 6.97 KB
Newer Older
1
2
3
4
5
6
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
from xml.etree import ElementTree as ET
7
from subprocess import Popen, PIPE
8
import re
9
import logging
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

def indent(elem, level=0):
    '''
    Add spaces and newlines to elements to allow pretty-printing of XML.

    http://effbot.org/zone/element-lib.htm#prettyprint
    '''
    i = "\n" + level*"  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i

def CMakeParseArguments(args, options=None, single_value=None, multi_value=None):
    '''
    Parse a list or strings using the logic of the CMake function
    CMAKE_PARSE_ARGUMENTS.

    >>> res = CMakeParseArguments(['USE', 'Gaudi', 'v25r0', 'DATA', 'Det/SQLDDDB'],
    ... multi_value=['USE', 'DATA'])
    >>> res['USE']
    ['Gaudi', 'v25r0']
    >>> res['DATA']
    ['Det/SQLDDDB']
    >>> res['UNPARSED']
    []
    >>> res = CMakeParseArguments('a b OPTION1 c FLAG1 d OPTION2 e f'.split(),
    ... options=['FLAG1', 'FLAG2'],
    ... single_value=['OPTION1', 'OPTION2'])
    >>> res['FLAG1']
    True
    >>> res['FLAG2']
    False
    >>> res['OPTION1']
    'c'
    >>> res['OPTION2']
    'e'
    >>> res['UNPARSED']
    ['a', 'b', 'd', 'f']
    '''
    args = list(args)
    options = set(options or [])
    single_value = set(single_value or [])
    multi_value = set(multi_value or [])
    all_keywords = options.union(single_value).union(multi_value)
    result = {'UNPARSED': []}
    result.update((k, False) for k in options)
    result.update((k, None) for k in single_value)
    result.update((k, []) for k in multi_value)

    while args:
        arg = args.pop(0)
        if arg in options:
            result[arg] = True
        elif arg in single_value:
            result[arg] = args.pop(0)
        elif arg in multi_value:
            while args and args[0] not in all_keywords:
                result[arg].append(args.pop(0))
        else:
            result['UNPARSED'].append(arg)
    return result

if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser(usage='%prog [options] <cmake_lists> <lcg_version> <platform>')
    parser.add_option('-o', '--output', action='store',
                      help='output filename')

    opts, args = parser.parse_args()

    if len(args) != 3:
        parser.error('wrong number of arguments')

    cmake_lists, lcg_version, platform = args

94
95
    logging.basicConfig(level=logging.INFO)

96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
    # look for the CMake configuration file
    if not os.path.exists(cmake_lists):
        print 'The project does not have a CMake configuration, I cannot produce a manifest.xml'
        sys.exit(0)

    project_args = []
    m = re.search(r'gaudi_project\s*\(([^)]*)\)',
                  open(cmake_lists).read(), re.MULTILINE)
    if m:
        project_args = m.group(1).split()
    if len(project_args) < 2:
        print 'error: invalid content of CMakeLists.txt'
        sys.exit(1)

    # parse gaudi_project arguments
    name, version = project_args[:2]
    project_args = project_args[2:]

    parsed_args = CMakeParseArguments(project_args,
                                      options=['FORTRAN'],
                                      multi_value=['USE', 'DATA'])

    # set the output
    if opts.output in ('-', None):
        output = sys.stdout
    else:
        output = opts.output

    # prepare the XML content
    manifest = ET.Element('manifest')
    manifest.append(ET.Element('project', name=name, version=version))

    heptools = ET.Element('heptools')
    ht_version = ET.Element('version')
    ht_version.text = lcg_version
    ht_bin_tag = ET.Element('binary_tag')
    ht_bin_tag.text = platform
    ht_system = ET.Element('lcg_system')
    ht_system.text = '-'.join(platform.split('-')[:-1])
    heptools.extend([ht_version, ht_bin_tag, ht_system])
    manifest.append(heptools)

    if parsed_args['USE']:
        used_projects = ET.Element('used_projects')
        used_projects.extend(ET.Element('project', name=name, version=version)
                             for name, version in zip(parsed_args['USE'][::2],
                                                      parsed_args['USE'][1::2]))
        manifest.append(used_projects)

    if parsed_args['DATA']:
        used_data_pkgs = ET.Element('used_data_pkgs')
        def data_pkgs(args):
            '''helper to translate the list of data packages'''
            args = list(args) # clone
            while args:
                pkg = args.pop(0)
                if len(args) >= 2 and args[0] == 'VERSION':
                    args.pop(0)
                    vers = args.pop(0)
                else:
                    vers = '*'
                yield (pkg, vers)
        used_data_pkgs.extend(ET.Element('package', name=pkg, version=vers)
                              for pkg, vers in data_pkgs(parsed_args['DATA']))
        manifest.append(used_data_pkgs)

162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177

    logging.debug('collecting external dependencies info (with CMT)')
    p = Popen(['cmt', 'show', 'uses'], stdout=PIPE)
    externals = [l.split()[1]
                 for l in p.stdout
                 if l.startswith('use') and
                    'LCG_Interfaces' in l]
    externals.sort()

    # get the versions of the externals
    def get_ext_vers(ext):
        '''
        Ask CMT the version of an external.
        '''
        logging.debug('getting version of %s', ext)
        vers = Popen(['cmt', 'show', 'macro_value',
178
                      '%s_native_version' % ext],
179
180
181
182
183
184
                     stdout=PIPE).communicate()[0].strip()
        logging.debug('using %s %s', ext, vers)
        if vers == 'dummy': # special case in LCG
            vers = ''
        return vers

185
186
    # mapping between LCG_Interface name and RPM name for special cases
    rpm_names = {'Expat': 'expat'}
187
188
189
190
191
192

    # Hack alert: tcmalloc LCG_interface corresponds to gperftools
    # as from LCG 84. We rename the external in that case...
    if int(filter(str.isdigit, lcg_version)) >= 84:
        rpm_names['tcmalloc'] = 'gperftools'
        
193
194
    fix_rpm_name = lambda n: rpm_names.get(n, n)

195
    packages = ET.Element('packages')
196
    packages.extend([ET.Element('package', name=fix_rpm_name(ext), version=vers)
197
198
199
200
201
202
203
204
205
206
                     for ext, vers in [(ext, get_ext_vers(ext))
                                       for ext in externals]
                     if vers])
    heptools.append(packages)

    destdir = os.path.dirname(output)
    if not os.path.exists(destdir):
        logging.debug('creating directory %s', destdir)
        os.makedirs(destdir)

207
    # finally write the produced XML
208
    logging.debug('writing manifest file %s', output)
209
210
211
    indent(manifest)
    ET.ElementTree(manifest).write(output,
                                   encoding="UTF-8", xml_declaration=True)
212
213

    logging.debug('%s written', output)