-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpc2cps
executable file
·278 lines (230 loc) · 9.86 KB
/
pc2cps
1
2
3
4
5
6
7
8
9
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
94
95
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#!/usr/bin/env python
import argparse
import cps
import json
import os
import re
import shlex
import subprocess
import sys
#==============================================================================
class pkgconfig(object):
_re_var = re.compile('(\\w+)=(.*)')
_re_attr = re.compile('([\\w.]+): (.*)')
_re_subst = re.compile('[$][{](\\w+)[}]')
_rre_lib_suffix = {
'dylib': '([.]so(?=([.][0-9]+)*$)|[.]dylib$)',
'archive': '([.]a$)'
}
_type_order = ['dylib', 'archive']
#--------------------------------------------------------------------------
def __init__(self, path, library_name=None, preferred_library_type=None,
libs_to_requires=False, keep_link_libs=set()):
self.name = os.path.splitext(os.path.basename(path))[0]
self.var = {}
self.attr = {}
self.requires = {}
self._ordered_requires = []
self._library_name = library_name or self.name
if preferred_library_type is not None:
self._preferred_library_type = preferred_library_type
else:
self._preferred_library_type = self._type_order[0]
with open(path) as f:
for l in f:
mv = self._re_var.match(l)
if mv is not None:
self.var[mv.group(1)] = mv.group(2)
continue
ma = self._re_attr.match(l)
if ma is not None:
self.attr[ma.group(1)] = self._expand(ma.group(2))
continue
self._extract_requires()
self._extract_component(libs_to_requires, keep_link_libs)
#--------------------------------------------------------------------------
def _expand(self, s):
def subst(m):
return self.var[m.group(1)]
n = self._re_subst.sub(subst, s)
if n != s:
return self._expand(n)
return n
#--------------------------------------------------------------------------
def _get_split(self, attr_name):
v = self.attr.get(attr_name)
if v is None:
return None
return shlex.split(v)
#--------------------------------------------------------------------------
def _extract_requires(self):
ds = self.attr.get('Requires')
if ds is None:
return None
deps = {}
odeps = []
ds = ds.replace(' >= ', '=')
for dep in ds.split():
dep = dep.split('=')
if len(dep) > 1:
deps[dep[0]] = {'Version': dep[1]}
else:
deps[dep[0]] = {}
odeps.append(dep[0])
self.requires = deps
self._ordered_requires = odeps
#--------------------------------------------------------------------------
def _find_library(self, lib_paths):
pt = self._preferred_library_type
types = [pt] + [x for x in self._type_order if x != pt]
# Search for the location of our library
for lib_type in types:
match = None
# Check all search paths
for path in lib_paths:
re_lib = re.compile('(lib)?{}{}'.format(
self._library_name, self._rre_lib_suffix[lib_type]))
for f in os.listdir(path):
m = re.match(re_lib, f)
# If a matching name is found, take the shortest match
if m is not None:
m = m.group(0)
if match is None or len(match) > m:
match = m
# If found, accept a match for the current type being searched
if match:
return os.path.join(path, match), lib_type
# Not found
return None, None
#--------------------------------------------------------------------------
def _extract_component(self, libs_to_requires, keep_link_libs):
def _keys(x):
return [] if x is None else x.keys()
self.component = {}
# Preprocess libraries
link_flags = self._get_split('Libs')
# Extract all library paths
lib_paths = [x[2:] for x in link_flags
if x.startswith('-L') and os.path.isdir(x[2:])]
# Extract list of libraries to link and find the location of this
# component's library
link_libs = [x[2:] for x in link_flags if x.startswith('-l')]
location, lib_type = self._find_library(lib_paths)
if location:
extend(self.component, 'Type', lib_type)
extend(self.component, 'Location', location)
# Remove self from list of link libraries
my_libnames = {self._library_name}
if self._library_name.startswith('lib'):
my_libnames.add(self._library_name[3:])
link_libs = [x for x in link_libs if x not in my_libnames]
# A component type is required; if we weren't able to determine the
# type automatically, assign the preferred library type (which has
# either been given by the user or which is the default type)
if 'Type' not in self.component:
extend(self.component, 'Type', self._preferred_library_type)
# Convert link libraries to Requires
pkg_deps = self._ordered_requires
link_deps = set()
if libs_to_requires:
for lib in link_libs:
if lib in keep_link_libs:
continue
# Add to Requires
if lib not in pkg_deps:
self.requires[lib] = {}
pkg_deps.append(lib)
# Mark for removal from link_libs
link_deps.add(lib)
# Remove converted link libraries from link_libs
link_libs = [x for x in link_libs if x not in link_deps]
# Update requires dictionary
self.requires.update({x: {} for x in link_deps})
# Remove from link flags anything that was removed from link_libs,
# which includes our own library, and any converted to Requires
if len(link_libs):
link_libs = ['-l' + x for x in link_libs]
link_flags = [x for x in link_flags
if x in link_libs or not x.startswith('-l')]
else:
# If link_libs is empty, strip all -l and -L from link_flags
link_flags = [x for x in link_flags
if not (x.startswith('-l') or x.startswith('-L'))]
# Finish filling in component information
extend(self.component, 'Link-Flags', link_flags)
extend(self.component, 'Requires', pkg_deps)
for f in self._get_split('Cflags'):
if f.startswith('-I'):
append(self.component, 'Includes', f[2:])
else:
append(self.component, 'Compile-Flags', f)
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#------------------------------------------------------------------------------
def fatal(message, result=1):
sys.stderr.write(message)
sys.exit(result)
#------------------------------------------------------------------------------
def parse(path_or_name, *args, **kwargs):
if not os.path.exists(path_or_name):
p = subprocess.Popen(['pkgconf', '--path', path_or_name],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
fatal("Package %r not found" % path_or_name)
path_or_name = out.strip()
return pkgconfig(path_or_name, *args, **kwargs)
#------------------------------------------------------------------------------
def is_empty(value):
try:
return len(value) == 0
except TypeError:
return value is None
#------------------------------------------------------------------------------
def extend(data, key, value):
if not is_empty(value):
data.update({key: value})
#------------------------------------------------------------------------------
def append(data, key, value):
if key not in data:
data[key] = []
data[key].append(value)
#------------------------------------------------------------------------------
def main(args):
parser = argparse.ArgumentParser()
parser.add_argument(
'input', metavar='PACKAGE', type=str,
help='Input pkg-config (.pc) file name or package name')
parser.add_argument(
'-n', '--library-name', required=False, type=str,
help='Name of component library (overrides guessing ' +
'from pkg-config package name)')
parser.add_argument(
'-t', '--library-type', action='store',
choices=pkgconfig._type_order,
default=pkgconfig._type_order[0],
help='Preferred library type')
parser.add_argument(
'-c', '--convert-link-libs', action='store_true',
help='Convert link libraries to Requires')
parser.add_argument(
'-k', '--keep-link-lib', type=str, action='append', default=[],
help='Link libraries to not convert to Requires (if -c is used)')
args = parser.parse_args(args)
package = parse(args.input, args.library_name, args.library_type,
args.convert_link_libs, set(args.keep_link_lib))
component_name = package.attr.get('Name', package.name)
spec = {
'Cps-Version': cps.current_version,
'Name': package.name,
'Components': {component_name: package.component},
'Default-Components': [':%s' % component_name],
}
extend(spec, 'Version', package.attr.get('Version'))
extend(spec, 'Description', package.attr.get('Description'))
extend(spec, 'Website', package.attr.get('URL'))
extend(spec, 'Requires', package.requires)
print(json.dumps(spec, indent=2, sort_keys=True))
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if __name__ == "__main__":
main(sys.argv[1:])