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.
7 from optparse
import OptionParser
8 import tempfile
, shutil
, os
9 from xml
.dom
import minidom
12 import xml
.etree
.cElementTree
as ET
# Python 2.5
15 import xml
.etree
.ElementTree
as ET
18 import cElementTree
as ET
# http://effbot.org
20 import elementtree
.ElementTree
as ET
24 from subprocess
import check_call
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',
40 'graphics' : 'Graphics',
44 rpm_group_to_freedesktop
= {
45 'Development/Libraries' : 'Development',
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:
83 # Load dependency mappings
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
109 if self
.packages_file
.endswith('.bz2'):
114 pkg_data
= "\n" + opener(self
.packages_file
).read()
116 i
= pkg_data
.index('\nPackage: %s\n' % pkg_name
)
118 raise Exception("Package '%s' not found in Packages file '%s'." % (pkg_name
, self
.packages_file
))
119 j
= pkg_data
.find('\n\n', i
)
121 pkg_info
= pkg_data
[i
:]
123 pkg_info
= pkg_data
[i
:j
]
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()
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
):
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]
147 for x
in description_and_summary
[1:]:
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(' ')
164 key
, value
= line
.split(':', 1)
165 value
= value
.strip()
167 package
.category
= deb_category_to_freedesktop
.get(value
)
168 if not package
.category
:
170 print >>sys
.stderr
, "Warning: no mapping for Debian category '%s'" % value
171 elif key
== 'Package':
173 elif key
== 'Version':
174 value
= value
.replace('cvs', '')
175 value
= value
.replace('svn', '')
176 package
.version
= distro
.try_cleanup_distro_version(value
)
177 elif key
== 'Architecture':
179 arch
, value
= value
.split('-', 1)
186 package
.arch
= arch
.capitalize() + '-' + value
187 elif key
== 'Depends':
188 for x
in value
.split(','):
189 req
= mappings
.process(x
)
191 package
.requires
.append(req
)
195 def __init__(self
, options
):
196 self
.packages_base_url
= (options
.mirror
or 'http://mirror.centos.org/centos') + '/'
197 self
.packages_base_dir
= (options
.path
or '5/os/i386') + '/'
198 self
.repomd_file
= options
.repomd_file
or 'repodata/repomd.xml'
199 if not os
.path
.isfile(self
.repomd_file
):
200 print >>sys
.stderr
, ("File '%s' not found (use -r to give its location).\n"
201 "Either download one (e.g. http://mirror.centos.org/centos/5/os/i386/repodata/repomd.xml),\n"
202 "or specify the full URL of the .rpm package to use.") % self
.repomd_file
205 def get_repo_metadata(self
, pkg_name
):
207 repomd
= minidom
.parse(self
.repomd_file
)
208 repo_top
= os
.path
.dirname(os
.path
.dirname(self
.repomd_file
))
209 for data
in repomd
.getElementsByTagName("data"):
210 if data
.attributes
["type"].nodeValue
== "primary":
211 for node
in data
.getElementsByTagName("location"):
212 primary_file
= os
.path
.join(repo_top
, node
.attributes
["href"].nodeValue
)
214 primary
= ET
.parse(gzip
.open(primary_file
))
215 NS
= "http://linux.duke.edu/metadata/common"
216 metadata
= primary
.getroot()
218 for package
in metadata
.findall("{%s}package" % NS
):
219 if package
.find("{%s}name" % NS
).text
== pkg_name
:
221 location
= pkg_data
.find("{%s}location" % NS
).get("href")
224 raise Exception("Package '%s' not found in repodata." % pkg_name
)
225 checksum
= pkg_data
.find("{%s}checksum" % NS
)
227 if checksum
.get("type") == "sha":
228 digest
["sha1"] = checksum
.text
229 if checksum
.get("type") == "sha256":
230 digest
["sha256"] = checksum
.text
232 raise Exception('location tag not found in primary metadata:\n' + primary_file
)
233 pkg_url
= self
.packages_base_url
+ self
.packages_base_dir
+ location
235 return pkg_url
, digest
237 def get_package_metadata(self
, pkg_file
):
240 query_format
= '%{SUMMARY}\\a%{DESCRIPTION}\\a%{NAME}\\a%{VERSION}\\a%{OS}\\a%{ARCH}\\a%{URL}\\a%{GROUP}\\a%{LICENSE}\\a%{BUILDTIME}\\a[%{REQUIRES}\\n]'
241 headers
= read_child(['rpm', '--qf', query_format
, '-qp', pkg_file
]).split('\a')
243 package
.summary
= headers
[0].strip()
244 package
.description
= headers
[1].strip()
246 package
.name
= headers
[2]
248 value
= value
.replace('cvs', '')
249 value
= value
.replace('svn', '')
250 value
= distro
.try_cleanup_distro_version(value
)
251 package
.version
= value
253 package
.arch
= value
.capitalize()
257 if value
== 'noarch':
259 package
.arch
+= '-' + value
260 value
= headers
[6].strip()
263 value
= headers
[7].strip()
264 package
.category
= rpm_group_to_freedesktop
.get(value
)
266 print >>sys
.stderr
, "Warning: no mapping for RPM group '%s'" % value
268 value
= headers
[8].strip()
269 package
.license
= value
270 value
= headers
[9].strip()
271 package
.buildtime
= long(value
)
272 value
= headers
[10].strip()
273 for x
in value
.split('\n'):
274 if x
.startswith('rpmlib'):
276 req
= mappings
.process(x
)
278 package
.requires
.append(req
)
281 if args
[0].endswith('.deb') or options
.packages_file
:
282 repo
= DebRepo(options
)
283 elif args
[0].endswith('.rpm') or options
.repomd_file
:
284 repo
= RPMRepo(options
)
286 print >>sys
.stderr
, "Use --packages-file for Debian, or --repomd-file for RPM"
291 if options
.archive_url
:
293 pkg_file
= os
.path
.abspath(args
[0])
294 archive_url
= options
.archive_url
295 archive_file
= os
.path
.abspath(archive_url
.rsplit('/', 1)[1])
297 assert os
.path
.exists(pkg_file
), ("%s doesn't exist!" % pkg_file
)
299 scheme
= args
[0].split(':', 1)[0]
300 if scheme
in ('http', 'https', 'ftp'):
301 archive_url
= args
[0]
304 archive_url
, digest
= repo
.get_repo_metadata(args
[0])
305 archive_file
= pkg_file
= os
.path
.abspath(archive_url
.rsplit('/', 1)[1])
307 # pkg_url, pkg_archive = .deb or .rpm with the metadata
308 # archive_url, archive_file = .dep, .rpm or .tar.bz2 with the contents
310 # Often pkg == archive, but sometimes it's useful to convert packages to tarballs
311 # so people don't need special tools to extract them.
314 # Download package, if required
316 if not os
.path
.exists(pkg_file
):
317 print >>sys
.stderr
, "File '%s' not found, so downloading from %s..." % (pkg_file
, pkg_url
)
318 check_call(['wget', pkg_url
])
320 # Check digest, if known
322 if "sha256" in digest
:
324 m
= hashlib
.new('sha256')
325 expected_digest
= digest
["sha256"]
326 elif "sha1" in digest
:
329 m
= hashlib
.new('sha1')
333 expected_digest
= digest
["sha1"]
338 m
.update(file(archive_file
).read())
339 actual
= m
.hexdigest()
340 if actual
!= expected_digest
:
341 raise Exception("Incorrect digest on package file! Was " + actual
+ ", but expected " + expected_digest
)
343 print "Package's digest matches value in reposistory metadata (" + actual
+ "). Good."
345 print >>sys
.stderr
, "Note: no SHA-1 or SHA-256 digest known for this package, so not checking..."
347 # Extract meta-data from package
349 pkg_metadata
= repo
.get_package_metadata(pkg_file
)
351 # Unpack package, find binaries and .desktop files, and add to cache
355 tmp
= tempfile
.mkdtemp(prefix
= 'pkg2zero-')
358 unpack
.unpack_archive(archive_file
, open(archive_file
), destdir
= unpack_dir
, extract
= options
.archive_extract
)
359 if options
.archive_extract
:
360 unpack_dir
= os
.path
.join(unpack_dir
, options
.archive_extract
)
364 for root
, dirs
, files
in os
.walk(unpack_dir
):
365 assert root
.startswith(unpack_dir
)
366 relative_root
= root
[len(unpack_dir
) + 1:]
368 full
= os
.path
.join(root
, name
)
369 f
= os
.path
.join(relative_root
, name
)
371 if f
.endswith('.desktop'):
372 for line
in file(full
):
373 if line
.startswith('Categories'):
374 for cat
in line
.split('=', 1)[1].split(';'):
376 if cat
in valid_categories
:
379 elif line
.startswith('Icon'):
380 icon
= line
.split('=', 1)[1].strip()
381 elif f
.startswith('bin/') or f
.startswith('usr/bin/') or f
.startswith('usr/games/'):
382 if os
.path
.isfile(full
):
383 possible_mains
.append(f
)
384 elif f
.endswith('.png'):
386 images
[os
.path
.basename(f
)] = full
387 # make sure to also map basename without the extension
388 images
[os
.path
.splitext(os
.path
.basename(f
))[0]] = full
392 print "Using %s for icon" % os
.path
.basename(images
[icon
])
393 icondata
= file(images
[icon
]).read()
395 manifest
= read_child(['0store', 'manifest', unpack_dir
, manifest_algorithm
])
396 digest
= manifest
.rsplit('\n', 2)[1]
397 check_call(['0store', 'add', digest
, unpack_dir
])
402 possible_mains
= sorted(possible_mains
, key
= len)
403 pkg_main
= possible_mains
[0]
404 if len(possible_mains
) > 1:
405 print "Warning: several possible main binaries found:"
406 print "- " + pkg_main
+ " (I chose this one)"
407 for x
in possible_mains
[1:]:
412 # Make sure we haven't added this version already...
415 target_feed_file
= args
[1]
416 target_icon_file
= args
[1].replace('.xml', '.png')
418 target_feed_file
= pkg_metadata
.name
+ '.xml'
419 target_icon_file
= pkg_metadata
.name
+ '.png'
423 if os
.path
.isfile(target_feed_file
):
424 dummy_dist
= distro
.Distribution()
425 dom
= qdom
.parse(file(target_feed_file
))
426 old_target_feed
= model
.ZeroInstallFeed(dom
, local_path
= target_feed_file
, distro
= dummy_dist
)
427 existing_impl
= old_target_feed
.implementations
.get(digest
)
429 print >>sys
.stderr
, ("Feed '%s' already contains an implementation with this digest!\n%s" % (target_feed_file
, existing_impl
))
432 # No target, so need to pick a URI
433 feed_uri
= mappings
.lookup(pkg_metadata
.name
)
435 suggestion
= mappings
.get_suggestion(pkg_metadata
.name
)
436 uri
= raw_input('Enter the URI for this feed [%s]: ' % suggestion
).strip()
439 assert uri
.startswith('http://') or uri
.startswith('https://') or uri
.startswith('ftp://'), uri
441 mappings
.add_mapping(pkg_metadata
.name
, uri
)
443 if icondata
and not os
.path
.isfile(target_icon_file
):
444 file = open(target_icon_file
, 'wb')
448 suggestion
= 'http://0install.net/feed_icons/' + target_icon_file
449 uri
= raw_input('Enter the URI for this icon [%s]: ' % suggestion
).strip()
452 assert uri
.startswith('http://') or uri
.startswith('https://') or uri
.startswith('ftp://'), uri
455 # Create a local feed with just the new version...
457 template
= '''<interface xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
459 doc
= minidom
.parseString(template
)
460 root
= doc
.documentElement
462 add_node(root
, 'name', pkg_metadata
.name
)
463 add_node(root
, 'summary', pkg_metadata
.summary
)
464 add_node(root
, 'description', pkg_metadata
.description
)
465 feed_for
= add_node(root
, 'feed-for', '')
467 feed_for
.setAttribute('interface', feed_uri
)
469 icon
= add_node(root
, 'icon')
470 icon
.setAttribute('href', icon_uri
)
471 icon
.setAttribute('type', 'image/png')
472 if pkg_metadata
.homepage
:
473 add_node(root
, 'homepage', pkg_metadata
.homepage
)
474 if pkg_metadata
.category
:
475 add_node(root
, 'category', pkg_metadata
.category
)
477 package
= add_node(root
, 'package-implementation', '')
478 package
.setAttribute('package', pkg_metadata
.name
)
480 group
= add_node(root
, 'group', '')
481 if pkg_metadata
.arch
:
482 group
.setAttribute('arch', pkg_metadata
.arch
)
484 print >>sys
.stderr
, "No Architecture: field in package"
485 if pkg_metadata
.license
:
486 group
.setAttribute('license', pkg_metadata
.license
)
488 for req
in pkg_metadata
.requires
:
489 req_element
= add_node(group
, 'requires', before
= '\n ', after
= '')
490 req_element
.setAttribute('interface', req
.interface
)
491 binding
= add_node(req_element
, 'environment', before
= '\n ', after
= '\n ')
492 binding
.setAttribute('name', 'LD_LIBRARY_PATH')
493 binding
.setAttribute('insert', 'usr/lib')
496 group
.setAttribute('main', pkg_main
)
497 package
.setAttribute('main', '/' + pkg_main
)
499 impl
= add_node(group
, 'implementation', before
= '\n ', after
= '\n ')
500 impl
.setAttribute('id', digest
)
501 assert pkg_metadata
.version
502 impl
.setAttribute('version', pkg_metadata
.version
)
504 if pkg_metadata
.buildtime
:
505 impl
.setAttribute('released', time
.strftime('%Y-%m-%d', time
.localtime(pkg_metadata
.buildtime
)))
507 impl
.setAttribute('released', time
.strftime('%Y-%m-%d'))
509 archive
= add_node(impl
, 'archive', before
= '\n ', after
= '\n ')
510 archive
.setAttribute('href', archive_url
)
511 archive
.setAttribute('size', str(os
.path
.getsize(archive_file
)))
512 if options
.archive_extract
:
513 archive
.setAttribute('extract', options
.archive_extract
)
515 # Add our new version to the main feed...
517 output_stream
= tempfile
.NamedTemporaryFile(prefix
= 'pkg2zero-')
519 output_stream
.write("<?xml version='1.0'?>\n")
520 root
.writexml(output_stream
)
521 output_stream
.write('\n')
522 output_stream
.flush()
524 publishing_options
= []
526 # Note: 0publish < 0.16 requires the --xmlsign option too
527 publishing_options
+= ['--xmlsign', '--key', options
.key
]
528 check_call([os
.environ
['PUBLISH_COMMAND']] + publishing_options
+ ['--local', output_stream
.name
, target_feed_file
])
529 print "Added version %s to %s" % (pkg_metadata
.version
, target_feed_file
)
531 output_stream
.close()