##// END OF EJS Templates
Minor tweak to the revgen algorithm
mpm@selenic.com -
r1023:bc806ba7 default
parent child Browse files
Show More
@@ -1,891 +1,892 b''
1 1 # hgweb.py - web interface to a mercurial repository
2 2 #
3 3 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
4 4 # Copyright 2005 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 import os, cgi, time, re, difflib, socket, sys, zlib
10 10 from mercurial.hg import *
11 11 from mercurial.ui import *
12 12
13 13 def templatepath():
14 14 for f in "templates", "../templates":
15 15 p = os.path.join(os.path.dirname(__file__), f)
16 16 if os.path.isdir(p): return p
17 17
18 18 def age(t):
19 19 def plural(t, c):
20 20 if c == 1: return t
21 21 return t + "s"
22 22 def fmt(t, c):
23 23 return "%d %s" % (c, plural(t, c))
24 24
25 25 now = time.time()
26 26 delta = max(1, int(now - t))
27 27
28 28 scales = [["second", 1],
29 29 ["minute", 60],
30 30 ["hour", 3600],
31 31 ["day", 3600 * 24],
32 32 ["week", 3600 * 24 * 7],
33 33 ["month", 3600 * 24 * 30],
34 34 ["year", 3600 * 24 * 365]]
35 35
36 36 scales.reverse()
37 37
38 38 for t, s in scales:
39 39 n = delta / s
40 40 if n >= 2 or s == 1: return fmt(t, n)
41 41
42 42 def nl2br(text):
43 43 return text.replace('\n', '<br/>\n')
44 44
45 45 def obfuscate(text):
46 46 return ''.join([ '&#%d;' % ord(c) for c in text ])
47 47
48 48 def up(p):
49 49 if p[0] != "/": p = "/" + p
50 50 if p[-1] == "/": p = p[:-1]
51 51 up = os.path.dirname(p)
52 52 if up == "/":
53 53 return "/"
54 54 return up + "/"
55 55
56 56 def httphdr(type):
57 57 sys.stdout.write('Content-type: %s\n\n' % type)
58 58
59 59 def write(*things):
60 60 for thing in things:
61 61 if hasattr(thing, "__iter__"):
62 62 for part in thing:
63 63 write(part)
64 64 else:
65 65 sys.stdout.write(str(thing))
66 66
67 67 class templater:
68 68 def __init__(self, mapfile, filters = {}, defaults = {}):
69 69 self.cache = {}
70 70 self.map = {}
71 71 self.base = os.path.dirname(mapfile)
72 72 self.filters = filters
73 73 self.defaults = defaults
74 74
75 75 for l in file(mapfile):
76 76 m = re.match(r'(\S+)\s*=\s*"(.*)"$', l)
77 77 if m:
78 78 self.cache[m.group(1)] = m.group(2)
79 79 else:
80 80 m = re.match(r'(\S+)\s*=\s*(\S+)', l)
81 81 if m:
82 82 self.map[m.group(1)] = os.path.join(self.base, m.group(2))
83 83 else:
84 84 raise "unknown map entry '%s'" % l
85 85
86 86 def __call__(self, t, **map):
87 87 m = self.defaults.copy()
88 88 m.update(map)
89 89 try:
90 90 tmpl = self.cache[t]
91 91 except KeyError:
92 92 tmpl = self.cache[t] = file(self.map[t]).read()
93 93 return self.template(tmpl, self.filters, **m)
94 94
95 95 def template(self, tmpl, filters = {}, **map):
96 96 while tmpl:
97 97 m = re.search(r"#([a-zA-Z0-9]+)((%[a-zA-Z0-9]+)*)((\|[a-zA-Z0-9]+)*)#", tmpl)
98 98 if m:
99 99 yield tmpl[:m.start(0)]
100 100 v = map.get(m.group(1), "")
101 101 v = callable(v) and v(**map) or v
102 102
103 103 format = m.group(2)
104 104 fl = m.group(4)
105 105
106 106 if format:
107 107 q = v.__iter__
108 108 for i in q():
109 109 lm = map.copy()
110 110 lm.update(i)
111 111 yield self(format[1:], **lm)
112 112
113 113 v = ""
114 114
115 115 elif fl:
116 116 for f in fl.split("|")[1:]:
117 117 v = filters[f](v)
118 118
119 119 yield v
120 120 tmpl = tmpl[m.end(0):]
121 121 else:
122 122 yield tmpl
123 123 return
124 124
125 125 def rfc822date(x):
126 126 return time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime(x))
127 127
128 128 common_filters = {
129 129 "escape": cgi.escape,
130 130 "age": age,
131 131 "date": (lambda x: time.asctime(time.gmtime(x))),
132 132 "addbreaks": nl2br,
133 133 "obfuscate": obfuscate,
134 134 "short": (lambda x: x[:12]),
135 135 "firstline": (lambda x: x.splitlines(1)[0]),
136 136 "permissions": (lambda x: x and "-rwxr-xr-x" or "-rw-r--r--"),
137 137 "rfc822date": rfc822date,
138 138 }
139 139
140 140 class hgweb:
141 141 def __init__(self, repo, name=None):
142 142 if type(repo) == type(""):
143 143 self.repo = repository(ui(), repo)
144 144 else:
145 145 self.repo = repo
146 146
147 147 self.mtime = -1
148 148 self.reponame = name or self.repo.ui.config("web", "name",
149 149 self.repo.root)
150 150
151 151 def refresh(self):
152 152 s = os.stat(os.path.join(self.repo.root, ".hg", "00changelog.i"))
153 153 if s.st_mtime != self.mtime:
154 154 self.mtime = s.st_mtime
155 155 self.repo = repository(self.repo.ui, self.repo.root)
156 156 self.maxchanges = self.repo.ui.config("web", "maxchanges", 10)
157 157 self.maxfiles = self.repo.ui.config("web", "maxchanges", 10)
158 158 self.allowpull = self.repo.ui.configbool("web", "allowpull", True)
159 159
160 160 def date(self, cs):
161 161 return time.asctime(time.gmtime(float(cs[2].split(' ')[0])))
162 162
163 163 def listfiles(self, files, mf):
164 164 for f in files[:self.maxfiles]:
165 165 yield self.t("filenodelink", node = hex(mf[f]), file = f)
166 166 if len(files) > self.maxfiles:
167 167 yield self.t("fileellipses")
168 168
169 169 def listfilediffs(self, files, changeset):
170 170 for f in files[:self.maxfiles]:
171 171 yield self.t("filedifflink", node = hex(changeset), file = f)
172 172 if len(files) > self.maxfiles:
173 173 yield self.t("fileellipses")
174 174
175 175 def parents(self, t1, nodes=[], rev=None,**args):
176 176 if not rev: rev = lambda x: ""
177 177 for node in nodes:
178 178 if node != nullid:
179 179 yield self.t(t1, node = hex(node), rev = rev(node), **args)
180 180
181 181 def showtag(self, t1, node=nullid, **args):
182 182 for t in self.repo.nodetags(node):
183 183 yield self.t(t1, tag = t, **args)
184 184
185 185 def diff(self, node1, node2, files):
186 186 def filterfiles(list, files):
187 187 l = [ x for x in list if x in files ]
188 188
189 189 for f in files:
190 190 if f[-1] != os.sep: f += os.sep
191 191 l += [ x for x in list if x.startswith(f) ]
192 192 return l
193 193
194 194 parity = [0]
195 195 def diffblock(diff, f, fn):
196 196 yield self.t("diffblock",
197 197 lines = prettyprintlines(diff),
198 198 parity = parity[0],
199 199 file = f,
200 200 filenode = hex(fn or nullid))
201 201 parity[0] = 1 - parity[0]
202 202
203 203 def prettyprintlines(diff):
204 204 for l in diff.splitlines(1):
205 205 if l.startswith('+'):
206 206 yield self.t("difflineplus", line = l)
207 207 elif l.startswith('-'):
208 208 yield self.t("difflineminus", line = l)
209 209 elif l.startswith('@'):
210 210 yield self.t("difflineat", line = l)
211 211 else:
212 212 yield self.t("diffline", line = l)
213 213
214 214 r = self.repo
215 215 cl = r.changelog
216 216 mf = r.manifest
217 217 change1 = cl.read(node1)
218 218 change2 = cl.read(node2)
219 219 mmap1 = mf.read(change1[0])
220 220 mmap2 = mf.read(change2[0])
221 221 date1 = self.date(change1)
222 222 date2 = self.date(change2)
223 223
224 224 c, a, d, u = r.changes(node1, node2)
225 225 if files:
226 226 c, a, d = map(lambda x: filterfiles(x, files), (c, a, d))
227 227
228 228 for f in c:
229 229 to = r.file(f).read(mmap1[f])
230 230 tn = r.file(f).read(mmap2[f])
231 231 yield diffblock(mdiff.unidiff(to, date1, tn, date2, f), f, tn)
232 232 for f in a:
233 233 to = None
234 234 tn = r.file(f).read(mmap2[f])
235 235 yield diffblock(mdiff.unidiff(to, date1, tn, date2, f), f, tn)
236 236 for f in d:
237 237 to = r.file(f).read(mmap1[f])
238 238 tn = None
239 239 yield diffblock(mdiff.unidiff(to, date1, tn, date2, f), f, tn)
240 240
241 241 def changelog(self, pos):
242 242 def changenav(**map):
243 243 def seq(factor = 1):
244 244 yield 1 * factor
245 245 yield 3 * factor
246 246 #yield 5 * factor
247 247 for f in seq(factor * 10):
248 248 yield f
249 249
250 250 l = []
251 251 for f in seq():
252 252 if f < self.maxchanges / 2: continue
253 253 if f > count: break
254 254 r = "%d" % f
255 255 if pos + f < count: l.append(("+" + r, pos + f))
256 256 if pos - f >= 0: l.insert(0, ("-" + r, pos - f))
257 257
258 258 yield {"rev": 0, "label": "(0)"}
259 259
260 260 for label, rev in l:
261 261 yield {"label": label, "rev": rev}
262 262
263 263 yield {"label": "tip", "rev": ""}
264 264
265 265 def changelist(**map):
266 266 parity = (start - end) & 1
267 267 cl = self.repo.changelog
268 268 l = [] # build a list in forward order for efficiency
269 269 for i in range(start, end):
270 270 n = cl.node(i)
271 271 changes = cl.read(n)
272 272 hn = hex(n)
273 273 t = float(changes[2].split(' ')[0])
274 274
275 275 l.insert(0, {
276 276 "parity": parity,
277 277 "author": changes[1],
278 278 "parent": self.parents("changelogparent",
279 279 cl.parents(n), cl.rev),
280 280 "changelogtag": self.showtag("changelogtag",n),
281 281 "manifest": hex(changes[0]),
282 282 "desc": changes[4],
283 283 "date": t,
284 284 "files": self.listfilediffs(changes[3], n),
285 285 "rev": i,
286 286 "node": hn})
287 287 parity = 1 - parity
288 288
289 289 for e in l: yield e
290 290
291 291 cl = self.repo.changelog
292 292 mf = cl.read(cl.tip())[0]
293 293 count = cl.count()
294 294 start = max(0, pos - self.maxchanges + 1)
295 295 end = min(count, start + self.maxchanges)
296 296 pos = end - 1
297 297
298 298 yield self.t('changelog',
299 299 changenav = changenav,
300 300 manifest = hex(mf),
301 301 rev = pos, changesets = count, entries = changelist)
302 302
303 303 def search(self, query):
304 304
305 305 def changelist(**map):
306 306 cl = self.repo.changelog
307 307 count = 0
308 308 qw = query.lower().split()
309 309
310 310 def revgen():
311 311 for i in range(cl.count() - 1, 0, -100):
312 312 l = []
313 313 for j in range(max(0, i - 100), i):
314 314 n = cl.node(j)
315 315 changes = cl.read(n)
316 l.insert(0, (n, j, changes))
316 l.append((n, j, changes))
317 l.reverse()
317 318 for e in l:
318 319 yield e
319 320
320 321 for n, i, changes in revgen():
321 322 miss = 0
322 323 for q in qw:
323 324 if not (q in changes[1].lower() or
324 325 q in changes[4].lower() or
325 326 q in " ".join(changes[3][:20]).lower()):
326 327 miss = 1
327 328 break
328 329 if miss: continue
329 330
330 331 count += 1
331 332 hn = hex(n)
332 333 t = float(changes[2].split(' ')[0])
333 334
334 335 yield self.t(
335 336 'searchentry',
336 337 parity = count & 1,
337 338 author = changes[1],
338 339 parent = self.parents("changelogparent",
339 340 cl.parents(n), cl.rev),
340 341 changelogtag = self.showtag("changelogtag",n),
341 342 manifest = hex(changes[0]),
342 343 desc = changes[4],
343 344 date = t,
344 345 files = self.listfilediffs(changes[3], n),
345 346 rev = i,
346 347 node = hn)
347 348
348 349 if count >= self.maxchanges: break
349 350
350 351 cl = self.repo.changelog
351 352 mf = cl.read(cl.tip())[0]
352 353
353 354 yield self.t('search',
354 355 query = query,
355 356 manifest = hex(mf),
356 357 entries = changelist)
357 358
358 359 def changeset(self, nodeid):
359 360 n = bin(nodeid)
360 361 cl = self.repo.changelog
361 362 changes = cl.read(n)
362 363 p1 = cl.parents(n)[0]
363 364 t = float(changes[2].split(' ')[0])
364 365
365 366 files = []
366 367 mf = self.repo.manifest.read(changes[0])
367 368 for f in changes[3]:
368 369 files.append(self.t("filenodelink",
369 370 filenode = hex(mf.get(f, nullid)), file = f))
370 371
371 372 def diff(**map):
372 373 yield self.diff(p1, n, None)
373 374
374 375 yield self.t('changeset',
375 376 diff = diff,
376 377 rev = cl.rev(n),
377 378 node = nodeid,
378 379 parent = self.parents("changesetparent",
379 380 cl.parents(n), cl.rev),
380 381 changesettag = self.showtag("changesettag",n),
381 382 manifest = hex(changes[0]),
382 383 author = changes[1],
383 384 desc = changes[4],
384 385 date = t,
385 386 files = files)
386 387
387 388 def filelog(self, f, filenode):
388 389 cl = self.repo.changelog
389 390 fl = self.repo.file(f)
390 391 count = fl.count()
391 392
392 393 def entries(**map):
393 394 l = []
394 395 parity = (count - 1) & 1
395 396
396 397 for i in range(count):
397 398
398 399 n = fl.node(i)
399 400 lr = fl.linkrev(n)
400 401 cn = cl.node(lr)
401 402 cs = cl.read(cl.node(lr))
402 403 t = float(cs[2].split(' ')[0])
403 404
404 405 l.insert(0, {"parity": parity,
405 406 "filenode": hex(n),
406 407 "filerev": i,
407 408 "file": f,
408 409 "node": hex(cn),
409 410 "author": cs[1],
410 411 "date": t,
411 412 "parent": self.parents("filelogparent",
412 413 fl.parents(n), fl.rev, file=f),
413 414 "desc": cs[4]})
414 415 parity = 1 - parity
415 416
416 417 for e in l: yield e
417 418
418 419 yield self.t("filelog",
419 420 file = f,
420 421 filenode = filenode,
421 422 entries = entries)
422 423
423 424 def filerevision(self, f, node):
424 425 fl = self.repo.file(f)
425 426 n = bin(node)
426 427 text = fl.read(n)
427 428 changerev = fl.linkrev(n)
428 429 cl = self.repo.changelog
429 430 cn = cl.node(changerev)
430 431 cs = cl.read(cn)
431 432 t = float(cs[2].split(' ')[0])
432 433 mfn = cs[0]
433 434
434 435 def lines():
435 436 for l, t in enumerate(text.splitlines(1)):
436 437 yield {"line": t,
437 438 "linenumber": "% 6d" % (l + 1),
438 439 "parity": l & 1}
439 440
440 441 yield self.t("filerevision", file = f,
441 442 filenode = node,
442 443 path = up(f),
443 444 text = lines(),
444 445 rev = changerev,
445 446 node = hex(cn),
446 447 manifest = hex(mfn),
447 448 author = cs[1],
448 449 date = t,
449 450 parent = self.parents("filerevparent",
450 451 fl.parents(n), fl.rev, file=f),
451 452 permissions = self.repo.manifest.readflags(mfn)[f])
452 453
453 454 def fileannotate(self, f, node):
454 455 bcache = {}
455 456 ncache = {}
456 457 fl = self.repo.file(f)
457 458 n = bin(node)
458 459 changerev = fl.linkrev(n)
459 460
460 461 cl = self.repo.changelog
461 462 cn = cl.node(changerev)
462 463 cs = cl.read(cn)
463 464 t = float(cs[2].split(' ')[0])
464 465 mfn = cs[0]
465 466
466 467 def annotate(**map):
467 468 parity = 1
468 469 last = None
469 470 for r, l in fl.annotate(n):
470 471 try:
471 472 cnode = ncache[r]
472 473 except KeyError:
473 474 cnode = ncache[r] = self.repo.changelog.node(r)
474 475
475 476 try:
476 477 name = bcache[r]
477 478 except KeyError:
478 479 cl = self.repo.changelog.read(cnode)
479 480 name = cl[1]
480 481 f = name.find('@')
481 482 if f >= 0:
482 483 name = name[:f]
483 484 f = name.find('<')
484 485 if f >= 0:
485 486 name = name[f+1:]
486 487 bcache[r] = name
487 488
488 489 if last != cnode:
489 490 parity = 1 - parity
490 491 last = cnode
491 492
492 493 yield {"parity": parity,
493 494 "node": hex(cnode),
494 495 "rev": r,
495 496 "author": name,
496 497 "file": f,
497 498 "line": l}
498 499
499 500 yield self.t("fileannotate",
500 501 file = f,
501 502 filenode = node,
502 503 annotate = annotate,
503 504 path = up(f),
504 505 rev = changerev,
505 506 node = hex(cn),
506 507 manifest = hex(mfn),
507 508 author = cs[1],
508 509 date = t,
509 510 parent = self.parents("fileannotateparent",
510 511 fl.parents(n), fl.rev, file=f),
511 512 permissions = self.repo.manifest.readflags(mfn)[f])
512 513
513 514 def manifest(self, mnode, path):
514 515 mf = self.repo.manifest.read(bin(mnode))
515 516 rev = self.repo.manifest.rev(bin(mnode))
516 517 node = self.repo.changelog.node(rev)
517 518 mff=self.repo.manifest.readflags(bin(mnode))
518 519
519 520 files = {}
520 521
521 522 p = path[1:]
522 523 l = len(p)
523 524
524 525 for f,n in mf.items():
525 526 if f[:l] != p:
526 527 continue
527 528 remain = f[l:]
528 529 if "/" in remain:
529 530 short = remain[:remain.find("/") + 1] # bleah
530 531 files[short] = (f, None)
531 532 else:
532 533 short = os.path.basename(remain)
533 534 files[short] = (f, n)
534 535
535 536 def filelist(**map):
536 537 parity = 0
537 538 fl = files.keys()
538 539 fl.sort()
539 540 for f in fl:
540 541 full, fnode = files[f]
541 542 if not fnode:
542 543 continue
543 544
544 545 yield {"file": full,
545 546 "manifest": mnode,
546 547 "filenode": hex(fnode),
547 548 "parity": parity,
548 549 "basename": f,
549 550 "permissions": mff[full]}
550 551 parity = 1 - parity
551 552
552 553 def dirlist(**map):
553 554 parity = 0
554 555 fl = files.keys()
555 556 fl.sort()
556 557 for f in fl:
557 558 full, fnode = files[f]
558 559 if fnode:
559 560 continue
560 561
561 562 yield {"parity": parity,
562 563 "path": os.path.join(path, f),
563 564 "manifest": mnode,
564 565 "basename": f[:-1]}
565 566 parity = 1 - parity
566 567
567 568 yield self.t("manifest",
568 569 manifest = mnode,
569 570 rev = rev,
570 571 node = hex(node),
571 572 path = path,
572 573 up = up(path),
573 574 fentries = filelist,
574 575 dentries = dirlist)
575 576
576 577 def tags(self):
577 578 cl = self.repo.changelog
578 579 mf = cl.read(cl.tip())[0]
579 580
580 581 i = self.repo.tagslist()
581 582 i.reverse()
582 583
583 584 def entries(**map):
584 585 parity = 0
585 586 for k,n in i:
586 587 yield {"parity": parity,
587 588 "tag": k,
588 589 "node": hex(n)}
589 590 parity = 1 - parity
590 591
591 592 yield self.t("tags",
592 593 manifest = hex(mf),
593 594 entries = entries)
594 595
595 596 def filediff(self, file, changeset):
596 597 n = bin(changeset)
597 598 cl = self.repo.changelog
598 599 p1 = cl.parents(n)[0]
599 600 cs = cl.read(n)
600 601 mf = self.repo.manifest.read(cs[0])
601 602
602 603 def diff(**map):
603 604 yield self.diff(p1, n, file)
604 605
605 606 yield self.t("filediff",
606 607 file = file,
607 608 filenode = hex(mf.get(file, nullid)),
608 609 node = changeset,
609 610 rev = self.repo.changelog.rev(n),
610 611 parent = self.parents("filediffparent",
611 612 cl.parents(n), cl.rev),
612 613 diff = diff)
613 614
614 615 # add tags to things
615 616 # tags -> list of changesets corresponding to tags
616 617 # find tag, changeset, file
617 618
618 619 def run(self):
619 620 def header(**map):
620 621 yield self.t("header", **map)
621 622
622 623 def footer(**map):
623 624 yield self.t("footer", **map)
624 625
625 626 self.refresh()
626 627 args = cgi.parse()
627 628
628 629 t = self.repo.ui.config("web", "templates", templatepath())
629 630 m = os.path.join(t, "map")
630 631 style = self.repo.ui.config("web", "style", "")
631 632 if args.has_key('style'):
632 633 style = args['style'][0]
633 634 if style:
634 635 b = os.path.basename("map-" + style)
635 636 p = os.path.join(t, b)
636 637 if os.path.isfile(p): m = p
637 638
638 639 port = os.environ["SERVER_PORT"]
639 640 port = port != "80" and (":" + port) or ""
640 641 uri = os.environ["REQUEST_URI"]
641 642 if "?" in uri: uri = uri.split("?")[0]
642 643 url = "http://%s%s%s" % (os.environ["SERVER_NAME"], port, uri)
643 644
644 645 self.t = templater(m, common_filters,
645 646 {"url":url,
646 647 "repo":self.reponame,
647 648 "header":header,
648 649 "footer":footer,
649 650 })
650 651
651 652 if not args.has_key('cmd'):
652 653 args['cmd'] = [self.t.cache['default'],]
653 654
654 655 if args['cmd'][0] == 'changelog':
655 656 c = self.repo.changelog.count() - 1
656 657 hi = c
657 658 if args.has_key('rev'):
658 659 hi = args['rev'][0]
659 660 try:
660 661 hi = self.repo.changelog.rev(self.repo.lookup(hi))
661 662 except RepoError:
662 663 write(self.search(hi))
663 664 return
664 665
665 666 write(self.changelog(hi))
666 667
667 668 elif args['cmd'][0] == 'changeset':
668 669 write(self.changeset(args['node'][0]))
669 670
670 671 elif args['cmd'][0] == 'manifest':
671 672 write(self.manifest(args['manifest'][0], args['path'][0]))
672 673
673 674 elif args['cmd'][0] == 'tags':
674 675 write(self.tags())
675 676
676 677 elif args['cmd'][0] == 'filediff':
677 678 write(self.filediff(args['file'][0], args['node'][0]))
678 679
679 680 elif args['cmd'][0] == 'file':
680 681 write(self.filerevision(args['file'][0], args['filenode'][0]))
681 682
682 683 elif args['cmd'][0] == 'annotate':
683 684 write(self.fileannotate(args['file'][0], args['filenode'][0]))
684 685
685 686 elif args['cmd'][0] == 'filelog':
686 687 write(self.filelog(args['file'][0], args['filenode'][0]))
687 688
688 689 elif args['cmd'][0] == 'heads':
689 690 httphdr("application/mercurial-0.1")
690 691 h = self.repo.heads()
691 692 sys.stdout.write(" ".join(map(hex, h)) + "\n")
692 693
693 694 elif args['cmd'][0] == 'branches':
694 695 httphdr("application/mercurial-0.1")
695 696 nodes = []
696 697 if args.has_key('nodes'):
697 698 nodes = map(bin, args['nodes'][0].split(" "))
698 699 for b in self.repo.branches(nodes):
699 700 sys.stdout.write(" ".join(map(hex, b)) + "\n")
700 701
701 702 elif args['cmd'][0] == 'between':
702 703 httphdr("application/mercurial-0.1")
703 704 nodes = []
704 705 if args.has_key('pairs'):
705 706 pairs = [ map(bin, p.split("-"))
706 707 for p in args['pairs'][0].split(" ") ]
707 708 for b in self.repo.between(pairs):
708 709 sys.stdout.write(" ".join(map(hex, b)) + "\n")
709 710
710 711 elif args['cmd'][0] == 'changegroup':
711 712 httphdr("application/mercurial-0.1")
712 713 nodes = []
713 714 if not self.allowpull:
714 715 return
715 716
716 717 if args.has_key('roots'):
717 718 nodes = map(bin, args['roots'][0].split(" "))
718 719
719 720 z = zlib.compressobj()
720 721 f = self.repo.changegroup(nodes)
721 722 while 1:
722 723 chunk = f.read(4096)
723 724 if not chunk: break
724 725 sys.stdout.write(z.compress(chunk))
725 726
726 727 sys.stdout.write(z.flush())
727 728
728 729 else:
729 730 write(self.t("error"))
730 731
731 732 def create_server(repo):
732 733
733 734 def openlog(opt, default):
734 735 if opt and opt != '-':
735 736 return open(opt, 'w')
736 737 return default
737 738
738 739 address = repo.ui.config("web", "address", "")
739 740 port = int(repo.ui.config("web", "port", 8000))
740 741 use_ipv6 = repo.ui.configbool("web", "ipv6")
741 742 accesslog = openlog(repo.ui.config("web", "accesslog", "-"), sys.stdout)
742 743 errorlog = openlog(repo.ui.config("web", "errorlog", "-"), sys.stderr)
743 744
744 745 import BaseHTTPServer
745 746
746 747 class IPv6HTTPServer(BaseHTTPServer.HTTPServer):
747 748 address_family = getattr(socket, 'AF_INET6', None)
748 749
749 750 def __init__(self, *args, **kwargs):
750 751 if self.address_family is None:
751 752 raise RepoError('IPv6 not available on this system')
752 753 BaseHTTPServer.HTTPServer.__init__(self, *args, **kwargs)
753 754
754 755 class hgwebhandler(BaseHTTPServer.BaseHTTPRequestHandler):
755 756 def log_error(self, format, *args):
756 757 errorlog.write("%s - - [%s] %s\n" % (self.address_string(),
757 758 self.log_date_time_string(),
758 759 format % args))
759 760
760 761 def log_message(self, format, *args):
761 762 accesslog.write("%s - - [%s] %s\n" % (self.address_string(),
762 763 self.log_date_time_string(),
763 764 format % args))
764 765
765 766 def do_POST(self):
766 767 try:
767 768 self.do_hgweb()
768 769 except socket.error, inst:
769 770 if inst.args[0] != 32: raise
770 771
771 772 def do_GET(self):
772 773 self.do_POST()
773 774
774 775 def do_hgweb(self):
775 776 query = ""
776 777 p = self.path.find("?")
777 778 if p:
778 779 query = self.path[p + 1:]
779 780 query = query.replace('+', ' ')
780 781
781 782 env = {}
782 783 env['GATEWAY_INTERFACE'] = 'CGI/1.1'
783 784 env['REQUEST_METHOD'] = self.command
784 785 env['SERVER_NAME'] = self.server.server_name
785 786 env['SERVER_PORT'] = str(self.server.server_port)
786 787 env['REQUEST_URI'] = "/"
787 788 if query:
788 789 env['QUERY_STRING'] = query
789 790 host = self.address_string()
790 791 if host != self.client_address[0]:
791 792 env['REMOTE_HOST'] = host
792 793 env['REMOTE_ADDR'] = self.client_address[0]
793 794
794 795 if self.headers.typeheader is None:
795 796 env['CONTENT_TYPE'] = self.headers.type
796 797 else:
797 798 env['CONTENT_TYPE'] = self.headers.typeheader
798 799 length = self.headers.getheader('content-length')
799 800 if length:
800 801 env['CONTENT_LENGTH'] = length
801 802 accept = []
802 803 for line in self.headers.getallmatchingheaders('accept'):
803 804 if line[:1] in "\t\n\r ":
804 805 accept.append(line.strip())
805 806 else:
806 807 accept = accept + line[7:].split(',')
807 808 env['HTTP_ACCEPT'] = ','.join(accept)
808 809
809 810 os.environ.update(env)
810 811
811 812 save = sys.argv, sys.stdin, sys.stdout, sys.stderr
812 813 try:
813 814 sys.stdin = self.rfile
814 815 sys.stdout = self.wfile
815 816 sys.argv = ["hgweb.py"]
816 817 if '=' not in query:
817 818 sys.argv.append(query)
818 819 self.send_response(200, "Script output follows")
819 820 hg.run()
820 821 finally:
821 822 sys.argv, sys.stdin, sys.stdout, sys.stderr = save
822 823
823 824 hg = hgweb(repo)
824 825 if use_ipv6:
825 826 return IPv6HTTPServer((address, port), hgwebhandler)
826 827 else:
827 828 return BaseHTTPServer.HTTPServer((address, port), hgwebhandler)
828 829
829 830 def server(path, name, templates, address, port, use_ipv6 = False,
830 831 accesslog = sys.stdout, errorlog = sys.stderr):
831 832 httpd = create_server(path, name, templates, address, port, use_ipv6,
832 833 accesslog, errorlog)
833 834 httpd.serve_forever()
834 835
835 836 # This is a stopgap
836 837 class hgwebdir:
837 838 def __init__(self, config):
838 839 self.cp = ConfigParser.SafeConfigParser()
839 840 self.cp.read(config)
840 841
841 842 def run(self):
842 843 try:
843 844 virtual = os.environ["PATH_INFO"]
844 845 except:
845 846 virtual = ""
846 847
847 848 if virtual[1:]:
848 849 real = self.cp.get("paths", virtual[1:])
849 850 h = hgweb(real)
850 851 h.run()
851 852 return
852 853
853 854 def header(**map):
854 855 yield tmpl("header", **map)
855 856
856 857 def footer(**map):
857 858 yield tmpl("footer", **map)
858 859
859 860 templates = templatepath()
860 861 m = os.path.join(templates, "map")
861 862 tmpl = templater(m, common_filters,
862 863 {"header": header, "footer": footer})
863 864
864 865 def entries(**map):
865 866 parity = 0
866 867 l = self.cp.items("paths")
867 868 l.sort()
868 869 for v,r in l:
869 870 cp2 = ConfigParser.SafeConfigParser()
870 871 cp2.read(os.path.join(r, ".hg", "hgrc"))
871 872
872 873 def get(sec, val, default):
873 874 try:
874 875 return cp2.get(sec, val)
875 876 except:
876 877 return default
877 878
878 879 url = os.environ["REQUEST_URI"] + "/" + v
879 880 url = url.replace("//", "/")
880 881
881 882 yield dict(author = get("web", "author", "unknown"),
882 883 name = get("web", "name", v),
883 884 url = url,
884 885 parity = parity,
885 886 shortdesc = get("web", "description", "unknown"),
886 887 lastupdate = os.stat(os.path.join(r, ".hg",
887 888 "00changelog.d")).st_mtime)
888 889
889 890 parity = 1 - parity
890 891
891 892 write(tmpl("index", entries = entries))
General Comments 0
You need to be logged in to leave comments. Login now