3 bup_python="$(dirname "$0")/bup-python" || exit $?
4 exec "$bup_python" "$0" ${1+"$@"}
8 import mimetypes, os, posixpath, stat, sys, time, urllib, webbrowser
10 from bup import options, git, vfs
11 from bup.helpers import debug1, handle_ctrl_c, log, resource_path
14 import tornado.httpserver
18 log('error: cannot find the python "tornado" module; please install it\n')
25 def _compute_breadcrumbs(path, show_hidden=False):
26 """Returns a list of breadcrumb objects for a path."""
28 breadcrumbs.append(('[root]', '/'))
29 path_parts = path.split('/')[1:-1]
31 for part in path_parts:
32 full_path += part + "/"
35 url_append = '?hidden=1'
36 breadcrumbs.append((part, full_path+url_append))
40 def _contains_hidden_files(n):
41 """Return True if n contains files starting with a '.', False otherwise."""
44 if len(name)>1 and name.startswith('.'):
50 def _compute_dir_contents(n, path, show_hidden=False):
51 """Given a vfs node, returns an iterator for display info of all subs."""
54 url_append = "?hidden=1"
57 yield('..', '../' + url_append, '')
60 link = urllib.quote(sub.name)
62 # link should be based on fully resolved type to avoid extra
64 if stat.S_ISDIR(sub.try_resolve().mode):
67 if not show_hidden and len(display)>1 and display.startswith('.'):
71 if stat.S_ISDIR(sub.mode):
73 elif stat.S_ISLNK(sub.mode):
77 size = (opt.human_readable and format_filesize(size)) or size
79 yield (display, link + url_append, size)
82 class BupRequestHandler(tornado.web.RequestHandler):
84 return self._process_request(path)
87 return self._process_request(path)
89 @tornado.web.asynchronous
90 def _process_request(self, path):
91 path = urllib.unquote(path)
92 print 'Handling request for %s' % path
95 except vfs.NoSuchFile:
99 if stat.S_ISDIR(n.mode):
100 self._list_directory(path, n)
102 self._get_file(path, n)
104 def _list_directory(self, path, n):
105 """Helper to produce a directory listing.
107 Return value is either a file object, or None (indicating an
108 error). In either case, the headers are sent.
110 if not path.endswith('/') and len(path) > 0:
111 print 'Redirecting from %s to %s' % (path, path + '/')
112 return self.redirect(path + '/', permanent=True)
115 show_hidden = int(self.request.arguments.get('hidden', [0])[-1])
116 except ValueError as e:
120 'list-directory.html',
122 breadcrumbs=_compute_breadcrumbs(path, show_hidden),
123 files_hidden=_contains_hidden_files(n),
124 hidden_shown=show_hidden,
125 dir_contents=_compute_dir_contents(n, path, show_hidden))
127 def _get_file(self, path, n):
128 """Process a request on a file.
130 Return value is either a file object, or None (indicating an error).
131 In either case, the headers are sent.
133 ctype = self._guess_type(path)
135 self.set_header("Last-Modified", self.date_time_string(n.mtime))
136 self.set_header("Content-Type", ctype)
138 self.set_header("Content-Length", str(size))
139 assert(len(n.hash) == 20)
140 self.set_header("Etag", n.hash.encode('hex'))
142 if self.request.method != 'HEAD':
149 except StopIteration:
153 self.request.connection.stream.write(blob,
154 callback=lambda: me(me))
155 write_more(write_more)
159 def _guess_type(self, path):
160 """Guess the type of a file.
162 Argument is a PATH (a filename).
164 Return value is a string of the form type/subtype,
165 usable for a MIME Content-type header.
167 The default implementation looks the file's extension
168 up in the table self.extensions_map, using application/octet-stream
169 as a default; however it would be permissible (if
170 slow) to look inside the data to make a better guess.
172 base, ext = posixpath.splitext(path)
173 if ext in self.extensions_map:
174 return self.extensions_map[ext]
176 if ext in self.extensions_map:
177 return self.extensions_map[ext]
179 return self.extensions_map['']
181 if not mimetypes.inited:
182 mimetypes.init() # try to read system mime.types
183 extensions_map = mimetypes.types_map.copy()
184 extensions_map.update({
185 '': 'text/plain', # Default
191 def date_time_string(self, t):
192 return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
196 bup web [[hostname]:port]
198 human-readable display human readable file sizes (i.e. 3.9K, 4.7M)
199 browser open the site in the default browser
201 o = options.Options(optspec)
202 (opt, flags, extra) = o.parse(sys.argv[1:])
205 o.fatal("at most one argument expected")
207 address = ('127.0.0.1', 8080)
209 addressl = extra[0].split(':', 1)
210 addressl[1] = int(addressl[1])
211 address = tuple(addressl)
213 git.check_repo_or_die()
214 top = vfs.RefList(None)
218 template_path = resource_path('web'),
219 static_path = resource_path('web/static')
222 # Disable buffering on stdout, for debug messages
223 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
225 application = tornado.web.Application([
226 (r"(/.*)", BupRequestHandler),
229 if __name__ == "__main__":
230 http_server = tornado.httpserver.HTTPServer(application)
231 http_server.listen(address[1], address=address[0])
234 sock = http_server._socket # tornado < 2.0
235 except AttributeError as e:
236 sock = http_server._sockets.values()[0]
238 print "Serving HTTP on %s:%d..." % sock.getsockname()
240 loop = tornado.ioloop.IOLoop.instance()
242 browser_addr = 'http://' + address[0] + ':' + str(address[1])
243 loop.add_callback(lambda : webbrowser.open(browser_addr))