##// END OF EJS Templates
hgwebdir: class hgwebdir should also accept a configparser instance
Michael Gebetsroither -
r4051:02205626 default
parent child Browse files
Show More
@@ -1,211 +1,214
1 1 # hgweb/hgwebdir_mod.py - Web interface for a directory of repositories.
2 2 #
3 3 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
4 4 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
5 5 #
6 6 # This software may be used and distributed according to the terms
7 7 # of the GNU General Public License, incorporated herein by reference.
8 8
9 9 from mercurial import demandimport; demandimport.enable()
10 10 import os, mimetools, cStringIO
11 11 from mercurial.i18n import gettext as _
12 12 from mercurial import ui, hg, util, templater
13 13 from common import get_mtime, staticfile, style_map
14 14 from hgweb_mod import hgweb
15 15
16 16 # This is a stopgap
17 17 class hgwebdir(object):
18 18 def __init__(self, config):
19 19 def cleannames(items):
20 20 return [(name.strip(os.sep), path) for name, path in items]
21 21
22 22 self.motd = ""
23 23 self.style = ""
24 24 self.repos_sorted = ('name', False)
25 25 if isinstance(config, (list, tuple)):
26 26 self.repos = cleannames(config)
27 27 self.repos_sorted = ('', False)
28 28 elif isinstance(config, dict):
29 29 self.repos = cleannames(config.items())
30 30 self.repos.sort()
31 31 else:
32 if isinstance(config, util.configparser):
33 cp = config
34 else:
32 35 cp = util.configparser()
33 36 cp.read(config)
34 37 self.repos = []
35 38 if cp.has_section('web'):
36 39 if cp.has_option('web', 'motd'):
37 40 self.motd = cp.get('web', 'motd')
38 41 if cp.has_option('web', 'style'):
39 42 self.style = cp.get('web', 'style')
40 43 if cp.has_section('paths'):
41 44 self.repos.extend(cleannames(cp.items('paths')))
42 45 if cp.has_section('collections'):
43 46 for prefix, root in cp.items('collections'):
44 47 for path in util.walkrepos(root):
45 48 repo = os.path.normpath(path)
46 49 name = repo
47 50 if name.startswith(prefix):
48 51 name = name[len(prefix):]
49 52 self.repos.append((name.lstrip(os.sep), repo))
50 53 self.repos.sort()
51 54
52 55 def run(self):
53 56 if not os.environ.get('GATEWAY_INTERFACE', '').startswith("CGI/1."):
54 57 raise RuntimeError("This function is only intended to be called while running as a CGI script.")
55 58 import mercurial.hgweb.wsgicgi as wsgicgi
56 59 from request import wsgiapplication
57 60 def make_web_app():
58 61 return self
59 62 wsgicgi.launch(wsgiapplication(make_web_app))
60 63
61 64 def run_wsgi(self, req):
62 65 def header(**map):
63 66 header_file = cStringIO.StringIO(
64 67 ''.join(tmpl("header", encoding=util._encoding, **map)))
65 68 msg = mimetools.Message(header_file, 0)
66 69 req.header(msg.items())
67 70 yield header_file.read()
68 71
69 72 def footer(**map):
70 73 yield tmpl("footer", **map)
71 74
72 75 def motd(**map):
73 76 yield self.motd
74 77
75 78 url = req.env['REQUEST_URI'].split('?')[0]
76 79 if not url.endswith('/'):
77 80 url += '/'
78 81
79 82 style = self.style
80 83 if req.form.has_key('style'):
81 84 style = req.form['style'][0]
82 85 mapfile = style_map(templater.templatepath(), style)
83 86 tmpl = templater.templater(mapfile, templater.common_filters,
84 87 defaults={"header": header,
85 88 "footer": footer,
86 89 "motd": motd,
87 90 "url": url})
88 91
89 92 def archivelist(ui, nodeid, url):
90 93 allowed = ui.configlist("web", "allow_archive", untrusted=True)
91 94 for i in [('zip', '.zip'), ('gz', '.tar.gz'), ('bz2', '.tar.bz2')]:
92 95 if i[0] in allowed or ui.configbool("web", "allow" + i[0],
93 96 untrusted=True):
94 97 yield {"type" : i[0], "extension": i[1],
95 98 "node": nodeid, "url": url}
96 99
97 100 def entries(sortcolumn="", descending=False, **map):
98 101 def sessionvars(**map):
99 102 fields = []
100 103 if req.form.has_key('style'):
101 104 style = req.form['style'][0]
102 105 if style != get('web', 'style', ''):
103 106 fields.append(('style', style))
104 107
105 108 separator = url[-1] == '?' and ';' or '?'
106 109 for name, value in fields:
107 110 yield dict(name=name, value=value, separator=separator)
108 111 separator = ';'
109 112
110 113 rows = []
111 114 parity = 0
112 115 for name, path in self.repos:
113 116 u = ui.ui(report_untrusted=False)
114 117 try:
115 118 u.readconfig(os.path.join(path, '.hg', 'hgrc'))
116 119 except IOError:
117 120 pass
118 121 def get(section, name, default=None):
119 122 return u.config(section, name, default, untrusted=True)
120 123
121 124 url = ('/'.join([req.env["REQUEST_URI"].split('?')[0], name])
122 125 .replace("//", "/")) + '/'
123 126
124 127 # update time with local timezone
125 128 try:
126 129 d = (get_mtime(path), util.makedate()[1])
127 130 except OSError:
128 131 continue
129 132
130 133 contact = (get("ui", "username") or # preferred
131 134 get("web", "contact") or # deprecated
132 135 get("web", "author", "")) # also
133 136 description = get("web", "description", "")
134 137 name = get("web", "name", name)
135 138 row = dict(contact=contact or "unknown",
136 139 contact_sort=contact.upper() or "unknown",
137 140 name=name,
138 141 name_sort=name,
139 142 url=url,
140 143 description=description or "unknown",
141 144 description_sort=description.upper() or "unknown",
142 145 lastchange=d,
143 146 lastchange_sort=d[1]-d[0],
144 147 sessionvars=sessionvars,
145 148 archives=archivelist(u, "tip", url))
146 149 if (not sortcolumn
147 150 or (sortcolumn, descending) == self.repos_sorted):
148 151 # fast path for unsorted output
149 152 row['parity'] = parity
150 153 parity = 1 - parity
151 154 yield row
152 155 else:
153 156 rows.append((row["%s_sort" % sortcolumn], row))
154 157 if rows:
155 158 rows.sort()
156 159 if descending:
157 160 rows.reverse()
158 161 for key, row in rows:
159 162 row['parity'] = parity
160 163 parity = 1 - parity
161 164 yield row
162 165
163 166 virtual = req.env.get("PATH_INFO", "").strip('/')
164 167 if virtual.startswith('static/'):
165 168 static = os.path.join(templater.templatepath(), 'static')
166 169 fname = virtual[7:]
167 170 req.write(staticfile(static, fname, req) or
168 171 tmpl('error', error='%r not found' % fname))
169 172 elif virtual:
170 173 while virtual:
171 174 real = dict(self.repos).get(virtual)
172 175 if real:
173 176 break
174 177 up = virtual.rfind('/')
175 178 if up < 0:
176 179 break
177 180 virtual = virtual[:up]
178 181 if real:
179 182 req.env['REPO_NAME'] = virtual
180 183 try:
181 184 hgweb(real).run_wsgi(req)
182 185 except IOError, inst:
183 186 req.write(tmpl("error", error=inst.strerror))
184 187 except hg.RepoError, inst:
185 188 req.write(tmpl("error", error=str(inst)))
186 189 else:
187 190 req.write(tmpl("notfound", repo=virtual))
188 191 else:
189 192 if req.form.has_key('static'):
190 193 static = os.path.join(templater.templatepath(), "static")
191 194 fname = req.form['static'][0]
192 195 req.write(staticfile(static, fname, req)
193 196 or tmpl("error", error="%r not found" % fname))
194 197 else:
195 198 sortable = ["name", "description", "contact", "lastchange"]
196 199 sortcolumn, descending = self.repos_sorted
197 200 if req.form.has_key('sort'):
198 201 sortcolumn = req.form['sort'][0]
199 202 descending = sortcolumn.startswith('-')
200 203 if descending:
201 204 sortcolumn = sortcolumn[1:]
202 205 if sortcolumn not in sortable:
203 206 sortcolumn = ""
204 207
205 208 sort = [("sort_%s" % column,
206 209 "%s%s" % ((not descending and column == sortcolumn)
207 210 and "-" or "", column))
208 211 for column in sortable]
209 212 req.write(tmpl("index", entries=entries,
210 213 sortcolumn=sortcolumn, descending=descending,
211 214 **dict(sort)))
General Comments 0
You need to be logged in to leave comments. Login now