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):
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 + '/'
20 breadcrumbs.append((part, full_path))
24 def _contains_hidden_files(n):
25 """Return True if n contains files starting with a '.', False otherwise."""
28 if len(name)>1 and name.startswith('.'):
34 def _compute_dir_contents(n, show_hidden=False):
35 """Given a vfs node, returns an iterator for display info of all subs."""
37 display = link = sub.name
39 if not show_hidden and len(display)>1 and display.startswith('.'):
42 # link should be based on fully resolved type to avoid extra
44 if stat.S_ISDIR(sub.try_resolve().mode):
48 if stat.S_ISDIR(sub.mode):
49 display = sub.name + '/'
50 elif stat.S_ISLNK(sub.mode):
51 display = sub.name + '@'
55 yield (display, link, size)
58 class BupRequestHandler(tornado.web.RequestHandler):
60 return self._process_request(path)
63 return self._process_request(path)
65 def _process_request(self, path):
66 path = urllib.unquote(path)
67 print 'Handling request for %s' % path
70 except vfs.NoSuchFile:
74 if stat.S_ISDIR(n.mode):
75 self._list_directory(path, n)
77 self._get_file(path, n)
79 def _list_directory(self, path, n):
80 """Helper to produce a directory listing.
82 Return value is either a file object, or None (indicating an
83 error). In either case, the headers are sent.
85 if not path.endswith('/') and len(path) > 0:
86 print 'Redirecting from %s to %s' % (path, path + '/')
87 return self.redirect(path + '/', permanent=True)
90 show_hidden = int(self.request.arguments.get('hidden', [0])[-1])
95 'list-directory.html',
97 breadcrumbs=_compute_breadcrumbs(path),
98 files_hidden=_contains_hidden_files(n),
99 hidden_shown=show_hidden,
100 dir_contents=_compute_dir_contents(n, show_hidden),
101 # We need the standard url_escape so we don't escape /
102 url_escape=urllib.quote)
104 def _get_file(self, path, n):
105 """Process a request on a file.
107 Return value is either a file object, or None (indicating an error).
108 In either case, the headers are sent.
110 ctype = self._guess_type(path)
112 self.set_header("Last-Modified", self.date_time_string(n.mtime))
113 self.set_header("Content-Type", ctype)
115 self.set_header("Content-Length", str(size))
117 if self.request.method != 'HEAD':
119 for blob in chunkyreader(f):
123 def _guess_type(self, path):
124 """Guess the type of a file.
126 Argument is a PATH (a filename).
128 Return value is a string of the form type/subtype,
129 usable for a MIME Content-type header.
131 The default implementation looks the file's extension
132 up in the table self.extensions_map, using application/octet-stream
133 as a default; however it would be permissible (if
134 slow) to look inside the data to make a better guess.
136 base, ext = posixpath.splitext(path)
137 if ext in self.extensions_map:
138 return self.extensions_map[ext]
140 if ext in self.extensions_map:
141 return self.extensions_map[ext]
143 return self.extensions_map['']
145 if not mimetypes.inited:
146 mimetypes.init() # try to read system mime.types
147 extensions_map = mimetypes.types_map.copy()
148 extensions_map.update({
149 '': 'text/plain', # Default
155 def date_time_string(self, t):
156 return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
160 bup web [[hostname]:port]
163 o = options.Options('bup web', optspec)
164 (opt, flags, extra) = o.parse(sys.argv[1:])
167 o.fatal("at most one argument expected")
169 address = ('127.0.0.1', 8080)
171 addressl = extra[0].split(':', 1)
172 addressl[1] = int(addressl[1])
173 address = tuple(addressl)
175 git.check_repo_or_die()
176 top = vfs.RefList(None)
180 template_path = resource_path('web'),
183 # Disable buffering on stdout, for debug messages
184 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
186 application = tornado.web.Application([
187 (r"(/.*)", BupRequestHandler),
190 if __name__ == "__main__":
191 http_server = tornado.httpserver.HTTPServer(application)
192 http_server.listen(address[1], address=address[0])
194 print "Serving HTTP on %s:%d..." % http_server._socket.getsockname()
195 loop = tornado.ioloop.IOLoop.instance()