3 bup_python="$(dirname "$0")/bup-python" || exit $?
4 exec "$bup_python" "$0" ${1+"$@"}
7 import sys, stat, urllib, mimetypes, posixpath, time, webbrowser
9 from bup import options, git, vfs
10 from bup.helpers import *
12 import tornado.httpserver
16 log('error: cannot find the python "tornado" module; please install it\n')
22 def _compute_breadcrumbs(path, show_hidden=False):
23 """Returns a list of breadcrumb objects for a path."""
25 breadcrumbs.append(('[root]', '/'))
26 path_parts = path.split('/')[1:-1]
28 for part in path_parts:
29 full_path += part + "/"
32 url_append = '?hidden=1'
33 breadcrumbs.append((part, full_path+url_append))
37 def _contains_hidden_files(n):
38 """Return True if n contains files starting with a '.', False otherwise."""
41 if len(name)>1 and name.startswith('.'):
47 def _compute_dir_contents(n, path, show_hidden=False):
48 """Given a vfs node, returns an iterator for display info of all subs."""
51 url_append = "?hidden=1"
54 yield('..', '../' + url_append, '')
57 link = urllib.quote(sub.name)
59 # link should be based on fully resolved type to avoid extra
61 if stat.S_ISDIR(sub.try_resolve().mode):
64 if not show_hidden and len(display)>1 and display.startswith('.'):
68 if stat.S_ISDIR(sub.mode):
70 elif stat.S_ISLNK(sub.mode):
74 size = (opt.human_readable and format_filesize(size)) or size
76 yield (display, link + url_append, size)
79 class BupRequestHandler(tornado.web.RequestHandler):
81 return self._process_request(path)
84 return self._process_request(path)
86 @tornado.web.asynchronous
87 def _process_request(self, path):
88 path = urllib.unquote(path)
89 print 'Handling request for %s' % path
92 except vfs.NoSuchFile:
96 if stat.S_ISDIR(n.mode):
97 self._list_directory(path, n)
99 self._get_file(path, n)
101 def _list_directory(self, path, n):
102 """Helper to produce a directory listing.
104 Return value is either a file object, or None (indicating an
105 error). In either case, the headers are sent.
107 if not path.endswith('/') and len(path) > 0:
108 print 'Redirecting from %s to %s' % (path, path + '/')
109 return self.redirect(path + '/', permanent=True)
112 show_hidden = int(self.request.arguments.get('hidden', [0])[-1])
113 except ValueError as e:
117 'list-directory.html',
119 breadcrumbs=_compute_breadcrumbs(path, show_hidden),
120 files_hidden=_contains_hidden_files(n),
121 hidden_shown=show_hidden,
122 dir_contents=_compute_dir_contents(n, path, show_hidden))
124 def _get_file(self, path, n):
125 """Process a request on a file.
127 Return value is either a file object, or None (indicating an error).
128 In either case, the headers are sent.
130 ctype = self._guess_type(path)
132 self.set_header("Last-Modified", self.date_time_string(n.mtime))
133 self.set_header("Content-Type", ctype)
135 self.set_header("Content-Length", str(size))
136 assert(len(n.hash) == 20)
137 self.set_header("Etag", n.hash.encode('hex'))
139 if self.request.method != 'HEAD':
146 except StopIteration:
150 self.request.connection.stream.write(blob,
151 callback=lambda: me(me))
152 write_more(write_more)
156 def _guess_type(self, path):
157 """Guess the type of a file.
159 Argument is a PATH (a filename).
161 Return value is a string of the form type/subtype,
162 usable for a MIME Content-type header.
164 The default implementation looks the file's extension
165 up in the table self.extensions_map, using application/octet-stream
166 as a default; however it would be permissible (if
167 slow) to look inside the data to make a better guess.
169 base, ext = posixpath.splitext(path)
170 if ext in self.extensions_map:
171 return self.extensions_map[ext]
173 if ext in self.extensions_map:
174 return self.extensions_map[ext]
176 return self.extensions_map['']
178 if not mimetypes.inited:
179 mimetypes.init() # try to read system mime.types
180 extensions_map = mimetypes.types_map.copy()
181 extensions_map.update({
182 '': 'text/plain', # Default
188 def date_time_string(self, t):
189 return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
193 bup web [[hostname]:port]
195 human-readable display human readable file sizes (i.e. 3.9K, 4.7M)
196 browser open the site in the default browser
198 o = options.Options(optspec)
199 (opt, flags, extra) = o.parse(sys.argv[1:])
202 o.fatal("at most one argument expected")
204 address = ('127.0.0.1', 8080)
206 addressl = extra[0].split(':', 1)
207 addressl[1] = int(addressl[1])
208 address = tuple(addressl)
210 git.check_repo_or_die()
211 top = vfs.RefList(None)
215 template_path = resource_path('web'),
216 static_path = resource_path('web/static')
219 # Disable buffering on stdout, for debug messages
220 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
222 application = tornado.web.Application([
223 (r"(/.*)", BupRequestHandler),
226 if __name__ == "__main__":
227 http_server = tornado.httpserver.HTTPServer(application)
228 http_server.listen(address[1], address=address[0])
231 sock = http_server._socket # tornado < 2.0
232 except AttributeError as e:
233 sock = http_server._sockets.values()[0]
235 print "Serving HTTP on %s:%d..." % sock.getsockname()
237 loop = tornado.ioloop.IOLoop.instance()
239 browser_addr = 'http://' + address[0] + ':' + str(address[1])
240 loop.add_callback(lambda : webbrowser.open(browser_addr))