Strip the Debian "epoch" from the version number
[deb2zero.git] / pkg2zero
blob1886c6a989e09e8bf64f44b880818224eddbaed0
1 #!/usr/bin/env python
2 # Copyright (C) 2009, Thomas Leonard
3 # Copyright (C) 2008, Anders F Bjorklund
4 # See the COPYING file for details, or visit http://0install.net.
6 import sys, time
7 from optparse import OptionParser
8 import tempfile, shutil, os
9 from xml.dom import minidom
10 import gzip
11 try:
12 import xml.etree.cElementTree as ET # Python 2.5
13 except ImportError:
14 try:
15 import xml.etree.ElementTree as ET
16 except ImportError:
17 try:
18 import cElementTree as ET # http://effbot.org
19 except ImportError:
20 import elementtree.ElementTree as ET
22 import subprocess
23 try:
24 from subprocess import check_call
25 except ImportError:
26 def check_call(*popenargs, **kwargs):
27 rc = subprocess.call(*popenargs, **kwargs)
28 if rc != 0: raise OSError, rc
30 from zeroinstall.injector import model, qdom, distro
31 from zeroinstall.zerostore import unpack
33 from support import read_child, add_node, Mappings
35 manifest_algorithm = 'sha1new'
37 deb_category_to_freedesktop = {
38 'devel' : 'Development',
39 'web' : 'Network',
40 'graphics' : 'Graphics',
41 'games' : 'Game',
44 rpm_group_to_freedesktop = {
45 'Development/Libraries' : 'Development',
48 valid_categories = [
49 'AudioVideo',
50 'Audio',
51 'Video',
52 'Development',
53 'Education',
54 'Game',
55 'Graphics',
56 'Network',
57 'Office',
58 'Settings',
59 'System',
60 'Utility',
63 # Parse command-line arguments
65 parser = OptionParser('usage: %prog [options] http://.../package.deb [target-feed.xml]\n'
66 ' %prog [options] http://.../package.rpm [target-feed.xml]\n'
67 ' %prog [options] package-name [target-feed.xml]\n'
68 'Publish a Debian or RPM package in a Zero Install feed.\n'
69 "target-feed.xml is created if it doesn't already exist.")
70 parser.add_option("-a", "--archive-url", help="archive to use as the package contents")
71 parser.add_option("", "--archive-extract", help="only extract files under this subdirectory")
72 parser.add_option("-r", "--repomd-file", help="repository metadata file")
73 parser.add_option("", "--path", help="location of packages [5/os/i386]")
74 parser.add_option("-p", "--packages-file", help="Debian package index file")
75 parser.add_option("-m", "--mirror", help="location of packages [http://ftp.debian.org/debian] or [http://mirror.centos.org/centos]")
76 parser.add_option("-k", "--key", help="key to use for signing")
77 (options, args) = parser.parse_args()
79 if len(args) < 1 or len(args) > 2:
80 parser.print_help()
81 sys.exit(1)
83 # Load dependency mappings
84 mappings = Mappings()
86 class Package:
87 name = '(unknown)'
88 version = None
89 arch = None
90 category = None
91 homepage = None
92 buildtime = None
93 license = None
95 def __init__(self):
96 self.requires = []
98 class DebRepo:
99 def __init__(self, options):
100 self.packages_base_url = (options.mirror or 'http://ftp.debian.org/debian') + '/'
101 self.packages_file = options.packages_file or 'Packages'
103 def get_repo_metadata(self, pkg_name):
104 if not os.path.isfile(self.packages_file):
105 print >>sys.stderr, ("File '%s' not found (use -p to give its location).\n"
106 "Either download one (e.g. ftp://ftp.debian.org/debian/dists/stable/main/binary-amd64/Packages.bz2),\n"
107 "or specify the full URL of the .deb package to use.") % self.packages_file
108 sys.exit(1)
109 if self.packages_file.endswith('.bz2'):
110 import bz2
111 opener = bz2.BZ2File
112 else:
113 opener = file
114 pkg_data = "\n" + opener(self.packages_file).read()
115 try:
116 i = pkg_data.index('\nPackage: %s\n' % pkg_name)
117 except ValueError:
118 raise Exception("Package '%s' not found in Packages file '%s'." % (pkg_name, self.packages_file))
119 j = pkg_data.find('\n\n', i)
120 if j == -1:
121 pkg_info = pkg_data[i:]
122 else:
123 pkg_info = pkg_data[i:j]
124 filename = None
125 digest = {}
126 for line in pkg_info.split('\n'):
127 if ':' in line and not line.startswith(' '):
128 key, value = line.split(':', 1)
129 if key == 'Filename':
130 filename = value.strip()
131 elif key in ('SHA1', 'SHA256'):
132 digest[key.lower()] = value.strip()
133 if filename is None:
134 raise Exception('Filename: field not found in package data:\n' + pkg_info)
135 pkg_url = self.packages_base_url + filename
137 return pkg_url, digest
139 def get_package_metadata(self, pkg_file):
140 package = Package()
142 details = read_child(['dpkg-deb', '--info', pkg_file])
144 description_and_summary = details.split('\n Description: ')[1].split('\n')
145 package.summary = description_and_summary[0]
146 description = ''
147 for x in description_and_summary[1:]:
148 if not x: continue
149 assert x[0] == ' '
150 x = x[1:]
151 if x[0] != ' ':
152 break
153 if x == ' .':
154 description += '\n'
155 else:
156 description += x[1:].replace('. ', '. ') + '\n'
157 package.description = description.strip()
159 for line in details.split('\n'):
160 if not line: continue
161 assert line.startswith(' ')
162 line = line[1:]
163 if ':' in line:
164 key, value = line.split(':', 1)
165 value = value.strip()
166 if key == 'Section':
167 package.category = deb_category_to_freedesktop.get(value)
168 if not package.category:
169 if value != 'libs':
170 print >>sys.stderr, "Warning: no mapping for Debian category '%s'" % value
171 elif key == 'Package':
172 package.name = value
173 elif key == 'Version':
174 value = value.replace('cvs', '')
175 value = value.replace('svn', '')
176 if ':' in value: value = value.split(':', 1)[1]
177 package.version = distro.try_cleanup_distro_version(value)
178 elif key == 'Architecture':
179 if '-' in value:
180 arch, value = value.split('-', 1)
181 else:
182 arch = 'linux'
183 if value == 'amd64':
184 value = 'x86_64'
185 elif value == 'all':
186 value = '*'
187 package.arch = arch.capitalize() + '-' + value
188 elif key == 'Depends':
189 for x in value.split(','):
190 req = mappings.process(x)
191 if req:
192 package.requires.append(req)
193 return package
195 class RPMRepo:
196 def __init__(self, options):
197 self.packages_base_url = (options.mirror or 'http://mirror.centos.org/centos') + '/'
198 self.packages_base_dir = (options.path or '5/os/i386') + '/'
199 self.repomd_file = options.repomd_file or 'repodata/repomd.xml'
200 if not os.path.isfile(self.repomd_file):
201 print >>sys.stderr, ("File '%s' not found (use -r to give its location).\n"
202 "Either download one (e.g. http://mirror.centos.org/centos/5/os/i386/repodata/repomd.xml),\n"
203 "or specify the full URL of the .rpm package to use.") % self.repomd_file
204 sys.exit(1)
206 def get_repo_metadata(self, pkg_name):
207 primary_file = None
208 repomd = minidom.parse(self.repomd_file)
209 repo_top = os.path.dirname(os.path.dirname(self.repomd_file))
210 for data in repomd.getElementsByTagName("data"):
211 if data.attributes["type"].nodeValue == "primary":
212 for node in data.getElementsByTagName("location"):
213 primary_file = os.path.join(repo_top, node.attributes["href"].nodeValue)
214 location = None
215 primary = ET.parse(gzip.open(primary_file))
216 NS = "http://linux.duke.edu/metadata/common"
217 metadata = primary.getroot()
218 pkg_data = None
219 for package in metadata.findall("{%s}package" % NS):
220 if package.find("{%s}name" % NS).text == pkg_name:
221 pkg_data = package
222 location = pkg_data.find("{%s}location" % NS).get("href")
223 break
224 if pkg_data is None:
225 raise Exception("Package '%s' not found in repodata." % pkg_name)
226 checksum = pkg_data.find("{%s}checksum" % NS)
227 digest = {}
228 if checksum.get("type") == "sha":
229 digest["sha1"] = checksum.text
230 if checksum.get("type") == "sha256":
231 digest["sha256"] = checksum.text
232 if location is None:
233 raise Exception('location tag not found in primary metadata:\n' + primary_file)
234 pkg_url = self.packages_base_url + self.packages_base_dir + location
236 return pkg_url, digest
238 def get_package_metadata(self, pkg_file):
239 package = Package()
241 query_format = '%{SUMMARY}\\a%{DESCRIPTION}\\a%{NAME}\\a%{VERSION}\\a%{OS}\\a%{ARCH}\\a%{URL}\\a%{GROUP}\\a%{LICENSE}\\a%{BUILDTIME}\\a[%{REQUIRES}\\n]'
242 headers = read_child(['rpm', '--qf', query_format, '-qp', pkg_file]).split('\a')
244 package.summary = headers[0].strip()
245 package.description = headers[1].strip()
247 package.name = headers[2]
248 value = headers[3]
249 value = value.replace('cvs', '')
250 value = value.replace('svn', '')
251 value = distro.try_cleanup_distro_version(value)
252 package.version = value
253 value = headers[4]
254 package.arch = value.capitalize()
255 value = headers[5]
256 if value == 'amd64':
257 value = 'x86_64'
258 if value == 'noarch':
259 value = '*'
260 package.arch += '-' + value
261 value = headers[6].strip()
262 package.page = value
263 category = None
264 value = headers[7].strip()
265 package.category = rpm_group_to_freedesktop.get(value)
266 if not category:
267 print >>sys.stderr, "Warning: no mapping for RPM group '%s'" % value
269 value = headers[8].strip()
270 package.license = value
271 value = headers[9].strip()
272 package.buildtime = long(value)
273 value = headers[10].strip()
274 for x in value.split('\n'):
275 if x.startswith('rpmlib'):
276 continue
277 req = mappings.process(x)
278 if req:
279 package.requires.append(req)
280 return package
282 if args[0].endswith('.deb') or options.packages_file:
283 repo = DebRepo(options)
284 elif args[0].endswith('.rpm') or options.repomd_file:
285 repo = RPMRepo(options)
286 else:
287 print >>sys.stderr, "Use --packages-file for Debian, or --repomd-file for RPM"
288 sys.exit(1)
290 pkg_data = None
292 if options.archive_url:
293 pkg_url = None
294 pkg_file = os.path.abspath(args[0])
295 archive_url = options.archive_url
296 archive_file = os.path.abspath(archive_url.rsplit('/', 1)[1])
297 digest = {}
298 assert os.path.exists(pkg_file), ("%s doesn't exist!" % pkg_file)
299 else:
300 scheme = args[0].split(':', 1)[0]
301 if scheme in ('http', 'https', 'ftp'):
302 archive_url = args[0]
303 digest = {}
304 else:
305 archive_url, digest = repo.get_repo_metadata(args[0])
306 archive_file = pkg_file = os.path.abspath(archive_url.rsplit('/', 1)[1])
308 # pkg_url, pkg_archive = .deb or .rpm with the metadata
309 # archive_url, archive_file = .dep, .rpm or .tar.bz2 with the contents
311 # Often pkg == archive, but sometimes it's useful to convert packages to tarballs
312 # so people don't need special tools to extract them.
315 # Download package, if required
317 if not os.path.exists(pkg_file):
318 print >>sys.stderr, "File '%s' not found, so downloading from %s..." % (pkg_file, pkg_url)
319 check_call(['wget', pkg_url])
321 # Check digest, if known
323 if "sha256" in digest:
324 import hashlib
325 m = hashlib.new('sha256')
326 expected_digest = digest["sha256"]
327 elif "sha1" in digest:
328 try:
329 import hashlib
330 m = hashlib.new('sha1')
331 except ImportError:
332 import sha
333 m = sha.new()
334 expected_digest = digest["sha1"]
335 else:
336 m = None
338 if m:
339 m.update(file(archive_file).read())
340 actual = m.hexdigest()
341 if actual != expected_digest:
342 raise Exception("Incorrect digest on package file! Was " + actual + ", but expected " + expected_digest)
343 else:
344 print "Package's digest matches value in reposistory metadata (" + actual + "). Good."
345 else:
346 print >>sys.stderr, "Note: no SHA-1 or SHA-256 digest known for this package, so not checking..."
348 # Extract meta-data from package
350 pkg_metadata = repo.get_package_metadata(pkg_file)
352 # Unpack package, find binaries and .desktop files, and add to cache
354 possible_mains = []
355 icondata = None
356 tmp = tempfile.mkdtemp(prefix = 'pkg2zero-')
357 try:
358 unpack_dir = tmp
359 unpack.unpack_archive(archive_file, open(archive_file), destdir = unpack_dir, extract = options.archive_extract)
360 if options.archive_extract:
361 unpack_dir = os.path.join(unpack_dir, options.archive_extract)
363 icon = None
364 images = {}
365 for root, dirs, files in os.walk(unpack_dir):
366 assert root.startswith(unpack_dir)
367 relative_root = root[len(unpack_dir) + 1:]
368 for name in files:
369 full = os.path.join(root, name)
370 f = os.path.join(relative_root, name)
371 print f
372 if f.endswith('.desktop'):
373 for line in file(full):
374 if line.startswith('Categories'):
375 for cat in line.split('=', 1)[1].split(';'):
376 cat = cat.strip()
377 if cat in valid_categories:
378 category = cat
379 break
380 elif line.startswith('Icon'):
381 icon = line.split('=', 1)[1].strip()
382 elif f.startswith('bin/') or f.startswith('usr/bin/') or f.startswith('usr/games/'):
383 if os.path.isfile(full):
384 possible_mains.append(f)
385 elif f.endswith('.png'):
386 images[f] = full
387 images[os.path.basename(f)] = full
388 # make sure to also map basename without the extension
389 images[os.path.splitext(os.path.basename(f))[0]] = full
391 icondata = None
392 if icon in images:
393 print "Using %s for icon" % os.path.basename(images[icon])
394 icondata = file(images[icon]).read()
396 manifest = read_child(['0store', 'manifest', unpack_dir, manifest_algorithm])
397 digest = manifest.rsplit('\n', 2)[1]
398 check_call(['0store', 'add', digest, unpack_dir])
399 finally:
400 shutil.rmtree(tmp)
402 if possible_mains:
403 possible_mains = sorted(possible_mains, key = len)
404 pkg_main = possible_mains[0]
405 if len(possible_mains) > 1:
406 print "Warning: several possible main binaries found:"
407 print "- " + pkg_main + " (I chose this one)"
408 for x in possible_mains[1:]:
409 print "- " + x
410 else:
411 pkg_main = None
413 # Make sure we haven't added this version already...
415 if len(args) > 1:
416 target_feed_file = args[1]
417 target_icon_file = args[1].replace('.xml', '.png')
418 else:
419 target_feed_file = pkg_metadata.name + '.xml'
420 target_icon_file = pkg_metadata.name + '.png'
422 feed_uri = None
423 icon_uri = None
424 if os.path.isfile(target_feed_file):
425 dummy_dist = distro.Distribution()
426 dom = qdom.parse(file(target_feed_file))
427 old_target_feed = model.ZeroInstallFeed(dom, local_path = target_feed_file, distro = dummy_dist)
428 existing_impl = old_target_feed.implementations.get(digest)
429 if existing_impl:
430 print >>sys.stderr, ("Feed '%s' already contains an implementation with this digest!\n%s" % (target_feed_file, existing_impl))
431 sys.exit(1)
432 else:
433 # No target, so need to pick a URI
434 feed_uri = mappings.lookup(pkg_metadata.name)
435 if feed_uri is None:
436 suggestion = mappings.get_suggestion(pkg_metadata.name)
437 uri = raw_input('Enter the URI for this feed [%s]: ' % suggestion).strip()
438 if not uri:
439 uri = suggestion
440 assert uri.startswith('http://') or uri.startswith('https://') or uri.startswith('ftp://'), uri
441 feed_uri = uri
442 mappings.add_mapping(pkg_metadata.name, uri)
444 if icondata and not os.path.isfile(target_icon_file):
445 file = open(target_icon_file, 'wb')
446 file.write(icondata)
447 file.close()
448 if icon_uri is None:
449 suggestion = 'http://0install.net/feed_icons/' + target_icon_file
450 uri = raw_input('Enter the URI for this icon [%s]: ' % suggestion).strip()
451 if not uri:
452 uri = suggestion
453 assert uri.startswith('http://') or uri.startswith('https://') or uri.startswith('ftp://'), uri
454 icon_uri = uri
456 # Create a local feed with just the new version...
458 template = '''<interface xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
459 </interface>'''
460 doc = minidom.parseString(template)
461 root = doc.documentElement
463 add_node(root, 'name', pkg_metadata.name)
464 add_node(root, 'summary', pkg_metadata.summary)
465 add_node(root, 'description', pkg_metadata.description)
466 feed_for = add_node(root, 'feed-for', '')
467 if feed_uri:
468 feed_for.setAttribute('interface', feed_uri)
469 if icon_uri:
470 icon = add_node(root, 'icon')
471 icon.setAttribute('href', icon_uri)
472 icon.setAttribute('type', 'image/png')
473 if pkg_metadata.homepage:
474 add_node(root, 'homepage', pkg_metadata.homepage)
475 if pkg_metadata.category:
476 add_node(root, 'category', pkg_metadata.category)
478 package = add_node(root, 'package-implementation', '')
479 package.setAttribute('package', pkg_metadata.name)
481 group = add_node(root, 'group', '')
482 if pkg_metadata.arch:
483 group.setAttribute('arch', pkg_metadata.arch)
484 else:
485 print >>sys.stderr, "No Architecture: field in package"
486 if pkg_metadata.license:
487 group.setAttribute('license', pkg_metadata.license)
489 for req in pkg_metadata.requires:
490 req_element = add_node(group, 'requires', before = '\n ', after = '')
491 req_element.setAttribute('interface', req.interface)
492 binding = add_node(req_element, 'environment', before = '\n ', after = '\n ')
493 binding.setAttribute('name', 'LD_LIBRARY_PATH')
494 binding.setAttribute('insert', 'usr/lib')
496 if pkg_main:
497 group.setAttribute('main', pkg_main)
498 package.setAttribute('main', '/' + pkg_main)
500 impl = add_node(group, 'implementation', before = '\n ', after = '\n ')
501 impl.setAttribute('id', digest)
502 assert pkg_metadata.version
503 impl.setAttribute('version', pkg_metadata.version)
505 if pkg_metadata.buildtime:
506 impl.setAttribute('released', time.strftime('%Y-%m-%d', time.localtime(pkg_metadata.buildtime)))
507 else:
508 impl.setAttribute('released', time.strftime('%Y-%m-%d'))
510 archive = add_node(impl, 'archive', before = '\n ', after = '\n ')
511 archive.setAttribute('href', archive_url)
512 archive.setAttribute('size', str(os.path.getsize(archive_file)))
513 if options.archive_extract:
514 archive.setAttribute('extract', options.archive_extract)
516 # Add our new version to the main feed...
518 output_stream = tempfile.NamedTemporaryFile(prefix = 'pkg2zero-')
519 try:
520 output_stream.write("<?xml version='1.0'?>\n")
521 root.writexml(output_stream)
522 output_stream.write('\n')
523 output_stream.flush()
525 publishing_options = []
526 if options.key:
527 # Note: 0publish < 0.16 requires the --xmlsign option too
528 publishing_options += ['--xmlsign', '--key', options.key]
529 check_call([os.environ['PUBLISH_COMMAND']] + publishing_options + ['--local', output_stream.name, target_feed_file])
530 print "Added version %s to %s" % (pkg_metadata.version, target_feed_file)
531 finally:
532 output_stream.close()