##// END OF EJS Templates
hgweb: don't use dict(key=value) to build a mapping dict in filelog...
Yuya Nishihara -
r38155:22005819 default
parent child Browse files
Show More
@@ -1,1472 +1,1476 b''
1 1 #
2 2 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from __future__ import absolute_import
9 9
10 10 import copy
11 11 import mimetypes
12 12 import os
13 13 import re
14 14
15 15 from ..i18n import _
16 16 from ..node import hex, short
17 17
18 18 from .common import (
19 19 ErrorResponse,
20 20 HTTP_FORBIDDEN,
21 21 HTTP_NOT_FOUND,
22 22 get_contact,
23 23 paritygen,
24 24 staticfile,
25 25 )
26 26
27 27 from .. import (
28 28 archival,
29 29 dagop,
30 30 encoding,
31 31 error,
32 32 graphmod,
33 33 pycompat,
34 34 revset,
35 35 revsetlang,
36 36 scmutil,
37 37 smartset,
38 38 templater,
39 39 templateutil,
40 40 )
41 41
42 42 from ..utils import (
43 43 stringutil,
44 44 )
45 45
46 46 from . import (
47 47 webutil,
48 48 )
49 49
50 50 __all__ = []
51 51 commands = {}
52 52
53 53 class webcommand(object):
54 54 """Decorator used to register a web command handler.
55 55
56 56 The decorator takes as its positional arguments the name/path the
57 57 command should be accessible under.
58 58
59 59 When called, functions receive as arguments a ``requestcontext``,
60 60 ``wsgirequest``, and a templater instance for generatoring output.
61 61 The functions should populate the ``rctx.res`` object with details
62 62 about the HTTP response.
63 63
64 64 The function returns a generator to be consumed by the WSGI application.
65 65 For most commands, this should be the result from
66 66 ``web.res.sendresponse()``. Many commands will call ``web.sendtemplate()``
67 67 to render a template.
68 68
69 69 Usage:
70 70
71 71 @webcommand('mycommand')
72 72 def mycommand(web):
73 73 pass
74 74 """
75 75
76 76 def __init__(self, name):
77 77 self.name = name
78 78
79 79 def __call__(self, func):
80 80 __all__.append(self.name)
81 81 commands[self.name] = func
82 82 return func
83 83
84 84 @webcommand('log')
85 85 def log(web):
86 86 """
87 87 /log[/{revision}[/{path}]]
88 88 --------------------------
89 89
90 90 Show repository or file history.
91 91
92 92 For URLs of the form ``/log/{revision}``, a list of changesets starting at
93 93 the specified changeset identifier is shown. If ``{revision}`` is not
94 94 defined, the default is ``tip``. This form is equivalent to the
95 95 ``changelog`` handler.
96 96
97 97 For URLs of the form ``/log/{revision}/{file}``, the history for a specific
98 98 file will be shown. This form is equivalent to the ``filelog`` handler.
99 99 """
100 100
101 101 if web.req.qsparams.get('file'):
102 102 return filelog(web)
103 103 else:
104 104 return changelog(web)
105 105
106 106 @webcommand('rawfile')
107 107 def rawfile(web):
108 108 guessmime = web.configbool('web', 'guessmime')
109 109
110 110 path = webutil.cleanpath(web.repo, web.req.qsparams.get('file', ''))
111 111 if not path:
112 112 return manifest(web)
113 113
114 114 try:
115 115 fctx = webutil.filectx(web.repo, web.req)
116 116 except error.LookupError as inst:
117 117 try:
118 118 return manifest(web)
119 119 except ErrorResponse:
120 120 raise inst
121 121
122 122 path = fctx.path()
123 123 text = fctx.data()
124 124 mt = 'application/binary'
125 125 if guessmime:
126 126 mt = mimetypes.guess_type(path)[0]
127 127 if mt is None:
128 128 if stringutil.binary(text):
129 129 mt = 'application/binary'
130 130 else:
131 131 mt = 'text/plain'
132 132 if mt.startswith('text/'):
133 133 mt += '; charset="%s"' % encoding.encoding
134 134
135 135 web.res.headers['Content-Type'] = mt
136 136 filename = (path.rpartition('/')[-1]
137 137 .replace('\\', '\\\\').replace('"', '\\"'))
138 138 web.res.headers['Content-Disposition'] = 'inline; filename="%s"' % filename
139 139 web.res.setbodybytes(text)
140 140 return web.res.sendresponse()
141 141
142 142 def _filerevision(web, fctx):
143 143 f = fctx.path()
144 144 text = fctx.data()
145 145 parity = paritygen(web.stripecount)
146 146 ishead = fctx.filerev() in fctx.filelog().headrevs()
147 147
148 148 if stringutil.binary(text):
149 149 mt = mimetypes.guess_type(f)[0] or 'application/octet-stream'
150 150 text = '(binary:%s)' % mt
151 151
152 152 def lines(context):
153 153 for lineno, t in enumerate(text.splitlines(True)):
154 154 yield {"line": t,
155 155 "lineid": "l%d" % (lineno + 1),
156 156 "linenumber": "% 6d" % (lineno + 1),
157 157 "parity": next(parity)}
158 158
159 159 return web.sendtemplate(
160 160 'filerevision',
161 161 file=f,
162 162 path=webutil.up(f),
163 163 text=templateutil.mappinggenerator(lines),
164 164 symrev=webutil.symrevorshortnode(web.req, fctx),
165 165 rename=webutil.renamelink(fctx),
166 166 permissions=fctx.manifest().flags(f),
167 167 ishead=int(ishead),
168 168 **pycompat.strkwargs(webutil.commonentry(web.repo, fctx)))
169 169
170 170 @webcommand('file')
171 171 def file(web):
172 172 """
173 173 /file/{revision}[/{path}]
174 174 -------------------------
175 175
176 176 Show information about a directory or file in the repository.
177 177
178 178 Info about the ``path`` given as a URL parameter will be rendered.
179 179
180 180 If ``path`` is a directory, information about the entries in that
181 181 directory will be rendered. This form is equivalent to the ``manifest``
182 182 handler.
183 183
184 184 If ``path`` is a file, information about that file will be shown via
185 185 the ``filerevision`` template.
186 186
187 187 If ``path`` is not defined, information about the root directory will
188 188 be rendered.
189 189 """
190 190 if web.req.qsparams.get('style') == 'raw':
191 191 return rawfile(web)
192 192
193 193 path = webutil.cleanpath(web.repo, web.req.qsparams.get('file', ''))
194 194 if not path:
195 195 return manifest(web)
196 196 try:
197 197 return _filerevision(web, webutil.filectx(web.repo, web.req))
198 198 except error.LookupError as inst:
199 199 try:
200 200 return manifest(web)
201 201 except ErrorResponse:
202 202 raise inst
203 203
204 204 def _search(web):
205 205 MODE_REVISION = 'rev'
206 206 MODE_KEYWORD = 'keyword'
207 207 MODE_REVSET = 'revset'
208 208
209 209 def revsearch(ctx):
210 210 yield ctx
211 211
212 212 def keywordsearch(query):
213 213 lower = encoding.lower
214 214 qw = lower(query).split()
215 215
216 216 def revgen():
217 217 cl = web.repo.changelog
218 218 for i in xrange(len(web.repo) - 1, 0, -100):
219 219 l = []
220 220 for j in cl.revs(max(0, i - 99), i):
221 221 ctx = web.repo[j]
222 222 l.append(ctx)
223 223 l.reverse()
224 224 for e in l:
225 225 yield e
226 226
227 227 for ctx in revgen():
228 228 miss = 0
229 229 for q in qw:
230 230 if not (q in lower(ctx.user()) or
231 231 q in lower(ctx.description()) or
232 232 q in lower(" ".join(ctx.files()))):
233 233 miss = 1
234 234 break
235 235 if miss:
236 236 continue
237 237
238 238 yield ctx
239 239
240 240 def revsetsearch(revs):
241 241 for r in revs:
242 242 yield web.repo[r]
243 243
244 244 searchfuncs = {
245 245 MODE_REVISION: (revsearch, 'exact revision search'),
246 246 MODE_KEYWORD: (keywordsearch, 'literal keyword search'),
247 247 MODE_REVSET: (revsetsearch, 'revset expression search'),
248 248 }
249 249
250 250 def getsearchmode(query):
251 251 try:
252 252 ctx = scmutil.revsymbol(web.repo, query)
253 253 except (error.RepoError, error.LookupError):
254 254 # query is not an exact revision pointer, need to
255 255 # decide if it's a revset expression or keywords
256 256 pass
257 257 else:
258 258 return MODE_REVISION, ctx
259 259
260 260 revdef = 'reverse(%s)' % query
261 261 try:
262 262 tree = revsetlang.parse(revdef)
263 263 except error.ParseError:
264 264 # can't parse to a revset tree
265 265 return MODE_KEYWORD, query
266 266
267 267 if revsetlang.depth(tree) <= 2:
268 268 # no revset syntax used
269 269 return MODE_KEYWORD, query
270 270
271 271 if any((token, (value or '')[:3]) == ('string', 're:')
272 272 for token, value, pos in revsetlang.tokenize(revdef)):
273 273 return MODE_KEYWORD, query
274 274
275 275 funcsused = revsetlang.funcsused(tree)
276 276 if not funcsused.issubset(revset.safesymbols):
277 277 return MODE_KEYWORD, query
278 278
279 279 mfunc = revset.match(web.repo.ui, revdef,
280 280 lookup=revset.lookupfn(web.repo))
281 281 try:
282 282 revs = mfunc(web.repo)
283 283 return MODE_REVSET, revs
284 284 # ParseError: wrongly placed tokens, wrongs arguments, etc
285 285 # RepoLookupError: no such revision, e.g. in 'revision:'
286 286 # Abort: bookmark/tag not exists
287 287 # LookupError: ambiguous identifier, e.g. in '(bc)' on a large repo
288 288 except (error.ParseError, error.RepoLookupError, error.Abort,
289 289 LookupError):
290 290 return MODE_KEYWORD, query
291 291
292 292 def changelist(context):
293 293 count = 0
294 294
295 295 for ctx in searchfunc[0](funcarg):
296 296 count += 1
297 297 n = ctx.node()
298 298 showtags = webutil.showtag(web.repo, 'changelogtag', n)
299 299 files = webutil.listfilediffs(ctx.files(), n, web.maxfiles)
300 300
301 301 lm = webutil.commonentry(web.repo, ctx)
302 302 lm.update({
303 303 'parity': next(parity),
304 304 'changelogtag': showtags,
305 305 'files': files,
306 306 })
307 307 yield lm
308 308
309 309 if count >= revcount:
310 310 break
311 311
312 312 query = web.req.qsparams['rev']
313 313 revcount = web.maxchanges
314 314 if 'revcount' in web.req.qsparams:
315 315 try:
316 316 revcount = int(web.req.qsparams.get('revcount', revcount))
317 317 revcount = max(revcount, 1)
318 318 web.tmpl.defaults['sessionvars']['revcount'] = revcount
319 319 except ValueError:
320 320 pass
321 321
322 322 lessvars = copy.copy(web.tmpl.defaults['sessionvars'])
323 323 lessvars['revcount'] = max(revcount // 2, 1)
324 324 lessvars['rev'] = query
325 325 morevars = copy.copy(web.tmpl.defaults['sessionvars'])
326 326 morevars['revcount'] = revcount * 2
327 327 morevars['rev'] = query
328 328
329 329 mode, funcarg = getsearchmode(query)
330 330
331 331 if 'forcekw' in web.req.qsparams:
332 332 showforcekw = ''
333 333 showunforcekw = searchfuncs[mode][1]
334 334 mode = MODE_KEYWORD
335 335 funcarg = query
336 336 else:
337 337 if mode != MODE_KEYWORD:
338 338 showforcekw = searchfuncs[MODE_KEYWORD][1]
339 339 else:
340 340 showforcekw = ''
341 341 showunforcekw = ''
342 342
343 343 searchfunc = searchfuncs[mode]
344 344
345 345 tip = web.repo['tip']
346 346 parity = paritygen(web.stripecount)
347 347
348 348 return web.sendtemplate(
349 349 'search',
350 350 query=query,
351 351 node=tip.hex(),
352 352 symrev='tip',
353 353 entries=templateutil.mappinggenerator(changelist, name='searchentry'),
354 354 archives=web.archivelist('tip'),
355 355 morevars=morevars,
356 356 lessvars=lessvars,
357 357 modedesc=searchfunc[1],
358 358 showforcekw=showforcekw,
359 359 showunforcekw=showunforcekw)
360 360
361 361 @webcommand('changelog')
362 362 def changelog(web, shortlog=False):
363 363 """
364 364 /changelog[/{revision}]
365 365 -----------------------
366 366
367 367 Show information about multiple changesets.
368 368
369 369 If the optional ``revision`` URL argument is absent, information about
370 370 all changesets starting at ``tip`` will be rendered. If the ``revision``
371 371 argument is present, changesets will be shown starting from the specified
372 372 revision.
373 373
374 374 If ``revision`` is absent, the ``rev`` query string argument may be
375 375 defined. This will perform a search for changesets.
376 376
377 377 The argument for ``rev`` can be a single revision, a revision set,
378 378 or a literal keyword to search for in changeset data (equivalent to
379 379 :hg:`log -k`).
380 380
381 381 The ``revcount`` query string argument defines the maximum numbers of
382 382 changesets to render.
383 383
384 384 For non-searches, the ``changelog`` template will be rendered.
385 385 """
386 386
387 387 query = ''
388 388 if 'node' in web.req.qsparams:
389 389 ctx = webutil.changectx(web.repo, web.req)
390 390 symrev = webutil.symrevorshortnode(web.req, ctx)
391 391 elif 'rev' in web.req.qsparams:
392 392 return _search(web)
393 393 else:
394 394 ctx = web.repo['tip']
395 395 symrev = 'tip'
396 396
397 397 def changelist():
398 398 revs = []
399 399 if pos != -1:
400 400 revs = web.repo.changelog.revs(pos, 0)
401 401
402 402 for entry in webutil.changelistentries(web, revs, revcount, parity):
403 403 yield entry
404 404
405 405 if shortlog:
406 406 revcount = web.maxshortchanges
407 407 else:
408 408 revcount = web.maxchanges
409 409
410 410 if 'revcount' in web.req.qsparams:
411 411 try:
412 412 revcount = int(web.req.qsparams.get('revcount', revcount))
413 413 revcount = max(revcount, 1)
414 414 web.tmpl.defaults['sessionvars']['revcount'] = revcount
415 415 except ValueError:
416 416 pass
417 417
418 418 lessvars = copy.copy(web.tmpl.defaults['sessionvars'])
419 419 lessvars['revcount'] = max(revcount // 2, 1)
420 420 morevars = copy.copy(web.tmpl.defaults['sessionvars'])
421 421 morevars['revcount'] = revcount * 2
422 422
423 423 count = len(web.repo)
424 424 pos = ctx.rev()
425 425 parity = paritygen(web.stripecount)
426 426
427 427 changenav = webutil.revnav(web.repo).gen(pos, revcount, count)
428 428
429 429 entries = list(changelist())
430 430 latestentry = entries[:1]
431 431 if len(entries) > revcount:
432 432 nextentry = entries[-1:]
433 433 entries = entries[:-1]
434 434 else:
435 435 nextentry = []
436 436
437 437 return web.sendtemplate(
438 438 'shortlog' if shortlog else 'changelog',
439 439 changenav=changenav,
440 440 node=ctx.hex(),
441 441 rev=pos,
442 442 symrev=symrev,
443 443 changesets=count,
444 444 entries=templateutil.mappinglist(entries),
445 445 latestentry=templateutil.mappinglist(latestentry),
446 446 nextentry=templateutil.mappinglist(nextentry),
447 447 archives=web.archivelist('tip'),
448 448 revcount=revcount,
449 449 morevars=morevars,
450 450 lessvars=lessvars,
451 451 query=query)
452 452
453 453 @webcommand('shortlog')
454 454 def shortlog(web):
455 455 """
456 456 /shortlog
457 457 ---------
458 458
459 459 Show basic information about a set of changesets.
460 460
461 461 This accepts the same parameters as the ``changelog`` handler. The only
462 462 difference is the ``shortlog`` template will be rendered instead of the
463 463 ``changelog`` template.
464 464 """
465 465 return changelog(web, shortlog=True)
466 466
467 467 @webcommand('changeset')
468 468 def changeset(web):
469 469 """
470 470 /changeset[/{revision}]
471 471 -----------------------
472 472
473 473 Show information about a single changeset.
474 474
475 475 A URL path argument is the changeset identifier to show. See ``hg help
476 476 revisions`` for possible values. If not defined, the ``tip`` changeset
477 477 will be shown.
478 478
479 479 The ``changeset`` template is rendered. Contents of the ``changesettag``,
480 480 ``changesetbookmark``, ``filenodelink``, ``filenolink``, and the many
481 481 templates related to diffs may all be used to produce the output.
482 482 """
483 483 ctx = webutil.changectx(web.repo, web.req)
484 484
485 485 return web.sendtemplate(
486 486 'changeset',
487 487 **webutil.changesetentry(web, ctx))
488 488
489 489 rev = webcommand('rev')(changeset)
490 490
491 491 def decodepath(path):
492 492 """Hook for mapping a path in the repository to a path in the
493 493 working copy.
494 494
495 495 Extensions (e.g., largefiles) can override this to remap files in
496 496 the virtual file system presented by the manifest command below."""
497 497 return path
498 498
499 499 @webcommand('manifest')
500 500 def manifest(web):
501 501 """
502 502 /manifest[/{revision}[/{path}]]
503 503 -------------------------------
504 504
505 505 Show information about a directory.
506 506
507 507 If the URL path arguments are omitted, information about the root
508 508 directory for the ``tip`` changeset will be shown.
509 509
510 510 Because this handler can only show information for directories, it
511 511 is recommended to use the ``file`` handler instead, as it can handle both
512 512 directories and files.
513 513
514 514 The ``manifest`` template will be rendered for this handler.
515 515 """
516 516 if 'node' in web.req.qsparams:
517 517 ctx = webutil.changectx(web.repo, web.req)
518 518 symrev = webutil.symrevorshortnode(web.req, ctx)
519 519 else:
520 520 ctx = web.repo['tip']
521 521 symrev = 'tip'
522 522 path = webutil.cleanpath(web.repo, web.req.qsparams.get('file', ''))
523 523 mf = ctx.manifest()
524 524 node = ctx.node()
525 525
526 526 files = {}
527 527 dirs = {}
528 528 parity = paritygen(web.stripecount)
529 529
530 530 if path and path[-1:] != "/":
531 531 path += "/"
532 532 l = len(path)
533 533 abspath = "/" + path
534 534
535 535 for full, n in mf.iteritems():
536 536 # the virtual path (working copy path) used for the full
537 537 # (repository) path
538 538 f = decodepath(full)
539 539
540 540 if f[:l] != path:
541 541 continue
542 542 remain = f[l:]
543 543 elements = remain.split('/')
544 544 if len(elements) == 1:
545 545 files[remain] = full
546 546 else:
547 547 h = dirs # need to retain ref to dirs (root)
548 548 for elem in elements[0:-1]:
549 549 if elem not in h:
550 550 h[elem] = {}
551 551 h = h[elem]
552 552 if len(h) > 1:
553 553 break
554 554 h[None] = None # denotes files present
555 555
556 556 if mf and not files and not dirs:
557 557 raise ErrorResponse(HTTP_NOT_FOUND, 'path not found: ' + path)
558 558
559 559 def filelist(context):
560 560 for f in sorted(files):
561 561 full = files[f]
562 562
563 563 fctx = ctx.filectx(full)
564 564 yield {"file": full,
565 565 "parity": next(parity),
566 566 "basename": f,
567 567 "date": fctx.date(),
568 568 "size": fctx.size(),
569 569 "permissions": mf.flags(full)}
570 570
571 571 def dirlist(context):
572 572 for d in sorted(dirs):
573 573
574 574 emptydirs = []
575 575 h = dirs[d]
576 576 while isinstance(h, dict) and len(h) == 1:
577 577 k, v = next(iter(h.items()))
578 578 if v:
579 579 emptydirs.append(k)
580 580 h = v
581 581
582 582 path = "%s%s" % (abspath, d)
583 583 yield {"parity": next(parity),
584 584 "path": path,
585 585 "emptydirs": "/".join(emptydirs),
586 586 "basename": d}
587 587
588 588 return web.sendtemplate(
589 589 'manifest',
590 590 symrev=symrev,
591 591 path=abspath,
592 592 up=webutil.up(abspath),
593 593 upparity=next(parity),
594 594 fentries=templateutil.mappinggenerator(filelist),
595 595 dentries=templateutil.mappinggenerator(dirlist),
596 596 archives=web.archivelist(hex(node)),
597 597 **pycompat.strkwargs(webutil.commonentry(web.repo, ctx)))
598 598
599 599 @webcommand('tags')
600 600 def tags(web):
601 601 """
602 602 /tags
603 603 -----
604 604
605 605 Show information about tags.
606 606
607 607 No arguments are accepted.
608 608
609 609 The ``tags`` template is rendered.
610 610 """
611 611 i = list(reversed(web.repo.tagslist()))
612 612 parity = paritygen(web.stripecount)
613 613
614 614 def entries(context, notip, latestonly):
615 615 t = i
616 616 if notip:
617 617 t = [(k, n) for k, n in i if k != "tip"]
618 618 if latestonly:
619 619 t = t[:1]
620 620 for k, n in t:
621 621 yield {"parity": next(parity),
622 622 "tag": k,
623 623 "date": web.repo[n].date(),
624 624 "node": hex(n)}
625 625
626 626 return web.sendtemplate(
627 627 'tags',
628 628 node=hex(web.repo.changelog.tip()),
629 629 entries=templateutil.mappinggenerator(entries, args=(False, False)),
630 630 entriesnotip=templateutil.mappinggenerator(entries,
631 631 args=(True, False)),
632 632 latestentry=templateutil.mappinggenerator(entries, args=(True, True)))
633 633
634 634 @webcommand('bookmarks')
635 635 def bookmarks(web):
636 636 """
637 637 /bookmarks
638 638 ----------
639 639
640 640 Show information about bookmarks.
641 641
642 642 No arguments are accepted.
643 643
644 644 The ``bookmarks`` template is rendered.
645 645 """
646 646 i = [b for b in web.repo._bookmarks.items() if b[1] in web.repo]
647 647 sortkey = lambda b: (web.repo[b[1]].rev(), b[0])
648 648 i = sorted(i, key=sortkey, reverse=True)
649 649 parity = paritygen(web.stripecount)
650 650
651 651 def entries(context, latestonly):
652 652 t = i
653 653 if latestonly:
654 654 t = i[:1]
655 655 for k, n in t:
656 656 yield {"parity": next(parity),
657 657 "bookmark": k,
658 658 "date": web.repo[n].date(),
659 659 "node": hex(n)}
660 660
661 661 if i:
662 662 latestrev = i[0][1]
663 663 else:
664 664 latestrev = -1
665 665 lastdate = web.repo[latestrev].date()
666 666
667 667 return web.sendtemplate(
668 668 'bookmarks',
669 669 node=hex(web.repo.changelog.tip()),
670 670 lastchange=templateutil.mappinglist([{'date': lastdate}]),
671 671 entries=templateutil.mappinggenerator(entries, args=(False,)),
672 672 latestentry=templateutil.mappinggenerator(entries, args=(True,)))
673 673
674 674 @webcommand('branches')
675 675 def branches(web):
676 676 """
677 677 /branches
678 678 ---------
679 679
680 680 Show information about branches.
681 681
682 682 All known branches are contained in the output, even closed branches.
683 683
684 684 No arguments are accepted.
685 685
686 686 The ``branches`` template is rendered.
687 687 """
688 688 entries = webutil.branchentries(web.repo, web.stripecount)
689 689 latestentry = webutil.branchentries(web.repo, web.stripecount, 1)
690 690
691 691 return web.sendtemplate(
692 692 'branches',
693 693 node=hex(web.repo.changelog.tip()),
694 694 entries=entries,
695 695 latestentry=latestentry)
696 696
697 697 @webcommand('summary')
698 698 def summary(web):
699 699 """
700 700 /summary
701 701 --------
702 702
703 703 Show a summary of repository state.
704 704
705 705 Information about the latest changesets, bookmarks, tags, and branches
706 706 is captured by this handler.
707 707
708 708 The ``summary`` template is rendered.
709 709 """
710 710 i = reversed(web.repo.tagslist())
711 711
712 712 def tagentries(context):
713 713 parity = paritygen(web.stripecount)
714 714 count = 0
715 715 for k, n in i:
716 716 if k == "tip": # skip tip
717 717 continue
718 718
719 719 count += 1
720 720 if count > 10: # limit to 10 tags
721 721 break
722 722
723 723 yield {
724 724 'parity': next(parity),
725 725 'tag': k,
726 726 'node': hex(n),
727 727 'date': web.repo[n].date(),
728 728 }
729 729
730 730 def bookmarks(context):
731 731 parity = paritygen(web.stripecount)
732 732 marks = [b for b in web.repo._bookmarks.items() if b[1] in web.repo]
733 733 sortkey = lambda b: (web.repo[b[1]].rev(), b[0])
734 734 marks = sorted(marks, key=sortkey, reverse=True)
735 735 for k, n in marks[:10]: # limit to 10 bookmarks
736 736 yield {'parity': next(parity),
737 737 'bookmark': k,
738 738 'date': web.repo[n].date(),
739 739 'node': hex(n)}
740 740
741 741 def changelist(context):
742 742 parity = paritygen(web.stripecount, offset=start - end)
743 743 l = [] # build a list in forward order for efficiency
744 744 revs = []
745 745 if start < end:
746 746 revs = web.repo.changelog.revs(start, end - 1)
747 747 for i in revs:
748 748 ctx = web.repo[i]
749 749 lm = webutil.commonentry(web.repo, ctx)
750 750 lm['parity'] = next(parity)
751 751 l.append(lm)
752 752
753 753 for entry in reversed(l):
754 754 yield entry
755 755
756 756 tip = web.repo['tip']
757 757 count = len(web.repo)
758 758 start = max(0, count - web.maxchanges)
759 759 end = min(count, start + web.maxchanges)
760 760
761 761 desc = web.config("web", "description")
762 762 if not desc:
763 763 desc = 'unknown'
764 764 labels = web.configlist('web', 'labels')
765 765
766 766 return web.sendtemplate(
767 767 'summary',
768 768 desc=desc,
769 769 owner=get_contact(web.config) or 'unknown',
770 770 lastchange=tip.date(),
771 771 tags=templateutil.mappinggenerator(tagentries, name='tagentry'),
772 772 bookmarks=templateutil.mappinggenerator(bookmarks),
773 773 branches=webutil.branchentries(web.repo, web.stripecount, 10),
774 774 shortlog=templateutil.mappinggenerator(changelist,
775 775 name='shortlogentry'),
776 776 node=tip.hex(),
777 777 symrev='tip',
778 778 archives=web.archivelist('tip'),
779 779 labels=templateutil.hybridlist(labels, name='label'))
780 780
781 781 @webcommand('filediff')
782 782 def filediff(web):
783 783 """
784 784 /diff/{revision}/{path}
785 785 -----------------------
786 786
787 787 Show how a file changed in a particular commit.
788 788
789 789 The ``filediff`` template is rendered.
790 790
791 791 This handler is registered under both the ``/diff`` and ``/filediff``
792 792 paths. ``/diff`` is used in modern code.
793 793 """
794 794 fctx, ctx = None, None
795 795 try:
796 796 fctx = webutil.filectx(web.repo, web.req)
797 797 except LookupError:
798 798 ctx = webutil.changectx(web.repo, web.req)
799 799 path = webutil.cleanpath(web.repo, web.req.qsparams['file'])
800 800 if path not in ctx.files():
801 801 raise
802 802
803 803 if fctx is not None:
804 804 path = fctx.path()
805 805 ctx = fctx.changectx()
806 806 basectx = ctx.p1()
807 807
808 808 style = web.config('web', 'style')
809 809 if 'style' in web.req.qsparams:
810 810 style = web.req.qsparams['style']
811 811
812 812 diffs = webutil.diffs(web, ctx, basectx, [path], style)
813 813 if fctx is not None:
814 814 rename = webutil.renamelink(fctx)
815 815 ctx = fctx
816 816 else:
817 817 rename = templateutil.mappinglist([])
818 818 ctx = ctx
819 819
820 820 return web.sendtemplate(
821 821 'filediff',
822 822 file=path,
823 823 symrev=webutil.symrevorshortnode(web.req, ctx),
824 824 rename=rename,
825 825 diff=diffs,
826 826 **pycompat.strkwargs(webutil.commonentry(web.repo, ctx)))
827 827
828 828 diff = webcommand('diff')(filediff)
829 829
830 830 @webcommand('comparison')
831 831 def comparison(web):
832 832 """
833 833 /comparison/{revision}/{path}
834 834 -----------------------------
835 835
836 836 Show a comparison between the old and new versions of a file from changes
837 837 made on a particular revision.
838 838
839 839 This is similar to the ``diff`` handler. However, this form features
840 840 a split or side-by-side diff rather than a unified diff.
841 841
842 842 The ``context`` query string argument can be used to control the lines of
843 843 context in the diff.
844 844
845 845 The ``filecomparison`` template is rendered.
846 846 """
847 847 ctx = webutil.changectx(web.repo, web.req)
848 848 if 'file' not in web.req.qsparams:
849 849 raise ErrorResponse(HTTP_NOT_FOUND, 'file not given')
850 850 path = webutil.cleanpath(web.repo, web.req.qsparams['file'])
851 851
852 852 parsecontext = lambda v: v == 'full' and -1 or int(v)
853 853 if 'context' in web.req.qsparams:
854 854 context = parsecontext(web.req.qsparams['context'])
855 855 else:
856 856 context = parsecontext(web.config('web', 'comparisoncontext', '5'))
857 857
858 858 def filelines(f):
859 859 if f.isbinary():
860 860 mt = mimetypes.guess_type(f.path())[0]
861 861 if not mt:
862 862 mt = 'application/octet-stream'
863 863 return [_('(binary file %s, hash: %s)') % (mt, hex(f.filenode()))]
864 864 return f.data().splitlines()
865 865
866 866 fctx = None
867 867 parent = ctx.p1()
868 868 leftrev = parent.rev()
869 869 leftnode = parent.node()
870 870 rightrev = ctx.rev()
871 871 rightnode = ctx.node()
872 872 if path in ctx:
873 873 fctx = ctx[path]
874 874 rightlines = filelines(fctx)
875 875 if path not in parent:
876 876 leftlines = ()
877 877 else:
878 878 pfctx = parent[path]
879 879 leftlines = filelines(pfctx)
880 880 else:
881 881 rightlines = ()
882 882 pfctx = ctx.parents()[0][path]
883 883 leftlines = filelines(pfctx)
884 884
885 885 comparison = webutil.compare(context, leftlines, rightlines)
886 886 if fctx is not None:
887 887 rename = webutil.renamelink(fctx)
888 888 ctx = fctx
889 889 else:
890 890 rename = templateutil.mappinglist([])
891 891 ctx = ctx
892 892
893 893 return web.sendtemplate(
894 894 'filecomparison',
895 895 file=path,
896 896 symrev=webutil.symrevorshortnode(web.req, ctx),
897 897 rename=rename,
898 898 leftrev=leftrev,
899 899 leftnode=hex(leftnode),
900 900 rightrev=rightrev,
901 901 rightnode=hex(rightnode),
902 902 comparison=comparison,
903 903 **pycompat.strkwargs(webutil.commonentry(web.repo, ctx)))
904 904
905 905 @webcommand('annotate')
906 906 def annotate(web):
907 907 """
908 908 /annotate/{revision}/{path}
909 909 ---------------------------
910 910
911 911 Show changeset information for each line in a file.
912 912
913 913 The ``ignorews``, ``ignorewsamount``, ``ignorewseol``, and
914 914 ``ignoreblanklines`` query string arguments have the same meaning as
915 915 their ``[annotate]`` config equivalents. It uses the hgrc boolean
916 916 parsing logic to interpret the value. e.g. ``0`` and ``false`` are
917 917 false and ``1`` and ``true`` are true. If not defined, the server
918 918 default settings are used.
919 919
920 920 The ``fileannotate`` template is rendered.
921 921 """
922 922 fctx = webutil.filectx(web.repo, web.req)
923 923 f = fctx.path()
924 924 parity = paritygen(web.stripecount)
925 925 ishead = fctx.filerev() in fctx.filelog().headrevs()
926 926
927 927 # parents() is called once per line and several lines likely belong to
928 928 # same revision. So it is worth caching.
929 929 # TODO there are still redundant operations within basefilectx.parents()
930 930 # and from the fctx.annotate() call itself that could be cached.
931 931 parentscache = {}
932 932 def parents(context, f):
933 933 rev = f.rev()
934 934 if rev not in parentscache:
935 935 parentscache[rev] = []
936 936 for p in f.parents():
937 937 entry = {
938 938 'node': p.hex(),
939 939 'rev': p.rev(),
940 940 }
941 941 parentscache[rev].append(entry)
942 942
943 943 for p in parentscache[rev]:
944 944 yield p
945 945
946 946 def annotate(context):
947 947 if fctx.isbinary():
948 948 mt = (mimetypes.guess_type(fctx.path())[0]
949 949 or 'application/octet-stream')
950 950 lines = [dagop.annotateline(fctx=fctx.filectx(fctx.filerev()),
951 951 lineno=1, text='(binary:%s)' % mt)]
952 952 else:
953 953 lines = webutil.annotate(web.req, fctx, web.repo.ui)
954 954
955 955 previousrev = None
956 956 blockparitygen = paritygen(1)
957 957 for lineno, aline in enumerate(lines):
958 958 f = aline.fctx
959 959 rev = f.rev()
960 960 if rev != previousrev:
961 961 blockhead = True
962 962 blockparity = next(blockparitygen)
963 963 else:
964 964 blockhead = None
965 965 previousrev = rev
966 966 yield {"parity": next(parity),
967 967 "node": f.hex(),
968 968 "rev": rev,
969 969 "author": f.user(),
970 970 "parents": templateutil.mappinggenerator(parents, args=(f,)),
971 971 "desc": f.description(),
972 972 "extra": f.extra(),
973 973 "file": f.path(),
974 974 "blockhead": blockhead,
975 975 "blockparity": blockparity,
976 976 "targetline": aline.lineno,
977 977 "line": aline.text,
978 978 "lineno": lineno + 1,
979 979 "lineid": "l%d" % (lineno + 1),
980 980 "linenumber": "% 6d" % (lineno + 1),
981 981 "revdate": f.date()}
982 982
983 983 diffopts = webutil.difffeatureopts(web.req, web.repo.ui, 'annotate')
984 984 diffopts = {k: getattr(diffopts, k) for k in diffopts.defaults}
985 985
986 986 return web.sendtemplate(
987 987 'fileannotate',
988 988 file=f,
989 989 annotate=templateutil.mappinggenerator(annotate),
990 990 path=webutil.up(f),
991 991 symrev=webutil.symrevorshortnode(web.req, fctx),
992 992 rename=webutil.renamelink(fctx),
993 993 permissions=fctx.manifest().flags(f),
994 994 ishead=int(ishead),
995 995 diffopts=templateutil.hybriddict(diffopts),
996 996 **pycompat.strkwargs(webutil.commonentry(web.repo, fctx)))
997 997
998 998 @webcommand('filelog')
999 999 def filelog(web):
1000 1000 """
1001 1001 /filelog/{revision}/{path}
1002 1002 --------------------------
1003 1003
1004 1004 Show information about the history of a file in the repository.
1005 1005
1006 1006 The ``revcount`` query string argument can be defined to control the
1007 1007 maximum number of entries to show.
1008 1008
1009 1009 The ``filelog`` template will be rendered.
1010 1010 """
1011 1011
1012 1012 try:
1013 1013 fctx = webutil.filectx(web.repo, web.req)
1014 1014 f = fctx.path()
1015 1015 fl = fctx.filelog()
1016 1016 except error.LookupError:
1017 1017 f = webutil.cleanpath(web.repo, web.req.qsparams['file'])
1018 1018 fl = web.repo.file(f)
1019 1019 numrevs = len(fl)
1020 1020 if not numrevs: # file doesn't exist at all
1021 1021 raise
1022 1022 rev = webutil.changectx(web.repo, web.req).rev()
1023 1023 first = fl.linkrev(0)
1024 1024 if rev < first: # current rev is from before file existed
1025 1025 raise
1026 1026 frev = numrevs - 1
1027 1027 while fl.linkrev(frev) > rev:
1028 1028 frev -= 1
1029 1029 fctx = web.repo.filectx(f, fl.linkrev(frev))
1030 1030
1031 1031 revcount = web.maxshortchanges
1032 1032 if 'revcount' in web.req.qsparams:
1033 1033 try:
1034 1034 revcount = int(web.req.qsparams.get('revcount', revcount))
1035 1035 revcount = max(revcount, 1)
1036 1036 web.tmpl.defaults['sessionvars']['revcount'] = revcount
1037 1037 except ValueError:
1038 1038 pass
1039 1039
1040 1040 lrange = webutil.linerange(web.req)
1041 1041
1042 1042 lessvars = copy.copy(web.tmpl.defaults['sessionvars'])
1043 1043 lessvars['revcount'] = max(revcount // 2, 1)
1044 1044 morevars = copy.copy(web.tmpl.defaults['sessionvars'])
1045 1045 morevars['revcount'] = revcount * 2
1046 1046
1047 1047 patch = 'patch' in web.req.qsparams
1048 1048 if patch:
1049 1049 lessvars['patch'] = morevars['patch'] = web.req.qsparams['patch']
1050 1050 descend = 'descend' in web.req.qsparams
1051 1051 if descend:
1052 1052 lessvars['descend'] = morevars['descend'] = web.req.qsparams['descend']
1053 1053
1054 1054 count = fctx.filerev() + 1
1055 1055 start = max(0, count - revcount) # first rev on this page
1056 1056 end = min(count, start + revcount) # last rev on this page
1057 1057 parity = paritygen(web.stripecount, offset=start - end)
1058 1058
1059 1059 repo = web.repo
1060 1060 filelog = fctx.filelog()
1061 1061 revs = [filerev for filerev in filelog.revs(start, end - 1)
1062 1062 if filelog.linkrev(filerev) in repo]
1063 1063 entries = []
1064 1064
1065 1065 diffstyle = web.config('web', 'style')
1066 1066 if 'style' in web.req.qsparams:
1067 1067 diffstyle = web.req.qsparams['style']
1068 1068
1069 1069 def diff(fctx, linerange=None):
1070 1070 ctx = fctx.changectx()
1071 1071 basectx = ctx.p1()
1072 1072 path = fctx.path()
1073 1073 return webutil.diffs(web, ctx, basectx, [path], diffstyle,
1074 1074 linerange=linerange,
1075 1075 lineidprefix='%s-' % ctx.hex()[:12])
1076 1076
1077 1077 linerange = None
1078 1078 if lrange is not None:
1079 1079 linerange = webutil.formatlinerange(*lrange)
1080 1080 # deactivate numeric nav links when linerange is specified as this
1081 1081 # would required a dedicated "revnav" class
1082 1082 nav = templateutil.mappinglist([])
1083 1083 if descend:
1084 1084 it = dagop.blockdescendants(fctx, *lrange)
1085 1085 else:
1086 1086 it = dagop.blockancestors(fctx, *lrange)
1087 1087 for i, (c, lr) in enumerate(it, 1):
1088 1088 diffs = None
1089 1089 if patch:
1090 1090 diffs = diff(c, linerange=lr)
1091 1091 # follow renames accross filtered (not in range) revisions
1092 1092 path = c.path()
1093 entries.append(dict(
1094 parity=next(parity),
1095 filerev=c.rev(),
1096 file=path,
1097 diff=diffs,
1098 linerange=webutil.formatlinerange(*lr),
1099 **pycompat.strkwargs(webutil.commonentry(repo, c))))
1093 lm = webutil.commonentry(repo, c)
1094 lm.update({
1095 'parity': next(parity),
1096 'filerev': c.rev(),
1097 'file': path,
1098 'diff': diffs,
1099 'linerange': webutil.formatlinerange(*lr),
1100 })
1101 entries.append(lm)
1100 1102 if i == revcount:
1101 1103 break
1102 1104 lessvars['linerange'] = webutil.formatlinerange(*lrange)
1103 1105 morevars['linerange'] = lessvars['linerange']
1104 1106 else:
1105 1107 for i in revs:
1106 1108 iterfctx = fctx.filectx(i)
1107 1109 diffs = None
1108 1110 if patch:
1109 1111 diffs = diff(iterfctx)
1110 entries.append(dict(
1111 parity=next(parity),
1112 filerev=i,
1113 file=f,
1114 diff=diffs,
1115 rename=webutil.renamelink(iterfctx),
1116 **pycompat.strkwargs(webutil.commonentry(repo, iterfctx))))
1112 lm = webutil.commonentry(repo, iterfctx)
1113 lm.update({
1114 'parity': next(parity),
1115 'filerev': i,
1116 'file': f,
1117 'diff': diffs,
1118 'rename': webutil.renamelink(iterfctx),
1119 })
1120 entries.append(lm)
1117 1121 entries.reverse()
1118 1122 revnav = webutil.filerevnav(web.repo, fctx.path())
1119 1123 nav = revnav.gen(end - 1, revcount, count)
1120 1124
1121 1125 latestentry = entries[:1]
1122 1126
1123 1127 return web.sendtemplate(
1124 1128 'filelog',
1125 1129 file=f,
1126 1130 nav=nav,
1127 1131 symrev=webutil.symrevorshortnode(web.req, fctx),
1128 1132 entries=entries,
1129 1133 descend=descend,
1130 1134 patch=patch,
1131 1135 latestentry=latestentry,
1132 1136 linerange=linerange,
1133 1137 revcount=revcount,
1134 1138 morevars=morevars,
1135 1139 lessvars=lessvars,
1136 1140 **pycompat.strkwargs(webutil.commonentry(web.repo, fctx)))
1137 1141
1138 1142 @webcommand('archive')
1139 1143 def archive(web):
1140 1144 """
1141 1145 /archive/{revision}.{format}[/{path}]
1142 1146 -------------------------------------
1143 1147
1144 1148 Obtain an archive of repository content.
1145 1149
1146 1150 The content and type of the archive is defined by a URL path parameter.
1147 1151 ``format`` is the file extension of the archive type to be generated. e.g.
1148 1152 ``zip`` or ``tar.bz2``. Not all archive types may be allowed by your
1149 1153 server configuration.
1150 1154
1151 1155 The optional ``path`` URL parameter controls content to include in the
1152 1156 archive. If omitted, every file in the specified revision is present in the
1153 1157 archive. If included, only the specified file or contents of the specified
1154 1158 directory will be included in the archive.
1155 1159
1156 1160 No template is used for this handler. Raw, binary content is generated.
1157 1161 """
1158 1162
1159 1163 type_ = web.req.qsparams.get('type')
1160 1164 allowed = web.configlist("web", "allow_archive")
1161 1165 key = web.req.qsparams['node']
1162 1166
1163 1167 if type_ not in webutil.archivespecs:
1164 1168 msg = 'Unsupported archive type: %s' % type_
1165 1169 raise ErrorResponse(HTTP_NOT_FOUND, msg)
1166 1170
1167 1171 if not ((type_ in allowed or
1168 1172 web.configbool("web", "allow" + type_))):
1169 1173 msg = 'Archive type not allowed: %s' % type_
1170 1174 raise ErrorResponse(HTTP_FORBIDDEN, msg)
1171 1175
1172 1176 reponame = re.sub(br"\W+", "-", os.path.basename(web.reponame))
1173 1177 cnode = web.repo.lookup(key)
1174 1178 arch_version = key
1175 1179 if cnode == key or key == 'tip':
1176 1180 arch_version = short(cnode)
1177 1181 name = "%s-%s" % (reponame, arch_version)
1178 1182
1179 1183 ctx = webutil.changectx(web.repo, web.req)
1180 1184 pats = []
1181 1185 match = scmutil.match(ctx, [])
1182 1186 file = web.req.qsparams.get('file')
1183 1187 if file:
1184 1188 pats = ['path:' + file]
1185 1189 match = scmutil.match(ctx, pats, default='path')
1186 1190 if pats:
1187 1191 files = [f for f in ctx.manifest().keys() if match(f)]
1188 1192 if not files:
1189 1193 raise ErrorResponse(HTTP_NOT_FOUND,
1190 1194 'file(s) not found: %s' % file)
1191 1195
1192 1196 mimetype, artype, extension, encoding = webutil.archivespecs[type_]
1193 1197
1194 1198 web.res.headers['Content-Type'] = mimetype
1195 1199 web.res.headers['Content-Disposition'] = 'attachment; filename=%s%s' % (
1196 1200 name, extension)
1197 1201
1198 1202 if encoding:
1199 1203 web.res.headers['Content-Encoding'] = encoding
1200 1204
1201 1205 web.res.setbodywillwrite()
1202 1206 if list(web.res.sendresponse()):
1203 1207 raise error.ProgrammingError('sendresponse() should not emit data '
1204 1208 'if writing later')
1205 1209
1206 1210 bodyfh = web.res.getbodyfile()
1207 1211
1208 1212 archival.archive(web.repo, bodyfh, cnode, artype, prefix=name,
1209 1213 matchfn=match,
1210 1214 subrepos=web.configbool("web", "archivesubrepos"))
1211 1215
1212 1216 return []
1213 1217
1214 1218 @webcommand('static')
1215 1219 def static(web):
1216 1220 fname = web.req.qsparams['file']
1217 1221 # a repo owner may set web.static in .hg/hgrc to get any file
1218 1222 # readable by the user running the CGI script
1219 1223 static = web.config("web", "static", None, untrusted=False)
1220 1224 if not static:
1221 1225 tp = web.templatepath or templater.templatepaths()
1222 1226 if isinstance(tp, str):
1223 1227 tp = [tp]
1224 1228 static = [os.path.join(p, 'static') for p in tp]
1225 1229
1226 1230 staticfile(static, fname, web.res)
1227 1231 return web.res.sendresponse()
1228 1232
1229 1233 @webcommand('graph')
1230 1234 def graph(web):
1231 1235 """
1232 1236 /graph[/{revision}]
1233 1237 -------------------
1234 1238
1235 1239 Show information about the graphical topology of the repository.
1236 1240
1237 1241 Information rendered by this handler can be used to create visual
1238 1242 representations of repository topology.
1239 1243
1240 1244 The ``revision`` URL parameter controls the starting changeset. If it's
1241 1245 absent, the default is ``tip``.
1242 1246
1243 1247 The ``revcount`` query string argument can define the number of changesets
1244 1248 to show information for.
1245 1249
1246 1250 The ``graphtop`` query string argument can specify the starting changeset
1247 1251 for producing ``jsdata`` variable that is used for rendering graph in
1248 1252 JavaScript. By default it has the same value as ``revision``.
1249 1253
1250 1254 This handler will render the ``graph`` template.
1251 1255 """
1252 1256
1253 1257 if 'node' in web.req.qsparams:
1254 1258 ctx = webutil.changectx(web.repo, web.req)
1255 1259 symrev = webutil.symrevorshortnode(web.req, ctx)
1256 1260 else:
1257 1261 ctx = web.repo['tip']
1258 1262 symrev = 'tip'
1259 1263 rev = ctx.rev()
1260 1264
1261 1265 bg_height = 39
1262 1266 revcount = web.maxshortchanges
1263 1267 if 'revcount' in web.req.qsparams:
1264 1268 try:
1265 1269 revcount = int(web.req.qsparams.get('revcount', revcount))
1266 1270 revcount = max(revcount, 1)
1267 1271 web.tmpl.defaults['sessionvars']['revcount'] = revcount
1268 1272 except ValueError:
1269 1273 pass
1270 1274
1271 1275 lessvars = copy.copy(web.tmpl.defaults['sessionvars'])
1272 1276 lessvars['revcount'] = max(revcount // 2, 1)
1273 1277 morevars = copy.copy(web.tmpl.defaults['sessionvars'])
1274 1278 morevars['revcount'] = revcount * 2
1275 1279
1276 1280 graphtop = web.req.qsparams.get('graphtop', ctx.hex())
1277 1281 graphvars = copy.copy(web.tmpl.defaults['sessionvars'])
1278 1282 graphvars['graphtop'] = graphtop
1279 1283
1280 1284 count = len(web.repo)
1281 1285 pos = rev
1282 1286
1283 1287 uprev = min(max(0, count - 1), rev + revcount)
1284 1288 downrev = max(0, rev - revcount)
1285 1289 changenav = webutil.revnav(web.repo).gen(pos, revcount, count)
1286 1290
1287 1291 tree = []
1288 1292 nextentry = []
1289 1293 lastrev = 0
1290 1294 if pos != -1:
1291 1295 allrevs = web.repo.changelog.revs(pos, 0)
1292 1296 revs = []
1293 1297 for i in allrevs:
1294 1298 revs.append(i)
1295 1299 if len(revs) >= revcount + 1:
1296 1300 break
1297 1301
1298 1302 if len(revs) > revcount:
1299 1303 nextentry = [webutil.commonentry(web.repo, web.repo[revs[-1]])]
1300 1304 revs = revs[:-1]
1301 1305
1302 1306 lastrev = revs[-1]
1303 1307
1304 1308 # We have to feed a baseset to dagwalker as it is expecting smartset
1305 1309 # object. This does not have a big impact on hgweb performance itself
1306 1310 # since hgweb graphing code is not itself lazy yet.
1307 1311 dag = graphmod.dagwalker(web.repo, smartset.baseset(revs))
1308 1312 # As we said one line above... not lazy.
1309 1313 tree = list(item for item in graphmod.colored(dag, web.repo)
1310 1314 if item[1] == graphmod.CHANGESET)
1311 1315
1312 1316 def fulltree():
1313 1317 pos = web.repo[graphtop].rev()
1314 1318 tree = []
1315 1319 if pos != -1:
1316 1320 revs = web.repo.changelog.revs(pos, lastrev)
1317 1321 dag = graphmod.dagwalker(web.repo, smartset.baseset(revs))
1318 1322 tree = list(item for item in graphmod.colored(dag, web.repo)
1319 1323 if item[1] == graphmod.CHANGESET)
1320 1324 return tree
1321 1325
1322 1326 def jsdata():
1323 1327 return [{'node': pycompat.bytestr(ctx),
1324 1328 'graphnode': webutil.getgraphnode(web.repo, ctx),
1325 1329 'vertex': vtx,
1326 1330 'edges': edges}
1327 1331 for (id, type, ctx, vtx, edges) in fulltree()]
1328 1332
1329 1333 def nodes():
1330 1334 parity = paritygen(web.stripecount)
1331 1335 for row, (id, type, ctx, vtx, edges) in enumerate(tree):
1332 1336 entry = webutil.commonentry(web.repo, ctx)
1333 1337 edgedata = [{'col': edge[0],
1334 1338 'nextcol': edge[1],
1335 1339 'color': (edge[2] - 1) % 6 + 1,
1336 1340 'width': edge[3],
1337 1341 'bcolor': edge[4]}
1338 1342 for edge in edges]
1339 1343
1340 1344 entry.update({'col': vtx[0],
1341 1345 'color': (vtx[1] - 1) % 6 + 1,
1342 1346 'parity': next(parity),
1343 1347 'edges': edgedata,
1344 1348 'row': row,
1345 1349 'nextrow': row + 1})
1346 1350
1347 1351 yield entry
1348 1352
1349 1353 rows = len(tree)
1350 1354
1351 1355 return web.sendtemplate(
1352 1356 'graph',
1353 1357 rev=rev,
1354 1358 symrev=symrev,
1355 1359 revcount=revcount,
1356 1360 uprev=uprev,
1357 1361 lessvars=lessvars,
1358 1362 morevars=morevars,
1359 1363 downrev=downrev,
1360 1364 graphvars=graphvars,
1361 1365 rows=rows,
1362 1366 bg_height=bg_height,
1363 1367 changesets=count,
1364 1368 nextentry=nextentry,
1365 1369 jsdata=lambda **x: jsdata(),
1366 1370 nodes=lambda **x: nodes(),
1367 1371 node=ctx.hex(),
1368 1372 changenav=changenav)
1369 1373
1370 1374 def _getdoc(e):
1371 1375 doc = e[0].__doc__
1372 1376 if doc:
1373 1377 doc = _(doc).partition('\n')[0]
1374 1378 else:
1375 1379 doc = _('(no help text available)')
1376 1380 return doc
1377 1381
1378 1382 @webcommand('help')
1379 1383 def help(web):
1380 1384 """
1381 1385 /help[/{topic}]
1382 1386 ---------------
1383 1387
1384 1388 Render help documentation.
1385 1389
1386 1390 This web command is roughly equivalent to :hg:`help`. If a ``topic``
1387 1391 is defined, that help topic will be rendered. If not, an index of
1388 1392 available help topics will be rendered.
1389 1393
1390 1394 The ``help`` template will be rendered when requesting help for a topic.
1391 1395 ``helptopics`` will be rendered for the index of help topics.
1392 1396 """
1393 1397 from .. import commands, help as helpmod # avoid cycle
1394 1398
1395 1399 topicname = web.req.qsparams.get('node')
1396 1400 if not topicname:
1397 1401 def topics(**map):
1398 1402 for entries, summary, _doc in helpmod.helptable:
1399 1403 yield {'topic': entries[0], 'summary': summary}
1400 1404
1401 1405 early, other = [], []
1402 1406 primary = lambda s: s.partition('|')[0]
1403 1407 for c, e in commands.table.iteritems():
1404 1408 doc = _getdoc(e)
1405 1409 if 'DEPRECATED' in doc or c.startswith('debug'):
1406 1410 continue
1407 1411 cmd = primary(c)
1408 1412 if cmd.startswith('^'):
1409 1413 early.append((cmd[1:], doc))
1410 1414 else:
1411 1415 other.append((cmd, doc))
1412 1416
1413 1417 early.sort()
1414 1418 other.sort()
1415 1419
1416 1420 def earlycommands(**map):
1417 1421 for c, doc in early:
1418 1422 yield {'topic': c, 'summary': doc}
1419 1423
1420 1424 def othercommands(**map):
1421 1425 for c, doc in other:
1422 1426 yield {'topic': c, 'summary': doc}
1423 1427
1424 1428 return web.sendtemplate(
1425 1429 'helptopics',
1426 1430 topics=topics,
1427 1431 earlycommands=earlycommands,
1428 1432 othercommands=othercommands,
1429 1433 title='Index')
1430 1434
1431 1435 # Render an index of sub-topics.
1432 1436 if topicname in helpmod.subtopics:
1433 1437 topics = []
1434 1438 for entries, summary, _doc in helpmod.subtopics[topicname]:
1435 1439 topics.append({
1436 1440 'topic': '%s.%s' % (topicname, entries[0]),
1437 1441 'basename': entries[0],
1438 1442 'summary': summary,
1439 1443 })
1440 1444
1441 1445 return web.sendtemplate(
1442 1446 'helptopics',
1443 1447 topics=topics,
1444 1448 title=topicname,
1445 1449 subindex=True)
1446 1450
1447 1451 u = webutil.wsgiui.load()
1448 1452 u.verbose = True
1449 1453
1450 1454 # Render a page from a sub-topic.
1451 1455 if '.' in topicname:
1452 1456 # TODO implement support for rendering sections, like
1453 1457 # `hg help` works.
1454 1458 topic, subtopic = topicname.split('.', 1)
1455 1459 if topic not in helpmod.subtopics:
1456 1460 raise ErrorResponse(HTTP_NOT_FOUND)
1457 1461 else:
1458 1462 topic = topicname
1459 1463 subtopic = None
1460 1464
1461 1465 try:
1462 1466 doc = helpmod.help_(u, commands, topic, subtopic=subtopic)
1463 1467 except error.Abort:
1464 1468 raise ErrorResponse(HTTP_NOT_FOUND)
1465 1469
1466 1470 return web.sendtemplate(
1467 1471 'help',
1468 1472 topic=topicname,
1469 1473 doc=doc)
1470 1474
1471 1475 # tell hggettext to extract docstrings from these functions:
1472 1476 i18nfunctions = commands.values()
General Comments 0
You need to be logged in to leave comments. Login now