comparison planemo/lib/python3.7/site-packages/galaxy/util/streamball.py @ 1:56ad4e20f292 draft

"planemo upload commit 6eee67778febed82ddd413c3ca40b3183a3898f1"
author guerler
date Fri, 31 Jul 2020 00:32:28 -0400
parents
children
comparison
equal deleted inserted replaced
0:d30785e31577 1:56ad4e20f292
1 """
2 A simple wrapper for writing tarballs as a stream.
3 """
4 from __future__ import absolute_import
5
6 import logging
7 import os
8 import tarfile
9
10 from galaxy.exceptions import ObjectNotFound
11 from .path import safe_walk
12
13 log = logging.getLogger(__name__)
14
15
16 class StreamBall(object):
17 def __init__(self, mode, members=None):
18 self.members = members
19 if members is None:
20 self.members = []
21 self.mode = mode
22 self.wsgi_status = None
23 self.wsgi_headeritems = None
24
25 def add(self, file, relpath, check_file=False):
26 if check_file and len(file) > 0:
27 if not os.path.isfile(file):
28 raise ObjectNotFound
29 else:
30 self.members.append((file, relpath))
31 else:
32 self.members.append((file, relpath))
33
34 def stream(self, environ, start_response):
35 response_write = start_response(self.wsgi_status, self.wsgi_headeritems)
36
37 class tarfileobj(object):
38 def write(self, *args, **kwargs):
39 response_write(*args, **kwargs)
40 tf = tarfile.open(mode=self.mode, fileobj=tarfileobj())
41 for (file, rel) in self.members:
42 tf.add(file, arcname=rel)
43 tf.close()
44 return []
45
46
47 class ZipBall(object):
48 def __init__(self, tmpf, tmpd):
49 self._tmpf = tmpf
50 self._tmpd = tmpd
51
52 def stream(self, environ, start_response):
53 response_write = start_response(self.wsgi_status, self.wsgi_headeritems)
54 tmpfh = open(self._tmpf)
55 response_write(tmpfh.read())
56 tmpfh.close()
57 try:
58 os.unlink(self._tmpf)
59 os.rmdir(self._tmpd)
60 except OSError:
61 log.exception("Unable to remove temporary library download archive and directory")
62 return []
63
64
65 def stream_archive(trans, path, upstream_gzip=False):
66 archive_type_string = 'w|gz'
67 archive_ext = 'tgz'
68 if upstream_gzip:
69 archive_type_string = 'w|'
70 archive_ext = 'tar'
71 archive = StreamBall(mode=archive_type_string)
72 for root, directories, files in safe_walk(path):
73 for filename in files:
74 p = os.path.join(root, filename)
75 relpath = os.path.relpath(p, os.path.join(path, os.pardir))
76 archive.add(file=os.path.join(path, p), relpath=relpath)
77 archive_name = "%s.%s" % (os.path.basename(path), archive_ext)
78 trans.response.set_content_type("application/x-tar")
79 trans.response.headers["Content-Disposition"] = 'attachment; filename="{}"'.format(archive_name)
80 archive.wsgi_status = trans.response.wsgi_status()
81 archive.wsgi_headeritems = trans.response.wsgi_headeritems()
82 return archive.stream