Snapshot version.
[0publish.git] / archive.py
blob0d3babdd793d69c8c777bf93fdc144e325926af4
1 from xml.dom import minidom
2 from zeroinstall.zerostore import Store, manifest
3 try:
4 from zeroinstall.zerostore import unpack
5 except ImportError:
6 # Older versions don't have it
7 import unpack
8 from zeroinstall.injector import namespaces
9 import os, time, re, shutil, tempfile
11 def manifest_for_dir(dir, alg):
12 if alg == 'sha1':
13 # (for older versions of the injector)
14 import sha
15 class SHA1:
16 def new_digest(self): return sha.new()
17 def generate_manifest(self, dir): return manifest.generate_manifest(dir)
18 def getID(self, digest): return 'sha1=' + digest.hexdigest()
19 algorithm = SHA1()
20 else:
21 algorithm = manifest.get_algorithm(alg)
23 digest = algorithm.new_digest()
24 for line in algorithm.generate_manifest(dir):
25 digest.update(line + '\n')
26 return algorithm.getID(digest)
28 def add_archive(data, url, local_file, extract, alg):
29 if local_file is None:
30 local_file = os.path.abspath(os.path.basename(url))
31 if not os.path.exists(local_file):
32 raise Exception("Use --archive-file option to specify a local copy of the archive "
33 "(default file '%s' does not exist)" % local_file)
35 doc = minidom.parseString(data)
37 if alg is None:
38 if local_file.endswith('.deb'):
39 # Debs require 0launch >= 0.20 anyway, so use the new hash to avoid
40 # problems with directory mtimes
41 alg = 'sha1new'
42 else:
43 alg = 'sha1'
45 all_impls = doc.documentElement.getElementsByTagNameNS(namespaces.XMLNS_IFACE, 'implementation')
46 tmpdir = tempfile.mkdtemp('-0publish')
47 try:
48 unpack.unpack_archive(url, file(local_file), tmpdir, extract)
49 if extract:
50 extracted = os.path.join(tmpdir, extract)
51 else:
52 extracted = tmpdir
54 archive_id = manifest_for_dir(extracted, alg)
55 finally:
56 shutil.rmtree(tmpdir)
58 local_ifaces = []
59 for impl in all_impls:
60 this_id = impl.getAttribute('id')
61 if this_id == archive_id:
62 break
63 if this_id.startswith('/') or this_id.startswith('.'):
64 local_ifaces.append(impl)
65 else:
66 if len(local_ifaces) == 0:
67 raise Exception('Nothing with id "%s", and no local implementations' % archive_id)
68 if len(local_ifaces) > 1:
69 raise Exception('Nothing with id "%s", and multiple local implementations!' % archive_id)
70 impl = local_ifaces[0]
71 impl.setAttribute('id', archive_id)
73 assert impl.getAttribute('id') == archive_id
75 nl = doc.createTextNode('\n ')
76 impl.appendChild(nl)
78 archive = doc.createElementNS(namespaces.XMLNS_IFACE, 'archive')
79 impl.appendChild(archive)
80 archive.setAttribute('href', url)
81 archive.setAttribute('size', str(os.stat(local_file).st_size))
82 if extract is not None:
83 archive.setAttribute('extract', extract)
85 nl = doc.createTextNode('\n ')
86 impl.appendChild(nl)
88 return doc.toxml()