12
class FileExtractException(Exception):
13
def __init__(self, info):
19
def extract_file_from_archive(filename, dest, tar=None):
21
if not os.path.isdir(dest):
24
temp = tempfile.mkdtemp()
27
tf = tarfile.open(glob.glob(os.path.join(os.getcwd(), '*.bz2'))[0], 'r')
29
tf = tarfile.open(tar, 'r')
30
tf.extract(filename, temp)
31
shutil.copyfile(os.path.join(temp, filename), os.path.join(dest, os.path.basename(filename)))
34
raise FileExtractException("No valid tar file found")
37
errstr = "File " + filename + " not found in archive"
38
raise FileExtractException(errstr)
41
filename = ": '" + e.filename + "'" if e.filename != None else ""
42
errstr = "IOError occurred whilst extracting file from archive: [Errno: " + str(e.errno) + "] " + e.strerror + filename
43
raise FileExtractException(errstr)
46
raise FileExtractException("Unexpected error")
52
if __name__ == '__main__':
54
opts, args = getopt.getopt(sys.argv[1:], 'd:o:')
55
except getopt.GetoptError, err:
65
dest = os.path.abspath(a)
67
tarball = os.path.abspath(a)
70
print >> sys.stderr, "Need to specify one file"
75
if os.path.exists(os.path.join(dest, filename)):
78
if filename.startswith('/'):
79
print >> sys.stderr, "Input filename shouldn't be absolute"
82
if not os.path.isdir(dest):
87
extract_file_from_archive(filename, dest)
89
except FileExtractException as e:
90
print >> sys.stderr, str(e)
94
print >> sys.stderr, "Unexpected error"
98
temp = tempfile.mkdtemp()
100
tb = tarfile.open(tarball, 'r')
101
names = tb.getnames()
103
if os.path.join(names[0], filename) in names:
104
tb.extract(os.path.join(names[0], filename), temp)
105
shutil.copyfile(os.path.join(temp, names[0], filename), os.path.join(dest, filename))
109
(root, ext) = os.path.splitext(name)
114
tb.extract(bz2file, temp)
116
print >> sys.stderr, "File not found and no valid embedded tar file found in source tarball"
119
extract_file_from_archive(filename, dest, os.path.join(temp, bz2file))
121
except FileExtractException as e:
122
print >> sys.stderr, str(e)