4
|
1 """
|
|
2 package model for python PAckage INTrospection
|
|
3 """
|
|
4
|
7
|
5 import os
|
|
6 import tarfile
|
5
|
7 import tempfile
|
7
|
8 import urllib2
|
|
9 import utils
|
5
|
10
|
4
|
11 class Package(object):
|
7
|
12 # XXX much of this is generic resource stuff and should be split off
|
4
|
13
|
|
14 def __init__(self, src):
|
|
15 self.src = src
|
5
|
16 self._tmppath = None
|
|
17
|
|
18 def path(self):
|
|
19 """filesystem path to package"""
|
7
|
20
|
|
21 # return cached copy if it exists
|
|
22 if self._tmppath:
|
|
23 return self._tmppath
|
|
24
|
|
25 # fetch from the web if a URL
|
|
26 tmpfile = None
|
|
27 src = self.src
|
5
|
28 if utils.isURL(self.src):
|
8
|
29 tmpfile = src = self.fetch()
|
7
|
30
|
|
31 # unpack if an archive
|
|
32 if self.is_archive(src):
|
8
|
33 try:
|
|
34 self.unpack(src)
|
|
35 finally:
|
|
36 if tmpfile:
|
|
37 os.remove(tmpfile)
|
7
|
38 return self._tmppath
|
|
39
|
5
|
40 return self.src
|
|
41
|
|
42 def fetch(self):
|
8
|
43 """fetch from remote source to a temporary file"""
|
7
|
44 fd, filename = tmpfile.mkstemp()
|
|
45 resource = urllib.urlopen(self.src)
|
|
46 os.write(fd, resource.read())
|
|
47 os.close(fd)
|
|
48 return filename
|
|
49
|
|
50 def unpack(self, archive):
|
|
51 """unpack the archive to a temporary destination"""
|
|
52 # TODO: should handle zipfile additionally at least
|
|
53 # Ideally, this would be pluggable, etc
|
8
|
54 assert tarfile.is_tarfile(archive), "%s is not an archive" % self.src
|
|
55 tarfile.TarFile.open(archive)
|
7
|
56
|
|
57 def is_archive(self, path):
|
|
58 """returns if the filesystem path is an archive"""
|
|
59 # TODO: should handle zipfile additionally at least
|
|
60 # Ideally, this would be pluggable, etc
|
|
61 return tarfile.is_tarfile(path)
|