3 bup_python="$(dirname "$0")/bup-python" || exit $?
4 exec "$bup_python" "$0" ${1+"$@"}
8 import mimetypes, os, posixpath, signal, stat, sys, time, urllib, webbrowser
10 from bup import options, git, vfs
11 from bup.helpers import (debug1, handle_ctrl_c, log, resource_path,
15 from tornado.ioloop import IOLoop
16 import tornado.httpserver
19 log('error: cannot find the python "tornado" module; please install it\n')
26 def _compute_breadcrumbs(path, show_hidden=False):
27 """Returns a list of breadcrumb objects for a path."""
29 breadcrumbs.append(('[root]', '/'))
30 path_parts = path.split('/')[1:-1]
32 for part in path_parts:
33 full_path += part + "/"
36 url_append = '?hidden=1'
37 breadcrumbs.append((part, full_path+url_append))
41 def _contains_hidden_files(n):
42 """Return True if n contains files starting with a '.', False otherwise."""
45 if len(name)>1 and name.startswith('.'):
51 def _compute_dir_contents(n, path, show_hidden=False):
52 """Given a vfs node, returns an iterator for display info of all subs."""
55 url_append = "?hidden=1"
58 yield('..', '../' + url_append, '')
61 link = urllib.quote(sub.name)
63 # link should be based on fully resolved type to avoid extra
65 if stat.S_ISDIR(sub.try_resolve().mode):
68 if not show_hidden and len(display)>1 and display.startswith('.'):
72 if stat.S_ISDIR(sub.mode):
74 elif stat.S_ISLNK(sub.mode):
78 size = (opt.human_readable and format_filesize(size)) or size
80 yield (display, link + url_append, size)
83 class BupRequestHandler(tornado.web.RequestHandler):
85 return self._process_request(path)
88 return self._process_request(path)
90 @tornado.web.asynchronous
91 def _process_request(self, path):
92 path = urllib.unquote(path)
93 print 'Handling request for %s' % path
96 except vfs.NoSuchFile:
100 if stat.S_ISDIR(n.mode):
101 self._list_directory(path, n)
103 self._get_file(path, n)
105 def _list_directory(self, path, n):
106 """Helper to produce a directory listing.
108 Return value is either a file object, or None (indicating an
109 error). In either case, the headers are sent.
111 if not path.endswith('/') and len(path) > 0:
112 print 'Redirecting from %s to %s' % (path, path + '/')
113 return self.redirect(path + '/', permanent=True)
116 show_hidden = int(self.request.arguments.get('hidden', [0])[-1])
117 except ValueError as e:
121 'list-directory.html',
123 breadcrumbs=_compute_breadcrumbs(path, show_hidden),
124 files_hidden=_contains_hidden_files(n),
125 hidden_shown=show_hidden,
126 dir_contents=_compute_dir_contents(n, path, show_hidden))
128 def _get_file(self, path, n):
129 """Process a request on a file.
131 Return value is either a file object, or None (indicating an error).
132 In either case, the headers are sent.
134 ctype = self._guess_type(path)
136 self.set_header("Last-Modified", self.date_time_string(n.mtime))
137 self.set_header("Content-Type", ctype)
139 self.set_header("Content-Length", str(size))
140 assert(len(n.hash) == 20)
141 self.set_header("Etag", n.hash.encode('hex'))
143 if self.request.method != 'HEAD':
150 except StopIteration:
154 self.request.connection.stream.write(blob,
155 callback=lambda: me(me))
156 write_more(write_more)
160 def _guess_type(self, path):
161 """Guess the type of a file.
163 Argument is a PATH (a filename).
165 Return value is a string of the form type/subtype,
166 usable for a MIME Content-type header.
168 The default implementation looks the file's extension
169 up in the table self.extensions_map, using application/octet-stream
170 as a default; however it would be permissible (if
171 slow) to look inside the data to make a better guess.
173 base, ext = posixpath.splitext(path)
174 if ext in self.extensions_map:
175 return self.extensions_map[ext]
177 if ext in self.extensions_map:
178 return self.extensions_map[ext]
180 return self.extensions_map['']
182 if not mimetypes.inited:
183 mimetypes.init() # try to read system mime.types
184 extensions_map = mimetypes.types_map.copy()
185 extensions_map.update({
186 '': 'text/plain', # Default
192 def date_time_string(self, t):
193 return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
198 def handle_sigterm(signum, frame):
200 debug1('\nbup-web: signal %d received\n' % signum)
201 log('Shutdown requested\n')
207 signal.signal(signal.SIGTERM, handle_sigterm)
210 bup web [[hostname]:port]
212 human-readable display human readable file sizes (i.e. 3.9K, 4.7M)
213 browser open the site in the default browser
215 o = options.Options(optspec)
216 (opt, flags, extra) = o.parse(sys.argv[1:])
219 o.fatal("at most one argument expected")
221 address = ('127.0.0.1', 8080)
223 addressl = extra[0].split(':', 1)
224 addressl[1] = int(addressl[1])
225 address = tuple(addressl)
227 git.check_repo_or_die()
228 top = vfs.RefList(None)
232 template_path = resource_path('web'),
233 static_path = resource_path('web/static')
236 # Disable buffering on stdout, for debug messages
237 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
239 application = tornado.web.Application([
240 (r"(/.*)", BupRequestHandler),
243 http_server = tornado.httpserver.HTTPServer(application)
244 http_server.listen(address[1], address=address[0])
247 sock = http_server._socket # tornado < 2.0
248 except AttributeError as e:
249 sock = http_server._sockets.values()[0]
251 print "Serving HTTP on %s:%d..." % sock.getsockname()
253 io_loop_pending = IOLoop.instance()
255 browser_addr = 'http://' + address[0] + ':' + str(address[1])
256 io_loop_pending.add_callback(lambda : webbrowser.open(browser_addr))
258 io_loop = io_loop_pending
262 log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))