2 import sys, stat, urllib, mimetypes, posixpath, time
3 import tornado.httpserver
6 from bup import options, git, vfs
7 from bup.helpers import *
12 def _compute_breadcrumbs(path, show_hidden=False):
13 """Returns a list of breadcrumb objects for a path."""
15 breadcrumbs.append(('[root]', '/'))
16 path_parts = path.split('/')[1:-1]
18 for part in path_parts:
19 full_path += part + "/"
22 url_append = '?hidden=1'
23 breadcrumbs.append((part, full_path+url_append))
27 def _contains_hidden_files(n):
28 """Return True if n contains files starting with a '.', False otherwise."""
31 if len(name)>1 and name.startswith('.'):
37 def _compute_dir_contents(n, show_hidden=False):
38 """Given a vfs node, returns an iterator for display info of all subs."""
40 display = link = sub.name
42 # link should be based on fully resolved type to avoid extra
44 if stat.S_ISDIR(sub.try_resolve().mode):
47 if not show_hidden and len(display)>1 and display.startswith('.'):
52 url_append = "?hidden=1"
55 if stat.S_ISDIR(sub.mode):
56 display = sub.name + '/'
57 elif stat.S_ISLNK(sub.mode):
58 display = sub.name + '@'
62 yield (display, link + url_append, size)
65 class BupRequestHandler(tornado.web.RequestHandler):
67 return self._process_request(path)
70 return self._process_request(path)
72 @tornado.web.asynchronous
73 def _process_request(self, path):
74 path = urllib.unquote(path)
75 print 'Handling request for %s' % path
78 except vfs.NoSuchFile:
82 if stat.S_ISDIR(n.mode):
83 self._list_directory(path, n)
85 self._get_file(path, n)
87 def _list_directory(self, path, n):
88 """Helper to produce a directory listing.
90 Return value is either a file object, or None (indicating an
91 error). In either case, the headers are sent.
93 if not path.endswith('/') and len(path) > 0:
94 print 'Redirecting from %s to %s' % (path, path + '/')
95 return self.redirect(path + '/', permanent=True)
98 show_hidden = int(self.request.arguments.get('hidden', [0])[-1])
103 'list-directory.html',
105 breadcrumbs=_compute_breadcrumbs(path, show_hidden),
106 files_hidden=_contains_hidden_files(n),
107 hidden_shown=show_hidden,
108 dir_contents=_compute_dir_contents(n, show_hidden))
110 def _get_file(self, path, n):
111 """Process a request on a file.
113 Return value is either a file object, or None (indicating an error).
114 In either case, the headers are sent.
116 ctype = self._guess_type(path)
118 self.set_header("Last-Modified", self.date_time_string(n.mtime))
119 self.set_header("Content-Type", ctype)
121 self.set_header("Content-Length", str(size))
122 assert(len(n.hash) == 20)
123 self.set_header("Etag", n.hash.encode('hex'))
125 if self.request.method != 'HEAD':
132 except StopIteration:
136 self.request.connection.stream.write(blob,
137 callback=lambda: me(me))
138 write_more(write_more)
140 def _guess_type(self, path):
141 """Guess the type of a file.
143 Argument is a PATH (a filename).
145 Return value is a string of the form type/subtype,
146 usable for a MIME Content-type header.
148 The default implementation looks the file's extension
149 up in the table self.extensions_map, using application/octet-stream
150 as a default; however it would be permissible (if
151 slow) to look inside the data to make a better guess.
153 base, ext = posixpath.splitext(path)
154 if ext in self.extensions_map:
155 return self.extensions_map[ext]
157 if ext in self.extensions_map:
158 return self.extensions_map[ext]
160 return self.extensions_map['']
162 if not mimetypes.inited:
163 mimetypes.init() # try to read system mime.types
164 extensions_map = mimetypes.types_map.copy()
165 extensions_map.update({
166 '': 'text/plain', # Default
172 def date_time_string(self, t):
173 return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
177 bup web [[hostname]:port]
180 o = options.Options('bup web', optspec)
181 (opt, flags, extra) = o.parse(sys.argv[1:])
184 o.fatal("at most one argument expected")
186 address = ('127.0.0.1', 8080)
188 addressl = extra[0].split(':', 1)
189 addressl[1] = int(addressl[1])
190 address = tuple(addressl)
192 git.check_repo_or_die()
193 top = vfs.RefList(None)
197 template_path = resource_path('web'),
198 static_path = resource_path('web/static')
201 # Disable buffering on stdout, for debug messages
202 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
204 application = tornado.web.Application([
205 (r"(/.*)", BupRequestHandler),
208 if __name__ == "__main__":
209 http_server = tornado.httpserver.HTTPServer(application)
210 http_server.listen(address[1], address=address[0])
212 print "Serving HTTP on %s:%d..." % http_server._socket.getsockname()
213 loop = tornado.ioloop.IOLoop.instance()