##// END OF EJS Templates
annotate: introduce attr for storing per-line annotate data...
Siddharth Agarwal -
r34433:2e32c6a3 default
parent child Browse files
Show More
@@ -1,5491 +1,5491 b''
1 1 # commands.py - command processing for mercurial
2 2 #
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 difflib
11 11 import errno
12 12 import os
13 13 import re
14 14 import sys
15 15
16 16 from .i18n import _
17 17 from .node import (
18 18 hex,
19 19 nullid,
20 20 nullrev,
21 21 short,
22 22 )
23 23 from . import (
24 24 archival,
25 25 bookmarks,
26 26 bundle2,
27 27 changegroup,
28 28 cmdutil,
29 29 copies,
30 30 debugcommands as debugcommandsmod,
31 31 destutil,
32 32 dirstateguard,
33 33 discovery,
34 34 encoding,
35 35 error,
36 36 exchange,
37 37 extensions,
38 38 formatter,
39 39 graphmod,
40 40 hbisect,
41 41 help,
42 42 hg,
43 43 lock as lockmod,
44 44 merge as mergemod,
45 45 obsolete,
46 46 patch,
47 47 phases,
48 48 pycompat,
49 49 rcutil,
50 50 registrar,
51 51 revsetlang,
52 52 scmutil,
53 53 server,
54 54 sshserver,
55 55 streamclone,
56 56 tags as tagsmod,
57 57 templatekw,
58 58 ui as uimod,
59 59 util,
60 60 )
61 61
62 62 release = lockmod.release
63 63
64 64 table = {}
65 65 table.update(debugcommandsmod.command._table)
66 66
67 67 command = registrar.command(table)
68 68
69 69 # common command options
70 70
71 71 globalopts = [
72 72 ('R', 'repository', '',
73 73 _('repository root directory or name of overlay bundle file'),
74 74 _('REPO')),
75 75 ('', 'cwd', '',
76 76 _('change working directory'), _('DIR')),
77 77 ('y', 'noninteractive', None,
78 78 _('do not prompt, automatically pick the first choice for all prompts')),
79 79 ('q', 'quiet', None, _('suppress output')),
80 80 ('v', 'verbose', None, _('enable additional output')),
81 81 ('', 'color', '',
82 82 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
83 83 # and should not be translated
84 84 _("when to colorize (boolean, always, auto, never, or debug)"),
85 85 _('TYPE')),
86 86 ('', 'config', [],
87 87 _('set/override config option (use \'section.name=value\')'),
88 88 _('CONFIG')),
89 89 ('', 'debug', None, _('enable debugging output')),
90 90 ('', 'debugger', None, _('start debugger')),
91 91 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
92 92 _('ENCODE')),
93 93 ('', 'encodingmode', encoding.encodingmode,
94 94 _('set the charset encoding mode'), _('MODE')),
95 95 ('', 'traceback', None, _('always print a traceback on exception')),
96 96 ('', 'time', None, _('time how long the command takes')),
97 97 ('', 'profile', None, _('print command execution profile')),
98 98 ('', 'version', None, _('output version information and exit')),
99 99 ('h', 'help', None, _('display help and exit')),
100 100 ('', 'hidden', False, _('consider hidden changesets')),
101 101 ('', 'pager', 'auto',
102 102 _("when to paginate (boolean, always, auto, or never)"), _('TYPE')),
103 103 ]
104 104
105 105 dryrunopts = cmdutil.dryrunopts
106 106 remoteopts = cmdutil.remoteopts
107 107 walkopts = cmdutil.walkopts
108 108 commitopts = cmdutil.commitopts
109 109 commitopts2 = cmdutil.commitopts2
110 110 formatteropts = cmdutil.formatteropts
111 111 templateopts = cmdutil.templateopts
112 112 logopts = cmdutil.logopts
113 113 diffopts = cmdutil.diffopts
114 114 diffwsopts = cmdutil.diffwsopts
115 115 diffopts2 = cmdutil.diffopts2
116 116 mergetoolopts = cmdutil.mergetoolopts
117 117 similarityopts = cmdutil.similarityopts
118 118 subrepoopts = cmdutil.subrepoopts
119 119 debugrevlogopts = cmdutil.debugrevlogopts
120 120
121 121 # Commands start here, listed alphabetically
122 122
123 123 @command('^add',
124 124 walkopts + subrepoopts + dryrunopts,
125 125 _('[OPTION]... [FILE]...'),
126 126 inferrepo=True)
127 127 def add(ui, repo, *pats, **opts):
128 128 """add the specified files on the next commit
129 129
130 130 Schedule files to be version controlled and added to the
131 131 repository.
132 132
133 133 The files will be added to the repository at the next commit. To
134 134 undo an add before that, see :hg:`forget`.
135 135
136 136 If no names are given, add all files to the repository (except
137 137 files matching ``.hgignore``).
138 138
139 139 .. container:: verbose
140 140
141 141 Examples:
142 142
143 143 - New (unknown) files are added
144 144 automatically by :hg:`add`::
145 145
146 146 $ ls
147 147 foo.c
148 148 $ hg status
149 149 ? foo.c
150 150 $ hg add
151 151 adding foo.c
152 152 $ hg status
153 153 A foo.c
154 154
155 155 - Specific files to be added can be specified::
156 156
157 157 $ ls
158 158 bar.c foo.c
159 159 $ hg status
160 160 ? bar.c
161 161 ? foo.c
162 162 $ hg add bar.c
163 163 $ hg status
164 164 A bar.c
165 165 ? foo.c
166 166
167 167 Returns 0 if all files are successfully added.
168 168 """
169 169
170 170 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
171 171 rejected = cmdutil.add(ui, repo, m, "", False, **opts)
172 172 return rejected and 1 or 0
173 173
174 174 @command('addremove',
175 175 similarityopts + subrepoopts + walkopts + dryrunopts,
176 176 _('[OPTION]... [FILE]...'),
177 177 inferrepo=True)
178 178 def addremove(ui, repo, *pats, **opts):
179 179 """add all new files, delete all missing files
180 180
181 181 Add all new files and remove all missing files from the
182 182 repository.
183 183
184 184 Unless names are given, new files are ignored if they match any of
185 185 the patterns in ``.hgignore``. As with add, these changes take
186 186 effect at the next commit.
187 187
188 188 Use the -s/--similarity option to detect renamed files. This
189 189 option takes a percentage between 0 (disabled) and 100 (files must
190 190 be identical) as its parameter. With a parameter greater than 0,
191 191 this compares every removed file with every added file and records
192 192 those similar enough as renames. Detecting renamed files this way
193 193 can be expensive. After using this option, :hg:`status -C` can be
194 194 used to check which files were identified as moved or renamed. If
195 195 not specified, -s/--similarity defaults to 100 and only renames of
196 196 identical files are detected.
197 197
198 198 .. container:: verbose
199 199
200 200 Examples:
201 201
202 202 - A number of files (bar.c and foo.c) are new,
203 203 while foobar.c has been removed (without using :hg:`remove`)
204 204 from the repository::
205 205
206 206 $ ls
207 207 bar.c foo.c
208 208 $ hg status
209 209 ! foobar.c
210 210 ? bar.c
211 211 ? foo.c
212 212 $ hg addremove
213 213 adding bar.c
214 214 adding foo.c
215 215 removing foobar.c
216 216 $ hg status
217 217 A bar.c
218 218 A foo.c
219 219 R foobar.c
220 220
221 221 - A file foobar.c was moved to foo.c without using :hg:`rename`.
222 222 Afterwards, it was edited slightly::
223 223
224 224 $ ls
225 225 foo.c
226 226 $ hg status
227 227 ! foobar.c
228 228 ? foo.c
229 229 $ hg addremove --similarity 90
230 230 removing foobar.c
231 231 adding foo.c
232 232 recording removal of foobar.c as rename to foo.c (94% similar)
233 233 $ hg status -C
234 234 A foo.c
235 235 foobar.c
236 236 R foobar.c
237 237
238 238 Returns 0 if all files are successfully added.
239 239 """
240 240 opts = pycompat.byteskwargs(opts)
241 241 try:
242 242 sim = float(opts.get('similarity') or 100)
243 243 except ValueError:
244 244 raise error.Abort(_('similarity must be a number'))
245 245 if sim < 0 or sim > 100:
246 246 raise error.Abort(_('similarity must be between 0 and 100'))
247 247 matcher = scmutil.match(repo[None], pats, opts)
248 248 return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
249 249
250 250 @command('^annotate|blame',
251 251 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
252 252 ('', 'follow', None,
253 253 _('follow copies/renames and list the filename (DEPRECATED)')),
254 254 ('', 'no-follow', None, _("don't follow copies and renames")),
255 255 ('a', 'text', None, _('treat all files as text')),
256 256 ('u', 'user', None, _('list the author (long with -v)')),
257 257 ('f', 'file', None, _('list the filename')),
258 258 ('d', 'date', None, _('list the date (short with -q)')),
259 259 ('n', 'number', None, _('list the revision number (default)')),
260 260 ('c', 'changeset', None, _('list the changeset')),
261 261 ('l', 'line-number', None, _('show line number at the first appearance')),
262 262 ('', 'skip', [], _('revision to not display (EXPERIMENTAL)'), _('REV')),
263 263 ] + diffwsopts + walkopts + formatteropts,
264 264 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
265 265 inferrepo=True)
266 266 def annotate(ui, repo, *pats, **opts):
267 267 """show changeset information by line for each file
268 268
269 269 List changes in files, showing the revision id responsible for
270 270 each line.
271 271
272 272 This command is useful for discovering when a change was made and
273 273 by whom.
274 274
275 275 If you include --file, --user, or --date, the revision number is
276 276 suppressed unless you also include --number.
277 277
278 278 Without the -a/--text option, annotate will avoid processing files
279 279 it detects as binary. With -a, annotate will annotate the file
280 280 anyway, although the results will probably be neither useful
281 281 nor desirable.
282 282
283 283 Returns 0 on success.
284 284 """
285 285 opts = pycompat.byteskwargs(opts)
286 286 if not pats:
287 287 raise error.Abort(_('at least one filename or pattern is required'))
288 288
289 289 if opts.get('follow'):
290 290 # --follow is deprecated and now just an alias for -f/--file
291 291 # to mimic the behavior of Mercurial before version 1.5
292 292 opts['file'] = True
293 293
294 294 ctx = scmutil.revsingle(repo, opts.get('rev'))
295 295
296 296 rootfm = ui.formatter('annotate', opts)
297 297 if ui.quiet:
298 298 datefunc = util.shortdate
299 299 else:
300 300 datefunc = util.datestr
301 301 if ctx.rev() is None:
302 302 def hexfn(node):
303 303 if node is None:
304 304 return None
305 305 else:
306 306 return rootfm.hexfunc(node)
307 307 if opts.get('changeset'):
308 308 # omit "+" suffix which is appended to node hex
309 309 def formatrev(rev):
310 310 if rev is None:
311 311 return '%d' % ctx.p1().rev()
312 312 else:
313 313 return '%d' % rev
314 314 else:
315 315 def formatrev(rev):
316 316 if rev is None:
317 317 return '%d+' % ctx.p1().rev()
318 318 else:
319 319 return '%d ' % rev
320 320 def formathex(hex):
321 321 if hex is None:
322 322 return '%s+' % rootfm.hexfunc(ctx.p1().node())
323 323 else:
324 324 return '%s ' % hex
325 325 else:
326 326 hexfn = rootfm.hexfunc
327 327 formatrev = formathex = pycompat.bytestr
328 328
329 opmap = [('user', ' ', lambda x: x[0].user(), ui.shortuser),
330 ('number', ' ', lambda x: x[0].rev(), formatrev),
331 ('changeset', ' ', lambda x: hexfn(x[0].node()), formathex),
332 ('date', ' ', lambda x: x[0].date(), util.cachefunc(datefunc)),
333 ('file', ' ', lambda x: x[0].path(), str),
334 ('line_number', ':', lambda x: x[1], str),
329 opmap = [('user', ' ', lambda x: x.fctx.user(), ui.shortuser),
330 ('number', ' ', lambda x: x.fctx.rev(), formatrev),
331 ('changeset', ' ', lambda x: hexfn(x.fctx.node()), formathex),
332 ('date', ' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
333 ('file', ' ', lambda x: x.fctx.path(), str),
334 ('line_number', ':', lambda x: x.lineno, str),
335 335 ]
336 336 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
337 337
338 338 if (not opts.get('user') and not opts.get('changeset')
339 339 and not opts.get('date') and not opts.get('file')):
340 340 opts['number'] = True
341 341
342 342 linenumber = opts.get('line_number') is not None
343 343 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
344 344 raise error.Abort(_('at least one of -n/-c is required for -l'))
345 345
346 346 ui.pager('annotate')
347 347
348 348 if rootfm.isplain():
349 349 def makefunc(get, fmt):
350 350 return lambda x: fmt(get(x))
351 351 else:
352 352 def makefunc(get, fmt):
353 353 return get
354 354 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
355 355 if opts.get(op)]
356 356 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
357 357 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
358 358 if opts.get(op))
359 359
360 360 def bad(x, y):
361 361 raise error.Abort("%s: %s" % (x, y))
362 362
363 363 m = scmutil.match(ctx, pats, opts, badfn=bad)
364 364
365 365 follow = not opts.get('no_follow')
366 366 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
367 367 whitespace=True)
368 368 skiprevs = opts.get('skip')
369 369 if skiprevs:
370 370 skiprevs = scmutil.revrange(repo, skiprevs)
371 371
372 372 for abs in ctx.walk(m):
373 373 fctx = ctx[abs]
374 374 rootfm.startitem()
375 375 rootfm.data(abspath=abs, path=m.rel(abs))
376 376 if not opts.get('text') and fctx.isbinary():
377 377 rootfm.plain(_("%s: binary file\n")
378 378 % ((pats and m.rel(abs)) or abs))
379 379 continue
380 380
381 381 fm = rootfm.nested('lines')
382 382 lines = fctx.annotate(follow=follow, linenumber=linenumber,
383 383 skiprevs=skiprevs, diffopts=diffopts)
384 384 if not lines:
385 385 fm.end()
386 386 continue
387 387 formats = []
388 388 pieces = []
389 389
390 390 for f, sep in funcmap:
391 391 l = [f(n) for n, dummy in lines]
392 392 if fm.isplain():
393 393 sizes = [encoding.colwidth(x) for x in l]
394 394 ml = max(sizes)
395 395 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
396 396 else:
397 397 formats.append(['%s' for x in l])
398 398 pieces.append(l)
399 399
400 400 for f, p, l in zip(zip(*formats), zip(*pieces), lines):
401 401 fm.startitem()
402 402 fm.write(fields, "".join(f), *p)
403 403 fm.write('line', ": %s", l[1])
404 404
405 405 if not lines[-1][1].endswith('\n'):
406 406 fm.plain('\n')
407 407 fm.end()
408 408
409 409 rootfm.end()
410 410
411 411 @command('archive',
412 412 [('', 'no-decode', None, _('do not pass files through decoders')),
413 413 ('p', 'prefix', '', _('directory prefix for files in archive'),
414 414 _('PREFIX')),
415 415 ('r', 'rev', '', _('revision to distribute'), _('REV')),
416 416 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
417 417 ] + subrepoopts + walkopts,
418 418 _('[OPTION]... DEST'))
419 419 def archive(ui, repo, dest, **opts):
420 420 '''create an unversioned archive of a repository revision
421 421
422 422 By default, the revision used is the parent of the working
423 423 directory; use -r/--rev to specify a different revision.
424 424
425 425 The archive type is automatically detected based on file
426 426 extension (to override, use -t/--type).
427 427
428 428 .. container:: verbose
429 429
430 430 Examples:
431 431
432 432 - create a zip file containing the 1.0 release::
433 433
434 434 hg archive -r 1.0 project-1.0.zip
435 435
436 436 - create a tarball excluding .hg files::
437 437
438 438 hg archive project.tar.gz -X ".hg*"
439 439
440 440 Valid types are:
441 441
442 442 :``files``: a directory full of files (default)
443 443 :``tar``: tar archive, uncompressed
444 444 :``tbz2``: tar archive, compressed using bzip2
445 445 :``tgz``: tar archive, compressed using gzip
446 446 :``uzip``: zip archive, uncompressed
447 447 :``zip``: zip archive, compressed using deflate
448 448
449 449 The exact name of the destination archive or directory is given
450 450 using a format string; see :hg:`help export` for details.
451 451
452 452 Each member added to an archive file has a directory prefix
453 453 prepended. Use -p/--prefix to specify a format string for the
454 454 prefix. The default is the basename of the archive, with suffixes
455 455 removed.
456 456
457 457 Returns 0 on success.
458 458 '''
459 459
460 460 opts = pycompat.byteskwargs(opts)
461 461 ctx = scmutil.revsingle(repo, opts.get('rev'))
462 462 if not ctx:
463 463 raise error.Abort(_('no working directory: please specify a revision'))
464 464 node = ctx.node()
465 465 dest = cmdutil.makefilename(repo, dest, node)
466 466 if os.path.realpath(dest) == repo.root:
467 467 raise error.Abort(_('repository root cannot be destination'))
468 468
469 469 kind = opts.get('type') or archival.guesskind(dest) or 'files'
470 470 prefix = opts.get('prefix')
471 471
472 472 if dest == '-':
473 473 if kind == 'files':
474 474 raise error.Abort(_('cannot archive plain files to stdout'))
475 475 dest = cmdutil.makefileobj(repo, dest)
476 476 if not prefix:
477 477 prefix = os.path.basename(repo.root) + '-%h'
478 478
479 479 prefix = cmdutil.makefilename(repo, prefix, node)
480 480 match = scmutil.match(ctx, [], opts)
481 481 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
482 482 match, prefix, subrepos=opts.get('subrepos'))
483 483
484 484 @command('backout',
485 485 [('', 'merge', None, _('merge with old dirstate parent after backout')),
486 486 ('', 'commit', None,
487 487 _('commit if no conflicts were encountered (DEPRECATED)')),
488 488 ('', 'no-commit', None, _('do not commit')),
489 489 ('', 'parent', '',
490 490 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
491 491 ('r', 'rev', '', _('revision to backout'), _('REV')),
492 492 ('e', 'edit', False, _('invoke editor on commit messages')),
493 493 ] + mergetoolopts + walkopts + commitopts + commitopts2,
494 494 _('[OPTION]... [-r] REV'))
495 495 def backout(ui, repo, node=None, rev=None, **opts):
496 496 '''reverse effect of earlier changeset
497 497
498 498 Prepare a new changeset with the effect of REV undone in the
499 499 current working directory. If no conflicts were encountered,
500 500 it will be committed immediately.
501 501
502 502 If REV is the parent of the working directory, then this new changeset
503 503 is committed automatically (unless --no-commit is specified).
504 504
505 505 .. note::
506 506
507 507 :hg:`backout` cannot be used to fix either an unwanted or
508 508 incorrect merge.
509 509
510 510 .. container:: verbose
511 511
512 512 Examples:
513 513
514 514 - Reverse the effect of the parent of the working directory.
515 515 This backout will be committed immediately::
516 516
517 517 hg backout -r .
518 518
519 519 - Reverse the effect of previous bad revision 23::
520 520
521 521 hg backout -r 23
522 522
523 523 - Reverse the effect of previous bad revision 23 and
524 524 leave changes uncommitted::
525 525
526 526 hg backout -r 23 --no-commit
527 527 hg commit -m "Backout revision 23"
528 528
529 529 By default, the pending changeset will have one parent,
530 530 maintaining a linear history. With --merge, the pending
531 531 changeset will instead have two parents: the old parent of the
532 532 working directory and a new child of REV that simply undoes REV.
533 533
534 534 Before version 1.7, the behavior without --merge was equivalent
535 535 to specifying --merge followed by :hg:`update --clean .` to
536 536 cancel the merge and leave the child of REV as a head to be
537 537 merged separately.
538 538
539 539 See :hg:`help dates` for a list of formats valid for -d/--date.
540 540
541 541 See :hg:`help revert` for a way to restore files to the state
542 542 of another revision.
543 543
544 544 Returns 0 on success, 1 if nothing to backout or there are unresolved
545 545 files.
546 546 '''
547 547 wlock = lock = None
548 548 try:
549 549 wlock = repo.wlock()
550 550 lock = repo.lock()
551 551 return _dobackout(ui, repo, node, rev, **opts)
552 552 finally:
553 553 release(lock, wlock)
554 554
555 555 def _dobackout(ui, repo, node=None, rev=None, **opts):
556 556 opts = pycompat.byteskwargs(opts)
557 557 if opts.get('commit') and opts.get('no_commit'):
558 558 raise error.Abort(_("cannot use --commit with --no-commit"))
559 559 if opts.get('merge') and opts.get('no_commit'):
560 560 raise error.Abort(_("cannot use --merge with --no-commit"))
561 561
562 562 if rev and node:
563 563 raise error.Abort(_("please specify just one revision"))
564 564
565 565 if not rev:
566 566 rev = node
567 567
568 568 if not rev:
569 569 raise error.Abort(_("please specify a revision to backout"))
570 570
571 571 date = opts.get('date')
572 572 if date:
573 573 opts['date'] = util.parsedate(date)
574 574
575 575 cmdutil.checkunfinished(repo)
576 576 cmdutil.bailifchanged(repo)
577 577 node = scmutil.revsingle(repo, rev).node()
578 578
579 579 op1, op2 = repo.dirstate.parents()
580 580 if not repo.changelog.isancestor(node, op1):
581 581 raise error.Abort(_('cannot backout change that is not an ancestor'))
582 582
583 583 p1, p2 = repo.changelog.parents(node)
584 584 if p1 == nullid:
585 585 raise error.Abort(_('cannot backout a change with no parents'))
586 586 if p2 != nullid:
587 587 if not opts.get('parent'):
588 588 raise error.Abort(_('cannot backout a merge changeset'))
589 589 p = repo.lookup(opts['parent'])
590 590 if p not in (p1, p2):
591 591 raise error.Abort(_('%s is not a parent of %s') %
592 592 (short(p), short(node)))
593 593 parent = p
594 594 else:
595 595 if opts.get('parent'):
596 596 raise error.Abort(_('cannot use --parent on non-merge changeset'))
597 597 parent = p1
598 598
599 599 # the backout should appear on the same branch
600 600 branch = repo.dirstate.branch()
601 601 bheads = repo.branchheads(branch)
602 602 rctx = scmutil.revsingle(repo, hex(parent))
603 603 if not opts.get('merge') and op1 != node:
604 604 dsguard = dirstateguard.dirstateguard(repo, 'backout')
605 605 try:
606 606 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
607 607 'backout')
608 608 stats = mergemod.update(repo, parent, True, True, node, False)
609 609 repo.setparents(op1, op2)
610 610 dsguard.close()
611 611 hg._showstats(repo, stats)
612 612 if stats[3]:
613 613 repo.ui.status(_("use 'hg resolve' to retry unresolved "
614 614 "file merges\n"))
615 615 return 1
616 616 finally:
617 617 ui.setconfig('ui', 'forcemerge', '', '')
618 618 lockmod.release(dsguard)
619 619 else:
620 620 hg.clean(repo, node, show_stats=False)
621 621 repo.dirstate.setbranch(branch)
622 622 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
623 623
624 624 if opts.get('no_commit'):
625 625 msg = _("changeset %s backed out, "
626 626 "don't forget to commit.\n")
627 627 ui.status(msg % short(node))
628 628 return 0
629 629
630 630 def commitfunc(ui, repo, message, match, opts):
631 631 editform = 'backout'
632 632 e = cmdutil.getcommiteditor(editform=editform,
633 633 **pycompat.strkwargs(opts))
634 634 if not message:
635 635 # we don't translate commit messages
636 636 message = "Backed out changeset %s" % short(node)
637 637 e = cmdutil.getcommiteditor(edit=True, editform=editform)
638 638 return repo.commit(message, opts.get('user'), opts.get('date'),
639 639 match, editor=e)
640 640 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
641 641 if not newnode:
642 642 ui.status(_("nothing changed\n"))
643 643 return 1
644 644 cmdutil.commitstatus(repo, newnode, branch, bheads)
645 645
646 646 def nice(node):
647 647 return '%d:%s' % (repo.changelog.rev(node), short(node))
648 648 ui.status(_('changeset %s backs out changeset %s\n') %
649 649 (nice(repo.changelog.tip()), nice(node)))
650 650 if opts.get('merge') and op1 != node:
651 651 hg.clean(repo, op1, show_stats=False)
652 652 ui.status(_('merging with changeset %s\n')
653 653 % nice(repo.changelog.tip()))
654 654 try:
655 655 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
656 656 'backout')
657 657 return hg.merge(repo, hex(repo.changelog.tip()))
658 658 finally:
659 659 ui.setconfig('ui', 'forcemerge', '', '')
660 660 return 0
661 661
662 662 @command('bisect',
663 663 [('r', 'reset', False, _('reset bisect state')),
664 664 ('g', 'good', False, _('mark changeset good')),
665 665 ('b', 'bad', False, _('mark changeset bad')),
666 666 ('s', 'skip', False, _('skip testing changeset')),
667 667 ('e', 'extend', False, _('extend the bisect range')),
668 668 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
669 669 ('U', 'noupdate', False, _('do not update to target'))],
670 670 _("[-gbsr] [-U] [-c CMD] [REV]"))
671 671 def bisect(ui, repo, rev=None, extra=None, command=None,
672 672 reset=None, good=None, bad=None, skip=None, extend=None,
673 673 noupdate=None):
674 674 """subdivision search of changesets
675 675
676 676 This command helps to find changesets which introduce problems. To
677 677 use, mark the earliest changeset you know exhibits the problem as
678 678 bad, then mark the latest changeset which is free from the problem
679 679 as good. Bisect will update your working directory to a revision
680 680 for testing (unless the -U/--noupdate option is specified). Once
681 681 you have performed tests, mark the working directory as good or
682 682 bad, and bisect will either update to another candidate changeset
683 683 or announce that it has found the bad revision.
684 684
685 685 As a shortcut, you can also use the revision argument to mark a
686 686 revision as good or bad without checking it out first.
687 687
688 688 If you supply a command, it will be used for automatic bisection.
689 689 The environment variable HG_NODE will contain the ID of the
690 690 changeset being tested. The exit status of the command will be
691 691 used to mark revisions as good or bad: status 0 means good, 125
692 692 means to skip the revision, 127 (command not found) will abort the
693 693 bisection, and any other non-zero exit status means the revision
694 694 is bad.
695 695
696 696 .. container:: verbose
697 697
698 698 Some examples:
699 699
700 700 - start a bisection with known bad revision 34, and good revision 12::
701 701
702 702 hg bisect --bad 34
703 703 hg bisect --good 12
704 704
705 705 - advance the current bisection by marking current revision as good or
706 706 bad::
707 707
708 708 hg bisect --good
709 709 hg bisect --bad
710 710
711 711 - mark the current revision, or a known revision, to be skipped (e.g. if
712 712 that revision is not usable because of another issue)::
713 713
714 714 hg bisect --skip
715 715 hg bisect --skip 23
716 716
717 717 - skip all revisions that do not touch directories ``foo`` or ``bar``::
718 718
719 719 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
720 720
721 721 - forget the current bisection::
722 722
723 723 hg bisect --reset
724 724
725 725 - use 'make && make tests' to automatically find the first broken
726 726 revision::
727 727
728 728 hg bisect --reset
729 729 hg bisect --bad 34
730 730 hg bisect --good 12
731 731 hg bisect --command "make && make tests"
732 732
733 733 - see all changesets whose states are already known in the current
734 734 bisection::
735 735
736 736 hg log -r "bisect(pruned)"
737 737
738 738 - see the changeset currently being bisected (especially useful
739 739 if running with -U/--noupdate)::
740 740
741 741 hg log -r "bisect(current)"
742 742
743 743 - see all changesets that took part in the current bisection::
744 744
745 745 hg log -r "bisect(range)"
746 746
747 747 - you can even get a nice graph::
748 748
749 749 hg log --graph -r "bisect(range)"
750 750
751 751 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
752 752
753 753 Returns 0 on success.
754 754 """
755 755 # backward compatibility
756 756 if rev in "good bad reset init".split():
757 757 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
758 758 cmd, rev, extra = rev, extra, None
759 759 if cmd == "good":
760 760 good = True
761 761 elif cmd == "bad":
762 762 bad = True
763 763 else:
764 764 reset = True
765 765 elif extra:
766 766 raise error.Abort(_('incompatible arguments'))
767 767
768 768 incompatibles = {
769 769 '--bad': bad,
770 770 '--command': bool(command),
771 771 '--extend': extend,
772 772 '--good': good,
773 773 '--reset': reset,
774 774 '--skip': skip,
775 775 }
776 776
777 777 enabled = [x for x in incompatibles if incompatibles[x]]
778 778
779 779 if len(enabled) > 1:
780 780 raise error.Abort(_('%s and %s are incompatible') %
781 781 tuple(sorted(enabled)[0:2]))
782 782
783 783 if reset:
784 784 hbisect.resetstate(repo)
785 785 return
786 786
787 787 state = hbisect.load_state(repo)
788 788
789 789 # update state
790 790 if good or bad or skip:
791 791 if rev:
792 792 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
793 793 else:
794 794 nodes = [repo.lookup('.')]
795 795 if good:
796 796 state['good'] += nodes
797 797 elif bad:
798 798 state['bad'] += nodes
799 799 elif skip:
800 800 state['skip'] += nodes
801 801 hbisect.save_state(repo, state)
802 802 if not (state['good'] and state['bad']):
803 803 return
804 804
805 805 def mayupdate(repo, node, show_stats=True):
806 806 """common used update sequence"""
807 807 if noupdate:
808 808 return
809 809 cmdutil.checkunfinished(repo)
810 810 cmdutil.bailifchanged(repo)
811 811 return hg.clean(repo, node, show_stats=show_stats)
812 812
813 813 displayer = cmdutil.show_changeset(ui, repo, {})
814 814
815 815 if command:
816 816 changesets = 1
817 817 if noupdate:
818 818 try:
819 819 node = state['current'][0]
820 820 except LookupError:
821 821 raise error.Abort(_('current bisect revision is unknown - '
822 822 'start a new bisect to fix'))
823 823 else:
824 824 node, p2 = repo.dirstate.parents()
825 825 if p2 != nullid:
826 826 raise error.Abort(_('current bisect revision is a merge'))
827 827 if rev:
828 828 node = repo[scmutil.revsingle(repo, rev, node)].node()
829 829 try:
830 830 while changesets:
831 831 # update state
832 832 state['current'] = [node]
833 833 hbisect.save_state(repo, state)
834 834 status = ui.system(command, environ={'HG_NODE': hex(node)},
835 835 blockedtag='bisect_check')
836 836 if status == 125:
837 837 transition = "skip"
838 838 elif status == 0:
839 839 transition = "good"
840 840 # status < 0 means process was killed
841 841 elif status == 127:
842 842 raise error.Abort(_("failed to execute %s") % command)
843 843 elif status < 0:
844 844 raise error.Abort(_("%s killed") % command)
845 845 else:
846 846 transition = "bad"
847 847 state[transition].append(node)
848 848 ctx = repo[node]
849 849 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
850 850 hbisect.checkstate(state)
851 851 # bisect
852 852 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
853 853 # update to next check
854 854 node = nodes[0]
855 855 mayupdate(repo, node, show_stats=False)
856 856 finally:
857 857 state['current'] = [node]
858 858 hbisect.save_state(repo, state)
859 859 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
860 860 return
861 861
862 862 hbisect.checkstate(state)
863 863
864 864 # actually bisect
865 865 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
866 866 if extend:
867 867 if not changesets:
868 868 extendnode = hbisect.extendrange(repo, state, nodes, good)
869 869 if extendnode is not None:
870 870 ui.write(_("Extending search to changeset %d:%s\n")
871 871 % (extendnode.rev(), extendnode))
872 872 state['current'] = [extendnode.node()]
873 873 hbisect.save_state(repo, state)
874 874 return mayupdate(repo, extendnode.node())
875 875 raise error.Abort(_("nothing to extend"))
876 876
877 877 if changesets == 0:
878 878 hbisect.printresult(ui, repo, state, displayer, nodes, good)
879 879 else:
880 880 assert len(nodes) == 1 # only a single node can be tested next
881 881 node = nodes[0]
882 882 # compute the approximate number of remaining tests
883 883 tests, size = 0, 2
884 884 while size <= changesets:
885 885 tests, size = tests + 1, size * 2
886 886 rev = repo.changelog.rev(node)
887 887 ui.write(_("Testing changeset %d:%s "
888 888 "(%d changesets remaining, ~%d tests)\n")
889 889 % (rev, short(node), changesets, tests))
890 890 state['current'] = [node]
891 891 hbisect.save_state(repo, state)
892 892 return mayupdate(repo, node)
893 893
894 894 @command('bookmarks|bookmark',
895 895 [('f', 'force', False, _('force')),
896 896 ('r', 'rev', '', _('revision for bookmark action'), _('REV')),
897 897 ('d', 'delete', False, _('delete a given bookmark')),
898 898 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
899 899 ('i', 'inactive', False, _('mark a bookmark inactive')),
900 900 ] + formatteropts,
901 901 _('hg bookmarks [OPTIONS]... [NAME]...'))
902 902 def bookmark(ui, repo, *names, **opts):
903 903 '''create a new bookmark or list existing bookmarks
904 904
905 905 Bookmarks are labels on changesets to help track lines of development.
906 906 Bookmarks are unversioned and can be moved, renamed and deleted.
907 907 Deleting or moving a bookmark has no effect on the associated changesets.
908 908
909 909 Creating or updating to a bookmark causes it to be marked as 'active'.
910 910 The active bookmark is indicated with a '*'.
911 911 When a commit is made, the active bookmark will advance to the new commit.
912 912 A plain :hg:`update` will also advance an active bookmark, if possible.
913 913 Updating away from a bookmark will cause it to be deactivated.
914 914
915 915 Bookmarks can be pushed and pulled between repositories (see
916 916 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
917 917 diverged, a new 'divergent bookmark' of the form 'name@path' will
918 918 be created. Using :hg:`merge` will resolve the divergence.
919 919
920 920 Specifying bookmark as '.' to -m or -d options is equivalent to specifying
921 921 the active bookmark's name.
922 922
923 923 A bookmark named '@' has the special property that :hg:`clone` will
924 924 check it out by default if it exists.
925 925
926 926 .. container:: verbose
927 927
928 928 Examples:
929 929
930 930 - create an active bookmark for a new line of development::
931 931
932 932 hg book new-feature
933 933
934 934 - create an inactive bookmark as a place marker::
935 935
936 936 hg book -i reviewed
937 937
938 938 - create an inactive bookmark on another changeset::
939 939
940 940 hg book -r .^ tested
941 941
942 942 - rename bookmark turkey to dinner::
943 943
944 944 hg book -m turkey dinner
945 945
946 946 - move the '@' bookmark from another branch::
947 947
948 948 hg book -f @
949 949 '''
950 950 force = opts.get(r'force')
951 951 rev = opts.get(r'rev')
952 952 delete = opts.get(r'delete')
953 953 rename = opts.get(r'rename')
954 954 inactive = opts.get(r'inactive')
955 955
956 956 if delete and rename:
957 957 raise error.Abort(_("--delete and --rename are incompatible"))
958 958 if delete and rev:
959 959 raise error.Abort(_("--rev is incompatible with --delete"))
960 960 if rename and rev:
961 961 raise error.Abort(_("--rev is incompatible with --rename"))
962 962 if not names and (delete or rev):
963 963 raise error.Abort(_("bookmark name required"))
964 964
965 965 if delete or rename or names or inactive:
966 966 with repo.wlock(), repo.lock(), repo.transaction('bookmark') as tr:
967 967 if delete:
968 968 names = pycompat.maplist(repo._bookmarks.expandname, names)
969 969 bookmarks.delete(repo, tr, names)
970 970 elif rename:
971 971 if not names:
972 972 raise error.Abort(_("new bookmark name required"))
973 973 elif len(names) > 1:
974 974 raise error.Abort(_("only one new bookmark name allowed"))
975 975 rename = repo._bookmarks.expandname(rename)
976 976 bookmarks.rename(repo, tr, rename, names[0], force, inactive)
977 977 elif names:
978 978 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
979 979 elif inactive:
980 980 if len(repo._bookmarks) == 0:
981 981 ui.status(_("no bookmarks set\n"))
982 982 elif not repo._activebookmark:
983 983 ui.status(_("no active bookmark\n"))
984 984 else:
985 985 bookmarks.deactivate(repo)
986 986 else: # show bookmarks
987 987 bookmarks.printbookmarks(ui, repo, **opts)
988 988
989 989 @command('branch',
990 990 [('f', 'force', None,
991 991 _('set branch name even if it shadows an existing branch')),
992 992 ('C', 'clean', None, _('reset branch name to parent branch name'))],
993 993 _('[-fC] [NAME]'))
994 994 def branch(ui, repo, label=None, **opts):
995 995 """set or show the current branch name
996 996
997 997 .. note::
998 998
999 999 Branch names are permanent and global. Use :hg:`bookmark` to create a
1000 1000 light-weight bookmark instead. See :hg:`help glossary` for more
1001 1001 information about named branches and bookmarks.
1002 1002
1003 1003 With no argument, show the current branch name. With one argument,
1004 1004 set the working directory branch name (the branch will not exist
1005 1005 in the repository until the next commit). Standard practice
1006 1006 recommends that primary development take place on the 'default'
1007 1007 branch.
1008 1008
1009 1009 Unless -f/--force is specified, branch will not let you set a
1010 1010 branch name that already exists.
1011 1011
1012 1012 Use -C/--clean to reset the working directory branch to that of
1013 1013 the parent of the working directory, negating a previous branch
1014 1014 change.
1015 1015
1016 1016 Use the command :hg:`update` to switch to an existing branch. Use
1017 1017 :hg:`commit --close-branch` to mark this branch head as closed.
1018 1018 When all heads of a branch are closed, the branch will be
1019 1019 considered closed.
1020 1020
1021 1021 Returns 0 on success.
1022 1022 """
1023 1023 opts = pycompat.byteskwargs(opts)
1024 1024 if label:
1025 1025 label = label.strip()
1026 1026
1027 1027 if not opts.get('clean') and not label:
1028 1028 ui.write("%s\n" % repo.dirstate.branch())
1029 1029 return
1030 1030
1031 1031 with repo.wlock():
1032 1032 if opts.get('clean'):
1033 1033 label = repo[None].p1().branch()
1034 1034 repo.dirstate.setbranch(label)
1035 1035 ui.status(_('reset working directory to branch %s\n') % label)
1036 1036 elif label:
1037 1037 if not opts.get('force') and label in repo.branchmap():
1038 1038 if label not in [p.branch() for p in repo[None].parents()]:
1039 1039 raise error.Abort(_('a branch of the same name already'
1040 1040 ' exists'),
1041 1041 # i18n: "it" refers to an existing branch
1042 1042 hint=_("use 'hg update' to switch to it"))
1043 1043 scmutil.checknewlabel(repo, label, 'branch')
1044 1044 repo.dirstate.setbranch(label)
1045 1045 ui.status(_('marked working directory as branch %s\n') % label)
1046 1046
1047 1047 # find any open named branches aside from default
1048 1048 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1049 1049 if n != "default" and not c]
1050 1050 if not others:
1051 1051 ui.status(_('(branches are permanent and global, '
1052 1052 'did you want a bookmark?)\n'))
1053 1053
1054 1054 @command('branches',
1055 1055 [('a', 'active', False,
1056 1056 _('show only branches that have unmerged heads (DEPRECATED)')),
1057 1057 ('c', 'closed', False, _('show normal and closed branches')),
1058 1058 ] + formatteropts,
1059 1059 _('[-c]'))
1060 1060 def branches(ui, repo, active=False, closed=False, **opts):
1061 1061 """list repository named branches
1062 1062
1063 1063 List the repository's named branches, indicating which ones are
1064 1064 inactive. If -c/--closed is specified, also list branches which have
1065 1065 been marked closed (see :hg:`commit --close-branch`).
1066 1066
1067 1067 Use the command :hg:`update` to switch to an existing branch.
1068 1068
1069 1069 Returns 0.
1070 1070 """
1071 1071
1072 1072 opts = pycompat.byteskwargs(opts)
1073 1073 ui.pager('branches')
1074 1074 fm = ui.formatter('branches', opts)
1075 1075 hexfunc = fm.hexfunc
1076 1076
1077 1077 allheads = set(repo.heads())
1078 1078 branches = []
1079 1079 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1080 1080 isactive = False
1081 1081 if not isclosed:
1082 1082 openheads = set(repo.branchmap().iteropen(heads))
1083 1083 isactive = bool(openheads & allheads)
1084 1084 branches.append((tag, repo[tip], isactive, not isclosed))
1085 1085 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1086 1086 reverse=True)
1087 1087
1088 1088 for tag, ctx, isactive, isopen in branches:
1089 1089 if active and not isactive:
1090 1090 continue
1091 1091 if isactive:
1092 1092 label = 'branches.active'
1093 1093 notice = ''
1094 1094 elif not isopen:
1095 1095 if not closed:
1096 1096 continue
1097 1097 label = 'branches.closed'
1098 1098 notice = _(' (closed)')
1099 1099 else:
1100 1100 label = 'branches.inactive'
1101 1101 notice = _(' (inactive)')
1102 1102 current = (tag == repo.dirstate.branch())
1103 1103 if current:
1104 1104 label = 'branches.current'
1105 1105
1106 1106 fm.startitem()
1107 1107 fm.write('branch', '%s', tag, label=label)
1108 1108 rev = ctx.rev()
1109 1109 padsize = max(31 - len(str(rev)) - encoding.colwidth(tag), 0)
1110 1110 fmt = ' ' * padsize + ' %d:%s'
1111 1111 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1112 1112 label='log.changeset changeset.%s' % ctx.phasestr())
1113 1113 fm.context(ctx=ctx)
1114 1114 fm.data(active=isactive, closed=not isopen, current=current)
1115 1115 if not ui.quiet:
1116 1116 fm.plain(notice)
1117 1117 fm.plain('\n')
1118 1118 fm.end()
1119 1119
1120 1120 @command('bundle',
1121 1121 [('f', 'force', None, _('run even when the destination is unrelated')),
1122 1122 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1123 1123 _('REV')),
1124 1124 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1125 1125 _('BRANCH')),
1126 1126 ('', 'base', [],
1127 1127 _('a base changeset assumed to be available at the destination'),
1128 1128 _('REV')),
1129 1129 ('a', 'all', None, _('bundle all changesets in the repository')),
1130 1130 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1131 1131 ] + remoteopts,
1132 1132 _('[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1133 1133 def bundle(ui, repo, fname, dest=None, **opts):
1134 1134 """create a bundle file
1135 1135
1136 1136 Generate a bundle file containing data to be added to a repository.
1137 1137
1138 1138 To create a bundle containing all changesets, use -a/--all
1139 1139 (or --base null). Otherwise, hg assumes the destination will have
1140 1140 all the nodes you specify with --base parameters. Otherwise, hg
1141 1141 will assume the repository has all the nodes in destination, or
1142 1142 default-push/default if no destination is specified.
1143 1143
1144 1144 You can change bundle format with the -t/--type option. See
1145 1145 :hg:`help bundlespec` for documentation on this format. By default,
1146 1146 the most appropriate format is used and compression defaults to
1147 1147 bzip2.
1148 1148
1149 1149 The bundle file can then be transferred using conventional means
1150 1150 and applied to another repository with the unbundle or pull
1151 1151 command. This is useful when direct push and pull are not
1152 1152 available or when exporting an entire repository is undesirable.
1153 1153
1154 1154 Applying bundles preserves all changeset contents including
1155 1155 permissions, copy/rename information, and revision history.
1156 1156
1157 1157 Returns 0 on success, 1 if no changes found.
1158 1158 """
1159 1159 opts = pycompat.byteskwargs(opts)
1160 1160 revs = None
1161 1161 if 'rev' in opts:
1162 1162 revstrings = opts['rev']
1163 1163 revs = scmutil.revrange(repo, revstrings)
1164 1164 if revstrings and not revs:
1165 1165 raise error.Abort(_('no commits to bundle'))
1166 1166
1167 1167 bundletype = opts.get('type', 'bzip2').lower()
1168 1168 try:
1169 1169 bcompression, cgversion, params = exchange.parsebundlespec(
1170 1170 repo, bundletype, strict=False)
1171 1171 except error.UnsupportedBundleSpecification as e:
1172 1172 raise error.Abort(str(e),
1173 1173 hint=_("see 'hg help bundlespec' for supported "
1174 1174 "values for --type"))
1175 1175
1176 1176 # Packed bundles are a pseudo bundle format for now.
1177 1177 if cgversion == 's1':
1178 1178 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1179 1179 hint=_("use 'hg debugcreatestreamclonebundle'"))
1180 1180
1181 1181 if opts.get('all'):
1182 1182 if dest:
1183 1183 raise error.Abort(_("--all is incompatible with specifying "
1184 1184 "a destination"))
1185 1185 if opts.get('base'):
1186 1186 ui.warn(_("ignoring --base because --all was specified\n"))
1187 1187 base = ['null']
1188 1188 else:
1189 1189 base = scmutil.revrange(repo, opts.get('base'))
1190 1190 if cgversion not in changegroup.supportedoutgoingversions(repo):
1191 1191 raise error.Abort(_("repository does not support bundle version %s") %
1192 1192 cgversion)
1193 1193
1194 1194 if base:
1195 1195 if dest:
1196 1196 raise error.Abort(_("--base is incompatible with specifying "
1197 1197 "a destination"))
1198 1198 common = [repo.lookup(rev) for rev in base]
1199 1199 heads = revs and map(repo.lookup, revs) or None
1200 1200 outgoing = discovery.outgoing(repo, common, heads)
1201 1201 else:
1202 1202 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1203 1203 dest, branches = hg.parseurl(dest, opts.get('branch'))
1204 1204 other = hg.peer(repo, opts, dest)
1205 1205 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1206 1206 heads = revs and map(repo.lookup, revs) or revs
1207 1207 outgoing = discovery.findcommonoutgoing(repo, other,
1208 1208 onlyheads=heads,
1209 1209 force=opts.get('force'),
1210 1210 portable=True)
1211 1211
1212 1212 if not outgoing.missing:
1213 1213 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1214 1214 return 1
1215 1215
1216 1216 if cgversion == '01': #bundle1
1217 1217 if bcompression is None:
1218 1218 bcompression = 'UN'
1219 1219 bversion = 'HG10' + bcompression
1220 1220 bcompression = None
1221 1221 elif cgversion in ('02', '03'):
1222 1222 bversion = 'HG20'
1223 1223 else:
1224 1224 raise error.ProgrammingError(
1225 1225 'bundle: unexpected changegroup version %s' % cgversion)
1226 1226
1227 1227 # TODO compression options should be derived from bundlespec parsing.
1228 1228 # This is a temporary hack to allow adjusting bundle compression
1229 1229 # level without a) formalizing the bundlespec changes to declare it
1230 1230 # b) introducing a command flag.
1231 1231 compopts = {}
1232 1232 complevel = ui.configint('experimental', 'bundlecomplevel')
1233 1233 if complevel is not None:
1234 1234 compopts['level'] = complevel
1235 1235
1236 1236
1237 1237 contentopts = {'cg.version': cgversion}
1238 1238 if repo.ui.configbool('experimental', 'stabilization.bundle-obsmarker'):
1239 1239 contentopts['obsolescence'] = True
1240 1240 if repo.ui.configbool('experimental', 'bundle-phases'):
1241 1241 contentopts['phases'] = True
1242 1242 bundle2.writenewbundle(ui, repo, 'bundle', fname, bversion, outgoing,
1243 1243 contentopts, compression=bcompression,
1244 1244 compopts=compopts)
1245 1245
1246 1246 @command('cat',
1247 1247 [('o', 'output', '',
1248 1248 _('print output to file with formatted name'), _('FORMAT')),
1249 1249 ('r', 'rev', '', _('print the given revision'), _('REV')),
1250 1250 ('', 'decode', None, _('apply any matching decode filter')),
1251 1251 ] + walkopts + formatteropts,
1252 1252 _('[OPTION]... FILE...'),
1253 1253 inferrepo=True)
1254 1254 def cat(ui, repo, file1, *pats, **opts):
1255 1255 """output the current or given revision of files
1256 1256
1257 1257 Print the specified files as they were at the given revision. If
1258 1258 no revision is given, the parent of the working directory is used.
1259 1259
1260 1260 Output may be to a file, in which case the name of the file is
1261 1261 given using a format string. The formatting rules as follows:
1262 1262
1263 1263 :``%%``: literal "%" character
1264 1264 :``%s``: basename of file being printed
1265 1265 :``%d``: dirname of file being printed, or '.' if in repository root
1266 1266 :``%p``: root-relative path name of file being printed
1267 1267 :``%H``: changeset hash (40 hexadecimal digits)
1268 1268 :``%R``: changeset revision number
1269 1269 :``%h``: short-form changeset hash (12 hexadecimal digits)
1270 1270 :``%r``: zero-padded changeset revision number
1271 1271 :``%b``: basename of the exporting repository
1272 1272
1273 1273 Returns 0 on success.
1274 1274 """
1275 1275 ctx = scmutil.revsingle(repo, opts.get('rev'))
1276 1276 m = scmutil.match(ctx, (file1,) + pats, opts)
1277 1277 fntemplate = opts.pop('output', '')
1278 1278 if cmdutil.isstdiofilename(fntemplate):
1279 1279 fntemplate = ''
1280 1280
1281 1281 if fntemplate:
1282 1282 fm = formatter.nullformatter(ui, 'cat')
1283 1283 else:
1284 1284 ui.pager('cat')
1285 1285 fm = ui.formatter('cat', opts)
1286 1286 with fm:
1287 1287 return cmdutil.cat(ui, repo, ctx, m, fm, fntemplate, '', **opts)
1288 1288
1289 1289 @command('^clone',
1290 1290 [('U', 'noupdate', None, _('the clone will include an empty working '
1291 1291 'directory (only a repository)')),
1292 1292 ('u', 'updaterev', '', _('revision, tag, or branch to check out'),
1293 1293 _('REV')),
1294 1294 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1295 1295 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1296 1296 ('', 'pull', None, _('use pull protocol to copy metadata')),
1297 1297 ('', 'uncompressed', None,
1298 1298 _('an alias to --stream (DEPRECATED)')),
1299 1299 ('', 'stream', None,
1300 1300 _('clone with minimal data processing')),
1301 1301 ] + remoteopts,
1302 1302 _('[OPTION]... SOURCE [DEST]'),
1303 1303 norepo=True)
1304 1304 def clone(ui, source, dest=None, **opts):
1305 1305 """make a copy of an existing repository
1306 1306
1307 1307 Create a copy of an existing repository in a new directory.
1308 1308
1309 1309 If no destination directory name is specified, it defaults to the
1310 1310 basename of the source.
1311 1311
1312 1312 The location of the source is added to the new repository's
1313 1313 ``.hg/hgrc`` file, as the default to be used for future pulls.
1314 1314
1315 1315 Only local paths and ``ssh://`` URLs are supported as
1316 1316 destinations. For ``ssh://`` destinations, no working directory or
1317 1317 ``.hg/hgrc`` will be created on the remote side.
1318 1318
1319 1319 If the source repository has a bookmark called '@' set, that
1320 1320 revision will be checked out in the new repository by default.
1321 1321
1322 1322 To check out a particular version, use -u/--update, or
1323 1323 -U/--noupdate to create a clone with no working directory.
1324 1324
1325 1325 To pull only a subset of changesets, specify one or more revisions
1326 1326 identifiers with -r/--rev or branches with -b/--branch. The
1327 1327 resulting clone will contain only the specified changesets and
1328 1328 their ancestors. These options (or 'clone src#rev dest') imply
1329 1329 --pull, even for local source repositories.
1330 1330
1331 1331 In normal clone mode, the remote normalizes repository data into a common
1332 1332 exchange format and the receiving end translates this data into its local
1333 1333 storage format. --stream activates a different clone mode that essentially
1334 1334 copies repository files from the remote with minimal data processing. This
1335 1335 significantly reduces the CPU cost of a clone both remotely and locally.
1336 1336 However, it often increases the transferred data size by 30-40%. This can
1337 1337 result in substantially faster clones where I/O throughput is plentiful,
1338 1338 especially for larger repositories. A side-effect of --stream clones is
1339 1339 that storage settings and requirements on the remote are applied locally:
1340 1340 a modern client may inherit legacy or inefficient storage used by the
1341 1341 remote or a legacy Mercurial client may not be able to clone from a
1342 1342 modern Mercurial remote.
1343 1343
1344 1344 .. note::
1345 1345
1346 1346 Specifying a tag will include the tagged changeset but not the
1347 1347 changeset containing the tag.
1348 1348
1349 1349 .. container:: verbose
1350 1350
1351 1351 For efficiency, hardlinks are used for cloning whenever the
1352 1352 source and destination are on the same filesystem (note this
1353 1353 applies only to the repository data, not to the working
1354 1354 directory). Some filesystems, such as AFS, implement hardlinking
1355 1355 incorrectly, but do not report errors. In these cases, use the
1356 1356 --pull option to avoid hardlinking.
1357 1357
1358 1358 Mercurial will update the working directory to the first applicable
1359 1359 revision from this list:
1360 1360
1361 1361 a) null if -U or the source repository has no changesets
1362 1362 b) if -u . and the source repository is local, the first parent of
1363 1363 the source repository's working directory
1364 1364 c) the changeset specified with -u (if a branch name, this means the
1365 1365 latest head of that branch)
1366 1366 d) the changeset specified with -r
1367 1367 e) the tipmost head specified with -b
1368 1368 f) the tipmost head specified with the url#branch source syntax
1369 1369 g) the revision marked with the '@' bookmark, if present
1370 1370 h) the tipmost head of the default branch
1371 1371 i) tip
1372 1372
1373 1373 When cloning from servers that support it, Mercurial may fetch
1374 1374 pre-generated data from a server-advertised URL. When this is done,
1375 1375 hooks operating on incoming changesets and changegroups may fire twice,
1376 1376 once for the bundle fetched from the URL and another for any additional
1377 1377 data not fetched from this URL. In addition, if an error occurs, the
1378 1378 repository may be rolled back to a partial clone. This behavior may
1379 1379 change in future releases. See :hg:`help -e clonebundles` for more.
1380 1380
1381 1381 Examples:
1382 1382
1383 1383 - clone a remote repository to a new directory named hg/::
1384 1384
1385 1385 hg clone https://www.mercurial-scm.org/repo/hg/
1386 1386
1387 1387 - create a lightweight local clone::
1388 1388
1389 1389 hg clone project/ project-feature/
1390 1390
1391 1391 - clone from an absolute path on an ssh server (note double-slash)::
1392 1392
1393 1393 hg clone ssh://user@server//home/projects/alpha/
1394 1394
1395 1395 - do a streaming clone while checking out a specified version::
1396 1396
1397 1397 hg clone --stream http://server/repo -u 1.5
1398 1398
1399 1399 - create a repository without changesets after a particular revision::
1400 1400
1401 1401 hg clone -r 04e544 experimental/ good/
1402 1402
1403 1403 - clone (and track) a particular named branch::
1404 1404
1405 1405 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1406 1406
1407 1407 See :hg:`help urls` for details on specifying URLs.
1408 1408
1409 1409 Returns 0 on success.
1410 1410 """
1411 1411 opts = pycompat.byteskwargs(opts)
1412 1412 if opts.get('noupdate') and opts.get('updaterev'):
1413 1413 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1414 1414
1415 1415 r = hg.clone(ui, opts, source, dest,
1416 1416 pull=opts.get('pull'),
1417 1417 stream=opts.get('stream') or opts.get('uncompressed'),
1418 1418 rev=opts.get('rev'),
1419 1419 update=opts.get('updaterev') or not opts.get('noupdate'),
1420 1420 branch=opts.get('branch'),
1421 1421 shareopts=opts.get('shareopts'))
1422 1422
1423 1423 return r is None
1424 1424
1425 1425 @command('^commit|ci',
1426 1426 [('A', 'addremove', None,
1427 1427 _('mark new/missing files as added/removed before committing')),
1428 1428 ('', 'close-branch', None,
1429 1429 _('mark a branch head as closed')),
1430 1430 ('', 'amend', None, _('amend the parent of the working directory')),
1431 1431 ('s', 'secret', None, _('use the secret phase for committing')),
1432 1432 ('e', 'edit', None, _('invoke editor on commit messages')),
1433 1433 ('i', 'interactive', None, _('use interactive mode')),
1434 1434 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1435 1435 _('[OPTION]... [FILE]...'),
1436 1436 inferrepo=True)
1437 1437 def commit(ui, repo, *pats, **opts):
1438 1438 """commit the specified files or all outstanding changes
1439 1439
1440 1440 Commit changes to the given files into the repository. Unlike a
1441 1441 centralized SCM, this operation is a local operation. See
1442 1442 :hg:`push` for a way to actively distribute your changes.
1443 1443
1444 1444 If a list of files is omitted, all changes reported by :hg:`status`
1445 1445 will be committed.
1446 1446
1447 1447 If you are committing the result of a merge, do not provide any
1448 1448 filenames or -I/-X filters.
1449 1449
1450 1450 If no commit message is specified, Mercurial starts your
1451 1451 configured editor where you can enter a message. In case your
1452 1452 commit fails, you will find a backup of your message in
1453 1453 ``.hg/last-message.txt``.
1454 1454
1455 1455 The --close-branch flag can be used to mark the current branch
1456 1456 head closed. When all heads of a branch are closed, the branch
1457 1457 will be considered closed and no longer listed.
1458 1458
1459 1459 The --amend flag can be used to amend the parent of the
1460 1460 working directory with a new commit that contains the changes
1461 1461 in the parent in addition to those currently reported by :hg:`status`,
1462 1462 if there are any. The old commit is stored in a backup bundle in
1463 1463 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1464 1464 on how to restore it).
1465 1465
1466 1466 Message, user and date are taken from the amended commit unless
1467 1467 specified. When a message isn't specified on the command line,
1468 1468 the editor will open with the message of the amended commit.
1469 1469
1470 1470 It is not possible to amend public changesets (see :hg:`help phases`)
1471 1471 or changesets that have children.
1472 1472
1473 1473 See :hg:`help dates` for a list of formats valid for -d/--date.
1474 1474
1475 1475 Returns 0 on success, 1 if nothing changed.
1476 1476
1477 1477 .. container:: verbose
1478 1478
1479 1479 Examples:
1480 1480
1481 1481 - commit all files ending in .py::
1482 1482
1483 1483 hg commit --include "set:**.py"
1484 1484
1485 1485 - commit all non-binary files::
1486 1486
1487 1487 hg commit --exclude "set:binary()"
1488 1488
1489 1489 - amend the current commit and set the date to now::
1490 1490
1491 1491 hg commit --amend --date now
1492 1492 """
1493 1493 wlock = lock = None
1494 1494 try:
1495 1495 wlock = repo.wlock()
1496 1496 lock = repo.lock()
1497 1497 return _docommit(ui, repo, *pats, **opts)
1498 1498 finally:
1499 1499 release(lock, wlock)
1500 1500
1501 1501 def _docommit(ui, repo, *pats, **opts):
1502 1502 if opts.get(r'interactive'):
1503 1503 opts.pop(r'interactive')
1504 1504 ret = cmdutil.dorecord(ui, repo, commit, None, False,
1505 1505 cmdutil.recordfilter, *pats,
1506 1506 **opts)
1507 1507 # ret can be 0 (no changes to record) or the value returned by
1508 1508 # commit(), 1 if nothing changed or None on success.
1509 1509 return 1 if ret == 0 else ret
1510 1510
1511 1511 opts = pycompat.byteskwargs(opts)
1512 1512 if opts.get('subrepos'):
1513 1513 if opts.get('amend'):
1514 1514 raise error.Abort(_('cannot amend with --subrepos'))
1515 1515 # Let --subrepos on the command line override config setting.
1516 1516 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1517 1517
1518 1518 cmdutil.checkunfinished(repo, commit=True)
1519 1519
1520 1520 branch = repo[None].branch()
1521 1521 bheads = repo.branchheads(branch)
1522 1522
1523 1523 extra = {}
1524 1524 if opts.get('close_branch'):
1525 1525 extra['close'] = 1
1526 1526
1527 1527 if not bheads:
1528 1528 raise error.Abort(_('can only close branch heads'))
1529 1529 elif opts.get('amend'):
1530 1530 if repo[None].parents()[0].p1().branch() != branch and \
1531 1531 repo[None].parents()[0].p2().branch() != branch:
1532 1532 raise error.Abort(_('can only close branch heads'))
1533 1533
1534 1534 if opts.get('amend'):
1535 1535 if ui.configbool('ui', 'commitsubrepos'):
1536 1536 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1537 1537
1538 1538 old = repo['.']
1539 1539 if not old.mutable():
1540 1540 raise error.Abort(_('cannot amend public changesets'))
1541 1541 if len(repo[None].parents()) > 1:
1542 1542 raise error.Abort(_('cannot amend while merging'))
1543 1543 allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
1544 1544 if not allowunstable and old.children():
1545 1545 raise error.Abort(_('cannot amend changeset with children'))
1546 1546
1547 1547 # Currently histedit gets confused if an amend happens while histedit
1548 1548 # is in progress. Since we have a checkunfinished command, we are
1549 1549 # temporarily honoring it.
1550 1550 #
1551 1551 # Note: eventually this guard will be removed. Please do not expect
1552 1552 # this behavior to remain.
1553 1553 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1554 1554 cmdutil.checkunfinished(repo)
1555 1555
1556 1556 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
1557 1557 if node == old.node():
1558 1558 ui.status(_("nothing changed\n"))
1559 1559 return 1
1560 1560 else:
1561 1561 def commitfunc(ui, repo, message, match, opts):
1562 1562 overrides = {}
1563 1563 if opts.get('secret'):
1564 1564 overrides[('phases', 'new-commit')] = 'secret'
1565 1565
1566 1566 baseui = repo.baseui
1567 1567 with baseui.configoverride(overrides, 'commit'):
1568 1568 with ui.configoverride(overrides, 'commit'):
1569 1569 editform = cmdutil.mergeeditform(repo[None],
1570 1570 'commit.normal')
1571 1571 editor = cmdutil.getcommiteditor(
1572 1572 editform=editform, **pycompat.strkwargs(opts))
1573 1573 return repo.commit(message,
1574 1574 opts.get('user'),
1575 1575 opts.get('date'),
1576 1576 match,
1577 1577 editor=editor,
1578 1578 extra=extra)
1579 1579
1580 1580 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1581 1581
1582 1582 if not node:
1583 1583 stat = cmdutil.postcommitstatus(repo, pats, opts)
1584 1584 if stat[3]:
1585 1585 ui.status(_("nothing changed (%d missing files, see "
1586 1586 "'hg status')\n") % len(stat[3]))
1587 1587 else:
1588 1588 ui.status(_("nothing changed\n"))
1589 1589 return 1
1590 1590
1591 1591 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1592 1592
1593 1593 @command('config|showconfig|debugconfig',
1594 1594 [('u', 'untrusted', None, _('show untrusted configuration options')),
1595 1595 ('e', 'edit', None, _('edit user config')),
1596 1596 ('l', 'local', None, _('edit repository config')),
1597 1597 ('g', 'global', None, _('edit global config'))] + formatteropts,
1598 1598 _('[-u] [NAME]...'),
1599 1599 optionalrepo=True)
1600 1600 def config(ui, repo, *values, **opts):
1601 1601 """show combined config settings from all hgrc files
1602 1602
1603 1603 With no arguments, print names and values of all config items.
1604 1604
1605 1605 With one argument of the form section.name, print just the value
1606 1606 of that config item.
1607 1607
1608 1608 With multiple arguments, print names and values of all config
1609 1609 items with matching section names.
1610 1610
1611 1611 With --edit, start an editor on the user-level config file. With
1612 1612 --global, edit the system-wide config file. With --local, edit the
1613 1613 repository-level config file.
1614 1614
1615 1615 With --debug, the source (filename and line number) is printed
1616 1616 for each config item.
1617 1617
1618 1618 See :hg:`help config` for more information about config files.
1619 1619
1620 1620 Returns 0 on success, 1 if NAME does not exist.
1621 1621
1622 1622 """
1623 1623
1624 1624 opts = pycompat.byteskwargs(opts)
1625 1625 if opts.get('edit') or opts.get('local') or opts.get('global'):
1626 1626 if opts.get('local') and opts.get('global'):
1627 1627 raise error.Abort(_("can't use --local and --global together"))
1628 1628
1629 1629 if opts.get('local'):
1630 1630 if not repo:
1631 1631 raise error.Abort(_("can't use --local outside a repository"))
1632 1632 paths = [repo.vfs.join('hgrc')]
1633 1633 elif opts.get('global'):
1634 1634 paths = rcutil.systemrcpath()
1635 1635 else:
1636 1636 paths = rcutil.userrcpath()
1637 1637
1638 1638 for f in paths:
1639 1639 if os.path.exists(f):
1640 1640 break
1641 1641 else:
1642 1642 if opts.get('global'):
1643 1643 samplehgrc = uimod.samplehgrcs['global']
1644 1644 elif opts.get('local'):
1645 1645 samplehgrc = uimod.samplehgrcs['local']
1646 1646 else:
1647 1647 samplehgrc = uimod.samplehgrcs['user']
1648 1648
1649 1649 f = paths[0]
1650 1650 fp = open(f, "wb")
1651 1651 fp.write(util.tonativeeol(samplehgrc))
1652 1652 fp.close()
1653 1653
1654 1654 editor = ui.geteditor()
1655 1655 ui.system("%s \"%s\"" % (editor, f),
1656 1656 onerr=error.Abort, errprefix=_("edit failed"),
1657 1657 blockedtag='config_edit')
1658 1658 return
1659 1659 ui.pager('config')
1660 1660 fm = ui.formatter('config', opts)
1661 1661 for t, f in rcutil.rccomponents():
1662 1662 if t == 'path':
1663 1663 ui.debug('read config from: %s\n' % f)
1664 1664 elif t == 'items':
1665 1665 for section, name, value, source in f:
1666 1666 ui.debug('set config by: %s\n' % source)
1667 1667 else:
1668 1668 raise error.ProgrammingError('unknown rctype: %s' % t)
1669 1669 untrusted = bool(opts.get('untrusted'))
1670 1670 if values:
1671 1671 sections = [v for v in values if '.' not in v]
1672 1672 items = [v for v in values if '.' in v]
1673 1673 if len(items) > 1 or items and sections:
1674 1674 raise error.Abort(_('only one config item permitted'))
1675 1675 matched = False
1676 1676 for section, name, value in ui.walkconfig(untrusted=untrusted):
1677 1677 source = ui.configsource(section, name, untrusted)
1678 1678 value = pycompat.bytestr(value)
1679 1679 if fm.isplain():
1680 1680 source = source or 'none'
1681 1681 value = value.replace('\n', '\\n')
1682 1682 entryname = section + '.' + name
1683 1683 if values:
1684 1684 for v in values:
1685 1685 if v == section:
1686 1686 fm.startitem()
1687 1687 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1688 1688 fm.write('name value', '%s=%s\n', entryname, value)
1689 1689 matched = True
1690 1690 elif v == entryname:
1691 1691 fm.startitem()
1692 1692 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1693 1693 fm.write('value', '%s\n', value)
1694 1694 fm.data(name=entryname)
1695 1695 matched = True
1696 1696 else:
1697 1697 fm.startitem()
1698 1698 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1699 1699 fm.write('name value', '%s=%s\n', entryname, value)
1700 1700 matched = True
1701 1701 fm.end()
1702 1702 if matched:
1703 1703 return 0
1704 1704 return 1
1705 1705
1706 1706 @command('copy|cp',
1707 1707 [('A', 'after', None, _('record a copy that has already occurred')),
1708 1708 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1709 1709 ] + walkopts + dryrunopts,
1710 1710 _('[OPTION]... [SOURCE]... DEST'))
1711 1711 def copy(ui, repo, *pats, **opts):
1712 1712 """mark files as copied for the next commit
1713 1713
1714 1714 Mark dest as having copies of source files. If dest is a
1715 1715 directory, copies are put in that directory. If dest is a file,
1716 1716 the source must be a single file.
1717 1717
1718 1718 By default, this command copies the contents of files as they
1719 1719 exist in the working directory. If invoked with -A/--after, the
1720 1720 operation is recorded, but no copying is performed.
1721 1721
1722 1722 This command takes effect with the next commit. To undo a copy
1723 1723 before that, see :hg:`revert`.
1724 1724
1725 1725 Returns 0 on success, 1 if errors are encountered.
1726 1726 """
1727 1727 opts = pycompat.byteskwargs(opts)
1728 1728 with repo.wlock(False):
1729 1729 return cmdutil.copy(ui, repo, pats, opts)
1730 1730
1731 1731 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
1732 1732 def debugcommands(ui, cmd='', *args):
1733 1733 """list all available commands and options"""
1734 1734 for cmd, vals in sorted(table.iteritems()):
1735 1735 cmd = cmd.split('|')[0].strip('^')
1736 1736 opts = ', '.join([i[1] for i in vals[1]])
1737 1737 ui.write('%s: %s\n' % (cmd, opts))
1738 1738
1739 1739 @command('debugcomplete',
1740 1740 [('o', 'options', None, _('show the command options'))],
1741 1741 _('[-o] CMD'),
1742 1742 norepo=True)
1743 1743 def debugcomplete(ui, cmd='', **opts):
1744 1744 """returns the completion list associated with the given command"""
1745 1745
1746 1746 if opts.get('options'):
1747 1747 options = []
1748 1748 otables = [globalopts]
1749 1749 if cmd:
1750 1750 aliases, entry = cmdutil.findcmd(cmd, table, False)
1751 1751 otables.append(entry[1])
1752 1752 for t in otables:
1753 1753 for o in t:
1754 1754 if "(DEPRECATED)" in o[3]:
1755 1755 continue
1756 1756 if o[0]:
1757 1757 options.append('-%s' % o[0])
1758 1758 options.append('--%s' % o[1])
1759 1759 ui.write("%s\n" % "\n".join(options))
1760 1760 return
1761 1761
1762 1762 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
1763 1763 if ui.verbose:
1764 1764 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1765 1765 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1766 1766
1767 1767 @command('^diff',
1768 1768 [('r', 'rev', [], _('revision'), _('REV')),
1769 1769 ('c', 'change', '', _('change made by revision'), _('REV'))
1770 1770 ] + diffopts + diffopts2 + walkopts + subrepoopts,
1771 1771 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
1772 1772 inferrepo=True)
1773 1773 def diff(ui, repo, *pats, **opts):
1774 1774 """diff repository (or selected files)
1775 1775
1776 1776 Show differences between revisions for the specified files.
1777 1777
1778 1778 Differences between files are shown using the unified diff format.
1779 1779
1780 1780 .. note::
1781 1781
1782 1782 :hg:`diff` may generate unexpected results for merges, as it will
1783 1783 default to comparing against the working directory's first
1784 1784 parent changeset if no revisions are specified.
1785 1785
1786 1786 When two revision arguments are given, then changes are shown
1787 1787 between those revisions. If only one revision is specified then
1788 1788 that revision is compared to the working directory, and, when no
1789 1789 revisions are specified, the working directory files are compared
1790 1790 to its first parent.
1791 1791
1792 1792 Alternatively you can specify -c/--change with a revision to see
1793 1793 the changes in that changeset relative to its first parent.
1794 1794
1795 1795 Without the -a/--text option, diff will avoid generating diffs of
1796 1796 files it detects as binary. With -a, diff will generate a diff
1797 1797 anyway, probably with undesirable results.
1798 1798
1799 1799 Use the -g/--git option to generate diffs in the git extended diff
1800 1800 format. For more information, read :hg:`help diffs`.
1801 1801
1802 1802 .. container:: verbose
1803 1803
1804 1804 Examples:
1805 1805
1806 1806 - compare a file in the current working directory to its parent::
1807 1807
1808 1808 hg diff foo.c
1809 1809
1810 1810 - compare two historical versions of a directory, with rename info::
1811 1811
1812 1812 hg diff --git -r 1.0:1.2 lib/
1813 1813
1814 1814 - get change stats relative to the last change on some date::
1815 1815
1816 1816 hg diff --stat -r "date('may 2')"
1817 1817
1818 1818 - diff all newly-added files that contain a keyword::
1819 1819
1820 1820 hg diff "set:added() and grep(GNU)"
1821 1821
1822 1822 - compare a revision and its parents::
1823 1823
1824 1824 hg diff -c 9353 # compare against first parent
1825 1825 hg diff -r 9353^:9353 # same using revset syntax
1826 1826 hg diff -r 9353^2:9353 # compare against the second parent
1827 1827
1828 1828 Returns 0 on success.
1829 1829 """
1830 1830
1831 1831 opts = pycompat.byteskwargs(opts)
1832 1832 revs = opts.get('rev')
1833 1833 change = opts.get('change')
1834 1834 stat = opts.get('stat')
1835 1835 reverse = opts.get('reverse')
1836 1836
1837 1837 if revs and change:
1838 1838 msg = _('cannot specify --rev and --change at the same time')
1839 1839 raise error.Abort(msg)
1840 1840 elif change:
1841 1841 node2 = scmutil.revsingle(repo, change, None).node()
1842 1842 node1 = repo[node2].p1().node()
1843 1843 else:
1844 1844 node1, node2 = scmutil.revpair(repo, revs)
1845 1845
1846 1846 if reverse:
1847 1847 node1, node2 = node2, node1
1848 1848
1849 1849 diffopts = patch.diffallopts(ui, opts)
1850 1850 m = scmutil.match(repo[node2], pats, opts)
1851 1851 ui.pager('diff')
1852 1852 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
1853 1853 listsubrepos=opts.get('subrepos'),
1854 1854 root=opts.get('root'))
1855 1855
1856 1856 @command('^export',
1857 1857 [('o', 'output', '',
1858 1858 _('print output to file with formatted name'), _('FORMAT')),
1859 1859 ('', 'switch-parent', None, _('diff against the second parent')),
1860 1860 ('r', 'rev', [], _('revisions to export'), _('REV')),
1861 1861 ] + diffopts,
1862 1862 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
1863 1863 def export(ui, repo, *changesets, **opts):
1864 1864 """dump the header and diffs for one or more changesets
1865 1865
1866 1866 Print the changeset header and diffs for one or more revisions.
1867 1867 If no revision is given, the parent of the working directory is used.
1868 1868
1869 1869 The information shown in the changeset header is: author, date,
1870 1870 branch name (if non-default), changeset hash, parent(s) and commit
1871 1871 comment.
1872 1872
1873 1873 .. note::
1874 1874
1875 1875 :hg:`export` may generate unexpected diff output for merge
1876 1876 changesets, as it will compare the merge changeset against its
1877 1877 first parent only.
1878 1878
1879 1879 Output may be to a file, in which case the name of the file is
1880 1880 given using a format string. The formatting rules are as follows:
1881 1881
1882 1882 :``%%``: literal "%" character
1883 1883 :``%H``: changeset hash (40 hexadecimal digits)
1884 1884 :``%N``: number of patches being generated
1885 1885 :``%R``: changeset revision number
1886 1886 :``%b``: basename of the exporting repository
1887 1887 :``%h``: short-form changeset hash (12 hexadecimal digits)
1888 1888 :``%m``: first line of the commit message (only alphanumeric characters)
1889 1889 :``%n``: zero-padded sequence number, starting at 1
1890 1890 :``%r``: zero-padded changeset revision number
1891 1891
1892 1892 Without the -a/--text option, export will avoid generating diffs
1893 1893 of files it detects as binary. With -a, export will generate a
1894 1894 diff anyway, probably with undesirable results.
1895 1895
1896 1896 Use the -g/--git option to generate diffs in the git extended diff
1897 1897 format. See :hg:`help diffs` for more information.
1898 1898
1899 1899 With the --switch-parent option, the diff will be against the
1900 1900 second parent. It can be useful to review a merge.
1901 1901
1902 1902 .. container:: verbose
1903 1903
1904 1904 Examples:
1905 1905
1906 1906 - use export and import to transplant a bugfix to the current
1907 1907 branch::
1908 1908
1909 1909 hg export -r 9353 | hg import -
1910 1910
1911 1911 - export all the changesets between two revisions to a file with
1912 1912 rename information::
1913 1913
1914 1914 hg export --git -r 123:150 > changes.txt
1915 1915
1916 1916 - split outgoing changes into a series of patches with
1917 1917 descriptive names::
1918 1918
1919 1919 hg export -r "outgoing()" -o "%n-%m.patch"
1920 1920
1921 1921 Returns 0 on success.
1922 1922 """
1923 1923 opts = pycompat.byteskwargs(opts)
1924 1924 changesets += tuple(opts.get('rev', []))
1925 1925 if not changesets:
1926 1926 changesets = ['.']
1927 1927 revs = scmutil.revrange(repo, changesets)
1928 1928 if not revs:
1929 1929 raise error.Abort(_("export requires at least one changeset"))
1930 1930 if len(revs) > 1:
1931 1931 ui.note(_('exporting patches:\n'))
1932 1932 else:
1933 1933 ui.note(_('exporting patch:\n'))
1934 1934 ui.pager('export')
1935 1935 cmdutil.export(repo, revs, fntemplate=opts.get('output'),
1936 1936 switch_parent=opts.get('switch_parent'),
1937 1937 opts=patch.diffallopts(ui, opts))
1938 1938
1939 1939 @command('files',
1940 1940 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
1941 1941 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
1942 1942 ] + walkopts + formatteropts + subrepoopts,
1943 1943 _('[OPTION]... [FILE]...'))
1944 1944 def files(ui, repo, *pats, **opts):
1945 1945 """list tracked files
1946 1946
1947 1947 Print files under Mercurial control in the working directory or
1948 1948 specified revision for given files (excluding removed files).
1949 1949 Files can be specified as filenames or filesets.
1950 1950
1951 1951 If no files are given to match, this command prints the names
1952 1952 of all files under Mercurial control.
1953 1953
1954 1954 .. container:: verbose
1955 1955
1956 1956 Examples:
1957 1957
1958 1958 - list all files under the current directory::
1959 1959
1960 1960 hg files .
1961 1961
1962 1962 - shows sizes and flags for current revision::
1963 1963
1964 1964 hg files -vr .
1965 1965
1966 1966 - list all files named README::
1967 1967
1968 1968 hg files -I "**/README"
1969 1969
1970 1970 - list all binary files::
1971 1971
1972 1972 hg files "set:binary()"
1973 1973
1974 1974 - find files containing a regular expression::
1975 1975
1976 1976 hg files "set:grep('bob')"
1977 1977
1978 1978 - search tracked file contents with xargs and grep::
1979 1979
1980 1980 hg files -0 | xargs -0 grep foo
1981 1981
1982 1982 See :hg:`help patterns` and :hg:`help filesets` for more information
1983 1983 on specifying file patterns.
1984 1984
1985 1985 Returns 0 if a match is found, 1 otherwise.
1986 1986
1987 1987 """
1988 1988
1989 1989 opts = pycompat.byteskwargs(opts)
1990 1990 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
1991 1991
1992 1992 end = '\n'
1993 1993 if opts.get('print0'):
1994 1994 end = '\0'
1995 1995 fmt = '%s' + end
1996 1996
1997 1997 m = scmutil.match(ctx, pats, opts)
1998 1998 ui.pager('files')
1999 1999 with ui.formatter('files', opts) as fm:
2000 2000 return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
2001 2001
2002 2002 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
2003 2003 def forget(ui, repo, *pats, **opts):
2004 2004 """forget the specified files on the next commit
2005 2005
2006 2006 Mark the specified files so they will no longer be tracked
2007 2007 after the next commit.
2008 2008
2009 2009 This only removes files from the current branch, not from the
2010 2010 entire project history, and it does not delete them from the
2011 2011 working directory.
2012 2012
2013 2013 To delete the file from the working directory, see :hg:`remove`.
2014 2014
2015 2015 To undo a forget before the next commit, see :hg:`add`.
2016 2016
2017 2017 .. container:: verbose
2018 2018
2019 2019 Examples:
2020 2020
2021 2021 - forget newly-added binary files::
2022 2022
2023 2023 hg forget "set:added() and binary()"
2024 2024
2025 2025 - forget files that would be excluded by .hgignore::
2026 2026
2027 2027 hg forget "set:hgignore()"
2028 2028
2029 2029 Returns 0 on success.
2030 2030 """
2031 2031
2032 2032 opts = pycompat.byteskwargs(opts)
2033 2033 if not pats:
2034 2034 raise error.Abort(_('no files specified'))
2035 2035
2036 2036 m = scmutil.match(repo[None], pats, opts)
2037 2037 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2038 2038 return rejected and 1 or 0
2039 2039
2040 2040 @command(
2041 2041 'graft',
2042 2042 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2043 2043 ('c', 'continue', False, _('resume interrupted graft')),
2044 2044 ('e', 'edit', False, _('invoke editor on commit messages')),
2045 2045 ('', 'log', None, _('append graft info to log message')),
2046 2046 ('f', 'force', False, _('force graft')),
2047 2047 ('D', 'currentdate', False,
2048 2048 _('record the current date as commit date')),
2049 2049 ('U', 'currentuser', False,
2050 2050 _('record the current user as committer'), _('DATE'))]
2051 2051 + commitopts2 + mergetoolopts + dryrunopts,
2052 2052 _('[OPTION]... [-r REV]... REV...'))
2053 2053 def graft(ui, repo, *revs, **opts):
2054 2054 '''copy changes from other branches onto the current branch
2055 2055
2056 2056 This command uses Mercurial's merge logic to copy individual
2057 2057 changes from other branches without merging branches in the
2058 2058 history graph. This is sometimes known as 'backporting' or
2059 2059 'cherry-picking'. By default, graft will copy user, date, and
2060 2060 description from the source changesets.
2061 2061
2062 2062 Changesets that are ancestors of the current revision, that have
2063 2063 already been grafted, or that are merges will be skipped.
2064 2064
2065 2065 If --log is specified, log messages will have a comment appended
2066 2066 of the form::
2067 2067
2068 2068 (grafted from CHANGESETHASH)
2069 2069
2070 2070 If --force is specified, revisions will be grafted even if they
2071 2071 are already ancestors of or have been grafted to the destination.
2072 2072 This is useful when the revisions have since been backed out.
2073 2073
2074 2074 If a graft merge results in conflicts, the graft process is
2075 2075 interrupted so that the current merge can be manually resolved.
2076 2076 Once all conflicts are addressed, the graft process can be
2077 2077 continued with the -c/--continue option.
2078 2078
2079 2079 .. note::
2080 2080
2081 2081 The -c/--continue option does not reapply earlier options, except
2082 2082 for --force.
2083 2083
2084 2084 .. container:: verbose
2085 2085
2086 2086 Examples:
2087 2087
2088 2088 - copy a single change to the stable branch and edit its description::
2089 2089
2090 2090 hg update stable
2091 2091 hg graft --edit 9393
2092 2092
2093 2093 - graft a range of changesets with one exception, updating dates::
2094 2094
2095 2095 hg graft -D "2085::2093 and not 2091"
2096 2096
2097 2097 - continue a graft after resolving conflicts::
2098 2098
2099 2099 hg graft -c
2100 2100
2101 2101 - show the source of a grafted changeset::
2102 2102
2103 2103 hg log --debug -r .
2104 2104
2105 2105 - show revisions sorted by date::
2106 2106
2107 2107 hg log -r "sort(all(), date)"
2108 2108
2109 2109 See :hg:`help revisions` for more about specifying revisions.
2110 2110
2111 2111 Returns 0 on successful completion.
2112 2112 '''
2113 2113 with repo.wlock():
2114 2114 return _dograft(ui, repo, *revs, **opts)
2115 2115
2116 2116 def _dograft(ui, repo, *revs, **opts):
2117 2117 opts = pycompat.byteskwargs(opts)
2118 2118 if revs and opts.get('rev'):
2119 2119 ui.warn(_('warning: inconsistent use of --rev might give unexpected '
2120 2120 'revision ordering!\n'))
2121 2121
2122 2122 revs = list(revs)
2123 2123 revs.extend(opts.get('rev'))
2124 2124
2125 2125 if not opts.get('user') and opts.get('currentuser'):
2126 2126 opts['user'] = ui.username()
2127 2127 if not opts.get('date') and opts.get('currentdate'):
2128 2128 opts['date'] = "%d %d" % util.makedate()
2129 2129
2130 2130 editor = cmdutil.getcommiteditor(editform='graft',
2131 2131 **pycompat.strkwargs(opts))
2132 2132
2133 2133 cont = False
2134 2134 if opts.get('continue'):
2135 2135 cont = True
2136 2136 if revs:
2137 2137 raise error.Abort(_("can't specify --continue and revisions"))
2138 2138 # read in unfinished revisions
2139 2139 try:
2140 2140 nodes = repo.vfs.read('graftstate').splitlines()
2141 2141 revs = [repo[node].rev() for node in nodes]
2142 2142 except IOError as inst:
2143 2143 if inst.errno != errno.ENOENT:
2144 2144 raise
2145 2145 cmdutil.wrongtooltocontinue(repo, _('graft'))
2146 2146 else:
2147 2147 cmdutil.checkunfinished(repo)
2148 2148 cmdutil.bailifchanged(repo)
2149 2149 if not revs:
2150 2150 raise error.Abort(_('no revisions specified'))
2151 2151 revs = scmutil.revrange(repo, revs)
2152 2152
2153 2153 skipped = set()
2154 2154 # check for merges
2155 2155 for rev in repo.revs('%ld and merge()', revs):
2156 2156 ui.warn(_('skipping ungraftable merge revision %d\n') % rev)
2157 2157 skipped.add(rev)
2158 2158 revs = [r for r in revs if r not in skipped]
2159 2159 if not revs:
2160 2160 return -1
2161 2161
2162 2162 # Don't check in the --continue case, in effect retaining --force across
2163 2163 # --continues. That's because without --force, any revisions we decided to
2164 2164 # skip would have been filtered out here, so they wouldn't have made their
2165 2165 # way to the graftstate. With --force, any revisions we would have otherwise
2166 2166 # skipped would not have been filtered out, and if they hadn't been applied
2167 2167 # already, they'd have been in the graftstate.
2168 2168 if not (cont or opts.get('force')):
2169 2169 # check for ancestors of dest branch
2170 2170 crev = repo['.'].rev()
2171 2171 ancestors = repo.changelog.ancestors([crev], inclusive=True)
2172 2172 # XXX make this lazy in the future
2173 2173 # don't mutate while iterating, create a copy
2174 2174 for rev in list(revs):
2175 2175 if rev in ancestors:
2176 2176 ui.warn(_('skipping ancestor revision %d:%s\n') %
2177 2177 (rev, repo[rev]))
2178 2178 # XXX remove on list is slow
2179 2179 revs.remove(rev)
2180 2180 if not revs:
2181 2181 return -1
2182 2182
2183 2183 # analyze revs for earlier grafts
2184 2184 ids = {}
2185 2185 for ctx in repo.set("%ld", revs):
2186 2186 ids[ctx.hex()] = ctx.rev()
2187 2187 n = ctx.extra().get('source')
2188 2188 if n:
2189 2189 ids[n] = ctx.rev()
2190 2190
2191 2191 # check ancestors for earlier grafts
2192 2192 ui.debug('scanning for duplicate grafts\n')
2193 2193
2194 2194 # The only changesets we can be sure doesn't contain grafts of any
2195 2195 # revs, are the ones that are common ancestors of *all* revs:
2196 2196 for rev in repo.revs('only(%d,ancestor(%ld))', crev, revs):
2197 2197 ctx = repo[rev]
2198 2198 n = ctx.extra().get('source')
2199 2199 if n in ids:
2200 2200 try:
2201 2201 r = repo[n].rev()
2202 2202 except error.RepoLookupError:
2203 2203 r = None
2204 2204 if r in revs:
2205 2205 ui.warn(_('skipping revision %d:%s '
2206 2206 '(already grafted to %d:%s)\n')
2207 2207 % (r, repo[r], rev, ctx))
2208 2208 revs.remove(r)
2209 2209 elif ids[n] in revs:
2210 2210 if r is None:
2211 2211 ui.warn(_('skipping already grafted revision %d:%s '
2212 2212 '(%d:%s also has unknown origin %s)\n')
2213 2213 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
2214 2214 else:
2215 2215 ui.warn(_('skipping already grafted revision %d:%s '
2216 2216 '(%d:%s also has origin %d:%s)\n')
2217 2217 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
2218 2218 revs.remove(ids[n])
2219 2219 elif ctx.hex() in ids:
2220 2220 r = ids[ctx.hex()]
2221 2221 ui.warn(_('skipping already grafted revision %d:%s '
2222 2222 '(was grafted from %d:%s)\n') %
2223 2223 (r, repo[r], rev, ctx))
2224 2224 revs.remove(r)
2225 2225 if not revs:
2226 2226 return -1
2227 2227
2228 2228 for pos, ctx in enumerate(repo.set("%ld", revs)):
2229 2229 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
2230 2230 ctx.description().split('\n', 1)[0])
2231 2231 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
2232 2232 if names:
2233 2233 desc += ' (%s)' % ' '.join(names)
2234 2234 ui.status(_('grafting %s\n') % desc)
2235 2235 if opts.get('dry_run'):
2236 2236 continue
2237 2237
2238 2238 source = ctx.extra().get('source')
2239 2239 extra = {}
2240 2240 if source:
2241 2241 extra['source'] = source
2242 2242 extra['intermediate-source'] = ctx.hex()
2243 2243 else:
2244 2244 extra['source'] = ctx.hex()
2245 2245 user = ctx.user()
2246 2246 if opts.get('user'):
2247 2247 user = opts['user']
2248 2248 date = ctx.date()
2249 2249 if opts.get('date'):
2250 2250 date = opts['date']
2251 2251 message = ctx.description()
2252 2252 if opts.get('log'):
2253 2253 message += '\n(grafted from %s)' % ctx.hex()
2254 2254
2255 2255 # we don't merge the first commit when continuing
2256 2256 if not cont:
2257 2257 # perform the graft merge with p1(rev) as 'ancestor'
2258 2258 try:
2259 2259 # ui.forcemerge is an internal variable, do not document
2260 2260 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
2261 2261 'graft')
2262 2262 stats = mergemod.graft(repo, ctx, ctx.p1(),
2263 2263 ['local', 'graft'])
2264 2264 finally:
2265 2265 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
2266 2266 # report any conflicts
2267 2267 if stats and stats[3] > 0:
2268 2268 # write out state for --continue
2269 2269 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2270 2270 repo.vfs.write('graftstate', ''.join(nodelines))
2271 2271 extra = ''
2272 2272 if opts.get('user'):
2273 2273 extra += ' --user %s' % util.shellquote(opts['user'])
2274 2274 if opts.get('date'):
2275 2275 extra += ' --date %s' % util.shellquote(opts['date'])
2276 2276 if opts.get('log'):
2277 2277 extra += ' --log'
2278 2278 hint=_("use 'hg resolve' and 'hg graft --continue%s'") % extra
2279 2279 raise error.Abort(
2280 2280 _("unresolved conflicts, can't continue"),
2281 2281 hint=hint)
2282 2282 else:
2283 2283 cont = False
2284 2284
2285 2285 # commit
2286 2286 node = repo.commit(text=message, user=user,
2287 2287 date=date, extra=extra, editor=editor)
2288 2288 if node is None:
2289 2289 ui.warn(
2290 2290 _('note: graft of %d:%s created no changes to commit\n') %
2291 2291 (ctx.rev(), ctx))
2292 2292
2293 2293 # remove state when we complete successfully
2294 2294 if not opts.get('dry_run'):
2295 2295 repo.vfs.unlinkpath('graftstate', ignoremissing=True)
2296 2296
2297 2297 return 0
2298 2298
2299 2299 @command('grep',
2300 2300 [('0', 'print0', None, _('end fields with NUL')),
2301 2301 ('', 'all', None, _('print all revisions that match')),
2302 2302 ('a', 'text', None, _('treat all files as text')),
2303 2303 ('f', 'follow', None,
2304 2304 _('follow changeset history,'
2305 2305 ' or file history across copies and renames')),
2306 2306 ('i', 'ignore-case', None, _('ignore case when matching')),
2307 2307 ('l', 'files-with-matches', None,
2308 2308 _('print only filenames and revisions that match')),
2309 2309 ('n', 'line-number', None, _('print matching line numbers')),
2310 2310 ('r', 'rev', [],
2311 2311 _('only search files changed within revision range'), _('REV')),
2312 2312 ('u', 'user', None, _('list the author (long with -v)')),
2313 2313 ('d', 'date', None, _('list the date (short with -q)')),
2314 2314 ] + formatteropts + walkopts,
2315 2315 _('[OPTION]... PATTERN [FILE]...'),
2316 2316 inferrepo=True)
2317 2317 def grep(ui, repo, pattern, *pats, **opts):
2318 2318 """search revision history for a pattern in specified files
2319 2319
2320 2320 Search revision history for a regular expression in the specified
2321 2321 files or the entire project.
2322 2322
2323 2323 By default, grep prints the most recent revision number for each
2324 2324 file in which it finds a match. To get it to print every revision
2325 2325 that contains a change in match status ("-" for a match that becomes
2326 2326 a non-match, or "+" for a non-match that becomes a match), use the
2327 2327 --all flag.
2328 2328
2329 2329 PATTERN can be any Python (roughly Perl-compatible) regular
2330 2330 expression.
2331 2331
2332 2332 If no FILEs are specified (and -f/--follow isn't set), all files in
2333 2333 the repository are searched, including those that don't exist in the
2334 2334 current branch or have been deleted in a prior changeset.
2335 2335
2336 2336 Returns 0 if a match is found, 1 otherwise.
2337 2337 """
2338 2338 opts = pycompat.byteskwargs(opts)
2339 2339 reflags = re.M
2340 2340 if opts.get('ignore_case'):
2341 2341 reflags |= re.I
2342 2342 try:
2343 2343 regexp = util.re.compile(pattern, reflags)
2344 2344 except re.error as inst:
2345 2345 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2346 2346 return 1
2347 2347 sep, eol = ':', '\n'
2348 2348 if opts.get('print0'):
2349 2349 sep = eol = '\0'
2350 2350
2351 2351 getfile = util.lrucachefunc(repo.file)
2352 2352
2353 2353 def matchlines(body):
2354 2354 begin = 0
2355 2355 linenum = 0
2356 2356 while begin < len(body):
2357 2357 match = regexp.search(body, begin)
2358 2358 if not match:
2359 2359 break
2360 2360 mstart, mend = match.span()
2361 2361 linenum += body.count('\n', begin, mstart) + 1
2362 2362 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2363 2363 begin = body.find('\n', mend) + 1 or len(body) + 1
2364 2364 lend = begin - 1
2365 2365 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2366 2366
2367 2367 class linestate(object):
2368 2368 def __init__(self, line, linenum, colstart, colend):
2369 2369 self.line = line
2370 2370 self.linenum = linenum
2371 2371 self.colstart = colstart
2372 2372 self.colend = colend
2373 2373
2374 2374 def __hash__(self):
2375 2375 return hash((self.linenum, self.line))
2376 2376
2377 2377 def __eq__(self, other):
2378 2378 return self.line == other.line
2379 2379
2380 2380 def findpos(self):
2381 2381 """Iterate all (start, end) indices of matches"""
2382 2382 yield self.colstart, self.colend
2383 2383 p = self.colend
2384 2384 while p < len(self.line):
2385 2385 m = regexp.search(self.line, p)
2386 2386 if not m:
2387 2387 break
2388 2388 yield m.span()
2389 2389 p = m.end()
2390 2390
2391 2391 matches = {}
2392 2392 copies = {}
2393 2393 def grepbody(fn, rev, body):
2394 2394 matches[rev].setdefault(fn, [])
2395 2395 m = matches[rev][fn]
2396 2396 for lnum, cstart, cend, line in matchlines(body):
2397 2397 s = linestate(line, lnum, cstart, cend)
2398 2398 m.append(s)
2399 2399
2400 2400 def difflinestates(a, b):
2401 2401 sm = difflib.SequenceMatcher(None, a, b)
2402 2402 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2403 2403 if tag == 'insert':
2404 2404 for i in xrange(blo, bhi):
2405 2405 yield ('+', b[i])
2406 2406 elif tag == 'delete':
2407 2407 for i in xrange(alo, ahi):
2408 2408 yield ('-', a[i])
2409 2409 elif tag == 'replace':
2410 2410 for i in xrange(alo, ahi):
2411 2411 yield ('-', a[i])
2412 2412 for i in xrange(blo, bhi):
2413 2413 yield ('+', b[i])
2414 2414
2415 2415 def display(fm, fn, ctx, pstates, states):
2416 2416 rev = ctx.rev()
2417 2417 if fm.isplain():
2418 2418 formatuser = ui.shortuser
2419 2419 else:
2420 2420 formatuser = str
2421 2421 if ui.quiet:
2422 2422 datefmt = '%Y-%m-%d'
2423 2423 else:
2424 2424 datefmt = '%a %b %d %H:%M:%S %Y %1%2'
2425 2425 found = False
2426 2426 @util.cachefunc
2427 2427 def binary():
2428 2428 flog = getfile(fn)
2429 2429 return util.binary(flog.read(ctx.filenode(fn)))
2430 2430
2431 2431 fieldnamemap = {'filename': 'file', 'linenumber': 'line_number'}
2432 2432 if opts.get('all'):
2433 2433 iter = difflinestates(pstates, states)
2434 2434 else:
2435 2435 iter = [('', l) for l in states]
2436 2436 for change, l in iter:
2437 2437 fm.startitem()
2438 2438 fm.data(node=fm.hexfunc(ctx.node()))
2439 2439 cols = [
2440 2440 ('filename', fn, True),
2441 2441 ('rev', rev, True),
2442 2442 ('linenumber', l.linenum, opts.get('line_number')),
2443 2443 ]
2444 2444 if opts.get('all'):
2445 2445 cols.append(('change', change, True))
2446 2446 cols.extend([
2447 2447 ('user', formatuser(ctx.user()), opts.get('user')),
2448 2448 ('date', fm.formatdate(ctx.date(), datefmt), opts.get('date')),
2449 2449 ])
2450 2450 lastcol = next(name for name, data, cond in reversed(cols) if cond)
2451 2451 for name, data, cond in cols:
2452 2452 field = fieldnamemap.get(name, name)
2453 2453 fm.condwrite(cond, field, '%s', data, label='grep.%s' % name)
2454 2454 if cond and name != lastcol:
2455 2455 fm.plain(sep, label='grep.sep')
2456 2456 if not opts.get('files_with_matches'):
2457 2457 fm.plain(sep, label='grep.sep')
2458 2458 if not opts.get('text') and binary():
2459 2459 fm.plain(_(" Binary file matches"))
2460 2460 else:
2461 2461 displaymatches(fm.nested('texts'), l)
2462 2462 fm.plain(eol)
2463 2463 found = True
2464 2464 if opts.get('files_with_matches'):
2465 2465 break
2466 2466 return found
2467 2467
2468 2468 def displaymatches(fm, l):
2469 2469 p = 0
2470 2470 for s, e in l.findpos():
2471 2471 if p < s:
2472 2472 fm.startitem()
2473 2473 fm.write('text', '%s', l.line[p:s])
2474 2474 fm.data(matched=False)
2475 2475 fm.startitem()
2476 2476 fm.write('text', '%s', l.line[s:e], label='grep.match')
2477 2477 fm.data(matched=True)
2478 2478 p = e
2479 2479 if p < len(l.line):
2480 2480 fm.startitem()
2481 2481 fm.write('text', '%s', l.line[p:])
2482 2482 fm.data(matched=False)
2483 2483 fm.end()
2484 2484
2485 2485 skip = {}
2486 2486 revfiles = {}
2487 2487 match = scmutil.match(repo[None], pats, opts)
2488 2488 found = False
2489 2489 follow = opts.get('follow')
2490 2490
2491 2491 def prep(ctx, fns):
2492 2492 rev = ctx.rev()
2493 2493 pctx = ctx.p1()
2494 2494 parent = pctx.rev()
2495 2495 matches.setdefault(rev, {})
2496 2496 matches.setdefault(parent, {})
2497 2497 files = revfiles.setdefault(rev, [])
2498 2498 for fn in fns:
2499 2499 flog = getfile(fn)
2500 2500 try:
2501 2501 fnode = ctx.filenode(fn)
2502 2502 except error.LookupError:
2503 2503 continue
2504 2504
2505 2505 copied = flog.renamed(fnode)
2506 2506 copy = follow and copied and copied[0]
2507 2507 if copy:
2508 2508 copies.setdefault(rev, {})[fn] = copy
2509 2509 if fn in skip:
2510 2510 if copy:
2511 2511 skip[copy] = True
2512 2512 continue
2513 2513 files.append(fn)
2514 2514
2515 2515 if fn not in matches[rev]:
2516 2516 grepbody(fn, rev, flog.read(fnode))
2517 2517
2518 2518 pfn = copy or fn
2519 2519 if pfn not in matches[parent]:
2520 2520 try:
2521 2521 fnode = pctx.filenode(pfn)
2522 2522 grepbody(pfn, parent, flog.read(fnode))
2523 2523 except error.LookupError:
2524 2524 pass
2525 2525
2526 2526 ui.pager('grep')
2527 2527 fm = ui.formatter('grep', opts)
2528 2528 for ctx in cmdutil.walkchangerevs(repo, match, opts, prep):
2529 2529 rev = ctx.rev()
2530 2530 parent = ctx.p1().rev()
2531 2531 for fn in sorted(revfiles.get(rev, [])):
2532 2532 states = matches[rev][fn]
2533 2533 copy = copies.get(rev, {}).get(fn)
2534 2534 if fn in skip:
2535 2535 if copy:
2536 2536 skip[copy] = True
2537 2537 continue
2538 2538 pstates = matches.get(parent, {}).get(copy or fn, [])
2539 2539 if pstates or states:
2540 2540 r = display(fm, fn, ctx, pstates, states)
2541 2541 found = found or r
2542 2542 if r and not opts.get('all'):
2543 2543 skip[fn] = True
2544 2544 if copy:
2545 2545 skip[copy] = True
2546 2546 del matches[rev]
2547 2547 del revfiles[rev]
2548 2548 fm.end()
2549 2549
2550 2550 return not found
2551 2551
2552 2552 @command('heads',
2553 2553 [('r', 'rev', '',
2554 2554 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2555 2555 ('t', 'topo', False, _('show topological heads only')),
2556 2556 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2557 2557 ('c', 'closed', False, _('show normal and closed branch heads')),
2558 2558 ] + templateopts,
2559 2559 _('[-ct] [-r STARTREV] [REV]...'))
2560 2560 def heads(ui, repo, *branchrevs, **opts):
2561 2561 """show branch heads
2562 2562
2563 2563 With no arguments, show all open branch heads in the repository.
2564 2564 Branch heads are changesets that have no descendants on the
2565 2565 same branch. They are where development generally takes place and
2566 2566 are the usual targets for update and merge operations.
2567 2567
2568 2568 If one or more REVs are given, only open branch heads on the
2569 2569 branches associated with the specified changesets are shown. This
2570 2570 means that you can use :hg:`heads .` to see the heads on the
2571 2571 currently checked-out branch.
2572 2572
2573 2573 If -c/--closed is specified, also show branch heads marked closed
2574 2574 (see :hg:`commit --close-branch`).
2575 2575
2576 2576 If STARTREV is specified, only those heads that are descendants of
2577 2577 STARTREV will be displayed.
2578 2578
2579 2579 If -t/--topo is specified, named branch mechanics will be ignored and only
2580 2580 topological heads (changesets with no children) will be shown.
2581 2581
2582 2582 Returns 0 if matching heads are found, 1 if not.
2583 2583 """
2584 2584
2585 2585 opts = pycompat.byteskwargs(opts)
2586 2586 start = None
2587 2587 if 'rev' in opts:
2588 2588 start = scmutil.revsingle(repo, opts['rev'], None).node()
2589 2589
2590 2590 if opts.get('topo'):
2591 2591 heads = [repo[h] for h in repo.heads(start)]
2592 2592 else:
2593 2593 heads = []
2594 2594 for branch in repo.branchmap():
2595 2595 heads += repo.branchheads(branch, start, opts.get('closed'))
2596 2596 heads = [repo[h] for h in heads]
2597 2597
2598 2598 if branchrevs:
2599 2599 branches = set(repo[br].branch() for br in branchrevs)
2600 2600 heads = [h for h in heads if h.branch() in branches]
2601 2601
2602 2602 if opts.get('active') and branchrevs:
2603 2603 dagheads = repo.heads(start)
2604 2604 heads = [h for h in heads if h.node() in dagheads]
2605 2605
2606 2606 if branchrevs:
2607 2607 haveheads = set(h.branch() for h in heads)
2608 2608 if branches - haveheads:
2609 2609 headless = ', '.join(b for b in branches - haveheads)
2610 2610 msg = _('no open branch heads found on branches %s')
2611 2611 if opts.get('rev'):
2612 2612 msg += _(' (started at %s)') % opts['rev']
2613 2613 ui.warn((msg + '\n') % headless)
2614 2614
2615 2615 if not heads:
2616 2616 return 1
2617 2617
2618 2618 ui.pager('heads')
2619 2619 heads = sorted(heads, key=lambda x: -x.rev())
2620 2620 displayer = cmdutil.show_changeset(ui, repo, opts)
2621 2621 for ctx in heads:
2622 2622 displayer.show(ctx)
2623 2623 displayer.close()
2624 2624
2625 2625 @command('help',
2626 2626 [('e', 'extension', None, _('show only help for extensions')),
2627 2627 ('c', 'command', None, _('show only help for commands')),
2628 2628 ('k', 'keyword', None, _('show topics matching keyword')),
2629 2629 ('s', 'system', [], _('show help for specific platform(s)')),
2630 2630 ],
2631 2631 _('[-ecks] [TOPIC]'),
2632 2632 norepo=True)
2633 2633 def help_(ui, name=None, **opts):
2634 2634 """show help for a given topic or a help overview
2635 2635
2636 2636 With no arguments, print a list of commands with short help messages.
2637 2637
2638 2638 Given a topic, extension, or command name, print help for that
2639 2639 topic.
2640 2640
2641 2641 Returns 0 if successful.
2642 2642 """
2643 2643
2644 2644 keep = opts.get(r'system') or []
2645 2645 if len(keep) == 0:
2646 2646 if pycompat.sysplatform.startswith('win'):
2647 2647 keep.append('windows')
2648 2648 elif pycompat.sysplatform == 'OpenVMS':
2649 2649 keep.append('vms')
2650 2650 elif pycompat.sysplatform == 'plan9':
2651 2651 keep.append('plan9')
2652 2652 else:
2653 2653 keep.append('unix')
2654 2654 keep.append(pycompat.sysplatform.lower())
2655 2655 if ui.verbose:
2656 2656 keep.append('verbose')
2657 2657
2658 2658 commands = sys.modules[__name__]
2659 2659 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
2660 2660 ui.pager('help')
2661 2661 ui.write(formatted)
2662 2662
2663 2663
2664 2664 @command('identify|id',
2665 2665 [('r', 'rev', '',
2666 2666 _('identify the specified revision'), _('REV')),
2667 2667 ('n', 'num', None, _('show local revision number')),
2668 2668 ('i', 'id', None, _('show global revision id')),
2669 2669 ('b', 'branch', None, _('show branch')),
2670 2670 ('t', 'tags', None, _('show tags')),
2671 2671 ('B', 'bookmarks', None, _('show bookmarks')),
2672 2672 ] + remoteopts + formatteropts,
2673 2673 _('[-nibtB] [-r REV] [SOURCE]'),
2674 2674 optionalrepo=True)
2675 2675 def identify(ui, repo, source=None, rev=None,
2676 2676 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
2677 2677 """identify the working directory or specified revision
2678 2678
2679 2679 Print a summary identifying the repository state at REV using one or
2680 2680 two parent hash identifiers, followed by a "+" if the working
2681 2681 directory has uncommitted changes, the branch name (if not default),
2682 2682 a list of tags, and a list of bookmarks.
2683 2683
2684 2684 When REV is not given, print a summary of the current state of the
2685 2685 repository.
2686 2686
2687 2687 Specifying a path to a repository root or Mercurial bundle will
2688 2688 cause lookup to operate on that repository/bundle.
2689 2689
2690 2690 .. container:: verbose
2691 2691
2692 2692 Examples:
2693 2693
2694 2694 - generate a build identifier for the working directory::
2695 2695
2696 2696 hg id --id > build-id.dat
2697 2697
2698 2698 - find the revision corresponding to a tag::
2699 2699
2700 2700 hg id -n -r 1.3
2701 2701
2702 2702 - check the most recent revision of a remote repository::
2703 2703
2704 2704 hg id -r tip https://www.mercurial-scm.org/repo/hg/
2705 2705
2706 2706 See :hg:`log` for generating more information about specific revisions,
2707 2707 including full hash identifiers.
2708 2708
2709 2709 Returns 0 if successful.
2710 2710 """
2711 2711
2712 2712 opts = pycompat.byteskwargs(opts)
2713 2713 if not repo and not source:
2714 2714 raise error.Abort(_("there is no Mercurial repository here "
2715 2715 "(.hg not found)"))
2716 2716
2717 2717 if ui.debugflag:
2718 2718 hexfunc = hex
2719 2719 else:
2720 2720 hexfunc = short
2721 2721 default = not (num or id or branch or tags or bookmarks)
2722 2722 output = []
2723 2723 revs = []
2724 2724
2725 2725 if source:
2726 2726 source, branches = hg.parseurl(ui.expandpath(source))
2727 2727 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
2728 2728 repo = peer.local()
2729 2729 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
2730 2730
2731 2731 fm = ui.formatter('identify', opts)
2732 2732 fm.startitem()
2733 2733
2734 2734 if not repo:
2735 2735 if num or branch or tags:
2736 2736 raise error.Abort(
2737 2737 _("can't query remote revision number, branch, or tags"))
2738 2738 if not rev and revs:
2739 2739 rev = revs[0]
2740 2740 if not rev:
2741 2741 rev = "tip"
2742 2742
2743 2743 remoterev = peer.lookup(rev)
2744 2744 hexrev = hexfunc(remoterev)
2745 2745 if default or id:
2746 2746 output = [hexrev]
2747 2747 fm.data(id=hexrev)
2748 2748
2749 2749 def getbms():
2750 2750 bms = []
2751 2751
2752 2752 if 'bookmarks' in peer.listkeys('namespaces'):
2753 2753 hexremoterev = hex(remoterev)
2754 2754 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
2755 2755 if bmr == hexremoterev]
2756 2756
2757 2757 return sorted(bms)
2758 2758
2759 2759 bms = getbms()
2760 2760 if bookmarks:
2761 2761 output.extend(bms)
2762 2762 elif default and not ui.quiet:
2763 2763 # multiple bookmarks for a single parent separated by '/'
2764 2764 bm = '/'.join(bms)
2765 2765 if bm:
2766 2766 output.append(bm)
2767 2767
2768 2768 fm.data(node=hex(remoterev))
2769 2769 fm.data(bookmarks=fm.formatlist(bms, name='bookmark'))
2770 2770 else:
2771 2771 ctx = scmutil.revsingle(repo, rev, None)
2772 2772
2773 2773 if ctx.rev() is None:
2774 2774 ctx = repo[None]
2775 2775 parents = ctx.parents()
2776 2776 taglist = []
2777 2777 for p in parents:
2778 2778 taglist.extend(p.tags())
2779 2779
2780 2780 dirty = ""
2781 2781 if ctx.dirty(missing=True, merge=False, branch=False):
2782 2782 dirty = '+'
2783 2783 fm.data(dirty=dirty)
2784 2784
2785 2785 hexoutput = [hexfunc(p.node()) for p in parents]
2786 2786 if default or id:
2787 2787 output = ["%s%s" % ('+'.join(hexoutput), dirty)]
2788 2788 fm.data(id="%s%s" % ('+'.join(hexoutput), dirty))
2789 2789
2790 2790 if num:
2791 2791 numoutput = ["%d" % p.rev() for p in parents]
2792 2792 output.append("%s%s" % ('+'.join(numoutput), dirty))
2793 2793
2794 2794 fn = fm.nested('parents')
2795 2795 for p in parents:
2796 2796 fn.startitem()
2797 2797 fn.data(rev=p.rev())
2798 2798 fn.data(node=p.hex())
2799 2799 fn.context(ctx=p)
2800 2800 fn.end()
2801 2801 else:
2802 2802 hexoutput = hexfunc(ctx.node())
2803 2803 if default or id:
2804 2804 output = [hexoutput]
2805 2805 fm.data(id=hexoutput)
2806 2806
2807 2807 if num:
2808 2808 output.append(pycompat.bytestr(ctx.rev()))
2809 2809 taglist = ctx.tags()
2810 2810
2811 2811 if default and not ui.quiet:
2812 2812 b = ctx.branch()
2813 2813 if b != 'default':
2814 2814 output.append("(%s)" % b)
2815 2815
2816 2816 # multiple tags for a single parent separated by '/'
2817 2817 t = '/'.join(taglist)
2818 2818 if t:
2819 2819 output.append(t)
2820 2820
2821 2821 # multiple bookmarks for a single parent separated by '/'
2822 2822 bm = '/'.join(ctx.bookmarks())
2823 2823 if bm:
2824 2824 output.append(bm)
2825 2825 else:
2826 2826 if branch:
2827 2827 output.append(ctx.branch())
2828 2828
2829 2829 if tags:
2830 2830 output.extend(taglist)
2831 2831
2832 2832 if bookmarks:
2833 2833 output.extend(ctx.bookmarks())
2834 2834
2835 2835 fm.data(node=ctx.hex())
2836 2836 fm.data(branch=ctx.branch())
2837 2837 fm.data(tags=fm.formatlist(taglist, name='tag', sep=':'))
2838 2838 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name='bookmark'))
2839 2839 fm.context(ctx=ctx)
2840 2840
2841 2841 fm.plain("%s\n" % ' '.join(output))
2842 2842 fm.end()
2843 2843
2844 2844 @command('import|patch',
2845 2845 [('p', 'strip', 1,
2846 2846 _('directory strip option for patch. This has the same '
2847 2847 'meaning as the corresponding patch option'), _('NUM')),
2848 2848 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
2849 2849 ('e', 'edit', False, _('invoke editor on commit messages')),
2850 2850 ('f', 'force', None,
2851 2851 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
2852 2852 ('', 'no-commit', None,
2853 2853 _("don't commit, just update the working directory")),
2854 2854 ('', 'bypass', None,
2855 2855 _("apply patch without touching the working directory")),
2856 2856 ('', 'partial', None,
2857 2857 _('commit even if some hunks fail')),
2858 2858 ('', 'exact', None,
2859 2859 _('abort if patch would apply lossily')),
2860 2860 ('', 'prefix', '',
2861 2861 _('apply patch to subdirectory'), _('DIR')),
2862 2862 ('', 'import-branch', None,
2863 2863 _('use any branch information in patch (implied by --exact)'))] +
2864 2864 commitopts + commitopts2 + similarityopts,
2865 2865 _('[OPTION]... PATCH...'))
2866 2866 def import_(ui, repo, patch1=None, *patches, **opts):
2867 2867 """import an ordered set of patches
2868 2868
2869 2869 Import a list of patches and commit them individually (unless
2870 2870 --no-commit is specified).
2871 2871
2872 2872 To read a patch from standard input (stdin), use "-" as the patch
2873 2873 name. If a URL is specified, the patch will be downloaded from
2874 2874 there.
2875 2875
2876 2876 Import first applies changes to the working directory (unless
2877 2877 --bypass is specified), import will abort if there are outstanding
2878 2878 changes.
2879 2879
2880 2880 Use --bypass to apply and commit patches directly to the
2881 2881 repository, without affecting the working directory. Without
2882 2882 --exact, patches will be applied on top of the working directory
2883 2883 parent revision.
2884 2884
2885 2885 You can import a patch straight from a mail message. Even patches
2886 2886 as attachments work (to use the body part, it must have type
2887 2887 text/plain or text/x-patch). From and Subject headers of email
2888 2888 message are used as default committer and commit message. All
2889 2889 text/plain body parts before first diff are added to the commit
2890 2890 message.
2891 2891
2892 2892 If the imported patch was generated by :hg:`export`, user and
2893 2893 description from patch override values from message headers and
2894 2894 body. Values given on command line with -m/--message and -u/--user
2895 2895 override these.
2896 2896
2897 2897 If --exact is specified, import will set the working directory to
2898 2898 the parent of each patch before applying it, and will abort if the
2899 2899 resulting changeset has a different ID than the one recorded in
2900 2900 the patch. This will guard against various ways that portable
2901 2901 patch formats and mail systems might fail to transfer Mercurial
2902 2902 data or metadata. See :hg:`bundle` for lossless transmission.
2903 2903
2904 2904 Use --partial to ensure a changeset will be created from the patch
2905 2905 even if some hunks fail to apply. Hunks that fail to apply will be
2906 2906 written to a <target-file>.rej file. Conflicts can then be resolved
2907 2907 by hand before :hg:`commit --amend` is run to update the created
2908 2908 changeset. This flag exists to let people import patches that
2909 2909 partially apply without losing the associated metadata (author,
2910 2910 date, description, ...).
2911 2911
2912 2912 .. note::
2913 2913
2914 2914 When no hunks apply cleanly, :hg:`import --partial` will create
2915 2915 an empty changeset, importing only the patch metadata.
2916 2916
2917 2917 With -s/--similarity, hg will attempt to discover renames and
2918 2918 copies in the patch in the same way as :hg:`addremove`.
2919 2919
2920 2920 It is possible to use external patch programs to perform the patch
2921 2921 by setting the ``ui.patch`` configuration option. For the default
2922 2922 internal tool, the fuzz can also be configured via ``patch.fuzz``.
2923 2923 See :hg:`help config` for more information about configuration
2924 2924 files and how to use these options.
2925 2925
2926 2926 See :hg:`help dates` for a list of formats valid for -d/--date.
2927 2927
2928 2928 .. container:: verbose
2929 2929
2930 2930 Examples:
2931 2931
2932 2932 - import a traditional patch from a website and detect renames::
2933 2933
2934 2934 hg import -s 80 http://example.com/bugfix.patch
2935 2935
2936 2936 - import a changeset from an hgweb server::
2937 2937
2938 2938 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
2939 2939
2940 2940 - import all the patches in an Unix-style mbox::
2941 2941
2942 2942 hg import incoming-patches.mbox
2943 2943
2944 2944 - import patches from stdin::
2945 2945
2946 2946 hg import -
2947 2947
2948 2948 - attempt to exactly restore an exported changeset (not always
2949 2949 possible)::
2950 2950
2951 2951 hg import --exact proposed-fix.patch
2952 2952
2953 2953 - use an external tool to apply a patch which is too fuzzy for
2954 2954 the default internal tool.
2955 2955
2956 2956 hg import --config ui.patch="patch --merge" fuzzy.patch
2957 2957
2958 2958 - change the default fuzzing from 2 to a less strict 7
2959 2959
2960 2960 hg import --config ui.fuzz=7 fuzz.patch
2961 2961
2962 2962 Returns 0 on success, 1 on partial success (see --partial).
2963 2963 """
2964 2964
2965 2965 opts = pycompat.byteskwargs(opts)
2966 2966 if not patch1:
2967 2967 raise error.Abort(_('need at least one patch to import'))
2968 2968
2969 2969 patches = (patch1,) + patches
2970 2970
2971 2971 date = opts.get('date')
2972 2972 if date:
2973 2973 opts['date'] = util.parsedate(date)
2974 2974
2975 2975 exact = opts.get('exact')
2976 2976 update = not opts.get('bypass')
2977 2977 if not update and opts.get('no_commit'):
2978 2978 raise error.Abort(_('cannot use --no-commit with --bypass'))
2979 2979 try:
2980 2980 sim = float(opts.get('similarity') or 0)
2981 2981 except ValueError:
2982 2982 raise error.Abort(_('similarity must be a number'))
2983 2983 if sim < 0 or sim > 100:
2984 2984 raise error.Abort(_('similarity must be between 0 and 100'))
2985 2985 if sim and not update:
2986 2986 raise error.Abort(_('cannot use --similarity with --bypass'))
2987 2987 if exact:
2988 2988 if opts.get('edit'):
2989 2989 raise error.Abort(_('cannot use --exact with --edit'))
2990 2990 if opts.get('prefix'):
2991 2991 raise error.Abort(_('cannot use --exact with --prefix'))
2992 2992
2993 2993 base = opts["base"]
2994 2994 wlock = dsguard = lock = tr = None
2995 2995 msgs = []
2996 2996 ret = 0
2997 2997
2998 2998
2999 2999 try:
3000 3000 wlock = repo.wlock()
3001 3001
3002 3002 if update:
3003 3003 cmdutil.checkunfinished(repo)
3004 3004 if (exact or not opts.get('force')):
3005 3005 cmdutil.bailifchanged(repo)
3006 3006
3007 3007 if not opts.get('no_commit'):
3008 3008 lock = repo.lock()
3009 3009 tr = repo.transaction('import')
3010 3010 else:
3011 3011 dsguard = dirstateguard.dirstateguard(repo, 'import')
3012 3012 parents = repo[None].parents()
3013 3013 for patchurl in patches:
3014 3014 if patchurl == '-':
3015 3015 ui.status(_('applying patch from stdin\n'))
3016 3016 patchfile = ui.fin
3017 3017 patchurl = 'stdin' # for error message
3018 3018 else:
3019 3019 patchurl = os.path.join(base, patchurl)
3020 3020 ui.status(_('applying %s\n') % patchurl)
3021 3021 patchfile = hg.openpath(ui, patchurl)
3022 3022
3023 3023 haspatch = False
3024 3024 for hunk in patch.split(patchfile):
3025 3025 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
3026 3026 parents, opts,
3027 3027 msgs, hg.clean)
3028 3028 if msg:
3029 3029 haspatch = True
3030 3030 ui.note(msg + '\n')
3031 3031 if update or exact:
3032 3032 parents = repo[None].parents()
3033 3033 else:
3034 3034 parents = [repo[node]]
3035 3035 if rej:
3036 3036 ui.write_err(_("patch applied partially\n"))
3037 3037 ui.write_err(_("(fix the .rej files and run "
3038 3038 "`hg commit --amend`)\n"))
3039 3039 ret = 1
3040 3040 break
3041 3041
3042 3042 if not haspatch:
3043 3043 raise error.Abort(_('%s: no diffs found') % patchurl)
3044 3044
3045 3045 if tr:
3046 3046 tr.close()
3047 3047 if msgs:
3048 3048 repo.savecommitmessage('\n* * *\n'.join(msgs))
3049 3049 if dsguard:
3050 3050 dsguard.close()
3051 3051 return ret
3052 3052 finally:
3053 3053 if tr:
3054 3054 tr.release()
3055 3055 release(lock, dsguard, wlock)
3056 3056
3057 3057 @command('incoming|in',
3058 3058 [('f', 'force', None,
3059 3059 _('run even if remote repository is unrelated')),
3060 3060 ('n', 'newest-first', None, _('show newest record first')),
3061 3061 ('', 'bundle', '',
3062 3062 _('file to store the bundles into'), _('FILE')),
3063 3063 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3064 3064 ('B', 'bookmarks', False, _("compare bookmarks")),
3065 3065 ('b', 'branch', [],
3066 3066 _('a specific branch you would like to pull'), _('BRANCH')),
3067 3067 ] + logopts + remoteopts + subrepoopts,
3068 3068 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3069 3069 def incoming(ui, repo, source="default", **opts):
3070 3070 """show new changesets found in source
3071 3071
3072 3072 Show new changesets found in the specified path/URL or the default
3073 3073 pull location. These are the changesets that would have been pulled
3074 3074 if a pull at the time you issued this command.
3075 3075
3076 3076 See pull for valid source format details.
3077 3077
3078 3078 .. container:: verbose
3079 3079
3080 3080 With -B/--bookmarks, the result of bookmark comparison between
3081 3081 local and remote repositories is displayed. With -v/--verbose,
3082 3082 status is also displayed for each bookmark like below::
3083 3083
3084 3084 BM1 01234567890a added
3085 3085 BM2 1234567890ab advanced
3086 3086 BM3 234567890abc diverged
3087 3087 BM4 34567890abcd changed
3088 3088
3089 3089 The action taken locally when pulling depends on the
3090 3090 status of each bookmark:
3091 3091
3092 3092 :``added``: pull will create it
3093 3093 :``advanced``: pull will update it
3094 3094 :``diverged``: pull will create a divergent bookmark
3095 3095 :``changed``: result depends on remote changesets
3096 3096
3097 3097 From the point of view of pulling behavior, bookmark
3098 3098 existing only in the remote repository are treated as ``added``,
3099 3099 even if it is in fact locally deleted.
3100 3100
3101 3101 .. container:: verbose
3102 3102
3103 3103 For remote repository, using --bundle avoids downloading the
3104 3104 changesets twice if the incoming is followed by a pull.
3105 3105
3106 3106 Examples:
3107 3107
3108 3108 - show incoming changes with patches and full description::
3109 3109
3110 3110 hg incoming -vp
3111 3111
3112 3112 - show incoming changes excluding merges, store a bundle::
3113 3113
3114 3114 hg in -vpM --bundle incoming.hg
3115 3115 hg pull incoming.hg
3116 3116
3117 3117 - briefly list changes inside a bundle::
3118 3118
3119 3119 hg in changes.hg -T "{desc|firstline}\\n"
3120 3120
3121 3121 Returns 0 if there are incoming changes, 1 otherwise.
3122 3122 """
3123 3123 opts = pycompat.byteskwargs(opts)
3124 3124 if opts.get('graph'):
3125 3125 cmdutil.checkunsupportedgraphflags([], opts)
3126 3126 def display(other, chlist, displayer):
3127 3127 revdag = cmdutil.graphrevs(other, chlist, opts)
3128 3128 cmdutil.displaygraph(ui, repo, revdag, displayer,
3129 3129 graphmod.asciiedges)
3130 3130
3131 3131 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3132 3132 return 0
3133 3133
3134 3134 if opts.get('bundle') and opts.get('subrepos'):
3135 3135 raise error.Abort(_('cannot combine --bundle and --subrepos'))
3136 3136
3137 3137 if opts.get('bookmarks'):
3138 3138 source, branches = hg.parseurl(ui.expandpath(source),
3139 3139 opts.get('branch'))
3140 3140 other = hg.peer(repo, opts, source)
3141 3141 if 'bookmarks' not in other.listkeys('namespaces'):
3142 3142 ui.warn(_("remote doesn't support bookmarks\n"))
3143 3143 return 0
3144 3144 ui.pager('incoming')
3145 3145 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3146 3146 return bookmarks.incoming(ui, repo, other)
3147 3147
3148 3148 repo._subtoppath = ui.expandpath(source)
3149 3149 try:
3150 3150 return hg.incoming(ui, repo, source, opts)
3151 3151 finally:
3152 3152 del repo._subtoppath
3153 3153
3154 3154
3155 3155 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
3156 3156 norepo=True)
3157 3157 def init(ui, dest=".", **opts):
3158 3158 """create a new repository in the given directory
3159 3159
3160 3160 Initialize a new repository in the given directory. If the given
3161 3161 directory does not exist, it will be created.
3162 3162
3163 3163 If no directory is given, the current directory is used.
3164 3164
3165 3165 It is possible to specify an ``ssh://`` URL as the destination.
3166 3166 See :hg:`help urls` for more information.
3167 3167
3168 3168 Returns 0 on success.
3169 3169 """
3170 3170 opts = pycompat.byteskwargs(opts)
3171 3171 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3172 3172
3173 3173 @command('locate',
3174 3174 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3175 3175 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3176 3176 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3177 3177 ] + walkopts,
3178 3178 _('[OPTION]... [PATTERN]...'))
3179 3179 def locate(ui, repo, *pats, **opts):
3180 3180 """locate files matching specific patterns (DEPRECATED)
3181 3181
3182 3182 Print files under Mercurial control in the working directory whose
3183 3183 names match the given patterns.
3184 3184
3185 3185 By default, this command searches all directories in the working
3186 3186 directory. To search just the current directory and its
3187 3187 subdirectories, use "--include .".
3188 3188
3189 3189 If no patterns are given to match, this command prints the names
3190 3190 of all files under Mercurial control in the working directory.
3191 3191
3192 3192 If you want to feed the output of this command into the "xargs"
3193 3193 command, use the -0 option to both this command and "xargs". This
3194 3194 will avoid the problem of "xargs" treating single filenames that
3195 3195 contain whitespace as multiple filenames.
3196 3196
3197 3197 See :hg:`help files` for a more versatile command.
3198 3198
3199 3199 Returns 0 if a match is found, 1 otherwise.
3200 3200 """
3201 3201 opts = pycompat.byteskwargs(opts)
3202 3202 if opts.get('print0'):
3203 3203 end = '\0'
3204 3204 else:
3205 3205 end = '\n'
3206 3206 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3207 3207
3208 3208 ret = 1
3209 3209 ctx = repo[rev]
3210 3210 m = scmutil.match(ctx, pats, opts, default='relglob',
3211 3211 badfn=lambda x, y: False)
3212 3212
3213 3213 ui.pager('locate')
3214 3214 for abs in ctx.matches(m):
3215 3215 if opts.get('fullpath'):
3216 3216 ui.write(repo.wjoin(abs), end)
3217 3217 else:
3218 3218 ui.write(((pats and m.rel(abs)) or abs), end)
3219 3219 ret = 0
3220 3220
3221 3221 return ret
3222 3222
3223 3223 @command('^log|history',
3224 3224 [('f', 'follow', None,
3225 3225 _('follow changeset history, or file history across copies and renames')),
3226 3226 ('', 'follow-first', None,
3227 3227 _('only follow the first parent of merge changesets (DEPRECATED)')),
3228 3228 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3229 3229 ('C', 'copies', None, _('show copied files')),
3230 3230 ('k', 'keyword', [],
3231 3231 _('do case-insensitive search for a given text'), _('TEXT')),
3232 3232 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
3233 3233 ('', 'removed', None, _('include revisions where files were removed')),
3234 3234 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3235 3235 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3236 3236 ('', 'only-branch', [],
3237 3237 _('show only changesets within the given named branch (DEPRECATED)'),
3238 3238 _('BRANCH')),
3239 3239 ('b', 'branch', [],
3240 3240 _('show changesets within the given named branch'), _('BRANCH')),
3241 3241 ('P', 'prune', [],
3242 3242 _('do not display revision or any of its ancestors'), _('REV')),
3243 3243 ] + logopts + walkopts,
3244 3244 _('[OPTION]... [FILE]'),
3245 3245 inferrepo=True)
3246 3246 def log(ui, repo, *pats, **opts):
3247 3247 """show revision history of entire repository or files
3248 3248
3249 3249 Print the revision history of the specified files or the entire
3250 3250 project.
3251 3251
3252 3252 If no revision range is specified, the default is ``tip:0`` unless
3253 3253 --follow is set, in which case the working directory parent is
3254 3254 used as the starting revision.
3255 3255
3256 3256 File history is shown without following rename or copy history of
3257 3257 files. Use -f/--follow with a filename to follow history across
3258 3258 renames and copies. --follow without a filename will only show
3259 3259 ancestors or descendants of the starting revision.
3260 3260
3261 3261 By default this command prints revision number and changeset id,
3262 3262 tags, non-trivial parents, user, date and time, and a summary for
3263 3263 each commit. When the -v/--verbose switch is used, the list of
3264 3264 changed files and full commit message are shown.
3265 3265
3266 3266 With --graph the revisions are shown as an ASCII art DAG with the most
3267 3267 recent changeset at the top.
3268 3268 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
3269 3269 and '+' represents a fork where the changeset from the lines below is a
3270 3270 parent of the 'o' merge on the same line.
3271 3271 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
3272 3272 of a '|' indicates one or more revisions in a path are omitted.
3273 3273
3274 3274 .. note::
3275 3275
3276 3276 :hg:`log --patch` may generate unexpected diff output for merge
3277 3277 changesets, as it will only compare the merge changeset against
3278 3278 its first parent. Also, only files different from BOTH parents
3279 3279 will appear in files:.
3280 3280
3281 3281 .. note::
3282 3282
3283 3283 For performance reasons, :hg:`log FILE` may omit duplicate changes
3284 3284 made on branches and will not show removals or mode changes. To
3285 3285 see all such changes, use the --removed switch.
3286 3286
3287 3287 .. container:: verbose
3288 3288
3289 3289 Some examples:
3290 3290
3291 3291 - changesets with full descriptions and file lists::
3292 3292
3293 3293 hg log -v
3294 3294
3295 3295 - changesets ancestral to the working directory::
3296 3296
3297 3297 hg log -f
3298 3298
3299 3299 - last 10 commits on the current branch::
3300 3300
3301 3301 hg log -l 10 -b .
3302 3302
3303 3303 - changesets showing all modifications of a file, including removals::
3304 3304
3305 3305 hg log --removed file.c
3306 3306
3307 3307 - all changesets that touch a directory, with diffs, excluding merges::
3308 3308
3309 3309 hg log -Mp lib/
3310 3310
3311 3311 - all revision numbers that match a keyword::
3312 3312
3313 3313 hg log -k bug --template "{rev}\\n"
3314 3314
3315 3315 - the full hash identifier of the working directory parent::
3316 3316
3317 3317 hg log -r . --template "{node}\\n"
3318 3318
3319 3319 - list available log templates::
3320 3320
3321 3321 hg log -T list
3322 3322
3323 3323 - check if a given changeset is included in a tagged release::
3324 3324
3325 3325 hg log -r "a21ccf and ancestor(1.9)"
3326 3326
3327 3327 - find all changesets by some user in a date range::
3328 3328
3329 3329 hg log -k alice -d "may 2008 to jul 2008"
3330 3330
3331 3331 - summary of all changesets after the last tag::
3332 3332
3333 3333 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3334 3334
3335 3335 See :hg:`help dates` for a list of formats valid for -d/--date.
3336 3336
3337 3337 See :hg:`help revisions` for more about specifying and ordering
3338 3338 revisions.
3339 3339
3340 3340 See :hg:`help templates` for more about pre-packaged styles and
3341 3341 specifying custom templates. The default template used by the log
3342 3342 command can be customized via the ``ui.logtemplate`` configuration
3343 3343 setting.
3344 3344
3345 3345 Returns 0 on success.
3346 3346
3347 3347 """
3348 3348 opts = pycompat.byteskwargs(opts)
3349 3349 if opts.get('follow') and opts.get('rev'):
3350 3350 opts['rev'] = [revsetlang.formatspec('reverse(::%lr)', opts.get('rev'))]
3351 3351 del opts['follow']
3352 3352
3353 3353 if opts.get('graph'):
3354 3354 return cmdutil.graphlog(ui, repo, pats, opts)
3355 3355
3356 3356 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
3357 3357 limit = cmdutil.loglimit(opts)
3358 3358 count = 0
3359 3359
3360 3360 getrenamed = None
3361 3361 if opts.get('copies'):
3362 3362 endrev = None
3363 3363 if opts.get('rev'):
3364 3364 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
3365 3365 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3366 3366
3367 3367 ui.pager('log')
3368 3368 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
3369 3369 for rev in revs:
3370 3370 if count == limit:
3371 3371 break
3372 3372 ctx = repo[rev]
3373 3373 copies = None
3374 3374 if getrenamed is not None and rev:
3375 3375 copies = []
3376 3376 for fn in ctx.files():
3377 3377 rename = getrenamed(fn, rev)
3378 3378 if rename:
3379 3379 copies.append((fn, rename[0]))
3380 3380 if filematcher:
3381 3381 revmatchfn = filematcher(ctx.rev())
3382 3382 else:
3383 3383 revmatchfn = None
3384 3384 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3385 3385 if displayer.flush(ctx):
3386 3386 count += 1
3387 3387
3388 3388 displayer.close()
3389 3389
3390 3390 @command('manifest',
3391 3391 [('r', 'rev', '', _('revision to display'), _('REV')),
3392 3392 ('', 'all', False, _("list files from all revisions"))]
3393 3393 + formatteropts,
3394 3394 _('[-r REV]'))
3395 3395 def manifest(ui, repo, node=None, rev=None, **opts):
3396 3396 """output the current or given revision of the project manifest
3397 3397
3398 3398 Print a list of version controlled files for the given revision.
3399 3399 If no revision is given, the first parent of the working directory
3400 3400 is used, or the null revision if no revision is checked out.
3401 3401
3402 3402 With -v, print file permissions, symlink and executable bits.
3403 3403 With --debug, print file revision hashes.
3404 3404
3405 3405 If option --all is specified, the list of all files from all revisions
3406 3406 is printed. This includes deleted and renamed files.
3407 3407
3408 3408 Returns 0 on success.
3409 3409 """
3410 3410 opts = pycompat.byteskwargs(opts)
3411 3411 fm = ui.formatter('manifest', opts)
3412 3412
3413 3413 if opts.get('all'):
3414 3414 if rev or node:
3415 3415 raise error.Abort(_("can't specify a revision with --all"))
3416 3416
3417 3417 res = []
3418 3418 prefix = "data/"
3419 3419 suffix = ".i"
3420 3420 plen = len(prefix)
3421 3421 slen = len(suffix)
3422 3422 with repo.lock():
3423 3423 for fn, b, size in repo.store.datafiles():
3424 3424 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3425 3425 res.append(fn[plen:-slen])
3426 3426 ui.pager('manifest')
3427 3427 for f in res:
3428 3428 fm.startitem()
3429 3429 fm.write("path", '%s\n', f)
3430 3430 fm.end()
3431 3431 return
3432 3432
3433 3433 if rev and node:
3434 3434 raise error.Abort(_("please specify just one revision"))
3435 3435
3436 3436 if not node:
3437 3437 node = rev
3438 3438
3439 3439 char = {'l': '@', 'x': '*', '': ''}
3440 3440 mode = {'l': '644', 'x': '755', '': '644'}
3441 3441 ctx = scmutil.revsingle(repo, node)
3442 3442 mf = ctx.manifest()
3443 3443 ui.pager('manifest')
3444 3444 for f in ctx:
3445 3445 fm.startitem()
3446 3446 fl = ctx[f].flags()
3447 3447 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
3448 3448 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
3449 3449 fm.write('path', '%s\n', f)
3450 3450 fm.end()
3451 3451
3452 3452 @command('^merge',
3453 3453 [('f', 'force', None,
3454 3454 _('force a merge including outstanding changes (DEPRECATED)')),
3455 3455 ('r', 'rev', '', _('revision to merge'), _('REV')),
3456 3456 ('P', 'preview', None,
3457 3457 _('review revisions to merge (no merge is performed)'))
3458 3458 ] + mergetoolopts,
3459 3459 _('[-P] [[-r] REV]'))
3460 3460 def merge(ui, repo, node=None, **opts):
3461 3461 """merge another revision into working directory
3462 3462
3463 3463 The current working directory is updated with all changes made in
3464 3464 the requested revision since the last common predecessor revision.
3465 3465
3466 3466 Files that changed between either parent are marked as changed for
3467 3467 the next commit and a commit must be performed before any further
3468 3468 updates to the repository are allowed. The next commit will have
3469 3469 two parents.
3470 3470
3471 3471 ``--tool`` can be used to specify the merge tool used for file
3472 3472 merges. It overrides the HGMERGE environment variable and your
3473 3473 configuration files. See :hg:`help merge-tools` for options.
3474 3474
3475 3475 If no revision is specified, the working directory's parent is a
3476 3476 head revision, and the current branch contains exactly one other
3477 3477 head, the other head is merged with by default. Otherwise, an
3478 3478 explicit revision with which to merge with must be provided.
3479 3479
3480 3480 See :hg:`help resolve` for information on handling file conflicts.
3481 3481
3482 3482 To undo an uncommitted merge, use :hg:`update --clean .` which
3483 3483 will check out a clean copy of the original merge parent, losing
3484 3484 all changes.
3485 3485
3486 3486 Returns 0 on success, 1 if there are unresolved files.
3487 3487 """
3488 3488
3489 3489 opts = pycompat.byteskwargs(opts)
3490 3490 if opts.get('rev') and node:
3491 3491 raise error.Abort(_("please specify just one revision"))
3492 3492 if not node:
3493 3493 node = opts.get('rev')
3494 3494
3495 3495 if node:
3496 3496 node = scmutil.revsingle(repo, node).node()
3497 3497
3498 3498 if not node:
3499 3499 node = repo[destutil.destmerge(repo)].node()
3500 3500
3501 3501 if opts.get('preview'):
3502 3502 # find nodes that are ancestors of p2 but not of p1
3503 3503 p1 = repo.lookup('.')
3504 3504 p2 = repo.lookup(node)
3505 3505 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3506 3506
3507 3507 displayer = cmdutil.show_changeset(ui, repo, opts)
3508 3508 for node in nodes:
3509 3509 displayer.show(repo[node])
3510 3510 displayer.close()
3511 3511 return 0
3512 3512
3513 3513 try:
3514 3514 # ui.forcemerge is an internal variable, do not document
3515 3515 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
3516 3516 force = opts.get('force')
3517 3517 labels = ['working copy', 'merge rev']
3518 3518 return hg.merge(repo, node, force=force, mergeforce=force,
3519 3519 labels=labels)
3520 3520 finally:
3521 3521 ui.setconfig('ui', 'forcemerge', '', 'merge')
3522 3522
3523 3523 @command('outgoing|out',
3524 3524 [('f', 'force', None, _('run even when the destination is unrelated')),
3525 3525 ('r', 'rev', [],
3526 3526 _('a changeset intended to be included in the destination'), _('REV')),
3527 3527 ('n', 'newest-first', None, _('show newest record first')),
3528 3528 ('B', 'bookmarks', False, _('compare bookmarks')),
3529 3529 ('b', 'branch', [], _('a specific branch you would like to push'),
3530 3530 _('BRANCH')),
3531 3531 ] + logopts + remoteopts + subrepoopts,
3532 3532 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3533 3533 def outgoing(ui, repo, dest=None, **opts):
3534 3534 """show changesets not found in the destination
3535 3535
3536 3536 Show changesets not found in the specified destination repository
3537 3537 or the default push location. These are the changesets that would
3538 3538 be pushed if a push was requested.
3539 3539
3540 3540 See pull for details of valid destination formats.
3541 3541
3542 3542 .. container:: verbose
3543 3543
3544 3544 With -B/--bookmarks, the result of bookmark comparison between
3545 3545 local and remote repositories is displayed. With -v/--verbose,
3546 3546 status is also displayed for each bookmark like below::
3547 3547
3548 3548 BM1 01234567890a added
3549 3549 BM2 deleted
3550 3550 BM3 234567890abc advanced
3551 3551 BM4 34567890abcd diverged
3552 3552 BM5 4567890abcde changed
3553 3553
3554 3554 The action taken when pushing depends on the
3555 3555 status of each bookmark:
3556 3556
3557 3557 :``added``: push with ``-B`` will create it
3558 3558 :``deleted``: push with ``-B`` will delete it
3559 3559 :``advanced``: push will update it
3560 3560 :``diverged``: push with ``-B`` will update it
3561 3561 :``changed``: push with ``-B`` will update it
3562 3562
3563 3563 From the point of view of pushing behavior, bookmarks
3564 3564 existing only in the remote repository are treated as
3565 3565 ``deleted``, even if it is in fact added remotely.
3566 3566
3567 3567 Returns 0 if there are outgoing changes, 1 otherwise.
3568 3568 """
3569 3569 opts = pycompat.byteskwargs(opts)
3570 3570 if opts.get('graph'):
3571 3571 cmdutil.checkunsupportedgraphflags([], opts)
3572 3572 o, other = hg._outgoing(ui, repo, dest, opts)
3573 3573 if not o:
3574 3574 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3575 3575 return
3576 3576
3577 3577 revdag = cmdutil.graphrevs(repo, o, opts)
3578 3578 ui.pager('outgoing')
3579 3579 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
3580 3580 cmdutil.displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges)
3581 3581 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3582 3582 return 0
3583 3583
3584 3584 if opts.get('bookmarks'):
3585 3585 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3586 3586 dest, branches = hg.parseurl(dest, opts.get('branch'))
3587 3587 other = hg.peer(repo, opts, dest)
3588 3588 if 'bookmarks' not in other.listkeys('namespaces'):
3589 3589 ui.warn(_("remote doesn't support bookmarks\n"))
3590 3590 return 0
3591 3591 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3592 3592 ui.pager('outgoing')
3593 3593 return bookmarks.outgoing(ui, repo, other)
3594 3594
3595 3595 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3596 3596 try:
3597 3597 return hg.outgoing(ui, repo, dest, opts)
3598 3598 finally:
3599 3599 del repo._subtoppath
3600 3600
3601 3601 @command('parents',
3602 3602 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3603 3603 ] + templateopts,
3604 3604 _('[-r REV] [FILE]'),
3605 3605 inferrepo=True)
3606 3606 def parents(ui, repo, file_=None, **opts):
3607 3607 """show the parents of the working directory or revision (DEPRECATED)
3608 3608
3609 3609 Print the working directory's parent revisions. If a revision is
3610 3610 given via -r/--rev, the parent of that revision will be printed.
3611 3611 If a file argument is given, the revision in which the file was
3612 3612 last changed (before the working directory revision or the
3613 3613 argument to --rev if given) is printed.
3614 3614
3615 3615 This command is equivalent to::
3616 3616
3617 3617 hg log -r "p1()+p2()" or
3618 3618 hg log -r "p1(REV)+p2(REV)" or
3619 3619 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
3620 3620 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
3621 3621
3622 3622 See :hg:`summary` and :hg:`help revsets` for related information.
3623 3623
3624 3624 Returns 0 on success.
3625 3625 """
3626 3626
3627 3627 opts = pycompat.byteskwargs(opts)
3628 3628 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3629 3629
3630 3630 if file_:
3631 3631 m = scmutil.match(ctx, (file_,), opts)
3632 3632 if m.anypats() or len(m.files()) != 1:
3633 3633 raise error.Abort(_('can only specify an explicit filename'))
3634 3634 file_ = m.files()[0]
3635 3635 filenodes = []
3636 3636 for cp in ctx.parents():
3637 3637 if not cp:
3638 3638 continue
3639 3639 try:
3640 3640 filenodes.append(cp.filenode(file_))
3641 3641 except error.LookupError:
3642 3642 pass
3643 3643 if not filenodes:
3644 3644 raise error.Abort(_("'%s' not found in manifest!") % file_)
3645 3645 p = []
3646 3646 for fn in filenodes:
3647 3647 fctx = repo.filectx(file_, fileid=fn)
3648 3648 p.append(fctx.node())
3649 3649 else:
3650 3650 p = [cp.node() for cp in ctx.parents()]
3651 3651
3652 3652 displayer = cmdutil.show_changeset(ui, repo, opts)
3653 3653 for n in p:
3654 3654 if n != nullid:
3655 3655 displayer.show(repo[n])
3656 3656 displayer.close()
3657 3657
3658 3658 @command('paths', formatteropts, _('[NAME]'), optionalrepo=True)
3659 3659 def paths(ui, repo, search=None, **opts):
3660 3660 """show aliases for remote repositories
3661 3661
3662 3662 Show definition of symbolic path name NAME. If no name is given,
3663 3663 show definition of all available names.
3664 3664
3665 3665 Option -q/--quiet suppresses all output when searching for NAME
3666 3666 and shows only the path names when listing all definitions.
3667 3667
3668 3668 Path names are defined in the [paths] section of your
3669 3669 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3670 3670 repository, ``.hg/hgrc`` is used, too.
3671 3671
3672 3672 The path names ``default`` and ``default-push`` have a special
3673 3673 meaning. When performing a push or pull operation, they are used
3674 3674 as fallbacks if no location is specified on the command-line.
3675 3675 When ``default-push`` is set, it will be used for push and
3676 3676 ``default`` will be used for pull; otherwise ``default`` is used
3677 3677 as the fallback for both. When cloning a repository, the clone
3678 3678 source is written as ``default`` in ``.hg/hgrc``.
3679 3679
3680 3680 .. note::
3681 3681
3682 3682 ``default`` and ``default-push`` apply to all inbound (e.g.
3683 3683 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
3684 3684 and :hg:`bundle`) operations.
3685 3685
3686 3686 See :hg:`help urls` for more information.
3687 3687
3688 3688 Returns 0 on success.
3689 3689 """
3690 3690
3691 3691 opts = pycompat.byteskwargs(opts)
3692 3692 ui.pager('paths')
3693 3693 if search:
3694 3694 pathitems = [(name, path) for name, path in ui.paths.iteritems()
3695 3695 if name == search]
3696 3696 else:
3697 3697 pathitems = sorted(ui.paths.iteritems())
3698 3698
3699 3699 fm = ui.formatter('paths', opts)
3700 3700 if fm.isplain():
3701 3701 hidepassword = util.hidepassword
3702 3702 else:
3703 3703 hidepassword = str
3704 3704 if ui.quiet:
3705 3705 namefmt = '%s\n'
3706 3706 else:
3707 3707 namefmt = '%s = '
3708 3708 showsubopts = not search and not ui.quiet
3709 3709
3710 3710 for name, path in pathitems:
3711 3711 fm.startitem()
3712 3712 fm.condwrite(not search, 'name', namefmt, name)
3713 3713 fm.condwrite(not ui.quiet, 'url', '%s\n', hidepassword(path.rawloc))
3714 3714 for subopt, value in sorted(path.suboptions.items()):
3715 3715 assert subopt not in ('name', 'url')
3716 3716 if showsubopts:
3717 3717 fm.plain('%s:%s = ' % (name, subopt))
3718 3718 fm.condwrite(showsubopts, subopt, '%s\n', value)
3719 3719
3720 3720 fm.end()
3721 3721
3722 3722 if search and not pathitems:
3723 3723 if not ui.quiet:
3724 3724 ui.warn(_("not found!\n"))
3725 3725 return 1
3726 3726 else:
3727 3727 return 0
3728 3728
3729 3729 @command('phase',
3730 3730 [('p', 'public', False, _('set changeset phase to public')),
3731 3731 ('d', 'draft', False, _('set changeset phase to draft')),
3732 3732 ('s', 'secret', False, _('set changeset phase to secret')),
3733 3733 ('f', 'force', False, _('allow to move boundary backward')),
3734 3734 ('r', 'rev', [], _('target revision'), _('REV')),
3735 3735 ],
3736 3736 _('[-p|-d|-s] [-f] [-r] [REV...]'))
3737 3737 def phase(ui, repo, *revs, **opts):
3738 3738 """set or show the current phase name
3739 3739
3740 3740 With no argument, show the phase name of the current revision(s).
3741 3741
3742 3742 With one of -p/--public, -d/--draft or -s/--secret, change the
3743 3743 phase value of the specified revisions.
3744 3744
3745 3745 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
3746 3746 lower phase to an higher phase. Phases are ordered as follows::
3747 3747
3748 3748 public < draft < secret
3749 3749
3750 3750 Returns 0 on success, 1 if some phases could not be changed.
3751 3751
3752 3752 (For more information about the phases concept, see :hg:`help phases`.)
3753 3753 """
3754 3754 opts = pycompat.byteskwargs(opts)
3755 3755 # search for a unique phase argument
3756 3756 targetphase = None
3757 3757 for idx, name in enumerate(phases.phasenames):
3758 3758 if opts[name]:
3759 3759 if targetphase is not None:
3760 3760 raise error.Abort(_('only one phase can be specified'))
3761 3761 targetphase = idx
3762 3762
3763 3763 # look for specified revision
3764 3764 revs = list(revs)
3765 3765 revs.extend(opts['rev'])
3766 3766 if not revs:
3767 3767 # display both parents as the second parent phase can influence
3768 3768 # the phase of a merge commit
3769 3769 revs = [c.rev() for c in repo[None].parents()]
3770 3770
3771 3771 revs = scmutil.revrange(repo, revs)
3772 3772
3773 3773 lock = None
3774 3774 ret = 0
3775 3775 if targetphase is None:
3776 3776 # display
3777 3777 for r in revs:
3778 3778 ctx = repo[r]
3779 3779 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
3780 3780 else:
3781 3781 tr = None
3782 3782 lock = repo.lock()
3783 3783 try:
3784 3784 tr = repo.transaction("phase")
3785 3785 # set phase
3786 3786 if not revs:
3787 3787 raise error.Abort(_('empty revision set'))
3788 3788 nodes = [repo[r].node() for r in revs]
3789 3789 # moving revision from public to draft may hide them
3790 3790 # We have to check result on an unfiltered repository
3791 3791 unfi = repo.unfiltered()
3792 3792 getphase = unfi._phasecache.phase
3793 3793 olddata = [getphase(unfi, r) for r in unfi]
3794 3794 phases.advanceboundary(repo, tr, targetphase, nodes)
3795 3795 if opts['force']:
3796 3796 phases.retractboundary(repo, tr, targetphase, nodes)
3797 3797 tr.close()
3798 3798 finally:
3799 3799 if tr is not None:
3800 3800 tr.release()
3801 3801 lock.release()
3802 3802 getphase = unfi._phasecache.phase
3803 3803 newdata = [getphase(unfi, r) for r in unfi]
3804 3804 changes = sum(newdata[r] != olddata[r] for r in unfi)
3805 3805 cl = unfi.changelog
3806 3806 rejected = [n for n in nodes
3807 3807 if newdata[cl.rev(n)] < targetphase]
3808 3808 if rejected:
3809 3809 ui.warn(_('cannot move %i changesets to a higher '
3810 3810 'phase, use --force\n') % len(rejected))
3811 3811 ret = 1
3812 3812 if changes:
3813 3813 msg = _('phase changed for %i changesets\n') % changes
3814 3814 if ret:
3815 3815 ui.status(msg)
3816 3816 else:
3817 3817 ui.note(msg)
3818 3818 else:
3819 3819 ui.warn(_('no phases changed\n'))
3820 3820 return ret
3821 3821
3822 3822 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
3823 3823 """Run after a changegroup has been added via pull/unbundle
3824 3824
3825 3825 This takes arguments below:
3826 3826
3827 3827 :modheads: change of heads by pull/unbundle
3828 3828 :optupdate: updating working directory is needed or not
3829 3829 :checkout: update destination revision (or None to default destination)
3830 3830 :brev: a name, which might be a bookmark to be activated after updating
3831 3831 """
3832 3832 if modheads == 0:
3833 3833 return
3834 3834 if optupdate:
3835 3835 try:
3836 3836 return hg.updatetotally(ui, repo, checkout, brev)
3837 3837 except error.UpdateAbort as inst:
3838 3838 msg = _("not updating: %s") % str(inst)
3839 3839 hint = inst.hint
3840 3840 raise error.UpdateAbort(msg, hint=hint)
3841 3841 if modheads > 1:
3842 3842 currentbranchheads = len(repo.branchheads())
3843 3843 if currentbranchheads == modheads:
3844 3844 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3845 3845 elif currentbranchheads > 1:
3846 3846 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
3847 3847 "merge)\n"))
3848 3848 else:
3849 3849 ui.status(_("(run 'hg heads' to see heads)\n"))
3850 3850 elif not ui.configbool('commands', 'update.requiredest'):
3851 3851 ui.status(_("(run 'hg update' to get a working copy)\n"))
3852 3852
3853 3853 @command('^pull',
3854 3854 [('u', 'update', None,
3855 3855 _('update to new branch head if changesets were pulled')),
3856 3856 ('f', 'force', None, _('run even when remote repository is unrelated')),
3857 3857 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3858 3858 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3859 3859 ('b', 'branch', [], _('a specific branch you would like to pull'),
3860 3860 _('BRANCH')),
3861 3861 ] + remoteopts,
3862 3862 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3863 3863 def pull(ui, repo, source="default", **opts):
3864 3864 """pull changes from the specified source
3865 3865
3866 3866 Pull changes from a remote repository to a local one.
3867 3867
3868 3868 This finds all changes from the repository at the specified path
3869 3869 or URL and adds them to a local repository (the current one unless
3870 3870 -R is specified). By default, this does not update the copy of the
3871 3871 project in the working directory.
3872 3872
3873 3873 Use :hg:`incoming` if you want to see what would have been added
3874 3874 by a pull at the time you issued this command. If you then decide
3875 3875 to add those changes to the repository, you should use :hg:`pull
3876 3876 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3877 3877
3878 3878 If SOURCE is omitted, the 'default' path will be used.
3879 3879 See :hg:`help urls` for more information.
3880 3880
3881 3881 Specifying bookmark as ``.`` is equivalent to specifying the active
3882 3882 bookmark's name.
3883 3883
3884 3884 Returns 0 on success, 1 if an update had unresolved files.
3885 3885 """
3886 3886
3887 3887 opts = pycompat.byteskwargs(opts)
3888 3888 if ui.configbool('commands', 'update.requiredest') and opts.get('update'):
3889 3889 msg = _('update destination required by configuration')
3890 3890 hint = _('use hg pull followed by hg update DEST')
3891 3891 raise error.Abort(msg, hint=hint)
3892 3892
3893 3893 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3894 3894 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3895 3895 other = hg.peer(repo, opts, source)
3896 3896 try:
3897 3897 revs, checkout = hg.addbranchrevs(repo, other, branches,
3898 3898 opts.get('rev'))
3899 3899
3900 3900
3901 3901 pullopargs = {}
3902 3902 if opts.get('bookmark'):
3903 3903 if not revs:
3904 3904 revs = []
3905 3905 # The list of bookmark used here is not the one used to actually
3906 3906 # update the bookmark name. This can result in the revision pulled
3907 3907 # not ending up with the name of the bookmark because of a race
3908 3908 # condition on the server. (See issue 4689 for details)
3909 3909 remotebookmarks = other.listkeys('bookmarks')
3910 3910 pullopargs['remotebookmarks'] = remotebookmarks
3911 3911 for b in opts['bookmark']:
3912 3912 b = repo._bookmarks.expandname(b)
3913 3913 if b not in remotebookmarks:
3914 3914 raise error.Abort(_('remote bookmark %s not found!') % b)
3915 3915 revs.append(remotebookmarks[b])
3916 3916
3917 3917 if revs:
3918 3918 try:
3919 3919 # When 'rev' is a bookmark name, we cannot guarantee that it
3920 3920 # will be updated with that name because of a race condition
3921 3921 # server side. (See issue 4689 for details)
3922 3922 oldrevs = revs
3923 3923 revs = [] # actually, nodes
3924 3924 for r in oldrevs:
3925 3925 node = other.lookup(r)
3926 3926 revs.append(node)
3927 3927 if r == checkout:
3928 3928 checkout = node
3929 3929 except error.CapabilityError:
3930 3930 err = _("other repository doesn't support revision lookup, "
3931 3931 "so a rev cannot be specified.")
3932 3932 raise error.Abort(err)
3933 3933
3934 3934 pullopargs.update(opts.get('opargs', {}))
3935 3935 modheads = exchange.pull(repo, other, heads=revs,
3936 3936 force=opts.get('force'),
3937 3937 bookmarks=opts.get('bookmark', ()),
3938 3938 opargs=pullopargs).cgresult
3939 3939
3940 3940 # brev is a name, which might be a bookmark to be activated at
3941 3941 # the end of the update. In other words, it is an explicit
3942 3942 # destination of the update
3943 3943 brev = None
3944 3944
3945 3945 if checkout:
3946 3946 checkout = str(repo.changelog.rev(checkout))
3947 3947
3948 3948 # order below depends on implementation of
3949 3949 # hg.addbranchrevs(). opts['bookmark'] is ignored,
3950 3950 # because 'checkout' is determined without it.
3951 3951 if opts.get('rev'):
3952 3952 brev = opts['rev'][0]
3953 3953 elif opts.get('branch'):
3954 3954 brev = opts['branch'][0]
3955 3955 else:
3956 3956 brev = branches[0]
3957 3957 repo._subtoppath = source
3958 3958 try:
3959 3959 ret = postincoming(ui, repo, modheads, opts.get('update'),
3960 3960 checkout, brev)
3961 3961
3962 3962 finally:
3963 3963 del repo._subtoppath
3964 3964
3965 3965 finally:
3966 3966 other.close()
3967 3967 return ret
3968 3968
3969 3969 @command('^push',
3970 3970 [('f', 'force', None, _('force push')),
3971 3971 ('r', 'rev', [],
3972 3972 _('a changeset intended to be included in the destination'),
3973 3973 _('REV')),
3974 3974 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
3975 3975 ('b', 'branch', [],
3976 3976 _('a specific branch you would like to push'), _('BRANCH')),
3977 3977 ('', 'new-branch', False, _('allow pushing a new branch')),
3978 3978 ('', 'pushvars', [], _('variables that can be sent to server (ADVANCED)')),
3979 3979 ] + remoteopts,
3980 3980 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
3981 3981 def push(ui, repo, dest=None, **opts):
3982 3982 """push changes to the specified destination
3983 3983
3984 3984 Push changesets from the local repository to the specified
3985 3985 destination.
3986 3986
3987 3987 This operation is symmetrical to pull: it is identical to a pull
3988 3988 in the destination repository from the current one.
3989 3989
3990 3990 By default, push will not allow creation of new heads at the
3991 3991 destination, since multiple heads would make it unclear which head
3992 3992 to use. In this situation, it is recommended to pull and merge
3993 3993 before pushing.
3994 3994
3995 3995 Use --new-branch if you want to allow push to create a new named
3996 3996 branch that is not present at the destination. This allows you to
3997 3997 only create a new branch without forcing other changes.
3998 3998
3999 3999 .. note::
4000 4000
4001 4001 Extra care should be taken with the -f/--force option,
4002 4002 which will push all new heads on all branches, an action which will
4003 4003 almost always cause confusion for collaborators.
4004 4004
4005 4005 If -r/--rev is used, the specified revision and all its ancestors
4006 4006 will be pushed to the remote repository.
4007 4007
4008 4008 If -B/--bookmark is used, the specified bookmarked revision, its
4009 4009 ancestors, and the bookmark will be pushed to the remote
4010 4010 repository. Specifying ``.`` is equivalent to specifying the active
4011 4011 bookmark's name.
4012 4012
4013 4013 Please see :hg:`help urls` for important details about ``ssh://``
4014 4014 URLs. If DESTINATION is omitted, a default path will be used.
4015 4015
4016 4016 .. container:: verbose
4017 4017
4018 4018 The --pushvars option sends strings to the server that become
4019 4019 environment variables prepended with ``HG_USERVAR_``. For example,
4020 4020 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
4021 4021 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
4022 4022
4023 4023 pushvars can provide for user-overridable hooks as well as set debug
4024 4024 levels. One example is having a hook that blocks commits containing
4025 4025 conflict markers, but enables the user to override the hook if the file
4026 4026 is using conflict markers for testing purposes or the file format has
4027 4027 strings that look like conflict markers.
4028 4028
4029 4029 By default, servers will ignore `--pushvars`. To enable it add the
4030 4030 following to your configuration file::
4031 4031
4032 4032 [push]
4033 4033 pushvars.server = true
4034 4034
4035 4035 Returns 0 if push was successful, 1 if nothing to push.
4036 4036 """
4037 4037
4038 4038 opts = pycompat.byteskwargs(opts)
4039 4039 if opts.get('bookmark'):
4040 4040 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4041 4041 for b in opts['bookmark']:
4042 4042 # translate -B options to -r so changesets get pushed
4043 4043 b = repo._bookmarks.expandname(b)
4044 4044 if b in repo._bookmarks:
4045 4045 opts.setdefault('rev', []).append(b)
4046 4046 else:
4047 4047 # if we try to push a deleted bookmark, translate it to null
4048 4048 # this lets simultaneous -r, -b options continue working
4049 4049 opts.setdefault('rev', []).append("null")
4050 4050
4051 4051 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4052 4052 if not path:
4053 4053 raise error.Abort(_('default repository not configured!'),
4054 4054 hint=_("see 'hg help config.paths'"))
4055 4055 dest = path.pushloc or path.loc
4056 4056 branches = (path.branch, opts.get('branch') or [])
4057 4057 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4058 4058 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4059 4059 other = hg.peer(repo, opts, dest)
4060 4060
4061 4061 if revs:
4062 4062 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4063 4063 if not revs:
4064 4064 raise error.Abort(_("specified revisions evaluate to an empty set"),
4065 4065 hint=_("use different revision arguments"))
4066 4066 elif path.pushrev:
4067 4067 # It doesn't make any sense to specify ancestor revisions. So limit
4068 4068 # to DAG heads to make discovery simpler.
4069 4069 expr = revsetlang.formatspec('heads(%r)', path.pushrev)
4070 4070 revs = scmutil.revrange(repo, [expr])
4071 4071 revs = [repo[rev].node() for rev in revs]
4072 4072 if not revs:
4073 4073 raise error.Abort(_('default push revset for path evaluates to an '
4074 4074 'empty set'))
4075 4075
4076 4076 repo._subtoppath = dest
4077 4077 try:
4078 4078 # push subrepos depth-first for coherent ordering
4079 4079 c = repo['']
4080 4080 subs = c.substate # only repos that are committed
4081 4081 for s in sorted(subs):
4082 4082 result = c.sub(s).push(opts)
4083 4083 if result == 0:
4084 4084 return not result
4085 4085 finally:
4086 4086 del repo._subtoppath
4087 4087
4088 4088 opargs = dict(opts.get('opargs', {})) # copy opargs since we may mutate it
4089 4089 opargs.setdefault('pushvars', []).extend(opts.get('pushvars', []))
4090 4090
4091 4091 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
4092 4092 newbranch=opts.get('new_branch'),
4093 4093 bookmarks=opts.get('bookmark', ()),
4094 4094 opargs=opargs)
4095 4095
4096 4096 result = not pushop.cgresult
4097 4097
4098 4098 if pushop.bkresult is not None:
4099 4099 if pushop.bkresult == 2:
4100 4100 result = 2
4101 4101 elif not result and pushop.bkresult:
4102 4102 result = 2
4103 4103
4104 4104 return result
4105 4105
4106 4106 @command('recover', [])
4107 4107 def recover(ui, repo):
4108 4108 """roll back an interrupted transaction
4109 4109
4110 4110 Recover from an interrupted commit or pull.
4111 4111
4112 4112 This command tries to fix the repository status after an
4113 4113 interrupted operation. It should only be necessary when Mercurial
4114 4114 suggests it.
4115 4115
4116 4116 Returns 0 if successful, 1 if nothing to recover or verify fails.
4117 4117 """
4118 4118 if repo.recover():
4119 4119 return hg.verify(repo)
4120 4120 return 1
4121 4121
4122 4122 @command('^remove|rm',
4123 4123 [('A', 'after', None, _('record delete for missing files')),
4124 4124 ('f', 'force', None,
4125 4125 _('forget added files, delete modified files')),
4126 4126 ] + subrepoopts + walkopts,
4127 4127 _('[OPTION]... FILE...'),
4128 4128 inferrepo=True)
4129 4129 def remove(ui, repo, *pats, **opts):
4130 4130 """remove the specified files on the next commit
4131 4131
4132 4132 Schedule the indicated files for removal from the current branch.
4133 4133
4134 4134 This command schedules the files to be removed at the next commit.
4135 4135 To undo a remove before that, see :hg:`revert`. To undo added
4136 4136 files, see :hg:`forget`.
4137 4137
4138 4138 .. container:: verbose
4139 4139
4140 4140 -A/--after can be used to remove only files that have already
4141 4141 been deleted, -f/--force can be used to force deletion, and -Af
4142 4142 can be used to remove files from the next revision without
4143 4143 deleting them from the working directory.
4144 4144
4145 4145 The following table details the behavior of remove for different
4146 4146 file states (columns) and option combinations (rows). The file
4147 4147 states are Added [A], Clean [C], Modified [M] and Missing [!]
4148 4148 (as reported by :hg:`status`). The actions are Warn, Remove
4149 4149 (from branch) and Delete (from disk):
4150 4150
4151 4151 ========= == == == ==
4152 4152 opt/state A C M !
4153 4153 ========= == == == ==
4154 4154 none W RD W R
4155 4155 -f R RD RD R
4156 4156 -A W W W R
4157 4157 -Af R R R R
4158 4158 ========= == == == ==
4159 4159
4160 4160 .. note::
4161 4161
4162 4162 :hg:`remove` never deletes files in Added [A] state from the
4163 4163 working directory, not even if ``--force`` is specified.
4164 4164
4165 4165 Returns 0 on success, 1 if any warnings encountered.
4166 4166 """
4167 4167
4168 4168 opts = pycompat.byteskwargs(opts)
4169 4169 after, force = opts.get('after'), opts.get('force')
4170 4170 if not pats and not after:
4171 4171 raise error.Abort(_('no files specified'))
4172 4172
4173 4173 m = scmutil.match(repo[None], pats, opts)
4174 4174 subrepos = opts.get('subrepos')
4175 4175 return cmdutil.remove(ui, repo, m, "", after, force, subrepos)
4176 4176
4177 4177 @command('rename|move|mv',
4178 4178 [('A', 'after', None, _('record a rename that has already occurred')),
4179 4179 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4180 4180 ] + walkopts + dryrunopts,
4181 4181 _('[OPTION]... SOURCE... DEST'))
4182 4182 def rename(ui, repo, *pats, **opts):
4183 4183 """rename files; equivalent of copy + remove
4184 4184
4185 4185 Mark dest as copies of sources; mark sources for deletion. If dest
4186 4186 is a directory, copies are put in that directory. If dest is a
4187 4187 file, there can only be one source.
4188 4188
4189 4189 By default, this command copies the contents of files as they
4190 4190 exist in the working directory. If invoked with -A/--after, the
4191 4191 operation is recorded, but no copying is performed.
4192 4192
4193 4193 This command takes effect at the next commit. To undo a rename
4194 4194 before that, see :hg:`revert`.
4195 4195
4196 4196 Returns 0 on success, 1 if errors are encountered.
4197 4197 """
4198 4198 opts = pycompat.byteskwargs(opts)
4199 4199 with repo.wlock(False):
4200 4200 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4201 4201
4202 4202 @command('resolve',
4203 4203 [('a', 'all', None, _('select all unresolved files')),
4204 4204 ('l', 'list', None, _('list state of files needing merge')),
4205 4205 ('m', 'mark', None, _('mark files as resolved')),
4206 4206 ('u', 'unmark', None, _('mark files as unresolved')),
4207 4207 ('n', 'no-status', None, _('hide status prefix'))]
4208 4208 + mergetoolopts + walkopts + formatteropts,
4209 4209 _('[OPTION]... [FILE]...'),
4210 4210 inferrepo=True)
4211 4211 def resolve(ui, repo, *pats, **opts):
4212 4212 """redo merges or set/view the merge status of files
4213 4213
4214 4214 Merges with unresolved conflicts are often the result of
4215 4215 non-interactive merging using the ``internal:merge`` configuration
4216 4216 setting, or a command-line merge tool like ``diff3``. The resolve
4217 4217 command is used to manage the files involved in a merge, after
4218 4218 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4219 4219 working directory must have two parents). See :hg:`help
4220 4220 merge-tools` for information on configuring merge tools.
4221 4221
4222 4222 The resolve command can be used in the following ways:
4223 4223
4224 4224 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4225 4225 files, discarding any previous merge attempts. Re-merging is not
4226 4226 performed for files already marked as resolved. Use ``--all/-a``
4227 4227 to select all unresolved files. ``--tool`` can be used to specify
4228 4228 the merge tool used for the given files. It overrides the HGMERGE
4229 4229 environment variable and your configuration files. Previous file
4230 4230 contents are saved with a ``.orig`` suffix.
4231 4231
4232 4232 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4233 4233 (e.g. after having manually fixed-up the files). The default is
4234 4234 to mark all unresolved files.
4235 4235
4236 4236 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4237 4237 default is to mark all resolved files.
4238 4238
4239 4239 - :hg:`resolve -l`: list files which had or still have conflicts.
4240 4240 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4241 4241 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
4242 4242 the list. See :hg:`help filesets` for details.
4243 4243
4244 4244 .. note::
4245 4245
4246 4246 Mercurial will not let you commit files with unresolved merge
4247 4247 conflicts. You must use :hg:`resolve -m ...` before you can
4248 4248 commit after a conflicting merge.
4249 4249
4250 4250 Returns 0 on success, 1 if any files fail a resolve attempt.
4251 4251 """
4252 4252
4253 4253 opts = pycompat.byteskwargs(opts)
4254 4254 flaglist = 'all mark unmark list no_status'.split()
4255 4255 all, mark, unmark, show, nostatus = \
4256 4256 [opts.get(o) for o in flaglist]
4257 4257
4258 4258 if (show and (mark or unmark)) or (mark and unmark):
4259 4259 raise error.Abort(_("too many options specified"))
4260 4260 if pats and all:
4261 4261 raise error.Abort(_("can't specify --all and patterns"))
4262 4262 if not (all or pats or show or mark or unmark):
4263 4263 raise error.Abort(_('no files or directories specified'),
4264 4264 hint=('use --all to re-merge all unresolved files'))
4265 4265
4266 4266 if show:
4267 4267 ui.pager('resolve')
4268 4268 fm = ui.formatter('resolve', opts)
4269 4269 ms = mergemod.mergestate.read(repo)
4270 4270 m = scmutil.match(repo[None], pats, opts)
4271 4271 for f in ms:
4272 4272 if not m(f):
4273 4273 continue
4274 4274 l = 'resolve.' + {'u': 'unresolved', 'r': 'resolved',
4275 4275 'd': 'driverresolved'}[ms[f]]
4276 4276 fm.startitem()
4277 4277 fm.condwrite(not nostatus, 'status', '%s ', ms[f].upper(), label=l)
4278 4278 fm.write('path', '%s\n', f, label=l)
4279 4279 fm.end()
4280 4280 return 0
4281 4281
4282 4282 with repo.wlock():
4283 4283 ms = mergemod.mergestate.read(repo)
4284 4284
4285 4285 if not (ms.active() or repo.dirstate.p2() != nullid):
4286 4286 raise error.Abort(
4287 4287 _('resolve command not applicable when not merging'))
4288 4288
4289 4289 wctx = repo[None]
4290 4290
4291 4291 if ms.mergedriver and ms.mdstate() == 'u':
4292 4292 proceed = mergemod.driverpreprocess(repo, ms, wctx)
4293 4293 ms.commit()
4294 4294 # allow mark and unmark to go through
4295 4295 if not mark and not unmark and not proceed:
4296 4296 return 1
4297 4297
4298 4298 m = scmutil.match(wctx, pats, opts)
4299 4299 ret = 0
4300 4300 didwork = False
4301 4301 runconclude = False
4302 4302
4303 4303 tocomplete = []
4304 4304 for f in ms:
4305 4305 if not m(f):
4306 4306 continue
4307 4307
4308 4308 didwork = True
4309 4309
4310 4310 # don't let driver-resolved files be marked, and run the conclude
4311 4311 # step if asked to resolve
4312 4312 if ms[f] == "d":
4313 4313 exact = m.exact(f)
4314 4314 if mark:
4315 4315 if exact:
4316 4316 ui.warn(_('not marking %s as it is driver-resolved\n')
4317 4317 % f)
4318 4318 elif unmark:
4319 4319 if exact:
4320 4320 ui.warn(_('not unmarking %s as it is driver-resolved\n')
4321 4321 % f)
4322 4322 else:
4323 4323 runconclude = True
4324 4324 continue
4325 4325
4326 4326 if mark:
4327 4327 ms.mark(f, "r")
4328 4328 elif unmark:
4329 4329 ms.mark(f, "u")
4330 4330 else:
4331 4331 # backup pre-resolve (merge uses .orig for its own purposes)
4332 4332 a = repo.wjoin(f)
4333 4333 try:
4334 4334 util.copyfile(a, a + ".resolve")
4335 4335 except (IOError, OSError) as inst:
4336 4336 if inst.errno != errno.ENOENT:
4337 4337 raise
4338 4338
4339 4339 try:
4340 4340 # preresolve file
4341 4341 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4342 4342 'resolve')
4343 4343 complete, r = ms.preresolve(f, wctx)
4344 4344 if not complete:
4345 4345 tocomplete.append(f)
4346 4346 elif r:
4347 4347 ret = 1
4348 4348 finally:
4349 4349 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4350 4350 ms.commit()
4351 4351
4352 4352 # replace filemerge's .orig file with our resolve file, but only
4353 4353 # for merges that are complete
4354 4354 if complete:
4355 4355 try:
4356 4356 util.rename(a + ".resolve",
4357 4357 scmutil.origpath(ui, repo, a))
4358 4358 except OSError as inst:
4359 4359 if inst.errno != errno.ENOENT:
4360 4360 raise
4361 4361
4362 4362 for f in tocomplete:
4363 4363 try:
4364 4364 # resolve file
4365 4365 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4366 4366 'resolve')
4367 4367 r = ms.resolve(f, wctx)
4368 4368 if r:
4369 4369 ret = 1
4370 4370 finally:
4371 4371 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4372 4372 ms.commit()
4373 4373
4374 4374 # replace filemerge's .orig file with our resolve file
4375 4375 a = repo.wjoin(f)
4376 4376 try:
4377 4377 util.rename(a + ".resolve", scmutil.origpath(ui, repo, a))
4378 4378 except OSError as inst:
4379 4379 if inst.errno != errno.ENOENT:
4380 4380 raise
4381 4381
4382 4382 ms.commit()
4383 4383 ms.recordactions()
4384 4384
4385 4385 if not didwork and pats:
4386 4386 hint = None
4387 4387 if not any([p for p in pats if p.find(':') >= 0]):
4388 4388 pats = ['path:%s' % p for p in pats]
4389 4389 m = scmutil.match(wctx, pats, opts)
4390 4390 for f in ms:
4391 4391 if not m(f):
4392 4392 continue
4393 4393 flags = ''.join(['-%s ' % o[0] for o in flaglist
4394 4394 if opts.get(o)])
4395 4395 hint = _("(try: hg resolve %s%s)\n") % (
4396 4396 flags,
4397 4397 ' '.join(pats))
4398 4398 break
4399 4399 ui.warn(_("arguments do not match paths that need resolving\n"))
4400 4400 if hint:
4401 4401 ui.warn(hint)
4402 4402 elif ms.mergedriver and ms.mdstate() != 's':
4403 4403 # run conclude step when either a driver-resolved file is requested
4404 4404 # or there are no driver-resolved files
4405 4405 # we can't use 'ret' to determine whether any files are unresolved
4406 4406 # because we might not have tried to resolve some
4407 4407 if ((runconclude or not list(ms.driverresolved()))
4408 4408 and not list(ms.unresolved())):
4409 4409 proceed = mergemod.driverconclude(repo, ms, wctx)
4410 4410 ms.commit()
4411 4411 if not proceed:
4412 4412 return 1
4413 4413
4414 4414 # Nudge users into finishing an unfinished operation
4415 4415 unresolvedf = list(ms.unresolved())
4416 4416 driverresolvedf = list(ms.driverresolved())
4417 4417 if not unresolvedf and not driverresolvedf:
4418 4418 ui.status(_('(no more unresolved files)\n'))
4419 4419 cmdutil.checkafterresolved(repo)
4420 4420 elif not unresolvedf:
4421 4421 ui.status(_('(no more unresolved files -- '
4422 4422 'run "hg resolve --all" to conclude)\n'))
4423 4423
4424 4424 return ret
4425 4425
4426 4426 @command('revert',
4427 4427 [('a', 'all', None, _('revert all changes when no arguments given')),
4428 4428 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4429 4429 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4430 4430 ('C', 'no-backup', None, _('do not save backup copies of files')),
4431 4431 ('i', 'interactive', None,
4432 4432 _('interactively select the changes (EXPERIMENTAL)')),
4433 4433 ] + walkopts + dryrunopts,
4434 4434 _('[OPTION]... [-r REV] [NAME]...'))
4435 4435 def revert(ui, repo, *pats, **opts):
4436 4436 """restore files to their checkout state
4437 4437
4438 4438 .. note::
4439 4439
4440 4440 To check out earlier revisions, you should use :hg:`update REV`.
4441 4441 To cancel an uncommitted merge (and lose your changes),
4442 4442 use :hg:`update --clean .`.
4443 4443
4444 4444 With no revision specified, revert the specified files or directories
4445 4445 to the contents they had in the parent of the working directory.
4446 4446 This restores the contents of files to an unmodified
4447 4447 state and unschedules adds, removes, copies, and renames. If the
4448 4448 working directory has two parents, you must explicitly specify a
4449 4449 revision.
4450 4450
4451 4451 Using the -r/--rev or -d/--date options, revert the given files or
4452 4452 directories to their states as of a specific revision. Because
4453 4453 revert does not change the working directory parents, this will
4454 4454 cause these files to appear modified. This can be helpful to "back
4455 4455 out" some or all of an earlier change. See :hg:`backout` for a
4456 4456 related method.
4457 4457
4458 4458 Modified files are saved with a .orig suffix before reverting.
4459 4459 To disable these backups, use --no-backup. It is possible to store
4460 4460 the backup files in a custom directory relative to the root of the
4461 4461 repository by setting the ``ui.origbackuppath`` configuration
4462 4462 option.
4463 4463
4464 4464 See :hg:`help dates` for a list of formats valid for -d/--date.
4465 4465
4466 4466 See :hg:`help backout` for a way to reverse the effect of an
4467 4467 earlier changeset.
4468 4468
4469 4469 Returns 0 on success.
4470 4470 """
4471 4471
4472 4472 if opts.get("date"):
4473 4473 if opts.get("rev"):
4474 4474 raise error.Abort(_("you can't specify a revision and a date"))
4475 4475 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4476 4476
4477 4477 parent, p2 = repo.dirstate.parents()
4478 4478 if not opts.get('rev') and p2 != nullid:
4479 4479 # revert after merge is a trap for new users (issue2915)
4480 4480 raise error.Abort(_('uncommitted merge with no revision specified'),
4481 4481 hint=_("use 'hg update' or see 'hg help revert'"))
4482 4482
4483 4483 ctx = scmutil.revsingle(repo, opts.get('rev'))
4484 4484
4485 4485 if (not (pats or opts.get('include') or opts.get('exclude') or
4486 4486 opts.get('all') or opts.get('interactive'))):
4487 4487 msg = _("no files or directories specified")
4488 4488 if p2 != nullid:
4489 4489 hint = _("uncommitted merge, use --all to discard all changes,"
4490 4490 " or 'hg update -C .' to abort the merge")
4491 4491 raise error.Abort(msg, hint=hint)
4492 4492 dirty = any(repo.status())
4493 4493 node = ctx.node()
4494 4494 if node != parent:
4495 4495 if dirty:
4496 4496 hint = _("uncommitted changes, use --all to discard all"
4497 4497 " changes, or 'hg update %s' to update") % ctx.rev()
4498 4498 else:
4499 4499 hint = _("use --all to revert all files,"
4500 4500 " or 'hg update %s' to update") % ctx.rev()
4501 4501 elif dirty:
4502 4502 hint = _("uncommitted changes, use --all to discard all changes")
4503 4503 else:
4504 4504 hint = _("use --all to revert all files")
4505 4505 raise error.Abort(msg, hint=hint)
4506 4506
4507 4507 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
4508 4508
4509 4509 @command('rollback', dryrunopts +
4510 4510 [('f', 'force', False, _('ignore safety measures'))])
4511 4511 def rollback(ui, repo, **opts):
4512 4512 """roll back the last transaction (DANGEROUS) (DEPRECATED)
4513 4513
4514 4514 Please use :hg:`commit --amend` instead of rollback to correct
4515 4515 mistakes in the last commit.
4516 4516
4517 4517 This command should be used with care. There is only one level of
4518 4518 rollback, and there is no way to undo a rollback. It will also
4519 4519 restore the dirstate at the time of the last transaction, losing
4520 4520 any dirstate changes since that time. This command does not alter
4521 4521 the working directory.
4522 4522
4523 4523 Transactions are used to encapsulate the effects of all commands
4524 4524 that create new changesets or propagate existing changesets into a
4525 4525 repository.
4526 4526
4527 4527 .. container:: verbose
4528 4528
4529 4529 For example, the following commands are transactional, and their
4530 4530 effects can be rolled back:
4531 4531
4532 4532 - commit
4533 4533 - import
4534 4534 - pull
4535 4535 - push (with this repository as the destination)
4536 4536 - unbundle
4537 4537
4538 4538 To avoid permanent data loss, rollback will refuse to rollback a
4539 4539 commit transaction if it isn't checked out. Use --force to
4540 4540 override this protection.
4541 4541
4542 4542 The rollback command can be entirely disabled by setting the
4543 4543 ``ui.rollback`` configuration setting to false. If you're here
4544 4544 because you want to use rollback and it's disabled, you can
4545 4545 re-enable the command by setting ``ui.rollback`` to true.
4546 4546
4547 4547 This command is not intended for use on public repositories. Once
4548 4548 changes are visible for pull by other users, rolling a transaction
4549 4549 back locally is ineffective (someone else may already have pulled
4550 4550 the changes). Furthermore, a race is possible with readers of the
4551 4551 repository; for example an in-progress pull from the repository
4552 4552 may fail if a rollback is performed.
4553 4553
4554 4554 Returns 0 on success, 1 if no rollback data is available.
4555 4555 """
4556 4556 if not ui.configbool('ui', 'rollback'):
4557 4557 raise error.Abort(_('rollback is disabled because it is unsafe'),
4558 4558 hint=('see `hg help -v rollback` for information'))
4559 4559 return repo.rollback(dryrun=opts.get(r'dry_run'),
4560 4560 force=opts.get(r'force'))
4561 4561
4562 4562 @command('root', [])
4563 4563 def root(ui, repo):
4564 4564 """print the root (top) of the current working directory
4565 4565
4566 4566 Print the root directory of the current repository.
4567 4567
4568 4568 Returns 0 on success.
4569 4569 """
4570 4570 ui.write(repo.root + "\n")
4571 4571
4572 4572 @command('^serve',
4573 4573 [('A', 'accesslog', '', _('name of access log file to write to'),
4574 4574 _('FILE')),
4575 4575 ('d', 'daemon', None, _('run server in background')),
4576 4576 ('', 'daemon-postexec', [], _('used internally by daemon mode')),
4577 4577 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4578 4578 # use string type, then we can check if something was passed
4579 4579 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4580 4580 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4581 4581 _('ADDR')),
4582 4582 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4583 4583 _('PREFIX')),
4584 4584 ('n', 'name', '',
4585 4585 _('name to show in web pages (default: working directory)'), _('NAME')),
4586 4586 ('', 'web-conf', '',
4587 4587 _("name of the hgweb config file (see 'hg help hgweb')"), _('FILE')),
4588 4588 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4589 4589 _('FILE')),
4590 4590 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4591 4591 ('', 'stdio', None, _('for remote clients (ADVANCED)')),
4592 4592 ('', 'cmdserver', '', _('for remote clients (ADVANCED)'), _('MODE')),
4593 4593 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4594 4594 ('', 'style', '', _('template style to use'), _('STYLE')),
4595 4595 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4596 4596 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))]
4597 4597 + subrepoopts,
4598 4598 _('[OPTION]...'),
4599 4599 optionalrepo=True)
4600 4600 def serve(ui, repo, **opts):
4601 4601 """start stand-alone webserver
4602 4602
4603 4603 Start a local HTTP repository browser and pull server. You can use
4604 4604 this for ad-hoc sharing and browsing of repositories. It is
4605 4605 recommended to use a real web server to serve a repository for
4606 4606 longer periods of time.
4607 4607
4608 4608 Please note that the server does not implement access control.
4609 4609 This means that, by default, anybody can read from the server and
4610 4610 nobody can write to it by default. Set the ``web.allow_push``
4611 4611 option to ``*`` to allow everybody to push to the server. You
4612 4612 should use a real web server if you need to authenticate users.
4613 4613
4614 4614 By default, the server logs accesses to stdout and errors to
4615 4615 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4616 4616 files.
4617 4617
4618 4618 To have the server choose a free port number to listen on, specify
4619 4619 a port number of 0; in this case, the server will print the port
4620 4620 number it uses.
4621 4621
4622 4622 Returns 0 on success.
4623 4623 """
4624 4624
4625 4625 opts = pycompat.byteskwargs(opts)
4626 4626 if opts["stdio"] and opts["cmdserver"]:
4627 4627 raise error.Abort(_("cannot use --stdio with --cmdserver"))
4628 4628
4629 4629 if opts["stdio"]:
4630 4630 if repo is None:
4631 4631 raise error.RepoError(_("there is no Mercurial repository here"
4632 4632 " (.hg not found)"))
4633 4633 s = sshserver.sshserver(ui, repo)
4634 4634 s.serve_forever()
4635 4635
4636 4636 service = server.createservice(ui, repo, opts)
4637 4637 return server.runservice(opts, initfn=service.init, runfn=service.run)
4638 4638
4639 4639 @command('^status|st',
4640 4640 [('A', 'all', None, _('show status of all files')),
4641 4641 ('m', 'modified', None, _('show only modified files')),
4642 4642 ('a', 'added', None, _('show only added files')),
4643 4643 ('r', 'removed', None, _('show only removed files')),
4644 4644 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4645 4645 ('c', 'clean', None, _('show only files without changes')),
4646 4646 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4647 4647 ('i', 'ignored', None, _('show only ignored files')),
4648 4648 ('n', 'no-status', None, _('hide status prefix')),
4649 4649 ('t', 'terse', '', _('show the terse output (EXPERIMENTAL)')),
4650 4650 ('C', 'copies', None, _('show source of copied files')),
4651 4651 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4652 4652 ('', 'rev', [], _('show difference from revision'), _('REV')),
4653 4653 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4654 4654 ] + walkopts + subrepoopts + formatteropts,
4655 4655 _('[OPTION]... [FILE]...'),
4656 4656 inferrepo=True)
4657 4657 def status(ui, repo, *pats, **opts):
4658 4658 """show changed files in the working directory
4659 4659
4660 4660 Show status of files in the repository. If names are given, only
4661 4661 files that match are shown. Files that are clean or ignored or
4662 4662 the source of a copy/move operation, are not listed unless
4663 4663 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4664 4664 Unless options described with "show only ..." are given, the
4665 4665 options -mardu are used.
4666 4666
4667 4667 Option -q/--quiet hides untracked (unknown and ignored) files
4668 4668 unless explicitly requested with -u/--unknown or -i/--ignored.
4669 4669
4670 4670 .. note::
4671 4671
4672 4672 :hg:`status` may appear to disagree with diff if permissions have
4673 4673 changed or a merge has occurred. The standard diff format does
4674 4674 not report permission changes and diff only reports changes
4675 4675 relative to one merge parent.
4676 4676
4677 4677 If one revision is given, it is used as the base revision.
4678 4678 If two revisions are given, the differences between them are
4679 4679 shown. The --change option can also be used as a shortcut to list
4680 4680 the changed files of a revision from its first parent.
4681 4681
4682 4682 The codes used to show the status of files are::
4683 4683
4684 4684 M = modified
4685 4685 A = added
4686 4686 R = removed
4687 4687 C = clean
4688 4688 ! = missing (deleted by non-hg command, but still tracked)
4689 4689 ? = not tracked
4690 4690 I = ignored
4691 4691 = origin of the previous file (with --copies)
4692 4692
4693 4693 .. container:: verbose
4694 4694
4695 4695 The -t/--terse option abbreviates the output by showing directory name
4696 4696 if all the files in it share the same status. The option expects a value
4697 4697 which can be a string formed by using 'm', 'a', 'r', 'd', 'u', 'i', 'c'
4698 4698 where, 'm' stands for 'modified', 'a' for 'added', 'r' for 'removed',
4699 4699 'd' for 'deleted', 'u' for 'unknown', 'i' for 'ignored' and 'c' for clean.
4700 4700
4701 4701 It terses the output of only those status which are passed. The ignored
4702 4702 files are not considered while tersing until 'i' is there in --terse value
4703 4703 or the --ignored option is used.
4704 4704
4705 4705 --verbose option shows more context about the state of the repo
4706 4706 like the repository is in unfinised merge, shelve, rebase state etc.
4707 4707 You can have this behaviour turned on by default by following config:
4708 4708
4709 4709 [commands]
4710 4710 status.verbose = true
4711 4711
4712 4712 You can also skip some states like bisect by adding following in
4713 4713 configuration file.
4714 4714
4715 4715 [commands]
4716 4716 status.skipstates = bisect
4717 4717
4718 4718 Examples:
4719 4719
4720 4720 - show changes in the working directory relative to a
4721 4721 changeset::
4722 4722
4723 4723 hg status --rev 9353
4724 4724
4725 4725 - show changes in the working directory relative to the
4726 4726 current directory (see :hg:`help patterns` for more information)::
4727 4727
4728 4728 hg status re:
4729 4729
4730 4730 - show all changes including copies in an existing changeset::
4731 4731
4732 4732 hg status --copies --change 9353
4733 4733
4734 4734 - get a NUL separated list of added files, suitable for xargs::
4735 4735
4736 4736 hg status -an0
4737 4737
4738 4738 Returns 0 on success.
4739 4739 """
4740 4740
4741 4741 opts = pycompat.byteskwargs(opts)
4742 4742 revs = opts.get('rev')
4743 4743 change = opts.get('change')
4744 4744 terse = opts.get('terse')
4745 4745
4746 4746 if revs and change:
4747 4747 msg = _('cannot specify --rev and --change at the same time')
4748 4748 raise error.Abort(msg)
4749 4749 elif revs and terse:
4750 4750 msg = _('cannot use --terse with --rev')
4751 4751 raise error.Abort(msg)
4752 4752 elif change:
4753 4753 node2 = scmutil.revsingle(repo, change, None).node()
4754 4754 node1 = repo[node2].p1().node()
4755 4755 else:
4756 4756 node1, node2 = scmutil.revpair(repo, revs)
4757 4757
4758 4758 if pats or ui.configbool('commands', 'status.relative'):
4759 4759 cwd = repo.getcwd()
4760 4760 else:
4761 4761 cwd = ''
4762 4762
4763 4763 if opts.get('print0'):
4764 4764 end = '\0'
4765 4765 else:
4766 4766 end = '\n'
4767 4767 copy = {}
4768 4768 states = 'modified added removed deleted unknown ignored clean'.split()
4769 4769 show = [k for k in states if opts.get(k)]
4770 4770 if opts.get('all'):
4771 4771 show += ui.quiet and (states[:4] + ['clean']) or states
4772 4772
4773 4773 if not show:
4774 4774 if ui.quiet:
4775 4775 show = states[:4]
4776 4776 else:
4777 4777 show = states[:5]
4778 4778
4779 4779 m = scmutil.match(repo[node2], pats, opts)
4780 4780 stat = repo.status(node1, node2, m,
4781 4781 'ignored' in show, 'clean' in show, 'unknown' in show,
4782 4782 opts.get('subrepos'))
4783 4783 if terse:
4784 4784 stat = cmdutil.tersestatus(repo.root, stat, terse,
4785 4785 repo.dirstate._ignore, opts.get('ignored'))
4786 4786 changestates = zip(states, pycompat.iterbytestr('MAR!?IC'), stat)
4787 4787
4788 4788 if (opts.get('all') or opts.get('copies')
4789 4789 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
4790 4790 copy = copies.pathcopies(repo[node1], repo[node2], m)
4791 4791
4792 4792 ui.pager('status')
4793 4793 fm = ui.formatter('status', opts)
4794 4794 fmt = '%s' + end
4795 4795 showchar = not opts.get('no_status')
4796 4796
4797 4797 for state, char, files in changestates:
4798 4798 if state in show:
4799 4799 label = 'status.' + state
4800 4800 for f in files:
4801 4801 fm.startitem()
4802 4802 fm.condwrite(showchar, 'status', '%s ', char, label=label)
4803 4803 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
4804 4804 if f in copy:
4805 4805 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
4806 4806 label='status.copied')
4807 4807
4808 4808 if ((ui.verbose or ui.configbool('commands', 'status.verbose'))
4809 4809 and not ui.plain()):
4810 4810 cmdutil.morestatus(repo, fm)
4811 4811 fm.end()
4812 4812
4813 4813 @command('^summary|sum',
4814 4814 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4815 4815 def summary(ui, repo, **opts):
4816 4816 """summarize working directory state
4817 4817
4818 4818 This generates a brief summary of the working directory state,
4819 4819 including parents, branch, commit status, phase and available updates.
4820 4820
4821 4821 With the --remote option, this will check the default paths for
4822 4822 incoming and outgoing changes. This can be time-consuming.
4823 4823
4824 4824 Returns 0 on success.
4825 4825 """
4826 4826
4827 4827 opts = pycompat.byteskwargs(opts)
4828 4828 ui.pager('summary')
4829 4829 ctx = repo[None]
4830 4830 parents = ctx.parents()
4831 4831 pnode = parents[0].node()
4832 4832 marks = []
4833 4833
4834 4834 ms = None
4835 4835 try:
4836 4836 ms = mergemod.mergestate.read(repo)
4837 4837 except error.UnsupportedMergeRecords as e:
4838 4838 s = ' '.join(e.recordtypes)
4839 4839 ui.warn(
4840 4840 _('warning: merge state has unsupported record types: %s\n') % s)
4841 4841 unresolved = []
4842 4842 else:
4843 4843 unresolved = list(ms.unresolved())
4844 4844
4845 4845 for p in parents:
4846 4846 # label with log.changeset (instead of log.parent) since this
4847 4847 # shows a working directory parent *changeset*:
4848 4848 # i18n: column positioning for "hg summary"
4849 4849 ui.write(_('parent: %d:%s ') % (p.rev(), p),
4850 4850 label=cmdutil._changesetlabels(p))
4851 4851 ui.write(' '.join(p.tags()), label='log.tag')
4852 4852 if p.bookmarks():
4853 4853 marks.extend(p.bookmarks())
4854 4854 if p.rev() == -1:
4855 4855 if not len(repo):
4856 4856 ui.write(_(' (empty repository)'))
4857 4857 else:
4858 4858 ui.write(_(' (no revision checked out)'))
4859 4859 if p.obsolete():
4860 4860 ui.write(_(' (obsolete)'))
4861 4861 if p.isunstable():
4862 4862 instabilities = (ui.label(instability, 'trouble.%s' % instability)
4863 4863 for instability in p.instabilities())
4864 4864 ui.write(' ('
4865 4865 + ', '.join(instabilities)
4866 4866 + ')')
4867 4867 ui.write('\n')
4868 4868 if p.description():
4869 4869 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4870 4870 label='log.summary')
4871 4871
4872 4872 branch = ctx.branch()
4873 4873 bheads = repo.branchheads(branch)
4874 4874 # i18n: column positioning for "hg summary"
4875 4875 m = _('branch: %s\n') % branch
4876 4876 if branch != 'default':
4877 4877 ui.write(m, label='log.branch')
4878 4878 else:
4879 4879 ui.status(m, label='log.branch')
4880 4880
4881 4881 if marks:
4882 4882 active = repo._activebookmark
4883 4883 # i18n: column positioning for "hg summary"
4884 4884 ui.write(_('bookmarks:'), label='log.bookmark')
4885 4885 if active is not None:
4886 4886 if active in marks:
4887 4887 ui.write(' *' + active, label=bookmarks.activebookmarklabel)
4888 4888 marks.remove(active)
4889 4889 else:
4890 4890 ui.write(' [%s]' % active, label=bookmarks.activebookmarklabel)
4891 4891 for m in marks:
4892 4892 ui.write(' ' + m, label='log.bookmark')
4893 4893 ui.write('\n', label='log.bookmark')
4894 4894
4895 4895 status = repo.status(unknown=True)
4896 4896
4897 4897 c = repo.dirstate.copies()
4898 4898 copied, renamed = [], []
4899 4899 for d, s in c.iteritems():
4900 4900 if s in status.removed:
4901 4901 status.removed.remove(s)
4902 4902 renamed.append(d)
4903 4903 else:
4904 4904 copied.append(d)
4905 4905 if d in status.added:
4906 4906 status.added.remove(d)
4907 4907
4908 4908 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
4909 4909
4910 4910 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
4911 4911 (ui.label(_('%d added'), 'status.added'), status.added),
4912 4912 (ui.label(_('%d removed'), 'status.removed'), status.removed),
4913 4913 (ui.label(_('%d renamed'), 'status.copied'), renamed),
4914 4914 (ui.label(_('%d copied'), 'status.copied'), copied),
4915 4915 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
4916 4916 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
4917 4917 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
4918 4918 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
4919 4919 t = []
4920 4920 for l, s in labels:
4921 4921 if s:
4922 4922 t.append(l % len(s))
4923 4923
4924 4924 t = ', '.join(t)
4925 4925 cleanworkdir = False
4926 4926
4927 4927 if repo.vfs.exists('graftstate'):
4928 4928 t += _(' (graft in progress)')
4929 4929 if repo.vfs.exists('updatestate'):
4930 4930 t += _(' (interrupted update)')
4931 4931 elif len(parents) > 1:
4932 4932 t += _(' (merge)')
4933 4933 elif branch != parents[0].branch():
4934 4934 t += _(' (new branch)')
4935 4935 elif (parents[0].closesbranch() and
4936 4936 pnode in repo.branchheads(branch, closed=True)):
4937 4937 t += _(' (head closed)')
4938 4938 elif not (status.modified or status.added or status.removed or renamed or
4939 4939 copied or subs):
4940 4940 t += _(' (clean)')
4941 4941 cleanworkdir = True
4942 4942 elif pnode not in bheads:
4943 4943 t += _(' (new branch head)')
4944 4944
4945 4945 if parents:
4946 4946 pendingphase = max(p.phase() for p in parents)
4947 4947 else:
4948 4948 pendingphase = phases.public
4949 4949
4950 4950 if pendingphase > phases.newcommitphase(ui):
4951 4951 t += ' (%s)' % phases.phasenames[pendingphase]
4952 4952
4953 4953 if cleanworkdir:
4954 4954 # i18n: column positioning for "hg summary"
4955 4955 ui.status(_('commit: %s\n') % t.strip())
4956 4956 else:
4957 4957 # i18n: column positioning for "hg summary"
4958 4958 ui.write(_('commit: %s\n') % t.strip())
4959 4959
4960 4960 # all ancestors of branch heads - all ancestors of parent = new csets
4961 4961 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
4962 4962 bheads))
4963 4963
4964 4964 if new == 0:
4965 4965 # i18n: column positioning for "hg summary"
4966 4966 ui.status(_('update: (current)\n'))
4967 4967 elif pnode not in bheads:
4968 4968 # i18n: column positioning for "hg summary"
4969 4969 ui.write(_('update: %d new changesets (update)\n') % new)
4970 4970 else:
4971 4971 # i18n: column positioning for "hg summary"
4972 4972 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
4973 4973 (new, len(bheads)))
4974 4974
4975 4975 t = []
4976 4976 draft = len(repo.revs('draft()'))
4977 4977 if draft:
4978 4978 t.append(_('%d draft') % draft)
4979 4979 secret = len(repo.revs('secret()'))
4980 4980 if secret:
4981 4981 t.append(_('%d secret') % secret)
4982 4982
4983 4983 if draft or secret:
4984 4984 ui.status(_('phases: %s\n') % ', '.join(t))
4985 4985
4986 4986 if obsolete.isenabled(repo, obsolete.createmarkersopt):
4987 4987 for trouble in ("orphan", "contentdivergent", "phasedivergent"):
4988 4988 numtrouble = len(repo.revs(trouble + "()"))
4989 4989 # We write all the possibilities to ease translation
4990 4990 troublemsg = {
4991 4991 "orphan": _("orphan: %d changesets"),
4992 4992 "contentdivergent": _("content-divergent: %d changesets"),
4993 4993 "phasedivergent": _("phase-divergent: %d changesets"),
4994 4994 }
4995 4995 if numtrouble > 0:
4996 4996 ui.status(troublemsg[trouble] % numtrouble + "\n")
4997 4997
4998 4998 cmdutil.summaryhooks(ui, repo)
4999 4999
5000 5000 if opts.get('remote'):
5001 5001 needsincoming, needsoutgoing = True, True
5002 5002 else:
5003 5003 needsincoming, needsoutgoing = False, False
5004 5004 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5005 5005 if i:
5006 5006 needsincoming = True
5007 5007 if o:
5008 5008 needsoutgoing = True
5009 5009 if not needsincoming and not needsoutgoing:
5010 5010 return
5011 5011
5012 5012 def getincoming():
5013 5013 source, branches = hg.parseurl(ui.expandpath('default'))
5014 5014 sbranch = branches[0]
5015 5015 try:
5016 5016 other = hg.peer(repo, {}, source)
5017 5017 except error.RepoError:
5018 5018 if opts.get('remote'):
5019 5019 raise
5020 5020 return source, sbranch, None, None, None
5021 5021 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5022 5022 if revs:
5023 5023 revs = [other.lookup(rev) for rev in revs]
5024 5024 ui.debug('comparing with %s\n' % util.hidepassword(source))
5025 5025 repo.ui.pushbuffer()
5026 5026 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5027 5027 repo.ui.popbuffer()
5028 5028 return source, sbranch, other, commoninc, commoninc[1]
5029 5029
5030 5030 if needsincoming:
5031 5031 source, sbranch, sother, commoninc, incoming = getincoming()
5032 5032 else:
5033 5033 source = sbranch = sother = commoninc = incoming = None
5034 5034
5035 5035 def getoutgoing():
5036 5036 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5037 5037 dbranch = branches[0]
5038 5038 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5039 5039 if source != dest:
5040 5040 try:
5041 5041 dother = hg.peer(repo, {}, dest)
5042 5042 except error.RepoError:
5043 5043 if opts.get('remote'):
5044 5044 raise
5045 5045 return dest, dbranch, None, None
5046 5046 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5047 5047 elif sother is None:
5048 5048 # there is no explicit destination peer, but source one is invalid
5049 5049 return dest, dbranch, None, None
5050 5050 else:
5051 5051 dother = sother
5052 5052 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5053 5053 common = None
5054 5054 else:
5055 5055 common = commoninc
5056 5056 if revs:
5057 5057 revs = [repo.lookup(rev) for rev in revs]
5058 5058 repo.ui.pushbuffer()
5059 5059 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5060 5060 commoninc=common)
5061 5061 repo.ui.popbuffer()
5062 5062 return dest, dbranch, dother, outgoing
5063 5063
5064 5064 if needsoutgoing:
5065 5065 dest, dbranch, dother, outgoing = getoutgoing()
5066 5066 else:
5067 5067 dest = dbranch = dother = outgoing = None
5068 5068
5069 5069 if opts.get('remote'):
5070 5070 t = []
5071 5071 if incoming:
5072 5072 t.append(_('1 or more incoming'))
5073 5073 o = outgoing.missing
5074 5074 if o:
5075 5075 t.append(_('%d outgoing') % len(o))
5076 5076 other = dother or sother
5077 5077 if 'bookmarks' in other.listkeys('namespaces'):
5078 5078 counts = bookmarks.summary(repo, other)
5079 5079 if counts[0] > 0:
5080 5080 t.append(_('%d incoming bookmarks') % counts[0])
5081 5081 if counts[1] > 0:
5082 5082 t.append(_('%d outgoing bookmarks') % counts[1])
5083 5083
5084 5084 if t:
5085 5085 # i18n: column positioning for "hg summary"
5086 5086 ui.write(_('remote: %s\n') % (', '.join(t)))
5087 5087 else:
5088 5088 # i18n: column positioning for "hg summary"
5089 5089 ui.status(_('remote: (synced)\n'))
5090 5090
5091 5091 cmdutil.summaryremotehooks(ui, repo, opts,
5092 5092 ((source, sbranch, sother, commoninc),
5093 5093 (dest, dbranch, dother, outgoing)))
5094 5094
5095 5095 @command('tag',
5096 5096 [('f', 'force', None, _('force tag')),
5097 5097 ('l', 'local', None, _('make the tag local')),
5098 5098 ('r', 'rev', '', _('revision to tag'), _('REV')),
5099 5099 ('', 'remove', None, _('remove a tag')),
5100 5100 # -l/--local is already there, commitopts cannot be used
5101 5101 ('e', 'edit', None, _('invoke editor on commit messages')),
5102 5102 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5103 5103 ] + commitopts2,
5104 5104 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5105 5105 def tag(ui, repo, name1, *names, **opts):
5106 5106 """add one or more tags for the current or given revision
5107 5107
5108 5108 Name a particular revision using <name>.
5109 5109
5110 5110 Tags are used to name particular revisions of the repository and are
5111 5111 very useful to compare different revisions, to go back to significant
5112 5112 earlier versions or to mark branch points as releases, etc. Changing
5113 5113 an existing tag is normally disallowed; use -f/--force to override.
5114 5114
5115 5115 If no revision is given, the parent of the working directory is
5116 5116 used.
5117 5117
5118 5118 To facilitate version control, distribution, and merging of tags,
5119 5119 they are stored as a file named ".hgtags" which is managed similarly
5120 5120 to other project files and can be hand-edited if necessary. This
5121 5121 also means that tagging creates a new commit. The file
5122 5122 ".hg/localtags" is used for local tags (not shared among
5123 5123 repositories).
5124 5124
5125 5125 Tag commits are usually made at the head of a branch. If the parent
5126 5126 of the working directory is not a branch head, :hg:`tag` aborts; use
5127 5127 -f/--force to force the tag commit to be based on a non-head
5128 5128 changeset.
5129 5129
5130 5130 See :hg:`help dates` for a list of formats valid for -d/--date.
5131 5131
5132 5132 Since tag names have priority over branch names during revision
5133 5133 lookup, using an existing branch name as a tag name is discouraged.
5134 5134
5135 5135 Returns 0 on success.
5136 5136 """
5137 5137 opts = pycompat.byteskwargs(opts)
5138 5138 wlock = lock = None
5139 5139 try:
5140 5140 wlock = repo.wlock()
5141 5141 lock = repo.lock()
5142 5142 rev_ = "."
5143 5143 names = [t.strip() for t in (name1,) + names]
5144 5144 if len(names) != len(set(names)):
5145 5145 raise error.Abort(_('tag names must be unique'))
5146 5146 for n in names:
5147 5147 scmutil.checknewlabel(repo, n, 'tag')
5148 5148 if not n:
5149 5149 raise error.Abort(_('tag names cannot consist entirely of '
5150 5150 'whitespace'))
5151 5151 if opts.get('rev') and opts.get('remove'):
5152 5152 raise error.Abort(_("--rev and --remove are incompatible"))
5153 5153 if opts.get('rev'):
5154 5154 rev_ = opts['rev']
5155 5155 message = opts.get('message')
5156 5156 if opts.get('remove'):
5157 5157 if opts.get('local'):
5158 5158 expectedtype = 'local'
5159 5159 else:
5160 5160 expectedtype = 'global'
5161 5161
5162 5162 for n in names:
5163 5163 if not repo.tagtype(n):
5164 5164 raise error.Abort(_("tag '%s' does not exist") % n)
5165 5165 if repo.tagtype(n) != expectedtype:
5166 5166 if expectedtype == 'global':
5167 5167 raise error.Abort(_("tag '%s' is not a global tag") % n)
5168 5168 else:
5169 5169 raise error.Abort(_("tag '%s' is not a local tag") % n)
5170 5170 rev_ = 'null'
5171 5171 if not message:
5172 5172 # we don't translate commit messages
5173 5173 message = 'Removed tag %s' % ', '.join(names)
5174 5174 elif not opts.get('force'):
5175 5175 for n in names:
5176 5176 if n in repo.tags():
5177 5177 raise error.Abort(_("tag '%s' already exists "
5178 5178 "(use -f to force)") % n)
5179 5179 if not opts.get('local'):
5180 5180 p1, p2 = repo.dirstate.parents()
5181 5181 if p2 != nullid:
5182 5182 raise error.Abort(_('uncommitted merge'))
5183 5183 bheads = repo.branchheads()
5184 5184 if not opts.get('force') and bheads and p1 not in bheads:
5185 5185 raise error.Abort(_('working directory is not at a branch head '
5186 5186 '(use -f to force)'))
5187 5187 r = scmutil.revsingle(repo, rev_).node()
5188 5188
5189 5189 if not message:
5190 5190 # we don't translate commit messages
5191 5191 message = ('Added tag %s for changeset %s' %
5192 5192 (', '.join(names), short(r)))
5193 5193
5194 5194 date = opts.get('date')
5195 5195 if date:
5196 5196 date = util.parsedate(date)
5197 5197
5198 5198 if opts.get('remove'):
5199 5199 editform = 'tag.remove'
5200 5200 else:
5201 5201 editform = 'tag.add'
5202 5202 editor = cmdutil.getcommiteditor(editform=editform,
5203 5203 **pycompat.strkwargs(opts))
5204 5204
5205 5205 # don't allow tagging the null rev
5206 5206 if (not opts.get('remove') and
5207 5207 scmutil.revsingle(repo, rev_).rev() == nullrev):
5208 5208 raise error.Abort(_("cannot tag null revision"))
5209 5209
5210 5210 tagsmod.tag(repo, names, r, message, opts.get('local'),
5211 5211 opts.get('user'), date, editor=editor)
5212 5212 finally:
5213 5213 release(lock, wlock)
5214 5214
5215 5215 @command('tags', formatteropts, '')
5216 5216 def tags(ui, repo, **opts):
5217 5217 """list repository tags
5218 5218
5219 5219 This lists both regular and local tags. When the -v/--verbose
5220 5220 switch is used, a third column "local" is printed for local tags.
5221 5221 When the -q/--quiet switch is used, only the tag name is printed.
5222 5222
5223 5223 Returns 0 on success.
5224 5224 """
5225 5225
5226 5226 opts = pycompat.byteskwargs(opts)
5227 5227 ui.pager('tags')
5228 5228 fm = ui.formatter('tags', opts)
5229 5229 hexfunc = fm.hexfunc
5230 5230 tagtype = ""
5231 5231
5232 5232 for t, n in reversed(repo.tagslist()):
5233 5233 hn = hexfunc(n)
5234 5234 label = 'tags.normal'
5235 5235 tagtype = ''
5236 5236 if repo.tagtype(t) == 'local':
5237 5237 label = 'tags.local'
5238 5238 tagtype = 'local'
5239 5239
5240 5240 fm.startitem()
5241 5241 fm.write('tag', '%s', t, label=label)
5242 5242 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5243 5243 fm.condwrite(not ui.quiet, 'rev node', fmt,
5244 5244 repo.changelog.rev(n), hn, label=label)
5245 5245 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5246 5246 tagtype, label=label)
5247 5247 fm.plain('\n')
5248 5248 fm.end()
5249 5249
5250 5250 @command('tip',
5251 5251 [('p', 'patch', None, _('show patch')),
5252 5252 ('g', 'git', None, _('use git extended diff format')),
5253 5253 ] + templateopts,
5254 5254 _('[-p] [-g]'))
5255 5255 def tip(ui, repo, **opts):
5256 5256 """show the tip revision (DEPRECATED)
5257 5257
5258 5258 The tip revision (usually just called the tip) is the changeset
5259 5259 most recently added to the repository (and therefore the most
5260 5260 recently changed head).
5261 5261
5262 5262 If you have just made a commit, that commit will be the tip. If
5263 5263 you have just pulled changes from another repository, the tip of
5264 5264 that repository becomes the current tip. The "tip" tag is special
5265 5265 and cannot be renamed or assigned to a different changeset.
5266 5266
5267 5267 This command is deprecated, please use :hg:`heads` instead.
5268 5268
5269 5269 Returns 0 on success.
5270 5270 """
5271 5271 opts = pycompat.byteskwargs(opts)
5272 5272 displayer = cmdutil.show_changeset(ui, repo, opts)
5273 5273 displayer.show(repo['tip'])
5274 5274 displayer.close()
5275 5275
5276 5276 @command('unbundle',
5277 5277 [('u', 'update', None,
5278 5278 _('update to new branch head if changesets were unbundled'))],
5279 5279 _('[-u] FILE...'))
5280 5280 def unbundle(ui, repo, fname1, *fnames, **opts):
5281 5281 """apply one or more bundle files
5282 5282
5283 5283 Apply one or more bundle files generated by :hg:`bundle`.
5284 5284
5285 5285 Returns 0 on success, 1 if an update has unresolved files.
5286 5286 """
5287 5287 fnames = (fname1,) + fnames
5288 5288
5289 5289 with repo.lock():
5290 5290 for fname in fnames:
5291 5291 f = hg.openpath(ui, fname)
5292 5292 gen = exchange.readbundle(ui, f, fname)
5293 5293 if isinstance(gen, streamclone.streamcloneapplier):
5294 5294 raise error.Abort(
5295 5295 _('packed bundles cannot be applied with '
5296 5296 '"hg unbundle"'),
5297 5297 hint=_('use "hg debugapplystreamclonebundle"'))
5298 5298 url = 'bundle:' + fname
5299 5299 try:
5300 5300 txnname = 'unbundle'
5301 5301 if not isinstance(gen, bundle2.unbundle20):
5302 5302 txnname = 'unbundle\n%s' % util.hidepassword(url)
5303 5303 with repo.transaction(txnname) as tr:
5304 5304 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
5305 5305 url=url)
5306 5306 except error.BundleUnknownFeatureError as exc:
5307 5307 raise error.Abort(
5308 5308 _('%s: unknown bundle feature, %s') % (fname, exc),
5309 5309 hint=_("see https://mercurial-scm.org/"
5310 5310 "wiki/BundleFeature for more "
5311 5311 "information"))
5312 5312 modheads = bundle2.combinechangegroupresults(op)
5313 5313
5314 5314 return postincoming(ui, repo, modheads, opts.get(r'update'), None, None)
5315 5315
5316 5316 @command('^update|up|checkout|co',
5317 5317 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5318 5318 ('c', 'check', None, _('require clean working directory')),
5319 5319 ('m', 'merge', None, _('merge uncommitted changes')),
5320 5320 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5321 5321 ('r', 'rev', '', _('revision'), _('REV'))
5322 5322 ] + mergetoolopts,
5323 5323 _('[-C|-c|-m] [-d DATE] [[-r] REV]'))
5324 5324 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
5325 5325 merge=None, tool=None):
5326 5326 """update working directory (or switch revisions)
5327 5327
5328 5328 Update the repository's working directory to the specified
5329 5329 changeset. If no changeset is specified, update to the tip of the
5330 5330 current named branch and move the active bookmark (see :hg:`help
5331 5331 bookmarks`).
5332 5332
5333 5333 Update sets the working directory's parent revision to the specified
5334 5334 changeset (see :hg:`help parents`).
5335 5335
5336 5336 If the changeset is not a descendant or ancestor of the working
5337 5337 directory's parent and there are uncommitted changes, the update is
5338 5338 aborted. With the -c/--check option, the working directory is checked
5339 5339 for uncommitted changes; if none are found, the working directory is
5340 5340 updated to the specified changeset.
5341 5341
5342 5342 .. container:: verbose
5343 5343
5344 5344 The -C/--clean, -c/--check, and -m/--merge options control what
5345 5345 happens if the working directory contains uncommitted changes.
5346 5346 At most of one of them can be specified.
5347 5347
5348 5348 1. If no option is specified, and if
5349 5349 the requested changeset is an ancestor or descendant of
5350 5350 the working directory's parent, the uncommitted changes
5351 5351 are merged into the requested changeset and the merged
5352 5352 result is left uncommitted. If the requested changeset is
5353 5353 not an ancestor or descendant (that is, it is on another
5354 5354 branch), the update is aborted and the uncommitted changes
5355 5355 are preserved.
5356 5356
5357 5357 2. With the -m/--merge option, the update is allowed even if the
5358 5358 requested changeset is not an ancestor or descendant of
5359 5359 the working directory's parent.
5360 5360
5361 5361 3. With the -c/--check option, the update is aborted and the
5362 5362 uncommitted changes are preserved.
5363 5363
5364 5364 4. With the -C/--clean option, uncommitted changes are discarded and
5365 5365 the working directory is updated to the requested changeset.
5366 5366
5367 5367 To cancel an uncommitted merge (and lose your changes), use
5368 5368 :hg:`update --clean .`.
5369 5369
5370 5370 Use null as the changeset to remove the working directory (like
5371 5371 :hg:`clone -U`).
5372 5372
5373 5373 If you want to revert just one file to an older revision, use
5374 5374 :hg:`revert [-r REV] NAME`.
5375 5375
5376 5376 See :hg:`help dates` for a list of formats valid for -d/--date.
5377 5377
5378 5378 Returns 0 on success, 1 if there are unresolved files.
5379 5379 """
5380 5380 if rev and node:
5381 5381 raise error.Abort(_("please specify just one revision"))
5382 5382
5383 5383 if ui.configbool('commands', 'update.requiredest'):
5384 5384 if not node and not rev and not date:
5385 5385 raise error.Abort(_('you must specify a destination'),
5386 5386 hint=_('for example: hg update ".::"'))
5387 5387
5388 5388 if rev is None or rev == '':
5389 5389 rev = node
5390 5390
5391 5391 if date and rev is not None:
5392 5392 raise error.Abort(_("you can't specify a revision and a date"))
5393 5393
5394 5394 if len([x for x in (clean, check, merge) if x]) > 1:
5395 5395 raise error.Abort(_("can only specify one of -C/--clean, -c/--check, "
5396 5396 "or -m/merge"))
5397 5397
5398 5398 updatecheck = None
5399 5399 if check:
5400 5400 updatecheck = 'abort'
5401 5401 elif merge:
5402 5402 updatecheck = 'none'
5403 5403
5404 5404 with repo.wlock():
5405 5405 cmdutil.clearunfinished(repo)
5406 5406
5407 5407 if date:
5408 5408 rev = cmdutil.finddate(ui, repo, date)
5409 5409
5410 5410 # if we defined a bookmark, we have to remember the original name
5411 5411 brev = rev
5412 5412 rev = scmutil.revsingle(repo, rev, rev).rev()
5413 5413
5414 5414 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
5415 5415
5416 5416 return hg.updatetotally(ui, repo, rev, brev, clean=clean,
5417 5417 updatecheck=updatecheck)
5418 5418
5419 5419 @command('verify', [])
5420 5420 def verify(ui, repo):
5421 5421 """verify the integrity of the repository
5422 5422
5423 5423 Verify the integrity of the current repository.
5424 5424
5425 5425 This will perform an extensive check of the repository's
5426 5426 integrity, validating the hashes and checksums of each entry in
5427 5427 the changelog, manifest, and tracked files, as well as the
5428 5428 integrity of their crosslinks and indices.
5429 5429
5430 5430 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
5431 5431 for more information about recovery from corruption of the
5432 5432 repository.
5433 5433
5434 5434 Returns 0 on success, 1 if errors are encountered.
5435 5435 """
5436 5436 return hg.verify(repo)
5437 5437
5438 5438 @command('version', [] + formatteropts, norepo=True)
5439 5439 def version_(ui, **opts):
5440 5440 """output version and copyright information"""
5441 5441 opts = pycompat.byteskwargs(opts)
5442 5442 if ui.verbose:
5443 5443 ui.pager('version')
5444 5444 fm = ui.formatter("version", opts)
5445 5445 fm.startitem()
5446 5446 fm.write("ver", _("Mercurial Distributed SCM (version %s)\n"),
5447 5447 util.version())
5448 5448 license = _(
5449 5449 "(see https://mercurial-scm.org for more information)\n"
5450 5450 "\nCopyright (C) 2005-2017 Matt Mackall and others\n"
5451 5451 "This is free software; see the source for copying conditions. "
5452 5452 "There is NO\nwarranty; "
5453 5453 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5454 5454 )
5455 5455 if not ui.quiet:
5456 5456 fm.plain(license)
5457 5457
5458 5458 if ui.verbose:
5459 5459 fm.plain(_("\nEnabled extensions:\n\n"))
5460 5460 # format names and versions into columns
5461 5461 names = []
5462 5462 vers = []
5463 5463 isinternals = []
5464 5464 for name, module in extensions.extensions():
5465 5465 names.append(name)
5466 5466 vers.append(extensions.moduleversion(module) or None)
5467 5467 isinternals.append(extensions.ismoduleinternal(module))
5468 5468 fn = fm.nested("extensions")
5469 5469 if names:
5470 5470 namefmt = " %%-%ds " % max(len(n) for n in names)
5471 5471 places = [_("external"), _("internal")]
5472 5472 for n, v, p in zip(names, vers, isinternals):
5473 5473 fn.startitem()
5474 5474 fn.condwrite(ui.verbose, "name", namefmt, n)
5475 5475 if ui.verbose:
5476 5476 fn.plain("%s " % places[p])
5477 5477 fn.data(bundled=p)
5478 5478 fn.condwrite(ui.verbose and v, "ver", "%s", v)
5479 5479 if ui.verbose:
5480 5480 fn.plain("\n")
5481 5481 fn.end()
5482 5482 fm.end()
5483 5483
5484 5484 def loadcmdtable(ui, name, cmdtable):
5485 5485 """Load command functions from specified cmdtable
5486 5486 """
5487 5487 overrides = [cmd for cmd in cmdtable if cmd in table]
5488 5488 if overrides:
5489 5489 ui.warn(_("extension '%s' overrides commands: %s\n")
5490 5490 % (name, " ".join(overrides)))
5491 5491 table.update(cmdtable)
@@ -1,2557 +1,2566 b''
1 1 # context.py - changeset and file context objects for mercurial
2 2 #
3 3 # Copyright 2006, 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 errno
11 11 import os
12 12 import re
13 13 import stat
14 14
15 15 from .i18n import _
16 16 from .node import (
17 17 addednodeid,
18 18 bin,
19 19 hex,
20 20 modifiednodeid,
21 21 nullid,
22 22 nullrev,
23 23 short,
24 24 wdirid,
25 25 wdirnodes,
26 26 wdirrev,
27 27 )
28 from .thirdparty import (
29 attr,
30 )
28 31 from . import (
29 32 encoding,
30 33 error,
31 34 fileset,
32 35 match as matchmod,
33 36 mdiff,
34 37 obsolete as obsmod,
35 38 patch,
36 39 pathutil,
37 40 phases,
38 41 pycompat,
39 42 repoview,
40 43 revlog,
41 44 scmutil,
42 45 sparse,
43 46 subrepo,
44 47 util,
45 48 )
46 49
47 50 propertycache = util.propertycache
48 51
49 52 nonascii = re.compile(r'[^\x21-\x7f]').search
50 53
51 54 class basectx(object):
52 55 """A basectx object represents the common logic for its children:
53 56 changectx: read-only context that is already present in the repo,
54 57 workingctx: a context that represents the working directory and can
55 58 be committed,
56 59 memctx: a context that represents changes in-memory and can also
57 60 be committed."""
58 61 def __new__(cls, repo, changeid='', *args, **kwargs):
59 62 if isinstance(changeid, basectx):
60 63 return changeid
61 64
62 65 o = super(basectx, cls).__new__(cls)
63 66
64 67 o._repo = repo
65 68 o._rev = nullrev
66 69 o._node = nullid
67 70
68 71 return o
69 72
70 73 def __bytes__(self):
71 74 return short(self.node())
72 75
73 76 __str__ = encoding.strmethod(__bytes__)
74 77
75 78 def __int__(self):
76 79 return self.rev()
77 80
78 81 def __repr__(self):
79 82 return r"<%s %s>" % (type(self).__name__, str(self))
80 83
81 84 def __eq__(self, other):
82 85 try:
83 86 return type(self) == type(other) and self._rev == other._rev
84 87 except AttributeError:
85 88 return False
86 89
87 90 def __ne__(self, other):
88 91 return not (self == other)
89 92
90 93 def __contains__(self, key):
91 94 return key in self._manifest
92 95
93 96 def __getitem__(self, key):
94 97 return self.filectx(key)
95 98
96 99 def __iter__(self):
97 100 return iter(self._manifest)
98 101
99 102 def _buildstatusmanifest(self, status):
100 103 """Builds a manifest that includes the given status results, if this is
101 104 a working copy context. For non-working copy contexts, it just returns
102 105 the normal manifest."""
103 106 return self.manifest()
104 107
105 108 def _matchstatus(self, other, match):
106 109 """This internal method provides a way for child objects to override the
107 110 match operator.
108 111 """
109 112 return match
110 113
111 114 def _buildstatus(self, other, s, match, listignored, listclean,
112 115 listunknown):
113 116 """build a status with respect to another context"""
114 117 # Load earliest manifest first for caching reasons. More specifically,
115 118 # if you have revisions 1000 and 1001, 1001 is probably stored as a
116 119 # delta against 1000. Thus, if you read 1000 first, we'll reconstruct
117 120 # 1000 and cache it so that when you read 1001, we just need to apply a
118 121 # delta to what's in the cache. So that's one full reconstruction + one
119 122 # delta application.
120 123 mf2 = None
121 124 if self.rev() is not None and self.rev() < other.rev():
122 125 mf2 = self._buildstatusmanifest(s)
123 126 mf1 = other._buildstatusmanifest(s)
124 127 if mf2 is None:
125 128 mf2 = self._buildstatusmanifest(s)
126 129
127 130 modified, added = [], []
128 131 removed = []
129 132 clean = []
130 133 deleted, unknown, ignored = s.deleted, s.unknown, s.ignored
131 134 deletedset = set(deleted)
132 135 d = mf1.diff(mf2, match=match, clean=listclean)
133 136 for fn, value in d.iteritems():
134 137 if fn in deletedset:
135 138 continue
136 139 if value is None:
137 140 clean.append(fn)
138 141 continue
139 142 (node1, flag1), (node2, flag2) = value
140 143 if node1 is None:
141 144 added.append(fn)
142 145 elif node2 is None:
143 146 removed.append(fn)
144 147 elif flag1 != flag2:
145 148 modified.append(fn)
146 149 elif node2 not in wdirnodes:
147 150 # When comparing files between two commits, we save time by
148 151 # not comparing the file contents when the nodeids differ.
149 152 # Note that this means we incorrectly report a reverted change
150 153 # to a file as a modification.
151 154 modified.append(fn)
152 155 elif self[fn].cmp(other[fn]):
153 156 modified.append(fn)
154 157 else:
155 158 clean.append(fn)
156 159
157 160 if removed:
158 161 # need to filter files if they are already reported as removed
159 162 unknown = [fn for fn in unknown if fn not in mf1 and
160 163 (not match or match(fn))]
161 164 ignored = [fn for fn in ignored if fn not in mf1 and
162 165 (not match or match(fn))]
163 166 # if they're deleted, don't report them as removed
164 167 removed = [fn for fn in removed if fn not in deletedset]
165 168
166 169 return scmutil.status(modified, added, removed, deleted, unknown,
167 170 ignored, clean)
168 171
169 172 @propertycache
170 173 def substate(self):
171 174 return subrepo.state(self, self._repo.ui)
172 175
173 176 def subrev(self, subpath):
174 177 return self.substate[subpath][1]
175 178
176 179 def rev(self):
177 180 return self._rev
178 181 def node(self):
179 182 return self._node
180 183 def hex(self):
181 184 return hex(self.node())
182 185 def manifest(self):
183 186 return self._manifest
184 187 def manifestctx(self):
185 188 return self._manifestctx
186 189 def repo(self):
187 190 return self._repo
188 191 def phasestr(self):
189 192 return phases.phasenames[self.phase()]
190 193 def mutable(self):
191 194 return self.phase() > phases.public
192 195
193 196 def getfileset(self, expr):
194 197 return fileset.getfileset(self, expr)
195 198
196 199 def obsolete(self):
197 200 """True if the changeset is obsolete"""
198 201 return self.rev() in obsmod.getrevs(self._repo, 'obsolete')
199 202
200 203 def extinct(self):
201 204 """True if the changeset is extinct"""
202 205 return self.rev() in obsmod.getrevs(self._repo, 'extinct')
203 206
204 207 def unstable(self):
205 208 msg = ("'context.unstable' is deprecated, "
206 209 "use 'context.orphan'")
207 210 self._repo.ui.deprecwarn(msg, '4.4')
208 211 return self.orphan()
209 212
210 213 def orphan(self):
211 214 """True if the changeset is not obsolete but it's ancestor are"""
212 215 return self.rev() in obsmod.getrevs(self._repo, 'orphan')
213 216
214 217 def bumped(self):
215 218 msg = ("'context.bumped' is deprecated, "
216 219 "use 'context.phasedivergent'")
217 220 self._repo.ui.deprecwarn(msg, '4.4')
218 221 return self.phasedivergent()
219 222
220 223 def phasedivergent(self):
221 224 """True if the changeset try to be a successor of a public changeset
222 225
223 226 Only non-public and non-obsolete changesets may be bumped.
224 227 """
225 228 return self.rev() in obsmod.getrevs(self._repo, 'phasedivergent')
226 229
227 230 def divergent(self):
228 231 msg = ("'context.divergent' is deprecated, "
229 232 "use 'context.contentdivergent'")
230 233 self._repo.ui.deprecwarn(msg, '4.4')
231 234 return self.contentdivergent()
232 235
233 236 def contentdivergent(self):
234 237 """Is a successors of a changeset with multiple possible successors set
235 238
236 239 Only non-public and non-obsolete changesets may be divergent.
237 240 """
238 241 return self.rev() in obsmod.getrevs(self._repo, 'contentdivergent')
239 242
240 243 def troubled(self):
241 244 msg = ("'context.troubled' is deprecated, "
242 245 "use 'context.isunstable'")
243 246 self._repo.ui.deprecwarn(msg, '4.4')
244 247 return self.isunstable()
245 248
246 249 def isunstable(self):
247 250 """True if the changeset is either unstable, bumped or divergent"""
248 251 return self.orphan() or self.phasedivergent() or self.contentdivergent()
249 252
250 253 def troubles(self):
251 254 """Keep the old version around in order to avoid breaking extensions
252 255 about different return values.
253 256 """
254 257 msg = ("'context.troubles' is deprecated, "
255 258 "use 'context.instabilities'")
256 259 self._repo.ui.deprecwarn(msg, '4.4')
257 260
258 261 troubles = []
259 262 if self.orphan():
260 263 troubles.append('orphan')
261 264 if self.phasedivergent():
262 265 troubles.append('bumped')
263 266 if self.contentdivergent():
264 267 troubles.append('divergent')
265 268 return troubles
266 269
267 270 def instabilities(self):
268 271 """return the list of instabilities affecting this changeset.
269 272
270 273 Instabilities are returned as strings. possible values are:
271 274 - orphan,
272 275 - phase-divergent,
273 276 - content-divergent.
274 277 """
275 278 instabilities = []
276 279 if self.orphan():
277 280 instabilities.append('orphan')
278 281 if self.phasedivergent():
279 282 instabilities.append('phase-divergent')
280 283 if self.contentdivergent():
281 284 instabilities.append('content-divergent')
282 285 return instabilities
283 286
284 287 def parents(self):
285 288 """return contexts for each parent changeset"""
286 289 return self._parents
287 290
288 291 def p1(self):
289 292 return self._parents[0]
290 293
291 294 def p2(self):
292 295 parents = self._parents
293 296 if len(parents) == 2:
294 297 return parents[1]
295 298 return changectx(self._repo, nullrev)
296 299
297 300 def _fileinfo(self, path):
298 301 if r'_manifest' in self.__dict__:
299 302 try:
300 303 return self._manifest[path], self._manifest.flags(path)
301 304 except KeyError:
302 305 raise error.ManifestLookupError(self._node, path,
303 306 _('not found in manifest'))
304 307 if r'_manifestdelta' in self.__dict__ or path in self.files():
305 308 if path in self._manifestdelta:
306 309 return (self._manifestdelta[path],
307 310 self._manifestdelta.flags(path))
308 311 mfl = self._repo.manifestlog
309 312 try:
310 313 node, flag = mfl[self._changeset.manifest].find(path)
311 314 except KeyError:
312 315 raise error.ManifestLookupError(self._node, path,
313 316 _('not found in manifest'))
314 317
315 318 return node, flag
316 319
317 320 def filenode(self, path):
318 321 return self._fileinfo(path)[0]
319 322
320 323 def flags(self, path):
321 324 try:
322 325 return self._fileinfo(path)[1]
323 326 except error.LookupError:
324 327 return ''
325 328
326 329 def sub(self, path, allowcreate=True):
327 330 '''return a subrepo for the stored revision of path, never wdir()'''
328 331 return subrepo.subrepo(self, path, allowcreate=allowcreate)
329 332
330 333 def nullsub(self, path, pctx):
331 334 return subrepo.nullsubrepo(self, path, pctx)
332 335
333 336 def workingsub(self, path):
334 337 '''return a subrepo for the stored revision, or wdir if this is a wdir
335 338 context.
336 339 '''
337 340 return subrepo.subrepo(self, path, allowwdir=True)
338 341
339 342 def match(self, pats=None, include=None, exclude=None, default='glob',
340 343 listsubrepos=False, badfn=None):
341 344 r = self._repo
342 345 return matchmod.match(r.root, r.getcwd(), pats,
343 346 include, exclude, default,
344 347 auditor=r.nofsauditor, ctx=self,
345 348 listsubrepos=listsubrepos, badfn=badfn)
346 349
347 350 def diff(self, ctx2=None, match=None, **opts):
348 351 """Returns a diff generator for the given contexts and matcher"""
349 352 if ctx2 is None:
350 353 ctx2 = self.p1()
351 354 if ctx2 is not None:
352 355 ctx2 = self._repo[ctx2]
353 356 diffopts = patch.diffopts(self._repo.ui, opts)
354 357 return patch.diff(self._repo, ctx2, self, match=match, opts=diffopts)
355 358
356 359 def dirs(self):
357 360 return self._manifest.dirs()
358 361
359 362 def hasdir(self, dir):
360 363 return self._manifest.hasdir(dir)
361 364
362 365 def status(self, other=None, match=None, listignored=False,
363 366 listclean=False, listunknown=False, listsubrepos=False):
364 367 """return status of files between two nodes or node and working
365 368 directory.
366 369
367 370 If other is None, compare this node with working directory.
368 371
369 372 returns (modified, added, removed, deleted, unknown, ignored, clean)
370 373 """
371 374
372 375 ctx1 = self
373 376 ctx2 = self._repo[other]
374 377
375 378 # This next code block is, admittedly, fragile logic that tests for
376 379 # reversing the contexts and wouldn't need to exist if it weren't for
377 380 # the fast (and common) code path of comparing the working directory
378 381 # with its first parent.
379 382 #
380 383 # What we're aiming for here is the ability to call:
381 384 #
382 385 # workingctx.status(parentctx)
383 386 #
384 387 # If we always built the manifest for each context and compared those,
385 388 # then we'd be done. But the special case of the above call means we
386 389 # just copy the manifest of the parent.
387 390 reversed = False
388 391 if (not isinstance(ctx1, changectx)
389 392 and isinstance(ctx2, changectx)):
390 393 reversed = True
391 394 ctx1, ctx2 = ctx2, ctx1
392 395
393 396 match = match or matchmod.always(self._repo.root, self._repo.getcwd())
394 397 match = ctx2._matchstatus(ctx1, match)
395 398 r = scmutil.status([], [], [], [], [], [], [])
396 399 r = ctx2._buildstatus(ctx1, r, match, listignored, listclean,
397 400 listunknown)
398 401
399 402 if reversed:
400 403 # Reverse added and removed. Clear deleted, unknown and ignored as
401 404 # these make no sense to reverse.
402 405 r = scmutil.status(r.modified, r.removed, r.added, [], [], [],
403 406 r.clean)
404 407
405 408 if listsubrepos:
406 409 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
407 410 try:
408 411 rev2 = ctx2.subrev(subpath)
409 412 except KeyError:
410 413 # A subrepo that existed in node1 was deleted between
411 414 # node1 and node2 (inclusive). Thus, ctx2's substate
412 415 # won't contain that subpath. The best we can do ignore it.
413 416 rev2 = None
414 417 submatch = matchmod.subdirmatcher(subpath, match)
415 418 s = sub.status(rev2, match=submatch, ignored=listignored,
416 419 clean=listclean, unknown=listunknown,
417 420 listsubrepos=True)
418 421 for rfiles, sfiles in zip(r, s):
419 422 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
420 423
421 424 for l in r:
422 425 l.sort()
423 426
424 427 return r
425 428
426 429 def _filterederror(repo, changeid):
427 430 """build an exception to be raised about a filtered changeid
428 431
429 432 This is extracted in a function to help extensions (eg: evolve) to
430 433 experiment with various message variants."""
431 434 if repo.filtername.startswith('visible'):
432 435 msg = _("hidden revision '%s'") % changeid
433 436 hint = _('use --hidden to access hidden revisions')
434 437 return error.FilteredRepoLookupError(msg, hint=hint)
435 438 msg = _("filtered revision '%s' (not in '%s' subset)")
436 439 msg %= (changeid, repo.filtername)
437 440 return error.FilteredRepoLookupError(msg)
438 441
439 442 class changectx(basectx):
440 443 """A changecontext object makes access to data related to a particular
441 444 changeset convenient. It represents a read-only context already present in
442 445 the repo."""
443 446 def __init__(self, repo, changeid=''):
444 447 """changeid is a revision number, node, or tag"""
445 448
446 449 # since basectx.__new__ already took care of copying the object, we
447 450 # don't need to do anything in __init__, so we just exit here
448 451 if isinstance(changeid, basectx):
449 452 return
450 453
451 454 if changeid == '':
452 455 changeid = '.'
453 456 self._repo = repo
454 457
455 458 try:
456 459 if isinstance(changeid, int):
457 460 self._node = repo.changelog.node(changeid)
458 461 self._rev = changeid
459 462 return
460 463 if not pycompat.ispy3 and isinstance(changeid, long):
461 464 changeid = str(changeid)
462 465 if changeid == 'null':
463 466 self._node = nullid
464 467 self._rev = nullrev
465 468 return
466 469 if changeid == 'tip':
467 470 self._node = repo.changelog.tip()
468 471 self._rev = repo.changelog.rev(self._node)
469 472 return
470 473 if changeid == '.' or changeid == repo.dirstate.p1():
471 474 # this is a hack to delay/avoid loading obsmarkers
472 475 # when we know that '.' won't be hidden
473 476 self._node = repo.dirstate.p1()
474 477 self._rev = repo.unfiltered().changelog.rev(self._node)
475 478 return
476 479 if len(changeid) == 20:
477 480 try:
478 481 self._node = changeid
479 482 self._rev = repo.changelog.rev(changeid)
480 483 return
481 484 except error.FilteredRepoLookupError:
482 485 raise
483 486 except LookupError:
484 487 pass
485 488
486 489 try:
487 490 r = int(changeid)
488 491 if '%d' % r != changeid:
489 492 raise ValueError
490 493 l = len(repo.changelog)
491 494 if r < 0:
492 495 r += l
493 496 if r < 0 or r >= l and r != wdirrev:
494 497 raise ValueError
495 498 self._rev = r
496 499 self._node = repo.changelog.node(r)
497 500 return
498 501 except error.FilteredIndexError:
499 502 raise
500 503 except (ValueError, OverflowError, IndexError):
501 504 pass
502 505
503 506 if len(changeid) == 40:
504 507 try:
505 508 self._node = bin(changeid)
506 509 self._rev = repo.changelog.rev(self._node)
507 510 return
508 511 except error.FilteredLookupError:
509 512 raise
510 513 except (TypeError, LookupError):
511 514 pass
512 515
513 516 # lookup bookmarks through the name interface
514 517 try:
515 518 self._node = repo.names.singlenode(repo, changeid)
516 519 self._rev = repo.changelog.rev(self._node)
517 520 return
518 521 except KeyError:
519 522 pass
520 523 except error.FilteredRepoLookupError:
521 524 raise
522 525 except error.RepoLookupError:
523 526 pass
524 527
525 528 self._node = repo.unfiltered().changelog._partialmatch(changeid)
526 529 if self._node is not None:
527 530 self._rev = repo.changelog.rev(self._node)
528 531 return
529 532
530 533 # lookup failed
531 534 # check if it might have come from damaged dirstate
532 535 #
533 536 # XXX we could avoid the unfiltered if we had a recognizable
534 537 # exception for filtered changeset access
535 538 if changeid in repo.unfiltered().dirstate.parents():
536 539 msg = _("working directory has unknown parent '%s'!")
537 540 raise error.Abort(msg % short(changeid))
538 541 try:
539 542 if len(changeid) == 20 and nonascii(changeid):
540 543 changeid = hex(changeid)
541 544 except TypeError:
542 545 pass
543 546 except (error.FilteredIndexError, error.FilteredLookupError,
544 547 error.FilteredRepoLookupError):
545 548 raise _filterederror(repo, changeid)
546 549 except IndexError:
547 550 pass
548 551 raise error.RepoLookupError(
549 552 _("unknown revision '%s'") % changeid)
550 553
551 554 def __hash__(self):
552 555 try:
553 556 return hash(self._rev)
554 557 except AttributeError:
555 558 return id(self)
556 559
557 560 def __nonzero__(self):
558 561 return self._rev != nullrev
559 562
560 563 __bool__ = __nonzero__
561 564
562 565 @propertycache
563 566 def _changeset(self):
564 567 return self._repo.changelog.changelogrevision(self.rev())
565 568
566 569 @propertycache
567 570 def _manifest(self):
568 571 return self._manifestctx.read()
569 572
570 573 @property
571 574 def _manifestctx(self):
572 575 return self._repo.manifestlog[self._changeset.manifest]
573 576
574 577 @propertycache
575 578 def _manifestdelta(self):
576 579 return self._manifestctx.readdelta()
577 580
578 581 @propertycache
579 582 def _parents(self):
580 583 repo = self._repo
581 584 p1, p2 = repo.changelog.parentrevs(self._rev)
582 585 if p2 == nullrev:
583 586 return [changectx(repo, p1)]
584 587 return [changectx(repo, p1), changectx(repo, p2)]
585 588
586 589 def changeset(self):
587 590 c = self._changeset
588 591 return (
589 592 c.manifest,
590 593 c.user,
591 594 c.date,
592 595 c.files,
593 596 c.description,
594 597 c.extra,
595 598 )
596 599 def manifestnode(self):
597 600 return self._changeset.manifest
598 601
599 602 def user(self):
600 603 return self._changeset.user
601 604 def date(self):
602 605 return self._changeset.date
603 606 def files(self):
604 607 return self._changeset.files
605 608 def description(self):
606 609 return self._changeset.description
607 610 def branch(self):
608 611 return encoding.tolocal(self._changeset.extra.get("branch"))
609 612 def closesbranch(self):
610 613 return 'close' in self._changeset.extra
611 614 def extra(self):
612 615 return self._changeset.extra
613 616 def tags(self):
614 617 return self._repo.nodetags(self._node)
615 618 def bookmarks(self):
616 619 return self._repo.nodebookmarks(self._node)
617 620 def phase(self):
618 621 return self._repo._phasecache.phase(self._repo, self._rev)
619 622 def hidden(self):
620 623 return self._rev in repoview.filterrevs(self._repo, 'visible')
621 624
622 625 def children(self):
623 626 """return contexts for each child changeset"""
624 627 c = self._repo.changelog.children(self._node)
625 628 return [changectx(self._repo, x) for x in c]
626 629
627 630 def ancestors(self):
628 631 for a in self._repo.changelog.ancestors([self._rev]):
629 632 yield changectx(self._repo, a)
630 633
631 634 def descendants(self):
632 635 for d in self._repo.changelog.descendants([self._rev]):
633 636 yield changectx(self._repo, d)
634 637
635 638 def filectx(self, path, fileid=None, filelog=None):
636 639 """get a file context from this changeset"""
637 640 if fileid is None:
638 641 fileid = self.filenode(path)
639 642 return filectx(self._repo, path, fileid=fileid,
640 643 changectx=self, filelog=filelog)
641 644
642 645 def ancestor(self, c2, warn=False):
643 646 """return the "best" ancestor context of self and c2
644 647
645 648 If there are multiple candidates, it will show a message and check
646 649 merge.preferancestor configuration before falling back to the
647 650 revlog ancestor."""
648 651 # deal with workingctxs
649 652 n2 = c2._node
650 653 if n2 is None:
651 654 n2 = c2._parents[0]._node
652 655 cahs = self._repo.changelog.commonancestorsheads(self._node, n2)
653 656 if not cahs:
654 657 anc = nullid
655 658 elif len(cahs) == 1:
656 659 anc = cahs[0]
657 660 else:
658 661 # experimental config: merge.preferancestor
659 662 for r in self._repo.ui.configlist('merge', 'preferancestor', ['*']):
660 663 try:
661 664 ctx = changectx(self._repo, r)
662 665 except error.RepoLookupError:
663 666 continue
664 667 anc = ctx.node()
665 668 if anc in cahs:
666 669 break
667 670 else:
668 671 anc = self._repo.changelog.ancestor(self._node, n2)
669 672 if warn:
670 673 self._repo.ui.status(
671 674 (_("note: using %s as ancestor of %s and %s\n") %
672 675 (short(anc), short(self._node), short(n2))) +
673 676 ''.join(_(" alternatively, use --config "
674 677 "merge.preferancestor=%s\n") %
675 678 short(n) for n in sorted(cahs) if n != anc))
676 679 return changectx(self._repo, anc)
677 680
678 681 def descendant(self, other):
679 682 """True if other is descendant of this changeset"""
680 683 return self._repo.changelog.descendant(self._rev, other._rev)
681 684
682 685 def walk(self, match):
683 686 '''Generates matching file names.'''
684 687
685 688 # Wrap match.bad method to have message with nodeid
686 689 def bad(fn, msg):
687 690 # The manifest doesn't know about subrepos, so don't complain about
688 691 # paths into valid subrepos.
689 692 if any(fn == s or fn.startswith(s + '/')
690 693 for s in self.substate):
691 694 return
692 695 match.bad(fn, _('no such file in rev %s') % self)
693 696
694 697 m = matchmod.badmatch(match, bad)
695 698 return self._manifest.walk(m)
696 699
697 700 def matches(self, match):
698 701 return self.walk(match)
699 702
700 703 class basefilectx(object):
701 704 """A filecontext object represents the common logic for its children:
702 705 filectx: read-only access to a filerevision that is already present
703 706 in the repo,
704 707 workingfilectx: a filecontext that represents files from the working
705 708 directory,
706 709 memfilectx: a filecontext that represents files in-memory,
707 710 overlayfilectx: duplicate another filecontext with some fields overridden.
708 711 """
709 712 @propertycache
710 713 def _filelog(self):
711 714 return self._repo.file(self._path)
712 715
713 716 @propertycache
714 717 def _changeid(self):
715 718 if r'_changeid' in self.__dict__:
716 719 return self._changeid
717 720 elif r'_changectx' in self.__dict__:
718 721 return self._changectx.rev()
719 722 elif r'_descendantrev' in self.__dict__:
720 723 # this file context was created from a revision with a known
721 724 # descendant, we can (lazily) correct for linkrev aliases
722 725 return self._adjustlinkrev(self._descendantrev)
723 726 else:
724 727 return self._filelog.linkrev(self._filerev)
725 728
726 729 @propertycache
727 730 def _filenode(self):
728 731 if r'_fileid' in self.__dict__:
729 732 return self._filelog.lookup(self._fileid)
730 733 else:
731 734 return self._changectx.filenode(self._path)
732 735
733 736 @propertycache
734 737 def _filerev(self):
735 738 return self._filelog.rev(self._filenode)
736 739
737 740 @propertycache
738 741 def _repopath(self):
739 742 return self._path
740 743
741 744 def __nonzero__(self):
742 745 try:
743 746 self._filenode
744 747 return True
745 748 except error.LookupError:
746 749 # file is missing
747 750 return False
748 751
749 752 __bool__ = __nonzero__
750 753
751 754 def __bytes__(self):
752 755 try:
753 756 return "%s@%s" % (self.path(), self._changectx)
754 757 except error.LookupError:
755 758 return "%s@???" % self.path()
756 759
757 760 __str__ = encoding.strmethod(__bytes__)
758 761
759 762 def __repr__(self):
760 763 return "<%s %s>" % (type(self).__name__, str(self))
761 764
762 765 def __hash__(self):
763 766 try:
764 767 return hash((self._path, self._filenode))
765 768 except AttributeError:
766 769 return id(self)
767 770
768 771 def __eq__(self, other):
769 772 try:
770 773 return (type(self) == type(other) and self._path == other._path
771 774 and self._filenode == other._filenode)
772 775 except AttributeError:
773 776 return False
774 777
775 778 def __ne__(self, other):
776 779 return not (self == other)
777 780
778 781 def filerev(self):
779 782 return self._filerev
780 783 def filenode(self):
781 784 return self._filenode
782 785 @propertycache
783 786 def _flags(self):
784 787 return self._changectx.flags(self._path)
785 788 def flags(self):
786 789 return self._flags
787 790 def filelog(self):
788 791 return self._filelog
789 792 def rev(self):
790 793 return self._changeid
791 794 def linkrev(self):
792 795 return self._filelog.linkrev(self._filerev)
793 796 def node(self):
794 797 return self._changectx.node()
795 798 def hex(self):
796 799 return self._changectx.hex()
797 800 def user(self):
798 801 return self._changectx.user()
799 802 def date(self):
800 803 return self._changectx.date()
801 804 def files(self):
802 805 return self._changectx.files()
803 806 def description(self):
804 807 return self._changectx.description()
805 808 def branch(self):
806 809 return self._changectx.branch()
807 810 def extra(self):
808 811 return self._changectx.extra()
809 812 def phase(self):
810 813 return self._changectx.phase()
811 814 def phasestr(self):
812 815 return self._changectx.phasestr()
813 816 def manifest(self):
814 817 return self._changectx.manifest()
815 818 def changectx(self):
816 819 return self._changectx
817 820 def renamed(self):
818 821 return self._copied
819 822 def repo(self):
820 823 return self._repo
821 824 def size(self):
822 825 return len(self.data())
823 826
824 827 def path(self):
825 828 return self._path
826 829
827 830 def isbinary(self):
828 831 try:
829 832 return util.binary(self.data())
830 833 except IOError:
831 834 return False
832 835 def isexec(self):
833 836 return 'x' in self.flags()
834 837 def islink(self):
835 838 return 'l' in self.flags()
836 839
837 840 def isabsent(self):
838 841 """whether this filectx represents a file not in self._changectx
839 842
840 843 This is mainly for merge code to detect change/delete conflicts. This is
841 844 expected to be True for all subclasses of basectx."""
842 845 return False
843 846
844 847 _customcmp = False
845 848 def cmp(self, fctx):
846 849 """compare with other file context
847 850
848 851 returns True if different than fctx.
849 852 """
850 853 if fctx._customcmp:
851 854 return fctx.cmp(self)
852 855
853 856 if (fctx._filenode is None
854 857 and (self._repo._encodefilterpats
855 858 # if file data starts with '\1\n', empty metadata block is
856 859 # prepended, which adds 4 bytes to filelog.size().
857 860 or self.size() - 4 == fctx.size())
858 861 or self.size() == fctx.size()):
859 862 return self._filelog.cmp(self._filenode, fctx.data())
860 863
861 864 return True
862 865
863 866 def _adjustlinkrev(self, srcrev, inclusive=False):
864 867 """return the first ancestor of <srcrev> introducing <fnode>
865 868
866 869 If the linkrev of the file revision does not point to an ancestor of
867 870 srcrev, we'll walk down the ancestors until we find one introducing
868 871 this file revision.
869 872
870 873 :srcrev: the changeset revision we search ancestors from
871 874 :inclusive: if true, the src revision will also be checked
872 875 """
873 876 repo = self._repo
874 877 cl = repo.unfiltered().changelog
875 878 mfl = repo.manifestlog
876 879 # fetch the linkrev
877 880 lkr = self.linkrev()
878 881 # hack to reuse ancestor computation when searching for renames
879 882 memberanc = getattr(self, '_ancestrycontext', None)
880 883 iteranc = None
881 884 if srcrev is None:
882 885 # wctx case, used by workingfilectx during mergecopy
883 886 revs = [p.rev() for p in self._repo[None].parents()]
884 887 inclusive = True # we skipped the real (revless) source
885 888 else:
886 889 revs = [srcrev]
887 890 if memberanc is None:
888 891 memberanc = iteranc = cl.ancestors(revs, lkr,
889 892 inclusive=inclusive)
890 893 # check if this linkrev is an ancestor of srcrev
891 894 if lkr not in memberanc:
892 895 if iteranc is None:
893 896 iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
894 897 fnode = self._filenode
895 898 path = self._path
896 899 for a in iteranc:
897 900 ac = cl.read(a) # get changeset data (we avoid object creation)
898 901 if path in ac[3]: # checking the 'files' field.
899 902 # The file has been touched, check if the content is
900 903 # similar to the one we search for.
901 904 if fnode == mfl[ac[0]].readfast().get(path):
902 905 return a
903 906 # In theory, we should never get out of that loop without a result.
904 907 # But if manifest uses a buggy file revision (not children of the
905 908 # one it replaces) we could. Such a buggy situation will likely
906 909 # result is crash somewhere else at to some point.
907 910 return lkr
908 911
909 912 def introrev(self):
910 913 """return the rev of the changeset which introduced this file revision
911 914
912 915 This method is different from linkrev because it take into account the
913 916 changeset the filectx was created from. It ensures the returned
914 917 revision is one of its ancestors. This prevents bugs from
915 918 'linkrev-shadowing' when a file revision is used by multiple
916 919 changesets.
917 920 """
918 921 lkr = self.linkrev()
919 922 attrs = vars(self)
920 923 noctx = not ('_changeid' in attrs or '_changectx' in attrs)
921 924 if noctx or self.rev() == lkr:
922 925 return self.linkrev()
923 926 return self._adjustlinkrev(self.rev(), inclusive=True)
924 927
925 928 def _parentfilectx(self, path, fileid, filelog):
926 929 """create parent filectx keeping ancestry info for _adjustlinkrev()"""
927 930 fctx = filectx(self._repo, path, fileid=fileid, filelog=filelog)
928 931 if '_changeid' in vars(self) or '_changectx' in vars(self):
929 932 # If self is associated with a changeset (probably explicitly
930 933 # fed), ensure the created filectx is associated with a
931 934 # changeset that is an ancestor of self.changectx.
932 935 # This lets us later use _adjustlinkrev to get a correct link.
933 936 fctx._descendantrev = self.rev()
934 937 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
935 938 elif '_descendantrev' in vars(self):
936 939 # Otherwise propagate _descendantrev if we have one associated.
937 940 fctx._descendantrev = self._descendantrev
938 941 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
939 942 return fctx
940 943
941 944 def parents(self):
942 945 _path = self._path
943 946 fl = self._filelog
944 947 parents = self._filelog.parents(self._filenode)
945 948 pl = [(_path, node, fl) for node in parents if node != nullid]
946 949
947 950 r = fl.renamed(self._filenode)
948 951 if r:
949 952 # - In the simple rename case, both parent are nullid, pl is empty.
950 953 # - In case of merge, only one of the parent is null id and should
951 954 # be replaced with the rename information. This parent is -always-
952 955 # the first one.
953 956 #
954 957 # As null id have always been filtered out in the previous list
955 958 # comprehension, inserting to 0 will always result in "replacing
956 959 # first nullid parent with rename information.
957 960 pl.insert(0, (r[0], r[1], self._repo.file(r[0])))
958 961
959 962 return [self._parentfilectx(path, fnode, l) for path, fnode, l in pl]
960 963
961 964 def p1(self):
962 965 return self.parents()[0]
963 966
964 967 def p2(self):
965 968 p = self.parents()
966 969 if len(p) == 2:
967 970 return p[1]
968 971 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
969 972
970 973 def annotate(self, follow=False, linenumber=False, skiprevs=None,
971 974 diffopts=None):
972 975 '''returns a list of tuples of ((ctx, number), line) for each line
973 976 in the file, where ctx is the filectx of the node where
974 977 that line was last changed; if linenumber parameter is true, number is
975 978 the line number at the first appearance in the managed file, otherwise,
976 979 number has a fixed value of False.
977 980 '''
978 981
979 982 def lines(text):
980 983 if text.endswith("\n"):
981 984 return text.count("\n")
982 985 return text.count("\n") + int(bool(text))
983 986
984 987 if linenumber:
985 988 def decorate(text, rev):
986 return ([(rev, i) for i in xrange(1, lines(text) + 1)], text)
989 return ([annotateline(fctx=rev, lineno=i)
990 for i in xrange(1, lines(text) + 1)], text)
987 991 else:
988 992 def decorate(text, rev):
989 return ([(rev, False)] * lines(text), text)
993 return ([annotateline(fctx=rev)] * lines(text), text)
990 994
991 995 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
992 996
993 997 def parents(f):
994 998 # Cut _descendantrev here to mitigate the penalty of lazy linkrev
995 999 # adjustment. Otherwise, p._adjustlinkrev() would walk changelog
996 1000 # from the topmost introrev (= srcrev) down to p.linkrev() if it
997 1001 # isn't an ancestor of the srcrev.
998 1002 f._changeid
999 1003 pl = f.parents()
1000 1004
1001 1005 # Don't return renamed parents if we aren't following.
1002 1006 if not follow:
1003 1007 pl = [p for p in pl if p.path() == f.path()]
1004 1008
1005 1009 # renamed filectx won't have a filelog yet, so set it
1006 1010 # from the cache to save time
1007 1011 for p in pl:
1008 1012 if not '_filelog' in p.__dict__:
1009 1013 p._filelog = getlog(p.path())
1010 1014
1011 1015 return pl
1012 1016
1013 1017 # use linkrev to find the first changeset where self appeared
1014 1018 base = self
1015 1019 introrev = self.introrev()
1016 1020 if self.rev() != introrev:
1017 1021 base = self.filectx(self.filenode(), changeid=introrev)
1018 1022 if getattr(base, '_ancestrycontext', None) is None:
1019 1023 cl = self._repo.changelog
1020 1024 if introrev is None:
1021 1025 # wctx is not inclusive, but works because _ancestrycontext
1022 1026 # is used to test filelog revisions
1023 1027 ac = cl.ancestors([p.rev() for p in base.parents()],
1024 1028 inclusive=True)
1025 1029 else:
1026 1030 ac = cl.ancestors([introrev], inclusive=True)
1027 1031 base._ancestrycontext = ac
1028 1032
1029 1033 # This algorithm would prefer to be recursive, but Python is a
1030 1034 # bit recursion-hostile. Instead we do an iterative
1031 1035 # depth-first search.
1032 1036
1033 1037 # 1st DFS pre-calculates pcache and needed
1034 1038 visit = [base]
1035 1039 pcache = {}
1036 1040 needed = {base: 1}
1037 1041 while visit:
1038 1042 f = visit.pop()
1039 1043 if f in pcache:
1040 1044 continue
1041 1045 pl = parents(f)
1042 1046 pcache[f] = pl
1043 1047 for p in pl:
1044 1048 needed[p] = needed.get(p, 0) + 1
1045 1049 if p not in pcache:
1046 1050 visit.append(p)
1047 1051
1048 1052 # 2nd DFS does the actual annotate
1049 1053 visit[:] = [base]
1050 1054 hist = {}
1051 1055 while visit:
1052 1056 f = visit[-1]
1053 1057 if f in hist:
1054 1058 visit.pop()
1055 1059 continue
1056 1060
1057 1061 ready = True
1058 1062 pl = pcache[f]
1059 1063 for p in pl:
1060 1064 if p not in hist:
1061 1065 ready = False
1062 1066 visit.append(p)
1063 1067 if ready:
1064 1068 visit.pop()
1065 1069 curr = decorate(f.data(), f)
1066 1070 skipchild = False
1067 1071 if skiprevs is not None:
1068 1072 skipchild = f._changeid in skiprevs
1069 1073 curr = _annotatepair([hist[p] for p in pl], f, curr, skipchild,
1070 1074 diffopts)
1071 1075 for p in pl:
1072 1076 if needed[p] == 1:
1073 1077 del hist[p]
1074 1078 del needed[p]
1075 1079 else:
1076 1080 needed[p] -= 1
1077 1081
1078 1082 hist[f] = curr
1079 1083 del pcache[f]
1080 1084
1081 1085 return zip(hist[base][0], hist[base][1].splitlines(True))
1082 1086
1083 1087 def ancestors(self, followfirst=False):
1084 1088 visit = {}
1085 1089 c = self
1086 1090 if followfirst:
1087 1091 cut = 1
1088 1092 else:
1089 1093 cut = None
1090 1094
1091 1095 while True:
1092 1096 for parent in c.parents()[:cut]:
1093 1097 visit[(parent.linkrev(), parent.filenode())] = parent
1094 1098 if not visit:
1095 1099 break
1096 1100 c = visit.pop(max(visit))
1097 1101 yield c
1098 1102
1099 1103 def decodeddata(self):
1100 1104 """Returns `data()` after running repository decoding filters.
1101 1105
1102 1106 This is often equivalent to how the data would be expressed on disk.
1103 1107 """
1104 1108 return self._repo.wwritedata(self.path(), self.data())
1105 1109
1110 @attr.s(slots=True, frozen=True)
1111 class annotateline(object):
1112 fctx = attr.ib()
1113 lineno = attr.ib(default=False)
1114
1106 1115 def _annotatepair(parents, childfctx, child, skipchild, diffopts):
1107 1116 r'''
1108 1117 Given parent and child fctxes and annotate data for parents, for all lines
1109 1118 in either parent that match the child, annotate the child with the parent's
1110 1119 data.
1111 1120
1112 1121 Additionally, if `skipchild` is True, replace all other lines with parent
1113 1122 annotate data as well such that child is never blamed for any lines.
1114 1123
1115 1124 See test-annotate.py for unit tests.
1116 1125 '''
1117 1126 pblocks = [(parent, mdiff.allblocks(parent[1], child[1], opts=diffopts))
1118 1127 for parent in parents]
1119 1128
1120 1129 if skipchild:
1121 1130 # Need to iterate over the blocks twice -- make it a list
1122 1131 pblocks = [(p, list(blocks)) for (p, blocks) in pblocks]
1123 1132 # Mercurial currently prefers p2 over p1 for annotate.
1124 1133 # TODO: change this?
1125 1134 for parent, blocks in pblocks:
1126 1135 for (a1, a2, b1, b2), t in blocks:
1127 1136 # Changed blocks ('!') or blocks made only of blank lines ('~')
1128 1137 # belong to the child.
1129 1138 if t == '=':
1130 1139 child[0][b1:b2] = parent[0][a1:a2]
1131 1140
1132 1141 if skipchild:
1133 1142 # Now try and match up anything that couldn't be matched,
1134 1143 # Reversing pblocks maintains bias towards p2, matching above
1135 1144 # behavior.
1136 1145 pblocks.reverse()
1137 1146
1138 1147 # The heuristics are:
1139 1148 # * Work on blocks of changed lines (effectively diff hunks with -U0).
1140 1149 # This could potentially be smarter but works well enough.
1141 1150 # * For a non-matching section, do a best-effort fit. Match lines in
1142 1151 # diff hunks 1:1, dropping lines as necessary.
1143 1152 # * Repeat the last line as a last resort.
1144 1153
1145 1154 # First, replace as much as possible without repeating the last line.
1146 1155 remaining = [(parent, []) for parent, _blocks in pblocks]
1147 1156 for idx, (parent, blocks) in enumerate(pblocks):
1148 1157 for (a1, a2, b1, b2), _t in blocks:
1149 1158 if a2 - a1 >= b2 - b1:
1150 1159 for bk in xrange(b1, b2):
1151 if child[0][bk][0] == childfctx:
1160 if child[0][bk].fctx == childfctx:
1152 1161 ak = min(a1 + (bk - b1), a2 - 1)
1153 1162 child[0][bk] = parent[0][ak]
1154 1163 else:
1155 1164 remaining[idx][1].append((a1, a2, b1, b2))
1156 1165
1157 1166 # Then, look at anything left, which might involve repeating the last
1158 1167 # line.
1159 1168 for parent, blocks in remaining:
1160 1169 for a1, a2, b1, b2 in blocks:
1161 1170 for bk in xrange(b1, b2):
1162 if child[0][bk][0] == childfctx:
1171 if child[0][bk].fctx == childfctx:
1163 1172 ak = min(a1 + (bk - b1), a2 - 1)
1164 1173 child[0][bk] = parent[0][ak]
1165 1174 return child
1166 1175
1167 1176 class filectx(basefilectx):
1168 1177 """A filecontext object makes access to data related to a particular
1169 1178 filerevision convenient."""
1170 1179 def __init__(self, repo, path, changeid=None, fileid=None,
1171 1180 filelog=None, changectx=None):
1172 1181 """changeid can be a changeset revision, node, or tag.
1173 1182 fileid can be a file revision or node."""
1174 1183 self._repo = repo
1175 1184 self._path = path
1176 1185
1177 1186 assert (changeid is not None
1178 1187 or fileid is not None
1179 1188 or changectx is not None), \
1180 1189 ("bad args: changeid=%r, fileid=%r, changectx=%r"
1181 1190 % (changeid, fileid, changectx))
1182 1191
1183 1192 if filelog is not None:
1184 1193 self._filelog = filelog
1185 1194
1186 1195 if changeid is not None:
1187 1196 self._changeid = changeid
1188 1197 if changectx is not None:
1189 1198 self._changectx = changectx
1190 1199 if fileid is not None:
1191 1200 self._fileid = fileid
1192 1201
1193 1202 @propertycache
1194 1203 def _changectx(self):
1195 1204 try:
1196 1205 return changectx(self._repo, self._changeid)
1197 1206 except error.FilteredRepoLookupError:
1198 1207 # Linkrev may point to any revision in the repository. When the
1199 1208 # repository is filtered this may lead to `filectx` trying to build
1200 1209 # `changectx` for filtered revision. In such case we fallback to
1201 1210 # creating `changectx` on the unfiltered version of the reposition.
1202 1211 # This fallback should not be an issue because `changectx` from
1203 1212 # `filectx` are not used in complex operations that care about
1204 1213 # filtering.
1205 1214 #
1206 1215 # This fallback is a cheap and dirty fix that prevent several
1207 1216 # crashes. It does not ensure the behavior is correct. However the
1208 1217 # behavior was not correct before filtering either and "incorrect
1209 1218 # behavior" is seen as better as "crash"
1210 1219 #
1211 1220 # Linkrevs have several serious troubles with filtering that are
1212 1221 # complicated to solve. Proper handling of the issue here should be
1213 1222 # considered when solving linkrev issue are on the table.
1214 1223 return changectx(self._repo.unfiltered(), self._changeid)
1215 1224
1216 1225 def filectx(self, fileid, changeid=None):
1217 1226 '''opens an arbitrary revision of the file without
1218 1227 opening a new filelog'''
1219 1228 return filectx(self._repo, self._path, fileid=fileid,
1220 1229 filelog=self._filelog, changeid=changeid)
1221 1230
1222 1231 def rawdata(self):
1223 1232 return self._filelog.revision(self._filenode, raw=True)
1224 1233
1225 1234 def rawflags(self):
1226 1235 """low-level revlog flags"""
1227 1236 return self._filelog.flags(self._filerev)
1228 1237
1229 1238 def data(self):
1230 1239 try:
1231 1240 return self._filelog.read(self._filenode)
1232 1241 except error.CensoredNodeError:
1233 1242 if self._repo.ui.config("censor", "policy") == "ignore":
1234 1243 return ""
1235 1244 raise error.Abort(_("censored node: %s") % short(self._filenode),
1236 1245 hint=_("set censor.policy to ignore errors"))
1237 1246
1238 1247 def size(self):
1239 1248 return self._filelog.size(self._filerev)
1240 1249
1241 1250 @propertycache
1242 1251 def _copied(self):
1243 1252 """check if file was actually renamed in this changeset revision
1244 1253
1245 1254 If rename logged in file revision, we report copy for changeset only
1246 1255 if file revisions linkrev points back to the changeset in question
1247 1256 or both changeset parents contain different file revisions.
1248 1257 """
1249 1258
1250 1259 renamed = self._filelog.renamed(self._filenode)
1251 1260 if not renamed:
1252 1261 return renamed
1253 1262
1254 1263 if self.rev() == self.linkrev():
1255 1264 return renamed
1256 1265
1257 1266 name = self.path()
1258 1267 fnode = self._filenode
1259 1268 for p in self._changectx.parents():
1260 1269 try:
1261 1270 if fnode == p.filenode(name):
1262 1271 return None
1263 1272 except error.LookupError:
1264 1273 pass
1265 1274 return renamed
1266 1275
1267 1276 def children(self):
1268 1277 # hard for renames
1269 1278 c = self._filelog.children(self._filenode)
1270 1279 return [filectx(self._repo, self._path, fileid=x,
1271 1280 filelog=self._filelog) for x in c]
1272 1281
1273 1282 class committablectx(basectx):
1274 1283 """A committablectx object provides common functionality for a context that
1275 1284 wants the ability to commit, e.g. workingctx or memctx."""
1276 1285 def __init__(self, repo, text="", user=None, date=None, extra=None,
1277 1286 changes=None):
1278 1287 self._repo = repo
1279 1288 self._rev = None
1280 1289 self._node = None
1281 1290 self._text = text
1282 1291 if date:
1283 1292 self._date = util.parsedate(date)
1284 1293 if user:
1285 1294 self._user = user
1286 1295 if changes:
1287 1296 self._status = changes
1288 1297
1289 1298 self._extra = {}
1290 1299 if extra:
1291 1300 self._extra = extra.copy()
1292 1301 if 'branch' not in self._extra:
1293 1302 try:
1294 1303 branch = encoding.fromlocal(self._repo.dirstate.branch())
1295 1304 except UnicodeDecodeError:
1296 1305 raise error.Abort(_('branch name not in UTF-8!'))
1297 1306 self._extra['branch'] = branch
1298 1307 if self._extra['branch'] == '':
1299 1308 self._extra['branch'] = 'default'
1300 1309
1301 1310 def __bytes__(self):
1302 1311 return bytes(self._parents[0]) + "+"
1303 1312
1304 1313 __str__ = encoding.strmethod(__bytes__)
1305 1314
1306 1315 def __nonzero__(self):
1307 1316 return True
1308 1317
1309 1318 __bool__ = __nonzero__
1310 1319
1311 1320 def _buildflagfunc(self):
1312 1321 # Create a fallback function for getting file flags when the
1313 1322 # filesystem doesn't support them
1314 1323
1315 1324 copiesget = self._repo.dirstate.copies().get
1316 1325 parents = self.parents()
1317 1326 if len(parents) < 2:
1318 1327 # when we have one parent, it's easy: copy from parent
1319 1328 man = parents[0].manifest()
1320 1329 def func(f):
1321 1330 f = copiesget(f, f)
1322 1331 return man.flags(f)
1323 1332 else:
1324 1333 # merges are tricky: we try to reconstruct the unstored
1325 1334 # result from the merge (issue1802)
1326 1335 p1, p2 = parents
1327 1336 pa = p1.ancestor(p2)
1328 1337 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1329 1338
1330 1339 def func(f):
1331 1340 f = copiesget(f, f) # may be wrong for merges with copies
1332 1341 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1333 1342 if fl1 == fl2:
1334 1343 return fl1
1335 1344 if fl1 == fla:
1336 1345 return fl2
1337 1346 if fl2 == fla:
1338 1347 return fl1
1339 1348 return '' # punt for conflicts
1340 1349
1341 1350 return func
1342 1351
1343 1352 @propertycache
1344 1353 def _flagfunc(self):
1345 1354 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1346 1355
1347 1356 @propertycache
1348 1357 def _status(self):
1349 1358 return self._repo.status()
1350 1359
1351 1360 @propertycache
1352 1361 def _user(self):
1353 1362 return self._repo.ui.username()
1354 1363
1355 1364 @propertycache
1356 1365 def _date(self):
1357 1366 ui = self._repo.ui
1358 1367 date = ui.configdate('devel', 'default-date')
1359 1368 if date is None:
1360 1369 date = util.makedate()
1361 1370 return date
1362 1371
1363 1372 def subrev(self, subpath):
1364 1373 return None
1365 1374
1366 1375 def manifestnode(self):
1367 1376 return None
1368 1377 def user(self):
1369 1378 return self._user or self._repo.ui.username()
1370 1379 def date(self):
1371 1380 return self._date
1372 1381 def description(self):
1373 1382 return self._text
1374 1383 def files(self):
1375 1384 return sorted(self._status.modified + self._status.added +
1376 1385 self._status.removed)
1377 1386
1378 1387 def modified(self):
1379 1388 return self._status.modified
1380 1389 def added(self):
1381 1390 return self._status.added
1382 1391 def removed(self):
1383 1392 return self._status.removed
1384 1393 def deleted(self):
1385 1394 return self._status.deleted
1386 1395 def branch(self):
1387 1396 return encoding.tolocal(self._extra['branch'])
1388 1397 def closesbranch(self):
1389 1398 return 'close' in self._extra
1390 1399 def extra(self):
1391 1400 return self._extra
1392 1401
1393 1402 def tags(self):
1394 1403 return []
1395 1404
1396 1405 def bookmarks(self):
1397 1406 b = []
1398 1407 for p in self.parents():
1399 1408 b.extend(p.bookmarks())
1400 1409 return b
1401 1410
1402 1411 def phase(self):
1403 1412 phase = phases.draft # default phase to draft
1404 1413 for p in self.parents():
1405 1414 phase = max(phase, p.phase())
1406 1415 return phase
1407 1416
1408 1417 def hidden(self):
1409 1418 return False
1410 1419
1411 1420 def children(self):
1412 1421 return []
1413 1422
1414 1423 def flags(self, path):
1415 1424 if r'_manifest' in self.__dict__:
1416 1425 try:
1417 1426 return self._manifest.flags(path)
1418 1427 except KeyError:
1419 1428 return ''
1420 1429
1421 1430 try:
1422 1431 return self._flagfunc(path)
1423 1432 except OSError:
1424 1433 return ''
1425 1434
1426 1435 def ancestor(self, c2):
1427 1436 """return the "best" ancestor context of self and c2"""
1428 1437 return self._parents[0].ancestor(c2) # punt on two parents for now
1429 1438
1430 1439 def walk(self, match):
1431 1440 '''Generates matching file names.'''
1432 1441 return sorted(self._repo.dirstate.walk(match,
1433 1442 subrepos=sorted(self.substate),
1434 1443 unknown=True, ignored=False))
1435 1444
1436 1445 def matches(self, match):
1437 1446 return sorted(self._repo.dirstate.matches(match))
1438 1447
1439 1448 def ancestors(self):
1440 1449 for p in self._parents:
1441 1450 yield p
1442 1451 for a in self._repo.changelog.ancestors(
1443 1452 [p.rev() for p in self._parents]):
1444 1453 yield changectx(self._repo, a)
1445 1454
1446 1455 def markcommitted(self, node):
1447 1456 """Perform post-commit cleanup necessary after committing this ctx
1448 1457
1449 1458 Specifically, this updates backing stores this working context
1450 1459 wraps to reflect the fact that the changes reflected by this
1451 1460 workingctx have been committed. For example, it marks
1452 1461 modified and added files as normal in the dirstate.
1453 1462
1454 1463 """
1455 1464
1456 1465 with self._repo.dirstate.parentchange():
1457 1466 for f in self.modified() + self.added():
1458 1467 self._repo.dirstate.normal(f)
1459 1468 for f in self.removed():
1460 1469 self._repo.dirstate.drop(f)
1461 1470 self._repo.dirstate.setparents(node)
1462 1471
1463 1472 # write changes out explicitly, because nesting wlock at
1464 1473 # runtime may prevent 'wlock.release()' in 'repo.commit()'
1465 1474 # from immediately doing so for subsequent changing files
1466 1475 self._repo.dirstate.write(self._repo.currenttransaction())
1467 1476
1468 1477 def dirty(self, missing=False, merge=True, branch=True):
1469 1478 return False
1470 1479
1471 1480 class workingctx(committablectx):
1472 1481 """A workingctx object makes access to data related to
1473 1482 the current working directory convenient.
1474 1483 date - any valid date string or (unixtime, offset), or None.
1475 1484 user - username string, or None.
1476 1485 extra - a dictionary of extra values, or None.
1477 1486 changes - a list of file lists as returned by localrepo.status()
1478 1487 or None to use the repository status.
1479 1488 """
1480 1489 def __init__(self, repo, text="", user=None, date=None, extra=None,
1481 1490 changes=None):
1482 1491 super(workingctx, self).__init__(repo, text, user, date, extra, changes)
1483 1492
1484 1493 def __iter__(self):
1485 1494 d = self._repo.dirstate
1486 1495 for f in d:
1487 1496 if d[f] != 'r':
1488 1497 yield f
1489 1498
1490 1499 def __contains__(self, key):
1491 1500 return self._repo.dirstate[key] not in "?r"
1492 1501
1493 1502 def hex(self):
1494 1503 return hex(wdirid)
1495 1504
1496 1505 @propertycache
1497 1506 def _parents(self):
1498 1507 p = self._repo.dirstate.parents()
1499 1508 if p[1] == nullid:
1500 1509 p = p[:-1]
1501 1510 return [changectx(self._repo, x) for x in p]
1502 1511
1503 1512 def filectx(self, path, filelog=None):
1504 1513 """get a file context from the working directory"""
1505 1514 return workingfilectx(self._repo, path, workingctx=self,
1506 1515 filelog=filelog)
1507 1516
1508 1517 def dirty(self, missing=False, merge=True, branch=True):
1509 1518 "check whether a working directory is modified"
1510 1519 # check subrepos first
1511 1520 for s in sorted(self.substate):
1512 1521 if self.sub(s).dirty(missing=missing):
1513 1522 return True
1514 1523 # check current working dir
1515 1524 return ((merge and self.p2()) or
1516 1525 (branch and self.branch() != self.p1().branch()) or
1517 1526 self.modified() or self.added() or self.removed() or
1518 1527 (missing and self.deleted()))
1519 1528
1520 1529 def add(self, list, prefix=""):
1521 1530 with self._repo.wlock():
1522 1531 ui, ds = self._repo.ui, self._repo.dirstate
1523 1532 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1524 1533 rejected = []
1525 1534 lstat = self._repo.wvfs.lstat
1526 1535 for f in list:
1527 1536 # ds.pathto() returns an absolute file when this is invoked from
1528 1537 # the keyword extension. That gets flagged as non-portable on
1529 1538 # Windows, since it contains the drive letter and colon.
1530 1539 scmutil.checkportable(ui, os.path.join(prefix, f))
1531 1540 try:
1532 1541 st = lstat(f)
1533 1542 except OSError:
1534 1543 ui.warn(_("%s does not exist!\n") % uipath(f))
1535 1544 rejected.append(f)
1536 1545 continue
1537 1546 if st.st_size > 10000000:
1538 1547 ui.warn(_("%s: up to %d MB of RAM may be required "
1539 1548 "to manage this file\n"
1540 1549 "(use 'hg revert %s' to cancel the "
1541 1550 "pending addition)\n")
1542 1551 % (f, 3 * st.st_size // 1000000, uipath(f)))
1543 1552 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1544 1553 ui.warn(_("%s not added: only files and symlinks "
1545 1554 "supported currently\n") % uipath(f))
1546 1555 rejected.append(f)
1547 1556 elif ds[f] in 'amn':
1548 1557 ui.warn(_("%s already tracked!\n") % uipath(f))
1549 1558 elif ds[f] == 'r':
1550 1559 ds.normallookup(f)
1551 1560 else:
1552 1561 ds.add(f)
1553 1562 return rejected
1554 1563
1555 1564 def forget(self, files, prefix=""):
1556 1565 with self._repo.wlock():
1557 1566 ds = self._repo.dirstate
1558 1567 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1559 1568 rejected = []
1560 1569 for f in files:
1561 1570 if f not in self._repo.dirstate:
1562 1571 self._repo.ui.warn(_("%s not tracked!\n") % uipath(f))
1563 1572 rejected.append(f)
1564 1573 elif self._repo.dirstate[f] != 'a':
1565 1574 self._repo.dirstate.remove(f)
1566 1575 else:
1567 1576 self._repo.dirstate.drop(f)
1568 1577 return rejected
1569 1578
1570 1579 def undelete(self, list):
1571 1580 pctxs = self.parents()
1572 1581 with self._repo.wlock():
1573 1582 ds = self._repo.dirstate
1574 1583 for f in list:
1575 1584 if self._repo.dirstate[f] != 'r':
1576 1585 self._repo.ui.warn(_("%s not removed!\n") % ds.pathto(f))
1577 1586 else:
1578 1587 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
1579 1588 t = fctx.data()
1580 1589 self._repo.wwrite(f, t, fctx.flags())
1581 1590 self._repo.dirstate.normal(f)
1582 1591
1583 1592 def copy(self, source, dest):
1584 1593 try:
1585 1594 st = self._repo.wvfs.lstat(dest)
1586 1595 except OSError as err:
1587 1596 if err.errno != errno.ENOENT:
1588 1597 raise
1589 1598 self._repo.ui.warn(_("%s does not exist!\n")
1590 1599 % self._repo.dirstate.pathto(dest))
1591 1600 return
1592 1601 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1593 1602 self._repo.ui.warn(_("copy failed: %s is not a file or a "
1594 1603 "symbolic link\n")
1595 1604 % self._repo.dirstate.pathto(dest))
1596 1605 else:
1597 1606 with self._repo.wlock():
1598 1607 if self._repo.dirstate[dest] in '?':
1599 1608 self._repo.dirstate.add(dest)
1600 1609 elif self._repo.dirstate[dest] in 'r':
1601 1610 self._repo.dirstate.normallookup(dest)
1602 1611 self._repo.dirstate.copy(source, dest)
1603 1612
1604 1613 def match(self, pats=None, include=None, exclude=None, default='glob',
1605 1614 listsubrepos=False, badfn=None):
1606 1615 r = self._repo
1607 1616
1608 1617 # Only a case insensitive filesystem needs magic to translate user input
1609 1618 # to actual case in the filesystem.
1610 1619 icasefs = not util.fscasesensitive(r.root)
1611 1620 return matchmod.match(r.root, r.getcwd(), pats, include, exclude,
1612 1621 default, auditor=r.auditor, ctx=self,
1613 1622 listsubrepos=listsubrepos, badfn=badfn,
1614 1623 icasefs=icasefs)
1615 1624
1616 1625 def flushall(self):
1617 1626 pass # For overlayworkingfilectx compatibility.
1618 1627
1619 1628 def _filtersuspectsymlink(self, files):
1620 1629 if not files or self._repo.dirstate._checklink:
1621 1630 return files
1622 1631
1623 1632 # Symlink placeholders may get non-symlink-like contents
1624 1633 # via user error or dereferencing by NFS or Samba servers,
1625 1634 # so we filter out any placeholders that don't look like a
1626 1635 # symlink
1627 1636 sane = []
1628 1637 for f in files:
1629 1638 if self.flags(f) == 'l':
1630 1639 d = self[f].data()
1631 1640 if d == '' or len(d) >= 1024 or '\n' in d or util.binary(d):
1632 1641 self._repo.ui.debug('ignoring suspect symlink placeholder'
1633 1642 ' "%s"\n' % f)
1634 1643 continue
1635 1644 sane.append(f)
1636 1645 return sane
1637 1646
1638 1647 def _checklookup(self, files):
1639 1648 # check for any possibly clean files
1640 1649 if not files:
1641 1650 return [], [], []
1642 1651
1643 1652 modified = []
1644 1653 deleted = []
1645 1654 fixup = []
1646 1655 pctx = self._parents[0]
1647 1656 # do a full compare of any files that might have changed
1648 1657 for f in sorted(files):
1649 1658 try:
1650 1659 # This will return True for a file that got replaced by a
1651 1660 # directory in the interim, but fixing that is pretty hard.
1652 1661 if (f not in pctx or self.flags(f) != pctx.flags(f)
1653 1662 or pctx[f].cmp(self[f])):
1654 1663 modified.append(f)
1655 1664 else:
1656 1665 fixup.append(f)
1657 1666 except (IOError, OSError):
1658 1667 # A file become inaccessible in between? Mark it as deleted,
1659 1668 # matching dirstate behavior (issue5584).
1660 1669 # The dirstate has more complex behavior around whether a
1661 1670 # missing file matches a directory, etc, but we don't need to
1662 1671 # bother with that: if f has made it to this point, we're sure
1663 1672 # it's in the dirstate.
1664 1673 deleted.append(f)
1665 1674
1666 1675 return modified, deleted, fixup
1667 1676
1668 1677 def _poststatusfixup(self, status, fixup):
1669 1678 """update dirstate for files that are actually clean"""
1670 1679 poststatus = self._repo.postdsstatus()
1671 1680 if fixup or poststatus:
1672 1681 try:
1673 1682 oldid = self._repo.dirstate.identity()
1674 1683
1675 1684 # updating the dirstate is optional
1676 1685 # so we don't wait on the lock
1677 1686 # wlock can invalidate the dirstate, so cache normal _after_
1678 1687 # taking the lock
1679 1688 with self._repo.wlock(False):
1680 1689 if self._repo.dirstate.identity() == oldid:
1681 1690 if fixup:
1682 1691 normal = self._repo.dirstate.normal
1683 1692 for f in fixup:
1684 1693 normal(f)
1685 1694 # write changes out explicitly, because nesting
1686 1695 # wlock at runtime may prevent 'wlock.release()'
1687 1696 # after this block from doing so for subsequent
1688 1697 # changing files
1689 1698 tr = self._repo.currenttransaction()
1690 1699 self._repo.dirstate.write(tr)
1691 1700
1692 1701 if poststatus:
1693 1702 for ps in poststatus:
1694 1703 ps(self, status)
1695 1704 else:
1696 1705 # in this case, writing changes out breaks
1697 1706 # consistency, because .hg/dirstate was
1698 1707 # already changed simultaneously after last
1699 1708 # caching (see also issue5584 for detail)
1700 1709 self._repo.ui.debug('skip updating dirstate: '
1701 1710 'identity mismatch\n')
1702 1711 except error.LockError:
1703 1712 pass
1704 1713 finally:
1705 1714 # Even if the wlock couldn't be grabbed, clear out the list.
1706 1715 self._repo.clearpostdsstatus()
1707 1716
1708 1717 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
1709 1718 '''Gets the status from the dirstate -- internal use only.'''
1710 1719 subrepos = []
1711 1720 if '.hgsub' in self:
1712 1721 subrepos = sorted(self.substate)
1713 1722 cmp, s = self._repo.dirstate.status(match, subrepos, ignored=ignored,
1714 1723 clean=clean, unknown=unknown)
1715 1724
1716 1725 # check for any possibly clean files
1717 1726 fixup = []
1718 1727 if cmp:
1719 1728 modified2, deleted2, fixup = self._checklookup(cmp)
1720 1729 s.modified.extend(modified2)
1721 1730 s.deleted.extend(deleted2)
1722 1731
1723 1732 if fixup and clean:
1724 1733 s.clean.extend(fixup)
1725 1734
1726 1735 self._poststatusfixup(s, fixup)
1727 1736
1728 1737 if match.always():
1729 1738 # cache for performance
1730 1739 if s.unknown or s.ignored or s.clean:
1731 1740 # "_status" is cached with list*=False in the normal route
1732 1741 self._status = scmutil.status(s.modified, s.added, s.removed,
1733 1742 s.deleted, [], [], [])
1734 1743 else:
1735 1744 self._status = s
1736 1745
1737 1746 return s
1738 1747
1739 1748 @propertycache
1740 1749 def _manifest(self):
1741 1750 """generate a manifest corresponding to the values in self._status
1742 1751
1743 1752 This reuse the file nodeid from parent, but we use special node
1744 1753 identifiers for added and modified files. This is used by manifests
1745 1754 merge to see that files are different and by update logic to avoid
1746 1755 deleting newly added files.
1747 1756 """
1748 1757 return self._buildstatusmanifest(self._status)
1749 1758
1750 1759 def _buildstatusmanifest(self, status):
1751 1760 """Builds a manifest that includes the given status results."""
1752 1761 parents = self.parents()
1753 1762
1754 1763 man = parents[0].manifest().copy()
1755 1764
1756 1765 ff = self._flagfunc
1757 1766 for i, l in ((addednodeid, status.added),
1758 1767 (modifiednodeid, status.modified)):
1759 1768 for f in l:
1760 1769 man[f] = i
1761 1770 try:
1762 1771 man.setflag(f, ff(f))
1763 1772 except OSError:
1764 1773 pass
1765 1774
1766 1775 for f in status.deleted + status.removed:
1767 1776 if f in man:
1768 1777 del man[f]
1769 1778
1770 1779 return man
1771 1780
1772 1781 def _buildstatus(self, other, s, match, listignored, listclean,
1773 1782 listunknown):
1774 1783 """build a status with respect to another context
1775 1784
1776 1785 This includes logic for maintaining the fast path of status when
1777 1786 comparing the working directory against its parent, which is to skip
1778 1787 building a new manifest if self (working directory) is not comparing
1779 1788 against its parent (repo['.']).
1780 1789 """
1781 1790 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1782 1791 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1783 1792 # might have accidentally ended up with the entire contents of the file
1784 1793 # they are supposed to be linking to.
1785 1794 s.modified[:] = self._filtersuspectsymlink(s.modified)
1786 1795 if other != self._repo['.']:
1787 1796 s = super(workingctx, self)._buildstatus(other, s, match,
1788 1797 listignored, listclean,
1789 1798 listunknown)
1790 1799 return s
1791 1800
1792 1801 def _matchstatus(self, other, match):
1793 1802 """override the match method with a filter for directory patterns
1794 1803
1795 1804 We use inheritance to customize the match.bad method only in cases of
1796 1805 workingctx since it belongs only to the working directory when
1797 1806 comparing against the parent changeset.
1798 1807
1799 1808 If we aren't comparing against the working directory's parent, then we
1800 1809 just use the default match object sent to us.
1801 1810 """
1802 1811 if other != self._repo['.']:
1803 1812 def bad(f, msg):
1804 1813 # 'f' may be a directory pattern from 'match.files()',
1805 1814 # so 'f not in ctx1' is not enough
1806 1815 if f not in other and not other.hasdir(f):
1807 1816 self._repo.ui.warn('%s: %s\n' %
1808 1817 (self._repo.dirstate.pathto(f), msg))
1809 1818 match.bad = bad
1810 1819 return match
1811 1820
1812 1821 def markcommitted(self, node):
1813 1822 super(workingctx, self).markcommitted(node)
1814 1823
1815 1824 sparse.aftercommit(self._repo, node)
1816 1825
1817 1826 class committablefilectx(basefilectx):
1818 1827 """A committablefilectx provides common functionality for a file context
1819 1828 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
1820 1829 def __init__(self, repo, path, filelog=None, ctx=None):
1821 1830 self._repo = repo
1822 1831 self._path = path
1823 1832 self._changeid = None
1824 1833 self._filerev = self._filenode = None
1825 1834
1826 1835 if filelog is not None:
1827 1836 self._filelog = filelog
1828 1837 if ctx:
1829 1838 self._changectx = ctx
1830 1839
1831 1840 def __nonzero__(self):
1832 1841 return True
1833 1842
1834 1843 __bool__ = __nonzero__
1835 1844
1836 1845 def linkrev(self):
1837 1846 # linked to self._changectx no matter if file is modified or not
1838 1847 return self.rev()
1839 1848
1840 1849 def parents(self):
1841 1850 '''return parent filectxs, following copies if necessary'''
1842 1851 def filenode(ctx, path):
1843 1852 return ctx._manifest.get(path, nullid)
1844 1853
1845 1854 path = self._path
1846 1855 fl = self._filelog
1847 1856 pcl = self._changectx._parents
1848 1857 renamed = self.renamed()
1849 1858
1850 1859 if renamed:
1851 1860 pl = [renamed + (None,)]
1852 1861 else:
1853 1862 pl = [(path, filenode(pcl[0], path), fl)]
1854 1863
1855 1864 for pc in pcl[1:]:
1856 1865 pl.append((path, filenode(pc, path), fl))
1857 1866
1858 1867 return [self._parentfilectx(p, fileid=n, filelog=l)
1859 1868 for p, n, l in pl if n != nullid]
1860 1869
1861 1870 def children(self):
1862 1871 return []
1863 1872
1864 1873 class workingfilectx(committablefilectx):
1865 1874 """A workingfilectx object makes access to data related to a particular
1866 1875 file in the working directory convenient."""
1867 1876 def __init__(self, repo, path, filelog=None, workingctx=None):
1868 1877 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
1869 1878
1870 1879 @propertycache
1871 1880 def _changectx(self):
1872 1881 return workingctx(self._repo)
1873 1882
1874 1883 def data(self):
1875 1884 return self._repo.wread(self._path)
1876 1885 def renamed(self):
1877 1886 rp = self._repo.dirstate.copied(self._path)
1878 1887 if not rp:
1879 1888 return None
1880 1889 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1881 1890
1882 1891 def size(self):
1883 1892 return self._repo.wvfs.lstat(self._path).st_size
1884 1893 def date(self):
1885 1894 t, tz = self._changectx.date()
1886 1895 try:
1887 1896 return (self._repo.wvfs.lstat(self._path).st_mtime, tz)
1888 1897 except OSError as err:
1889 1898 if err.errno != errno.ENOENT:
1890 1899 raise
1891 1900 return (t, tz)
1892 1901
1893 1902 def exists(self):
1894 1903 return self._repo.wvfs.exists(self._path)
1895 1904
1896 1905 def lexists(self):
1897 1906 return self._repo.wvfs.lexists(self._path)
1898 1907
1899 1908 def audit(self):
1900 1909 return self._repo.wvfs.audit(self._path)
1901 1910
1902 1911 def cmp(self, fctx):
1903 1912 """compare with other file context
1904 1913
1905 1914 returns True if different than fctx.
1906 1915 """
1907 1916 # fctx should be a filectx (not a workingfilectx)
1908 1917 # invert comparison to reuse the same code path
1909 1918 return fctx.cmp(self)
1910 1919
1911 1920 def remove(self, ignoremissing=False):
1912 1921 """wraps unlink for a repo's working directory"""
1913 1922 self._repo.wvfs.unlinkpath(self._path, ignoremissing=ignoremissing)
1914 1923
1915 1924 def write(self, data, flags, backgroundclose=False):
1916 1925 """wraps repo.wwrite"""
1917 1926 self._repo.wwrite(self._path, data, flags,
1918 1927 backgroundclose=backgroundclose)
1919 1928
1920 1929 def clearunknown(self):
1921 1930 """Removes conflicting items in the working directory so that
1922 1931 ``write()`` can be called successfully.
1923 1932 """
1924 1933 wvfs = self._repo.wvfs
1925 1934 if wvfs.isdir(self._path) and not wvfs.islink(self._path):
1926 1935 wvfs.removedirs(self._path)
1927 1936
1928 1937 def setflags(self, l, x):
1929 1938 self._repo.wvfs.setflags(self._path, l, x)
1930 1939
1931 1940 class overlayworkingctx(workingctx):
1932 1941 """Wraps another mutable context with a write-back cache that can be flushed
1933 1942 at a later time.
1934 1943
1935 1944 self._cache[path] maps to a dict with keys: {
1936 1945 'exists': bool?
1937 1946 'date': date?
1938 1947 'data': str?
1939 1948 'flags': str?
1940 1949 }
1941 1950 If `exists` is True, `flags` must be non-None and 'date' is non-None. If it
1942 1951 is `False`, the file was deleted.
1943 1952 """
1944 1953
1945 1954 def __init__(self, repo, wrappedctx):
1946 1955 super(overlayworkingctx, self).__init__(repo)
1947 1956 self._repo = repo
1948 1957 self._wrappedctx = wrappedctx
1949 1958 self._clean()
1950 1959
1951 1960 def data(self, path):
1952 1961 if self.isdirty(path):
1953 1962 if self._cache[path]['exists']:
1954 1963 if self._cache[path]['data']:
1955 1964 return self._cache[path]['data']
1956 1965 else:
1957 1966 # Must fallback here, too, because we only set flags.
1958 1967 return self._wrappedctx[path].data()
1959 1968 else:
1960 1969 raise error.ProgrammingError("No such file or directory: %s" %
1961 1970 self._path)
1962 1971 else:
1963 1972 return self._wrappedctx[path].data()
1964 1973
1965 1974 def filedate(self, path):
1966 1975 if self.isdirty(path):
1967 1976 return self._cache[path]['date']
1968 1977 else:
1969 1978 return self._wrappedctx[path].date()
1970 1979
1971 1980 def flags(self, path):
1972 1981 if self.isdirty(path):
1973 1982 if self._cache[path]['exists']:
1974 1983 return self._cache[path]['flags']
1975 1984 else:
1976 1985 raise error.ProgrammingError("No such file or directory: %s" %
1977 1986 self._path)
1978 1987 else:
1979 1988 return self._wrappedctx[path].flags()
1980 1989
1981 1990 def write(self, path, data, flags=''):
1982 1991 if data is None:
1983 1992 raise error.ProgrammingError("data must be non-None")
1984 1993 self._markdirty(path, exists=True, data=data, date=util.makedate(),
1985 1994 flags=flags)
1986 1995
1987 1996 def setflags(self, path, l, x):
1988 1997 self._markdirty(path, exists=True, date=util.makedate(),
1989 1998 flags=(l and 'l' or '') + (x and 'x' or ''))
1990 1999
1991 2000 def remove(self, path):
1992 2001 self._markdirty(path, exists=False)
1993 2002
1994 2003 def exists(self, path):
1995 2004 """exists behaves like `lexists`, but needs to follow symlinks and
1996 2005 return False if they are broken.
1997 2006 """
1998 2007 if self.isdirty(path):
1999 2008 # If this path exists and is a symlink, "follow" it by calling
2000 2009 # exists on the destination path.
2001 2010 if (self._cache[path]['exists'] and
2002 2011 'l' in self._cache[path]['flags']):
2003 2012 return self.exists(self._cache[path]['data'].strip())
2004 2013 else:
2005 2014 return self._cache[path]['exists']
2006 2015 return self._wrappedctx[path].exists()
2007 2016
2008 2017 def lexists(self, path):
2009 2018 """lexists returns True if the path exists"""
2010 2019 if self.isdirty(path):
2011 2020 return self._cache[path]['exists']
2012 2021 return self._wrappedctx[path].lexists()
2013 2022
2014 2023 def size(self, path):
2015 2024 if self.isdirty(path):
2016 2025 if self._cache[path]['exists']:
2017 2026 return len(self._cache[path]['data'])
2018 2027 else:
2019 2028 raise error.ProgrammingError("No such file or directory: %s" %
2020 2029 self._path)
2021 2030 return self._wrappedctx[path].size()
2022 2031
2023 2032 def flushall(self):
2024 2033 for path in self._writeorder:
2025 2034 entry = self._cache[path]
2026 2035 if entry['exists']:
2027 2036 self._wrappedctx[path].clearunknown()
2028 2037 if entry['data'] is not None:
2029 2038 if entry['flags'] is None:
2030 2039 raise error.ProgrammingError('data set but not flags')
2031 2040 self._wrappedctx[path].write(
2032 2041 entry['data'],
2033 2042 entry['flags'])
2034 2043 else:
2035 2044 self._wrappedctx[path].setflags(
2036 2045 'l' in entry['flags'],
2037 2046 'x' in entry['flags'])
2038 2047 else:
2039 2048 self._wrappedctx[path].remove(path)
2040 2049 self._clean()
2041 2050
2042 2051 def isdirty(self, path):
2043 2052 return path in self._cache
2044 2053
2045 2054 def _clean(self):
2046 2055 self._cache = {}
2047 2056 self._writeorder = []
2048 2057
2049 2058 def _markdirty(self, path, exists, data=None, date=None, flags=''):
2050 2059 if path not in self._cache:
2051 2060 self._writeorder.append(path)
2052 2061
2053 2062 self._cache[path] = {
2054 2063 'exists': exists,
2055 2064 'data': data,
2056 2065 'date': date,
2057 2066 'flags': flags,
2058 2067 }
2059 2068
2060 2069 def filectx(self, path, filelog=None):
2061 2070 return overlayworkingfilectx(self._repo, path, parent=self,
2062 2071 filelog=filelog)
2063 2072
2064 2073 class overlayworkingfilectx(workingfilectx):
2065 2074 """Wrap a ``workingfilectx`` but intercepts all writes into an in-memory
2066 2075 cache, which can be flushed through later by calling ``flush()``."""
2067 2076
2068 2077 def __init__(self, repo, path, filelog=None, parent=None):
2069 2078 super(overlayworkingfilectx, self).__init__(repo, path, filelog,
2070 2079 parent)
2071 2080 self._repo = repo
2072 2081 self._parent = parent
2073 2082 self._path = path
2074 2083
2075 2084 def ctx(self):
2076 2085 return self._parent
2077 2086
2078 2087 def data(self):
2079 2088 return self._parent.data(self._path)
2080 2089
2081 2090 def date(self):
2082 2091 return self._parent.filedate(self._path)
2083 2092
2084 2093 def exists(self):
2085 2094 return self.lexists()
2086 2095
2087 2096 def lexists(self):
2088 2097 return self._parent.exists(self._path)
2089 2098
2090 2099 def renamed(self):
2091 2100 # Copies are currently tracked in the dirstate as before. Straight copy
2092 2101 # from workingfilectx.
2093 2102 rp = self._repo.dirstate.copied(self._path)
2094 2103 if not rp:
2095 2104 return None
2096 2105 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
2097 2106
2098 2107 def size(self):
2099 2108 return self._parent.size(self._path)
2100 2109
2101 2110 def audit(self):
2102 2111 pass
2103 2112
2104 2113 def flags(self):
2105 2114 return self._parent.flags(self._path)
2106 2115
2107 2116 def setflags(self, islink, isexec):
2108 2117 return self._parent.setflags(self._path, islink, isexec)
2109 2118
2110 2119 def write(self, data, flags, backgroundclose=False):
2111 2120 return self._parent.write(self._path, data, flags)
2112 2121
2113 2122 def remove(self, ignoremissing=False):
2114 2123 return self._parent.remove(self._path)
2115 2124
2116 2125 class workingcommitctx(workingctx):
2117 2126 """A workingcommitctx object makes access to data related to
2118 2127 the revision being committed convenient.
2119 2128
2120 2129 This hides changes in the working directory, if they aren't
2121 2130 committed in this context.
2122 2131 """
2123 2132 def __init__(self, repo, changes,
2124 2133 text="", user=None, date=None, extra=None):
2125 2134 super(workingctx, self).__init__(repo, text, user, date, extra,
2126 2135 changes)
2127 2136
2128 2137 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
2129 2138 """Return matched files only in ``self._status``
2130 2139
2131 2140 Uncommitted files appear "clean" via this context, even if
2132 2141 they aren't actually so in the working directory.
2133 2142 """
2134 2143 if clean:
2135 2144 clean = [f for f in self._manifest if f not in self._changedset]
2136 2145 else:
2137 2146 clean = []
2138 2147 return scmutil.status([f for f in self._status.modified if match(f)],
2139 2148 [f for f in self._status.added if match(f)],
2140 2149 [f for f in self._status.removed if match(f)],
2141 2150 [], [], [], clean)
2142 2151
2143 2152 @propertycache
2144 2153 def _changedset(self):
2145 2154 """Return the set of files changed in this context
2146 2155 """
2147 2156 changed = set(self._status.modified)
2148 2157 changed.update(self._status.added)
2149 2158 changed.update(self._status.removed)
2150 2159 return changed
2151 2160
2152 2161 def makecachingfilectxfn(func):
2153 2162 """Create a filectxfn that caches based on the path.
2154 2163
2155 2164 We can't use util.cachefunc because it uses all arguments as the cache
2156 2165 key and this creates a cycle since the arguments include the repo and
2157 2166 memctx.
2158 2167 """
2159 2168 cache = {}
2160 2169
2161 2170 def getfilectx(repo, memctx, path):
2162 2171 if path not in cache:
2163 2172 cache[path] = func(repo, memctx, path)
2164 2173 return cache[path]
2165 2174
2166 2175 return getfilectx
2167 2176
2168 2177 def memfilefromctx(ctx):
2169 2178 """Given a context return a memfilectx for ctx[path]
2170 2179
2171 2180 This is a convenience method for building a memctx based on another
2172 2181 context.
2173 2182 """
2174 2183 def getfilectx(repo, memctx, path):
2175 2184 fctx = ctx[path]
2176 2185 # this is weird but apparently we only keep track of one parent
2177 2186 # (why not only store that instead of a tuple?)
2178 2187 copied = fctx.renamed()
2179 2188 if copied:
2180 2189 copied = copied[0]
2181 2190 return memfilectx(repo, path, fctx.data(),
2182 2191 islink=fctx.islink(), isexec=fctx.isexec(),
2183 2192 copied=copied, memctx=memctx)
2184 2193
2185 2194 return getfilectx
2186 2195
2187 2196 def memfilefrompatch(patchstore):
2188 2197 """Given a patch (e.g. patchstore object) return a memfilectx
2189 2198
2190 2199 This is a convenience method for building a memctx based on a patchstore.
2191 2200 """
2192 2201 def getfilectx(repo, memctx, path):
2193 2202 data, mode, copied = patchstore.getfile(path)
2194 2203 if data is None:
2195 2204 return None
2196 2205 islink, isexec = mode
2197 2206 return memfilectx(repo, path, data, islink=islink,
2198 2207 isexec=isexec, copied=copied,
2199 2208 memctx=memctx)
2200 2209
2201 2210 return getfilectx
2202 2211
2203 2212 class memctx(committablectx):
2204 2213 """Use memctx to perform in-memory commits via localrepo.commitctx().
2205 2214
2206 2215 Revision information is supplied at initialization time while
2207 2216 related files data and is made available through a callback
2208 2217 mechanism. 'repo' is the current localrepo, 'parents' is a
2209 2218 sequence of two parent revisions identifiers (pass None for every
2210 2219 missing parent), 'text' is the commit message and 'files' lists
2211 2220 names of files touched by the revision (normalized and relative to
2212 2221 repository root).
2213 2222
2214 2223 filectxfn(repo, memctx, path) is a callable receiving the
2215 2224 repository, the current memctx object and the normalized path of
2216 2225 requested file, relative to repository root. It is fired by the
2217 2226 commit function for every file in 'files', but calls order is
2218 2227 undefined. If the file is available in the revision being
2219 2228 committed (updated or added), filectxfn returns a memfilectx
2220 2229 object. If the file was removed, filectxfn return None for recent
2221 2230 Mercurial. Moved files are represented by marking the source file
2222 2231 removed and the new file added with copy information (see
2223 2232 memfilectx).
2224 2233
2225 2234 user receives the committer name and defaults to current
2226 2235 repository username, date is the commit date in any format
2227 2236 supported by util.parsedate() and defaults to current date, extra
2228 2237 is a dictionary of metadata or is left empty.
2229 2238 """
2230 2239
2231 2240 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
2232 2241 # Extensions that need to retain compatibility across Mercurial 3.1 can use
2233 2242 # this field to determine what to do in filectxfn.
2234 2243 _returnnoneformissingfiles = True
2235 2244
2236 2245 def __init__(self, repo, parents, text, files, filectxfn, user=None,
2237 2246 date=None, extra=None, branch=None, editor=False):
2238 2247 super(memctx, self).__init__(repo, text, user, date, extra)
2239 2248 self._rev = None
2240 2249 self._node = None
2241 2250 parents = [(p or nullid) for p in parents]
2242 2251 p1, p2 = parents
2243 2252 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
2244 2253 files = sorted(set(files))
2245 2254 self._files = files
2246 2255 if branch is not None:
2247 2256 self._extra['branch'] = encoding.fromlocal(branch)
2248 2257 self.substate = {}
2249 2258
2250 2259 if isinstance(filectxfn, patch.filestore):
2251 2260 filectxfn = memfilefrompatch(filectxfn)
2252 2261 elif not callable(filectxfn):
2253 2262 # if store is not callable, wrap it in a function
2254 2263 filectxfn = memfilefromctx(filectxfn)
2255 2264
2256 2265 # memoizing increases performance for e.g. vcs convert scenarios.
2257 2266 self._filectxfn = makecachingfilectxfn(filectxfn)
2258 2267
2259 2268 if editor:
2260 2269 self._text = editor(self._repo, self, [])
2261 2270 self._repo.savecommitmessage(self._text)
2262 2271
2263 2272 def filectx(self, path, filelog=None):
2264 2273 """get a file context from the working directory
2265 2274
2266 2275 Returns None if file doesn't exist and should be removed."""
2267 2276 return self._filectxfn(self._repo, self, path)
2268 2277
2269 2278 def commit(self):
2270 2279 """commit context to the repo"""
2271 2280 return self._repo.commitctx(self)
2272 2281
2273 2282 @propertycache
2274 2283 def _manifest(self):
2275 2284 """generate a manifest based on the return values of filectxfn"""
2276 2285
2277 2286 # keep this simple for now; just worry about p1
2278 2287 pctx = self._parents[0]
2279 2288 man = pctx.manifest().copy()
2280 2289
2281 2290 for f in self._status.modified:
2282 2291 p1node = nullid
2283 2292 p2node = nullid
2284 2293 p = pctx[f].parents() # if file isn't in pctx, check p2?
2285 2294 if len(p) > 0:
2286 2295 p1node = p[0].filenode()
2287 2296 if len(p) > 1:
2288 2297 p2node = p[1].filenode()
2289 2298 man[f] = revlog.hash(self[f].data(), p1node, p2node)
2290 2299
2291 2300 for f in self._status.added:
2292 2301 man[f] = revlog.hash(self[f].data(), nullid, nullid)
2293 2302
2294 2303 for f in self._status.removed:
2295 2304 if f in man:
2296 2305 del man[f]
2297 2306
2298 2307 return man
2299 2308
2300 2309 @propertycache
2301 2310 def _status(self):
2302 2311 """Calculate exact status from ``files`` specified at construction
2303 2312 """
2304 2313 man1 = self.p1().manifest()
2305 2314 p2 = self._parents[1]
2306 2315 # "1 < len(self._parents)" can't be used for checking
2307 2316 # existence of the 2nd parent, because "memctx._parents" is
2308 2317 # explicitly initialized by the list, of which length is 2.
2309 2318 if p2.node() != nullid:
2310 2319 man2 = p2.manifest()
2311 2320 managing = lambda f: f in man1 or f in man2
2312 2321 else:
2313 2322 managing = lambda f: f in man1
2314 2323
2315 2324 modified, added, removed = [], [], []
2316 2325 for f in self._files:
2317 2326 if not managing(f):
2318 2327 added.append(f)
2319 2328 elif self[f]:
2320 2329 modified.append(f)
2321 2330 else:
2322 2331 removed.append(f)
2323 2332
2324 2333 return scmutil.status(modified, added, removed, [], [], [], [])
2325 2334
2326 2335 class memfilectx(committablefilectx):
2327 2336 """memfilectx represents an in-memory file to commit.
2328 2337
2329 2338 See memctx and committablefilectx for more details.
2330 2339 """
2331 2340 def __init__(self, repo, path, data, islink=False,
2332 2341 isexec=False, copied=None, memctx=None):
2333 2342 """
2334 2343 path is the normalized file path relative to repository root.
2335 2344 data is the file content as a string.
2336 2345 islink is True if the file is a symbolic link.
2337 2346 isexec is True if the file is executable.
2338 2347 copied is the source file path if current file was copied in the
2339 2348 revision being committed, or None."""
2340 2349 super(memfilectx, self).__init__(repo, path, None, memctx)
2341 2350 self._data = data
2342 2351 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
2343 2352 self._copied = None
2344 2353 if copied:
2345 2354 self._copied = (copied, nullid)
2346 2355
2347 2356 def data(self):
2348 2357 return self._data
2349 2358
2350 2359 def remove(self, ignoremissing=False):
2351 2360 """wraps unlink for a repo's working directory"""
2352 2361 # need to figure out what to do here
2353 2362 del self._changectx[self._path]
2354 2363
2355 2364 def write(self, data, flags):
2356 2365 """wraps repo.wwrite"""
2357 2366 self._data = data
2358 2367
2359 2368 class overlayfilectx(committablefilectx):
2360 2369 """Like memfilectx but take an original filectx and optional parameters to
2361 2370 override parts of it. This is useful when fctx.data() is expensive (i.e.
2362 2371 flag processor is expensive) and raw data, flags, and filenode could be
2363 2372 reused (ex. rebase or mode-only amend a REVIDX_EXTSTORED file).
2364 2373 """
2365 2374
2366 2375 def __init__(self, originalfctx, datafunc=None, path=None, flags=None,
2367 2376 copied=None, ctx=None):
2368 2377 """originalfctx: filecontext to duplicate
2369 2378
2370 2379 datafunc: None or a function to override data (file content). It is a
2371 2380 function to be lazy. path, flags, copied, ctx: None or overridden value
2372 2381
2373 2382 copied could be (path, rev), or False. copied could also be just path,
2374 2383 and will be converted to (path, nullid). This simplifies some callers.
2375 2384 """
2376 2385
2377 2386 if path is None:
2378 2387 path = originalfctx.path()
2379 2388 if ctx is None:
2380 2389 ctx = originalfctx.changectx()
2381 2390 ctxmatch = lambda: True
2382 2391 else:
2383 2392 ctxmatch = lambda: ctx == originalfctx.changectx()
2384 2393
2385 2394 repo = originalfctx.repo()
2386 2395 flog = originalfctx.filelog()
2387 2396 super(overlayfilectx, self).__init__(repo, path, flog, ctx)
2388 2397
2389 2398 if copied is None:
2390 2399 copied = originalfctx.renamed()
2391 2400 copiedmatch = lambda: True
2392 2401 else:
2393 2402 if copied and not isinstance(copied, tuple):
2394 2403 # repo._filecommit will recalculate copyrev so nullid is okay
2395 2404 copied = (copied, nullid)
2396 2405 copiedmatch = lambda: copied == originalfctx.renamed()
2397 2406
2398 2407 # When data, copied (could affect data), ctx (could affect filelog
2399 2408 # parents) are not overridden, rawdata, rawflags, and filenode may be
2400 2409 # reused (repo._filecommit should double check filelog parents).
2401 2410 #
2402 2411 # path, flags are not hashed in filelog (but in manifestlog) so they do
2403 2412 # not affect reusable here.
2404 2413 #
2405 2414 # If ctx or copied is overridden to a same value with originalfctx,
2406 2415 # still consider it's reusable. originalfctx.renamed() may be a bit
2407 2416 # expensive so it's not called unless necessary. Assuming datafunc is
2408 2417 # always expensive, do not call it for this "reusable" test.
2409 2418 reusable = datafunc is None and ctxmatch() and copiedmatch()
2410 2419
2411 2420 if datafunc is None:
2412 2421 datafunc = originalfctx.data
2413 2422 if flags is None:
2414 2423 flags = originalfctx.flags()
2415 2424
2416 2425 self._datafunc = datafunc
2417 2426 self._flags = flags
2418 2427 self._copied = copied
2419 2428
2420 2429 if reusable:
2421 2430 # copy extra fields from originalfctx
2422 2431 attrs = ['rawdata', 'rawflags', '_filenode', '_filerev']
2423 2432 for attr_ in attrs:
2424 2433 if util.safehasattr(originalfctx, attr_):
2425 2434 setattr(self, attr_, getattr(originalfctx, attr_))
2426 2435
2427 2436 def data(self):
2428 2437 return self._datafunc()
2429 2438
2430 2439 class metadataonlyctx(committablectx):
2431 2440 """Like memctx but it's reusing the manifest of different commit.
2432 2441 Intended to be used by lightweight operations that are creating
2433 2442 metadata-only changes.
2434 2443
2435 2444 Revision information is supplied at initialization time. 'repo' is the
2436 2445 current localrepo, 'ctx' is original revision which manifest we're reuisng
2437 2446 'parents' is a sequence of two parent revisions identifiers (pass None for
2438 2447 every missing parent), 'text' is the commit.
2439 2448
2440 2449 user receives the committer name and defaults to current repository
2441 2450 username, date is the commit date in any format supported by
2442 2451 util.parsedate() and defaults to current date, extra is a dictionary of
2443 2452 metadata or is left empty.
2444 2453 """
2445 2454 def __new__(cls, repo, originalctx, *args, **kwargs):
2446 2455 return super(metadataonlyctx, cls).__new__(cls, repo)
2447 2456
2448 2457 def __init__(self, repo, originalctx, parents=None, text=None, user=None,
2449 2458 date=None, extra=None, editor=False):
2450 2459 if text is None:
2451 2460 text = originalctx.description()
2452 2461 super(metadataonlyctx, self).__init__(repo, text, user, date, extra)
2453 2462 self._rev = None
2454 2463 self._node = None
2455 2464 self._originalctx = originalctx
2456 2465 self._manifestnode = originalctx.manifestnode()
2457 2466 if parents is None:
2458 2467 parents = originalctx.parents()
2459 2468 else:
2460 2469 parents = [repo[p] for p in parents if p is not None]
2461 2470 parents = parents[:]
2462 2471 while len(parents) < 2:
2463 2472 parents.append(repo[nullid])
2464 2473 p1, p2 = self._parents = parents
2465 2474
2466 2475 # sanity check to ensure that the reused manifest parents are
2467 2476 # manifests of our commit parents
2468 2477 mp1, mp2 = self.manifestctx().parents
2469 2478 if p1 != nullid and p1.manifestnode() != mp1:
2470 2479 raise RuntimeError('can\'t reuse the manifest: '
2471 2480 'its p1 doesn\'t match the new ctx p1')
2472 2481 if p2 != nullid and p2.manifestnode() != mp2:
2473 2482 raise RuntimeError('can\'t reuse the manifest: '
2474 2483 'its p2 doesn\'t match the new ctx p2')
2475 2484
2476 2485 self._files = originalctx.files()
2477 2486 self.substate = {}
2478 2487
2479 2488 if editor:
2480 2489 self._text = editor(self._repo, self, [])
2481 2490 self._repo.savecommitmessage(self._text)
2482 2491
2483 2492 def manifestnode(self):
2484 2493 return self._manifestnode
2485 2494
2486 2495 @property
2487 2496 def _manifestctx(self):
2488 2497 return self._repo.manifestlog[self._manifestnode]
2489 2498
2490 2499 def filectx(self, path, filelog=None):
2491 2500 return self._originalctx.filectx(path, filelog=filelog)
2492 2501
2493 2502 def commit(self):
2494 2503 """commit context to the repo"""
2495 2504 return self._repo.commitctx(self)
2496 2505
2497 2506 @property
2498 2507 def _manifest(self):
2499 2508 return self._originalctx.manifest()
2500 2509
2501 2510 @propertycache
2502 2511 def _status(self):
2503 2512 """Calculate exact status from ``files`` specified in the ``origctx``
2504 2513 and parents manifests.
2505 2514 """
2506 2515 man1 = self.p1().manifest()
2507 2516 p2 = self._parents[1]
2508 2517 # "1 < len(self._parents)" can't be used for checking
2509 2518 # existence of the 2nd parent, because "metadataonlyctx._parents" is
2510 2519 # explicitly initialized by the list, of which length is 2.
2511 2520 if p2.node() != nullid:
2512 2521 man2 = p2.manifest()
2513 2522 managing = lambda f: f in man1 or f in man2
2514 2523 else:
2515 2524 managing = lambda f: f in man1
2516 2525
2517 2526 modified, added, removed = [], [], []
2518 2527 for f in self._files:
2519 2528 if not managing(f):
2520 2529 added.append(f)
2521 2530 elif f in self:
2522 2531 modified.append(f)
2523 2532 else:
2524 2533 removed.append(f)
2525 2534
2526 2535 return scmutil.status(modified, added, removed, [], [], [], [])
2527 2536
2528 2537 class arbitraryfilectx(object):
2529 2538 """Allows you to use filectx-like functions on a file in an arbitrary
2530 2539 location on disk, possibly not in the working directory.
2531 2540 """
2532 2541 def __init__(self, path):
2533 2542 self._path = path
2534 2543
2535 2544 def cmp(self, otherfilectx):
2536 2545 return self.data() != otherfilectx.data()
2537 2546
2538 2547 def path(self):
2539 2548 return self._path
2540 2549
2541 2550 def flags(self):
2542 2551 return ''
2543 2552
2544 2553 def data(self):
2545 2554 return util.readfile(self._path)
2546 2555
2547 2556 def decodeddata(self):
2548 2557 with open(self._path, "rb") as f:
2549 2558 return f.read()
2550 2559
2551 2560 def remove(self):
2552 2561 util.unlink(self._path)
2553 2562
2554 2563 def write(self, data, flags):
2555 2564 assert not flags
2556 2565 with open(self._path, "w") as f:
2557 2566 f.write(data)
@@ -1,1399 +1,1400 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 cgi
11 11 import copy
12 12 import mimetypes
13 13 import os
14 14 import re
15 15
16 16 from ..i18n import _
17 17 from ..node import hex, short
18 18
19 19 from .common import (
20 20 ErrorResponse,
21 21 HTTP_FORBIDDEN,
22 22 HTTP_NOT_FOUND,
23 23 HTTP_OK,
24 24 get_contact,
25 25 paritygen,
26 26 staticfile,
27 27 )
28 28
29 29 from .. import (
30 30 archival,
31 31 dagop,
32 32 encoding,
33 33 error,
34 34 graphmod,
35 35 revset,
36 36 revsetlang,
37 37 scmutil,
38 38 smartset,
39 39 templatefilters,
40 40 templater,
41 41 util,
42 42 )
43 43
44 44 from . import (
45 45 webutil,
46 46 )
47 47
48 48 __all__ = []
49 49 commands = {}
50 50
51 51 class webcommand(object):
52 52 """Decorator used to register a web command handler.
53 53
54 54 The decorator takes as its positional arguments the name/path the
55 55 command should be accessible under.
56 56
57 57 Usage:
58 58
59 59 @webcommand('mycommand')
60 60 def mycommand(web, req, tmpl):
61 61 pass
62 62 """
63 63
64 64 def __init__(self, name):
65 65 self.name = name
66 66
67 67 def __call__(self, func):
68 68 __all__.append(self.name)
69 69 commands[self.name] = func
70 70 return func
71 71
72 72 @webcommand('log')
73 73 def log(web, req, tmpl):
74 74 """
75 75 /log[/{revision}[/{path}]]
76 76 --------------------------
77 77
78 78 Show repository or file history.
79 79
80 80 For URLs of the form ``/log/{revision}``, a list of changesets starting at
81 81 the specified changeset identifier is shown. If ``{revision}`` is not
82 82 defined, the default is ``tip``. This form is equivalent to the
83 83 ``changelog`` handler.
84 84
85 85 For URLs of the form ``/log/{revision}/{file}``, the history for a specific
86 86 file will be shown. This form is equivalent to the ``filelog`` handler.
87 87 """
88 88
89 89 if 'file' in req.form and req.form['file'][0]:
90 90 return filelog(web, req, tmpl)
91 91 else:
92 92 return changelog(web, req, tmpl)
93 93
94 94 @webcommand('rawfile')
95 95 def rawfile(web, req, tmpl):
96 96 guessmime = web.configbool('web', 'guessmime', False)
97 97
98 98 path = webutil.cleanpath(web.repo, req.form.get('file', [''])[0])
99 99 if not path:
100 100 content = manifest(web, req, tmpl)
101 101 req.respond(HTTP_OK, web.ctype)
102 102 return content
103 103
104 104 try:
105 105 fctx = webutil.filectx(web.repo, req)
106 106 except error.LookupError as inst:
107 107 try:
108 108 content = manifest(web, req, tmpl)
109 109 req.respond(HTTP_OK, web.ctype)
110 110 return content
111 111 except ErrorResponse:
112 112 raise inst
113 113
114 114 path = fctx.path()
115 115 text = fctx.data()
116 116 mt = 'application/binary'
117 117 if guessmime:
118 118 mt = mimetypes.guess_type(path)[0]
119 119 if mt is None:
120 120 if util.binary(text):
121 121 mt = 'application/binary'
122 122 else:
123 123 mt = 'text/plain'
124 124 if mt.startswith('text/'):
125 125 mt += '; charset="%s"' % encoding.encoding
126 126
127 127 req.respond(HTTP_OK, mt, path, body=text)
128 128 return []
129 129
130 130 def _filerevision(web, req, tmpl, fctx):
131 131 f = fctx.path()
132 132 text = fctx.data()
133 133 parity = paritygen(web.stripecount)
134 134 ishead = fctx.filerev() in fctx.filelog().headrevs()
135 135
136 136 if util.binary(text):
137 137 mt = mimetypes.guess_type(f)[0] or 'application/octet-stream'
138 138 text = '(binary:%s)' % mt
139 139
140 140 def lines():
141 141 for lineno, t in enumerate(text.splitlines(True)):
142 142 yield {"line": t,
143 143 "lineid": "l%d" % (lineno + 1),
144 144 "linenumber": "% 6d" % (lineno + 1),
145 145 "parity": next(parity)}
146 146
147 147 return tmpl("filerevision",
148 148 file=f,
149 149 path=webutil.up(f),
150 150 text=lines(),
151 151 symrev=webutil.symrevorshortnode(req, fctx),
152 152 rename=webutil.renamelink(fctx),
153 153 permissions=fctx.manifest().flags(f),
154 154 ishead=int(ishead),
155 155 **webutil.commonentry(web.repo, fctx))
156 156
157 157 @webcommand('file')
158 158 def file(web, req, tmpl):
159 159 """
160 160 /file/{revision}[/{path}]
161 161 -------------------------
162 162
163 163 Show information about a directory or file in the repository.
164 164
165 165 Info about the ``path`` given as a URL parameter will be rendered.
166 166
167 167 If ``path`` is a directory, information about the entries in that
168 168 directory will be rendered. This form is equivalent to the ``manifest``
169 169 handler.
170 170
171 171 If ``path`` is a file, information about that file will be shown via
172 172 the ``filerevision`` template.
173 173
174 174 If ``path`` is not defined, information about the root directory will
175 175 be rendered.
176 176 """
177 177 path = webutil.cleanpath(web.repo, req.form.get('file', [''])[0])
178 178 if not path:
179 179 return manifest(web, req, tmpl)
180 180 try:
181 181 return _filerevision(web, req, tmpl, webutil.filectx(web.repo, req))
182 182 except error.LookupError as inst:
183 183 try:
184 184 return manifest(web, req, tmpl)
185 185 except ErrorResponse:
186 186 raise inst
187 187
188 188 def _search(web, req, tmpl):
189 189 MODE_REVISION = 'rev'
190 190 MODE_KEYWORD = 'keyword'
191 191 MODE_REVSET = 'revset'
192 192
193 193 def revsearch(ctx):
194 194 yield ctx
195 195
196 196 def keywordsearch(query):
197 197 lower = encoding.lower
198 198 qw = lower(query).split()
199 199
200 200 def revgen():
201 201 cl = web.repo.changelog
202 202 for i in xrange(len(web.repo) - 1, 0, -100):
203 203 l = []
204 204 for j in cl.revs(max(0, i - 99), i):
205 205 ctx = web.repo[j]
206 206 l.append(ctx)
207 207 l.reverse()
208 208 for e in l:
209 209 yield e
210 210
211 211 for ctx in revgen():
212 212 miss = 0
213 213 for q in qw:
214 214 if not (q in lower(ctx.user()) or
215 215 q in lower(ctx.description()) or
216 216 q in lower(" ".join(ctx.files()))):
217 217 miss = 1
218 218 break
219 219 if miss:
220 220 continue
221 221
222 222 yield ctx
223 223
224 224 def revsetsearch(revs):
225 225 for r in revs:
226 226 yield web.repo[r]
227 227
228 228 searchfuncs = {
229 229 MODE_REVISION: (revsearch, 'exact revision search'),
230 230 MODE_KEYWORD: (keywordsearch, 'literal keyword search'),
231 231 MODE_REVSET: (revsetsearch, 'revset expression search'),
232 232 }
233 233
234 234 def getsearchmode(query):
235 235 try:
236 236 ctx = web.repo[query]
237 237 except (error.RepoError, error.LookupError):
238 238 # query is not an exact revision pointer, need to
239 239 # decide if it's a revset expression or keywords
240 240 pass
241 241 else:
242 242 return MODE_REVISION, ctx
243 243
244 244 revdef = 'reverse(%s)' % query
245 245 try:
246 246 tree = revsetlang.parse(revdef)
247 247 except error.ParseError:
248 248 # can't parse to a revset tree
249 249 return MODE_KEYWORD, query
250 250
251 251 if revsetlang.depth(tree) <= 2:
252 252 # no revset syntax used
253 253 return MODE_KEYWORD, query
254 254
255 255 if any((token, (value or '')[:3]) == ('string', 're:')
256 256 for token, value, pos in revsetlang.tokenize(revdef)):
257 257 return MODE_KEYWORD, query
258 258
259 259 funcsused = revsetlang.funcsused(tree)
260 260 if not funcsused.issubset(revset.safesymbols):
261 261 return MODE_KEYWORD, query
262 262
263 263 mfunc = revset.match(web.repo.ui, revdef, repo=web.repo)
264 264 try:
265 265 revs = mfunc(web.repo)
266 266 return MODE_REVSET, revs
267 267 # ParseError: wrongly placed tokens, wrongs arguments, etc
268 268 # RepoLookupError: no such revision, e.g. in 'revision:'
269 269 # Abort: bookmark/tag not exists
270 270 # LookupError: ambiguous identifier, e.g. in '(bc)' on a large repo
271 271 except (error.ParseError, error.RepoLookupError, error.Abort,
272 272 LookupError):
273 273 return MODE_KEYWORD, query
274 274
275 275 def changelist(**map):
276 276 count = 0
277 277
278 278 for ctx in searchfunc[0](funcarg):
279 279 count += 1
280 280 n = ctx.node()
281 281 showtags = webutil.showtag(web.repo, tmpl, 'changelogtag', n)
282 282 files = webutil.listfilediffs(tmpl, ctx.files(), n, web.maxfiles)
283 283
284 284 yield tmpl('searchentry',
285 285 parity=next(parity),
286 286 changelogtag=showtags,
287 287 files=files,
288 288 **webutil.commonentry(web.repo, ctx))
289 289
290 290 if count >= revcount:
291 291 break
292 292
293 293 query = req.form['rev'][0]
294 294 revcount = web.maxchanges
295 295 if 'revcount' in req.form:
296 296 try:
297 297 revcount = int(req.form.get('revcount', [revcount])[0])
298 298 revcount = max(revcount, 1)
299 299 tmpl.defaults['sessionvars']['revcount'] = revcount
300 300 except ValueError:
301 301 pass
302 302
303 303 lessvars = copy.copy(tmpl.defaults['sessionvars'])
304 304 lessvars['revcount'] = max(revcount / 2, 1)
305 305 lessvars['rev'] = query
306 306 morevars = copy.copy(tmpl.defaults['sessionvars'])
307 307 morevars['revcount'] = revcount * 2
308 308 morevars['rev'] = query
309 309
310 310 mode, funcarg = getsearchmode(query)
311 311
312 312 if 'forcekw' in req.form:
313 313 showforcekw = ''
314 314 showunforcekw = searchfuncs[mode][1]
315 315 mode = MODE_KEYWORD
316 316 funcarg = query
317 317 else:
318 318 if mode != MODE_KEYWORD:
319 319 showforcekw = searchfuncs[MODE_KEYWORD][1]
320 320 else:
321 321 showforcekw = ''
322 322 showunforcekw = ''
323 323
324 324 searchfunc = searchfuncs[mode]
325 325
326 326 tip = web.repo['tip']
327 327 parity = paritygen(web.stripecount)
328 328
329 329 return tmpl('search', query=query, node=tip.hex(), symrev='tip',
330 330 entries=changelist, archives=web.archivelist("tip"),
331 331 morevars=morevars, lessvars=lessvars,
332 332 modedesc=searchfunc[1],
333 333 showforcekw=showforcekw, showunforcekw=showunforcekw)
334 334
335 335 @webcommand('changelog')
336 336 def changelog(web, req, tmpl, shortlog=False):
337 337 """
338 338 /changelog[/{revision}]
339 339 -----------------------
340 340
341 341 Show information about multiple changesets.
342 342
343 343 If the optional ``revision`` URL argument is absent, information about
344 344 all changesets starting at ``tip`` will be rendered. If the ``revision``
345 345 argument is present, changesets will be shown starting from the specified
346 346 revision.
347 347
348 348 If ``revision`` is absent, the ``rev`` query string argument may be
349 349 defined. This will perform a search for changesets.
350 350
351 351 The argument for ``rev`` can be a single revision, a revision set,
352 352 or a literal keyword to search for in changeset data (equivalent to
353 353 :hg:`log -k`).
354 354
355 355 The ``revcount`` query string argument defines the maximum numbers of
356 356 changesets to render.
357 357
358 358 For non-searches, the ``changelog`` template will be rendered.
359 359 """
360 360
361 361 query = ''
362 362 if 'node' in req.form:
363 363 ctx = webutil.changectx(web.repo, req)
364 364 symrev = webutil.symrevorshortnode(req, ctx)
365 365 elif 'rev' in req.form:
366 366 return _search(web, req, tmpl)
367 367 else:
368 368 ctx = web.repo['tip']
369 369 symrev = 'tip'
370 370
371 371 def changelist():
372 372 revs = []
373 373 if pos != -1:
374 374 revs = web.repo.changelog.revs(pos, 0)
375 375 curcount = 0
376 376 for rev in revs:
377 377 curcount += 1
378 378 if curcount > revcount + 1:
379 379 break
380 380
381 381 entry = webutil.changelistentry(web, web.repo[rev], tmpl)
382 382 entry['parity'] = next(parity)
383 383 yield entry
384 384
385 385 if shortlog:
386 386 revcount = web.maxshortchanges
387 387 else:
388 388 revcount = web.maxchanges
389 389
390 390 if 'revcount' in req.form:
391 391 try:
392 392 revcount = int(req.form.get('revcount', [revcount])[0])
393 393 revcount = max(revcount, 1)
394 394 tmpl.defaults['sessionvars']['revcount'] = revcount
395 395 except ValueError:
396 396 pass
397 397
398 398 lessvars = copy.copy(tmpl.defaults['sessionvars'])
399 399 lessvars['revcount'] = max(revcount / 2, 1)
400 400 morevars = copy.copy(tmpl.defaults['sessionvars'])
401 401 morevars['revcount'] = revcount * 2
402 402
403 403 count = len(web.repo)
404 404 pos = ctx.rev()
405 405 parity = paritygen(web.stripecount)
406 406
407 407 changenav = webutil.revnav(web.repo).gen(pos, revcount, count)
408 408
409 409 entries = list(changelist())
410 410 latestentry = entries[:1]
411 411 if len(entries) > revcount:
412 412 nextentry = entries[-1:]
413 413 entries = entries[:-1]
414 414 else:
415 415 nextentry = []
416 416
417 417 return tmpl(shortlog and 'shortlog' or 'changelog', changenav=changenav,
418 418 node=ctx.hex(), rev=pos, symrev=symrev, changesets=count,
419 419 entries=entries,
420 420 latestentry=latestentry, nextentry=nextentry,
421 421 archives=web.archivelist("tip"), revcount=revcount,
422 422 morevars=morevars, lessvars=lessvars, query=query)
423 423
424 424 @webcommand('shortlog')
425 425 def shortlog(web, req, tmpl):
426 426 """
427 427 /shortlog
428 428 ---------
429 429
430 430 Show basic information about a set of changesets.
431 431
432 432 This accepts the same parameters as the ``changelog`` handler. The only
433 433 difference is the ``shortlog`` template will be rendered instead of the
434 434 ``changelog`` template.
435 435 """
436 436 return changelog(web, req, tmpl, shortlog=True)
437 437
438 438 @webcommand('changeset')
439 439 def changeset(web, req, tmpl):
440 440 """
441 441 /changeset[/{revision}]
442 442 -----------------------
443 443
444 444 Show information about a single changeset.
445 445
446 446 A URL path argument is the changeset identifier to show. See ``hg help
447 447 revisions`` for possible values. If not defined, the ``tip`` changeset
448 448 will be shown.
449 449
450 450 The ``changeset`` template is rendered. Contents of the ``changesettag``,
451 451 ``changesetbookmark``, ``filenodelink``, ``filenolink``, and the many
452 452 templates related to diffs may all be used to produce the output.
453 453 """
454 454 ctx = webutil.changectx(web.repo, req)
455 455
456 456 return tmpl('changeset', **webutil.changesetentry(web, req, tmpl, ctx))
457 457
458 458 rev = webcommand('rev')(changeset)
459 459
460 460 def decodepath(path):
461 461 """Hook for mapping a path in the repository to a path in the
462 462 working copy.
463 463
464 464 Extensions (e.g., largefiles) can override this to remap files in
465 465 the virtual file system presented by the manifest command below."""
466 466 return path
467 467
468 468 @webcommand('manifest')
469 469 def manifest(web, req, tmpl):
470 470 """
471 471 /manifest[/{revision}[/{path}]]
472 472 -------------------------------
473 473
474 474 Show information about a directory.
475 475
476 476 If the URL path arguments are omitted, information about the root
477 477 directory for the ``tip`` changeset will be shown.
478 478
479 479 Because this handler can only show information for directories, it
480 480 is recommended to use the ``file`` handler instead, as it can handle both
481 481 directories and files.
482 482
483 483 The ``manifest`` template will be rendered for this handler.
484 484 """
485 485 if 'node' in req.form:
486 486 ctx = webutil.changectx(web.repo, req)
487 487 symrev = webutil.symrevorshortnode(req, ctx)
488 488 else:
489 489 ctx = web.repo['tip']
490 490 symrev = 'tip'
491 491 path = webutil.cleanpath(web.repo, req.form.get('file', [''])[0])
492 492 mf = ctx.manifest()
493 493 node = ctx.node()
494 494
495 495 files = {}
496 496 dirs = {}
497 497 parity = paritygen(web.stripecount)
498 498
499 499 if path and path[-1] != "/":
500 500 path += "/"
501 501 l = len(path)
502 502 abspath = "/" + path
503 503
504 504 for full, n in mf.iteritems():
505 505 # the virtual path (working copy path) used for the full
506 506 # (repository) path
507 507 f = decodepath(full)
508 508
509 509 if f[:l] != path:
510 510 continue
511 511 remain = f[l:]
512 512 elements = remain.split('/')
513 513 if len(elements) == 1:
514 514 files[remain] = full
515 515 else:
516 516 h = dirs # need to retain ref to dirs (root)
517 517 for elem in elements[0:-1]:
518 518 if elem not in h:
519 519 h[elem] = {}
520 520 h = h[elem]
521 521 if len(h) > 1:
522 522 break
523 523 h[None] = None # denotes files present
524 524
525 525 if mf and not files and not dirs:
526 526 raise ErrorResponse(HTTP_NOT_FOUND, 'path not found: ' + path)
527 527
528 528 def filelist(**map):
529 529 for f in sorted(files):
530 530 full = files[f]
531 531
532 532 fctx = ctx.filectx(full)
533 533 yield {"file": full,
534 534 "parity": next(parity),
535 535 "basename": f,
536 536 "date": fctx.date(),
537 537 "size": fctx.size(),
538 538 "permissions": mf.flags(full)}
539 539
540 540 def dirlist(**map):
541 541 for d in sorted(dirs):
542 542
543 543 emptydirs = []
544 544 h = dirs[d]
545 545 while isinstance(h, dict) and len(h) == 1:
546 546 k, v = h.items()[0]
547 547 if v:
548 548 emptydirs.append(k)
549 549 h = v
550 550
551 551 path = "%s%s" % (abspath, d)
552 552 yield {"parity": next(parity),
553 553 "path": path,
554 554 "emptydirs": "/".join(emptydirs),
555 555 "basename": d}
556 556
557 557 return tmpl("manifest",
558 558 symrev=symrev,
559 559 path=abspath,
560 560 up=webutil.up(abspath),
561 561 upparity=next(parity),
562 562 fentries=filelist,
563 563 dentries=dirlist,
564 564 archives=web.archivelist(hex(node)),
565 565 **webutil.commonentry(web.repo, ctx))
566 566
567 567 @webcommand('tags')
568 568 def tags(web, req, tmpl):
569 569 """
570 570 /tags
571 571 -----
572 572
573 573 Show information about tags.
574 574
575 575 No arguments are accepted.
576 576
577 577 The ``tags`` template is rendered.
578 578 """
579 579 i = list(reversed(web.repo.tagslist()))
580 580 parity = paritygen(web.stripecount)
581 581
582 582 def entries(notip, latestonly, **map):
583 583 t = i
584 584 if notip:
585 585 t = [(k, n) for k, n in i if k != "tip"]
586 586 if latestonly:
587 587 t = t[:1]
588 588 for k, n in t:
589 589 yield {"parity": next(parity),
590 590 "tag": k,
591 591 "date": web.repo[n].date(),
592 592 "node": hex(n)}
593 593
594 594 return tmpl("tags",
595 595 node=hex(web.repo.changelog.tip()),
596 596 entries=lambda **x: entries(False, False, **x),
597 597 entriesnotip=lambda **x: entries(True, False, **x),
598 598 latestentry=lambda **x: entries(True, True, **x))
599 599
600 600 @webcommand('bookmarks')
601 601 def bookmarks(web, req, tmpl):
602 602 """
603 603 /bookmarks
604 604 ----------
605 605
606 606 Show information about bookmarks.
607 607
608 608 No arguments are accepted.
609 609
610 610 The ``bookmarks`` template is rendered.
611 611 """
612 612 i = [b for b in web.repo._bookmarks.items() if b[1] in web.repo]
613 613 sortkey = lambda b: (web.repo[b[1]].rev(), b[0])
614 614 i = sorted(i, key=sortkey, reverse=True)
615 615 parity = paritygen(web.stripecount)
616 616
617 617 def entries(latestonly, **map):
618 618 t = i
619 619 if latestonly:
620 620 t = i[:1]
621 621 for k, n in t:
622 622 yield {"parity": next(parity),
623 623 "bookmark": k,
624 624 "date": web.repo[n].date(),
625 625 "node": hex(n)}
626 626
627 627 if i:
628 628 latestrev = i[0][1]
629 629 else:
630 630 latestrev = -1
631 631
632 632 return tmpl("bookmarks",
633 633 node=hex(web.repo.changelog.tip()),
634 634 lastchange=[{"date": web.repo[latestrev].date()}],
635 635 entries=lambda **x: entries(latestonly=False, **x),
636 636 latestentry=lambda **x: entries(latestonly=True, **x))
637 637
638 638 @webcommand('branches')
639 639 def branches(web, req, tmpl):
640 640 """
641 641 /branches
642 642 ---------
643 643
644 644 Show information about branches.
645 645
646 646 All known branches are contained in the output, even closed branches.
647 647
648 648 No arguments are accepted.
649 649
650 650 The ``branches`` template is rendered.
651 651 """
652 652 entries = webutil.branchentries(web.repo, web.stripecount)
653 653 latestentry = webutil.branchentries(web.repo, web.stripecount, 1)
654 654 return tmpl('branches', node=hex(web.repo.changelog.tip()),
655 655 entries=entries, latestentry=latestentry)
656 656
657 657 @webcommand('summary')
658 658 def summary(web, req, tmpl):
659 659 """
660 660 /summary
661 661 --------
662 662
663 663 Show a summary of repository state.
664 664
665 665 Information about the latest changesets, bookmarks, tags, and branches
666 666 is captured by this handler.
667 667
668 668 The ``summary`` template is rendered.
669 669 """
670 670 i = reversed(web.repo.tagslist())
671 671
672 672 def tagentries(**map):
673 673 parity = paritygen(web.stripecount)
674 674 count = 0
675 675 for k, n in i:
676 676 if k == "tip": # skip tip
677 677 continue
678 678
679 679 count += 1
680 680 if count > 10: # limit to 10 tags
681 681 break
682 682
683 683 yield tmpl("tagentry",
684 684 parity=next(parity),
685 685 tag=k,
686 686 node=hex(n),
687 687 date=web.repo[n].date())
688 688
689 689 def bookmarks(**map):
690 690 parity = paritygen(web.stripecount)
691 691 marks = [b for b in web.repo._bookmarks.items() if b[1] in web.repo]
692 692 sortkey = lambda b: (web.repo[b[1]].rev(), b[0])
693 693 marks = sorted(marks, key=sortkey, reverse=True)
694 694 for k, n in marks[:10]: # limit to 10 bookmarks
695 695 yield {'parity': next(parity),
696 696 'bookmark': k,
697 697 'date': web.repo[n].date(),
698 698 'node': hex(n)}
699 699
700 700 def changelist(**map):
701 701 parity = paritygen(web.stripecount, offset=start - end)
702 702 l = [] # build a list in forward order for efficiency
703 703 revs = []
704 704 if start < end:
705 705 revs = web.repo.changelog.revs(start, end - 1)
706 706 for i in revs:
707 707 ctx = web.repo[i]
708 708
709 709 l.append(tmpl(
710 710 'shortlogentry',
711 711 parity=next(parity),
712 712 **webutil.commonentry(web.repo, ctx)))
713 713
714 714 for entry in reversed(l):
715 715 yield entry
716 716
717 717 tip = web.repo['tip']
718 718 count = len(web.repo)
719 719 start = max(0, count - web.maxchanges)
720 720 end = min(count, start + web.maxchanges)
721 721
722 722 desc = web.config("web", "description")
723 723 if not desc:
724 724 desc = 'unknown'
725 725 return tmpl("summary",
726 726 desc=desc,
727 727 owner=get_contact(web.config) or "unknown",
728 728 lastchange=tip.date(),
729 729 tags=tagentries,
730 730 bookmarks=bookmarks,
731 731 branches=webutil.branchentries(web.repo, web.stripecount, 10),
732 732 shortlog=changelist,
733 733 node=tip.hex(),
734 734 symrev='tip',
735 735 archives=web.archivelist("tip"),
736 736 labels=web.configlist('web', 'labels'))
737 737
738 738 @webcommand('filediff')
739 739 def filediff(web, req, tmpl):
740 740 """
741 741 /diff/{revision}/{path}
742 742 -----------------------
743 743
744 744 Show how a file changed in a particular commit.
745 745
746 746 The ``filediff`` template is rendered.
747 747
748 748 This handler is registered under both the ``/diff`` and ``/filediff``
749 749 paths. ``/diff`` is used in modern code.
750 750 """
751 751 fctx, ctx = None, None
752 752 try:
753 753 fctx = webutil.filectx(web.repo, req)
754 754 except LookupError:
755 755 ctx = webutil.changectx(web.repo, req)
756 756 path = webutil.cleanpath(web.repo, req.form['file'][0])
757 757 if path not in ctx.files():
758 758 raise
759 759
760 760 if fctx is not None:
761 761 path = fctx.path()
762 762 ctx = fctx.changectx()
763 763 basectx = ctx.p1()
764 764
765 765 style = web.config('web', 'style')
766 766 if 'style' in req.form:
767 767 style = req.form['style'][0]
768 768
769 769 diffs = webutil.diffs(web, tmpl, ctx, basectx, [path], style)
770 770 if fctx is not None:
771 771 rename = webutil.renamelink(fctx)
772 772 ctx = fctx
773 773 else:
774 774 rename = []
775 775 ctx = ctx
776 776 return tmpl("filediff",
777 777 file=path,
778 778 symrev=webutil.symrevorshortnode(req, ctx),
779 779 rename=rename,
780 780 diff=diffs,
781 781 **webutil.commonentry(web.repo, ctx))
782 782
783 783 diff = webcommand('diff')(filediff)
784 784
785 785 @webcommand('comparison')
786 786 def comparison(web, req, tmpl):
787 787 """
788 788 /comparison/{revision}/{path}
789 789 -----------------------------
790 790
791 791 Show a comparison between the old and new versions of a file from changes
792 792 made on a particular revision.
793 793
794 794 This is similar to the ``diff`` handler. However, this form features
795 795 a split or side-by-side diff rather than a unified diff.
796 796
797 797 The ``context`` query string argument can be used to control the lines of
798 798 context in the diff.
799 799
800 800 The ``filecomparison`` template is rendered.
801 801 """
802 802 ctx = webutil.changectx(web.repo, req)
803 803 if 'file' not in req.form:
804 804 raise ErrorResponse(HTTP_NOT_FOUND, 'file not given')
805 805 path = webutil.cleanpath(web.repo, req.form['file'][0])
806 806
807 807 parsecontext = lambda v: v == 'full' and -1 or int(v)
808 808 if 'context' in req.form:
809 809 context = parsecontext(req.form['context'][0])
810 810 else:
811 811 context = parsecontext(web.config('web', 'comparisoncontext', '5'))
812 812
813 813 def filelines(f):
814 814 if f.isbinary():
815 815 mt = mimetypes.guess_type(f.path())[0]
816 816 if not mt:
817 817 mt = 'application/octet-stream'
818 818 return [_('(binary file %s, hash: %s)') % (mt, hex(f.filenode()))]
819 819 return f.data().splitlines()
820 820
821 821 fctx = None
822 822 parent = ctx.p1()
823 823 leftrev = parent.rev()
824 824 leftnode = parent.node()
825 825 rightrev = ctx.rev()
826 826 rightnode = ctx.node()
827 827 if path in ctx:
828 828 fctx = ctx[path]
829 829 rightlines = filelines(fctx)
830 830 if path not in parent:
831 831 leftlines = ()
832 832 else:
833 833 pfctx = parent[path]
834 834 leftlines = filelines(pfctx)
835 835 else:
836 836 rightlines = ()
837 837 pfctx = ctx.parents()[0][path]
838 838 leftlines = filelines(pfctx)
839 839
840 840 comparison = webutil.compare(tmpl, context, leftlines, rightlines)
841 841 if fctx is not None:
842 842 rename = webutil.renamelink(fctx)
843 843 ctx = fctx
844 844 else:
845 845 rename = []
846 846 ctx = ctx
847 847 return tmpl('filecomparison',
848 848 file=path,
849 849 symrev=webutil.symrevorshortnode(req, ctx),
850 850 rename=rename,
851 851 leftrev=leftrev,
852 852 leftnode=hex(leftnode),
853 853 rightrev=rightrev,
854 854 rightnode=hex(rightnode),
855 855 comparison=comparison,
856 856 **webutil.commonentry(web.repo, ctx))
857 857
858 858 @webcommand('annotate')
859 859 def annotate(web, req, tmpl):
860 860 """
861 861 /annotate/{revision}/{path}
862 862 ---------------------------
863 863
864 864 Show changeset information for each line in a file.
865 865
866 866 The ``ignorews``, ``ignorewsamount``, ``ignorewseol``, and
867 867 ``ignoreblanklines`` query string arguments have the same meaning as
868 868 their ``[annotate]`` config equivalents. It uses the hgrc boolean
869 869 parsing logic to interpret the value. e.g. ``0`` and ``false`` are
870 870 false and ``1`` and ``true`` are true. If not defined, the server
871 871 default settings are used.
872 872
873 873 The ``fileannotate`` template is rendered.
874 874 """
875 875 fctx = webutil.filectx(web.repo, req)
876 876 f = fctx.path()
877 877 parity = paritygen(web.stripecount)
878 878 ishead = fctx.filerev() in fctx.filelog().headrevs()
879 879
880 880 # parents() is called once per line and several lines likely belong to
881 881 # same revision. So it is worth caching.
882 882 # TODO there are still redundant operations within basefilectx.parents()
883 883 # and from the fctx.annotate() call itself that could be cached.
884 884 parentscache = {}
885 885 def parents(f):
886 886 rev = f.rev()
887 887 if rev not in parentscache:
888 888 parentscache[rev] = []
889 889 for p in f.parents():
890 890 entry = {
891 891 'node': p.hex(),
892 892 'rev': p.rev(),
893 893 }
894 894 parentscache[rev].append(entry)
895 895
896 896 for p in parentscache[rev]:
897 897 yield p
898 898
899 899 def annotate(**map):
900 900 if fctx.isbinary():
901 901 mt = (mimetypes.guess_type(fctx.path())[0]
902 902 or 'application/octet-stream')
903 903 lines = [((fctx.filectx(fctx.filerev()), 1), '(binary:%s)' % mt)]
904 904 else:
905 905 lines = webutil.annotate(req, fctx, web.repo.ui)
906 906
907 907 previousrev = None
908 908 blockparitygen = paritygen(1)
909 for lineno, ((f, targetline), l) in enumerate(lines):
909 for lineno, (aline, l) in enumerate(lines):
910 f = aline.fctx
910 911 rev = f.rev()
911 912 if rev != previousrev:
912 913 blockhead = True
913 914 blockparity = next(blockparitygen)
914 915 else:
915 916 blockhead = None
916 917 previousrev = rev
917 918 yield {"parity": next(parity),
918 919 "node": f.hex(),
919 920 "rev": rev,
920 921 "author": f.user(),
921 922 "parents": parents(f),
922 923 "desc": f.description(),
923 924 "extra": f.extra(),
924 925 "file": f.path(),
925 926 "blockhead": blockhead,
926 927 "blockparity": blockparity,
927 "targetline": targetline,
928 "targetline": aline.lineno,
928 929 "line": l,
929 930 "lineno": lineno + 1,
930 931 "lineid": "l%d" % (lineno + 1),
931 932 "linenumber": "% 6d" % (lineno + 1),
932 933 "revdate": f.date()}
933 934
934 935 diffopts = webutil.difffeatureopts(req, web.repo.ui, 'annotate')
935 936 diffopts = {k: getattr(diffopts, k) for k in diffopts.defaults}
936 937
937 938 return tmpl("fileannotate",
938 939 file=f,
939 940 annotate=annotate,
940 941 path=webutil.up(f),
941 942 symrev=webutil.symrevorshortnode(req, fctx),
942 943 rename=webutil.renamelink(fctx),
943 944 permissions=fctx.manifest().flags(f),
944 945 ishead=int(ishead),
945 946 diffopts=diffopts,
946 947 **webutil.commonentry(web.repo, fctx))
947 948
948 949 @webcommand('filelog')
949 950 def filelog(web, req, tmpl):
950 951 """
951 952 /filelog/{revision}/{path}
952 953 --------------------------
953 954
954 955 Show information about the history of a file in the repository.
955 956
956 957 The ``revcount`` query string argument can be defined to control the
957 958 maximum number of entries to show.
958 959
959 960 The ``filelog`` template will be rendered.
960 961 """
961 962
962 963 try:
963 964 fctx = webutil.filectx(web.repo, req)
964 965 f = fctx.path()
965 966 fl = fctx.filelog()
966 967 except error.LookupError:
967 968 f = webutil.cleanpath(web.repo, req.form['file'][0])
968 969 fl = web.repo.file(f)
969 970 numrevs = len(fl)
970 971 if not numrevs: # file doesn't exist at all
971 972 raise
972 973 rev = webutil.changectx(web.repo, req).rev()
973 974 first = fl.linkrev(0)
974 975 if rev < first: # current rev is from before file existed
975 976 raise
976 977 frev = numrevs - 1
977 978 while fl.linkrev(frev) > rev:
978 979 frev -= 1
979 980 fctx = web.repo.filectx(f, fl.linkrev(frev))
980 981
981 982 revcount = web.maxshortchanges
982 983 if 'revcount' in req.form:
983 984 try:
984 985 revcount = int(req.form.get('revcount', [revcount])[0])
985 986 revcount = max(revcount, 1)
986 987 tmpl.defaults['sessionvars']['revcount'] = revcount
987 988 except ValueError:
988 989 pass
989 990
990 991 lrange = webutil.linerange(req)
991 992
992 993 lessvars = copy.copy(tmpl.defaults['sessionvars'])
993 994 lessvars['revcount'] = max(revcount / 2, 1)
994 995 morevars = copy.copy(tmpl.defaults['sessionvars'])
995 996 morevars['revcount'] = revcount * 2
996 997
997 998 patch = 'patch' in req.form
998 999 if patch:
999 1000 lessvars['patch'] = morevars['patch'] = req.form['patch'][0]
1000 1001 descend = 'descend' in req.form
1001 1002 if descend:
1002 1003 lessvars['descend'] = morevars['descend'] = req.form['descend'][0]
1003 1004
1004 1005 count = fctx.filerev() + 1
1005 1006 start = max(0, count - revcount) # first rev on this page
1006 1007 end = min(count, start + revcount) # last rev on this page
1007 1008 parity = paritygen(web.stripecount, offset=start - end)
1008 1009
1009 1010 repo = web.repo
1010 1011 revs = fctx.filelog().revs(start, end - 1)
1011 1012 entries = []
1012 1013
1013 1014 diffstyle = web.config('web', 'style')
1014 1015 if 'style' in req.form:
1015 1016 diffstyle = req.form['style'][0]
1016 1017
1017 1018 def diff(fctx, linerange=None):
1018 1019 ctx = fctx.changectx()
1019 1020 basectx = ctx.p1()
1020 1021 path = fctx.path()
1021 1022 return webutil.diffs(web, tmpl, ctx, basectx, [path], diffstyle,
1022 1023 linerange=linerange,
1023 1024 lineidprefix='%s-' % ctx.hex()[:12])
1024 1025
1025 1026 linerange = None
1026 1027 if lrange is not None:
1027 1028 linerange = webutil.formatlinerange(*lrange)
1028 1029 # deactivate numeric nav links when linerange is specified as this
1029 1030 # would required a dedicated "revnav" class
1030 1031 nav = None
1031 1032 if descend:
1032 1033 it = dagop.blockdescendants(fctx, *lrange)
1033 1034 else:
1034 1035 it = dagop.blockancestors(fctx, *lrange)
1035 1036 for i, (c, lr) in enumerate(it, 1):
1036 1037 diffs = None
1037 1038 if patch:
1038 1039 diffs = diff(c, linerange=lr)
1039 1040 # follow renames accross filtered (not in range) revisions
1040 1041 path = c.path()
1041 1042 entries.append(dict(
1042 1043 parity=next(parity),
1043 1044 filerev=c.rev(),
1044 1045 file=path,
1045 1046 diff=diffs,
1046 1047 linerange=webutil.formatlinerange(*lr),
1047 1048 **webutil.commonentry(repo, c)))
1048 1049 if i == revcount:
1049 1050 break
1050 1051 lessvars['linerange'] = webutil.formatlinerange(*lrange)
1051 1052 morevars['linerange'] = lessvars['linerange']
1052 1053 else:
1053 1054 for i in revs:
1054 1055 iterfctx = fctx.filectx(i)
1055 1056 diffs = None
1056 1057 if patch:
1057 1058 diffs = diff(iterfctx)
1058 1059 entries.append(dict(
1059 1060 parity=next(parity),
1060 1061 filerev=i,
1061 1062 file=f,
1062 1063 diff=diffs,
1063 1064 rename=webutil.renamelink(iterfctx),
1064 1065 **webutil.commonentry(repo, iterfctx)))
1065 1066 entries.reverse()
1066 1067 revnav = webutil.filerevnav(web.repo, fctx.path())
1067 1068 nav = revnav.gen(end - 1, revcount, count)
1068 1069
1069 1070 latestentry = entries[:1]
1070 1071
1071 1072 return tmpl("filelog",
1072 1073 file=f,
1073 1074 nav=nav,
1074 1075 symrev=webutil.symrevorshortnode(req, fctx),
1075 1076 entries=entries,
1076 1077 descend=descend,
1077 1078 patch=patch,
1078 1079 latestentry=latestentry,
1079 1080 linerange=linerange,
1080 1081 revcount=revcount,
1081 1082 morevars=morevars,
1082 1083 lessvars=lessvars,
1083 1084 **webutil.commonentry(web.repo, fctx))
1084 1085
1085 1086 @webcommand('archive')
1086 1087 def archive(web, req, tmpl):
1087 1088 """
1088 1089 /archive/{revision}.{format}[/{path}]
1089 1090 -------------------------------------
1090 1091
1091 1092 Obtain an archive of repository content.
1092 1093
1093 1094 The content and type of the archive is defined by a URL path parameter.
1094 1095 ``format`` is the file extension of the archive type to be generated. e.g.
1095 1096 ``zip`` or ``tar.bz2``. Not all archive types may be allowed by your
1096 1097 server configuration.
1097 1098
1098 1099 The optional ``path`` URL parameter controls content to include in the
1099 1100 archive. If omitted, every file in the specified revision is present in the
1100 1101 archive. If included, only the specified file or contents of the specified
1101 1102 directory will be included in the archive.
1102 1103
1103 1104 No template is used for this handler. Raw, binary content is generated.
1104 1105 """
1105 1106
1106 1107 type_ = req.form.get('type', [None])[0]
1107 1108 allowed = web.configlist("web", "allow_archive")
1108 1109 key = req.form['node'][0]
1109 1110
1110 1111 if type_ not in web.archivespecs:
1111 1112 msg = 'Unsupported archive type: %s' % type_
1112 1113 raise ErrorResponse(HTTP_NOT_FOUND, msg)
1113 1114
1114 1115 if not ((type_ in allowed or
1115 1116 web.configbool("web", "allow" + type_, False))):
1116 1117 msg = 'Archive type not allowed: %s' % type_
1117 1118 raise ErrorResponse(HTTP_FORBIDDEN, msg)
1118 1119
1119 1120 reponame = re.sub(r"\W+", "-", os.path.basename(web.reponame))
1120 1121 cnode = web.repo.lookup(key)
1121 1122 arch_version = key
1122 1123 if cnode == key or key == 'tip':
1123 1124 arch_version = short(cnode)
1124 1125 name = "%s-%s" % (reponame, arch_version)
1125 1126
1126 1127 ctx = webutil.changectx(web.repo, req)
1127 1128 pats = []
1128 1129 match = scmutil.match(ctx, [])
1129 1130 file = req.form.get('file', None)
1130 1131 if file:
1131 1132 pats = ['path:' + file[0]]
1132 1133 match = scmutil.match(ctx, pats, default='path')
1133 1134 if pats:
1134 1135 files = [f for f in ctx.manifest().keys() if match(f)]
1135 1136 if not files:
1136 1137 raise ErrorResponse(HTTP_NOT_FOUND,
1137 1138 'file(s) not found: %s' % file[0])
1138 1139
1139 1140 mimetype, artype, extension, encoding = web.archivespecs[type_]
1140 1141 headers = [
1141 1142 ('Content-Disposition', 'attachment; filename=%s%s' % (name, extension))
1142 1143 ]
1143 1144 if encoding:
1144 1145 headers.append(('Content-Encoding', encoding))
1145 1146 req.headers.extend(headers)
1146 1147 req.respond(HTTP_OK, mimetype)
1147 1148
1148 1149 archival.archive(web.repo, req, cnode, artype, prefix=name,
1149 1150 matchfn=match,
1150 1151 subrepos=web.configbool("web", "archivesubrepos"))
1151 1152 return []
1152 1153
1153 1154
1154 1155 @webcommand('static')
1155 1156 def static(web, req, tmpl):
1156 1157 fname = req.form['file'][0]
1157 1158 # a repo owner may set web.static in .hg/hgrc to get any file
1158 1159 # readable by the user running the CGI script
1159 1160 static = web.config("web", "static", None, untrusted=False)
1160 1161 if not static:
1161 1162 tp = web.templatepath or templater.templatepaths()
1162 1163 if isinstance(tp, str):
1163 1164 tp = [tp]
1164 1165 static = [os.path.join(p, 'static') for p in tp]
1165 1166 staticfile(static, fname, req)
1166 1167 return []
1167 1168
1168 1169 @webcommand('graph')
1169 1170 def graph(web, req, tmpl):
1170 1171 """
1171 1172 /graph[/{revision}]
1172 1173 -------------------
1173 1174
1174 1175 Show information about the graphical topology of the repository.
1175 1176
1176 1177 Information rendered by this handler can be used to create visual
1177 1178 representations of repository topology.
1178 1179
1179 1180 The ``revision`` URL parameter controls the starting changeset.
1180 1181
1181 1182 The ``revcount`` query string argument can define the number of changesets
1182 1183 to show information for.
1183 1184
1184 1185 This handler will render the ``graph`` template.
1185 1186 """
1186 1187
1187 1188 if 'node' in req.form:
1188 1189 ctx = webutil.changectx(web.repo, req)
1189 1190 symrev = webutil.symrevorshortnode(req, ctx)
1190 1191 else:
1191 1192 ctx = web.repo['tip']
1192 1193 symrev = 'tip'
1193 1194 rev = ctx.rev()
1194 1195
1195 1196 bg_height = 39
1196 1197 revcount = web.maxshortchanges
1197 1198 if 'revcount' in req.form:
1198 1199 try:
1199 1200 revcount = int(req.form.get('revcount', [revcount])[0])
1200 1201 revcount = max(revcount, 1)
1201 1202 tmpl.defaults['sessionvars']['revcount'] = revcount
1202 1203 except ValueError:
1203 1204 pass
1204 1205
1205 1206 lessvars = copy.copy(tmpl.defaults['sessionvars'])
1206 1207 lessvars['revcount'] = max(revcount / 2, 1)
1207 1208 morevars = copy.copy(tmpl.defaults['sessionvars'])
1208 1209 morevars['revcount'] = revcount * 2
1209 1210
1210 1211 count = len(web.repo)
1211 1212 pos = rev
1212 1213
1213 1214 uprev = min(max(0, count - 1), rev + revcount)
1214 1215 downrev = max(0, rev - revcount)
1215 1216 changenav = webutil.revnav(web.repo).gen(pos, revcount, count)
1216 1217
1217 1218 tree = []
1218 1219 if pos != -1:
1219 1220 allrevs = web.repo.changelog.revs(pos, 0)
1220 1221 revs = []
1221 1222 for i in allrevs:
1222 1223 revs.append(i)
1223 1224 if len(revs) >= revcount:
1224 1225 break
1225 1226
1226 1227 # We have to feed a baseset to dagwalker as it is expecting smartset
1227 1228 # object. This does not have a big impact on hgweb performance itself
1228 1229 # since hgweb graphing code is not itself lazy yet.
1229 1230 dag = graphmod.dagwalker(web.repo, smartset.baseset(revs))
1230 1231 # As we said one line above... not lazy.
1231 1232 tree = list(graphmod.colored(dag, web.repo))
1232 1233
1233 1234 def getcolumns(tree):
1234 1235 cols = 0
1235 1236 for (id, type, ctx, vtx, edges) in tree:
1236 1237 if type != graphmod.CHANGESET:
1237 1238 continue
1238 1239 cols = max(cols, max([edge[0] for edge in edges] or [0]),
1239 1240 max([edge[1] for edge in edges] or [0]))
1240 1241 return cols
1241 1242
1242 1243 def graphdata(usetuples, encodestr):
1243 1244 data = []
1244 1245
1245 1246 row = 0
1246 1247 for (id, type, ctx, vtx, edges) in tree:
1247 1248 if type != graphmod.CHANGESET:
1248 1249 continue
1249 1250 node = str(ctx)
1250 1251 age = encodestr(templatefilters.age(ctx.date()))
1251 1252 desc = templatefilters.firstline(encodestr(ctx.description()))
1252 1253 desc = cgi.escape(templatefilters.nonempty(desc))
1253 1254 user = cgi.escape(templatefilters.person(encodestr(ctx.user())))
1254 1255 branch = cgi.escape(encodestr(ctx.branch()))
1255 1256 try:
1256 1257 branchnode = web.repo.branchtip(branch)
1257 1258 except error.RepoLookupError:
1258 1259 branchnode = None
1259 1260 branch = branch, branchnode == ctx.node()
1260 1261
1261 1262 if usetuples:
1262 1263 data.append((node, vtx, edges, desc, user, age, branch,
1263 1264 [cgi.escape(encodestr(x)) for x in ctx.tags()],
1264 1265 [cgi.escape(encodestr(x))
1265 1266 for x in ctx.bookmarks()]))
1266 1267 else:
1267 1268 edgedata = [{'col': edge[0], 'nextcol': edge[1],
1268 1269 'color': (edge[2] - 1) % 6 + 1,
1269 1270 'width': edge[3], 'bcolor': edge[4]}
1270 1271 for edge in edges]
1271 1272
1272 1273 data.append(
1273 1274 {'node': node,
1274 1275 'col': vtx[0],
1275 1276 'color': (vtx[1] - 1) % 6 + 1,
1276 1277 'edges': edgedata,
1277 1278 'row': row,
1278 1279 'nextrow': row + 1,
1279 1280 'desc': desc,
1280 1281 'user': user,
1281 1282 'age': age,
1282 1283 'bookmarks': webutil.nodebookmarksdict(
1283 1284 web.repo, ctx.node()),
1284 1285 'branches': webutil.nodebranchdict(web.repo, ctx),
1285 1286 'inbranch': webutil.nodeinbranch(web.repo, ctx),
1286 1287 'tags': webutil.nodetagsdict(web.repo, ctx.node())})
1287 1288
1288 1289 row += 1
1289 1290
1290 1291 return data
1291 1292
1292 1293 cols = getcolumns(tree)
1293 1294 rows = len(tree)
1294 1295 canvasheight = (rows + 1) * bg_height - 27
1295 1296
1296 1297 return tmpl('graph', rev=rev, symrev=symrev, revcount=revcount,
1297 1298 uprev=uprev,
1298 1299 lessvars=lessvars, morevars=morevars, downrev=downrev,
1299 1300 cols=cols, rows=rows,
1300 1301 canvaswidth=(cols + 1) * bg_height,
1301 1302 truecanvasheight=rows * bg_height,
1302 1303 canvasheight=canvasheight, bg_height=bg_height,
1303 1304 # {jsdata} will be passed to |json, so it must be in utf-8
1304 1305 jsdata=lambda **x: graphdata(True, encoding.fromlocal),
1305 1306 nodes=lambda **x: graphdata(False, str),
1306 1307 node=ctx.hex(), changenav=changenav)
1307 1308
1308 1309 def _getdoc(e):
1309 1310 doc = e[0].__doc__
1310 1311 if doc:
1311 1312 doc = _(doc).partition('\n')[0]
1312 1313 else:
1313 1314 doc = _('(no help text available)')
1314 1315 return doc
1315 1316
1316 1317 @webcommand('help')
1317 1318 def help(web, req, tmpl):
1318 1319 """
1319 1320 /help[/{topic}]
1320 1321 ---------------
1321 1322
1322 1323 Render help documentation.
1323 1324
1324 1325 This web command is roughly equivalent to :hg:`help`. If a ``topic``
1325 1326 is defined, that help topic will be rendered. If not, an index of
1326 1327 available help topics will be rendered.
1327 1328
1328 1329 The ``help`` template will be rendered when requesting help for a topic.
1329 1330 ``helptopics`` will be rendered for the index of help topics.
1330 1331 """
1331 1332 from .. import commands, help as helpmod # avoid cycle
1332 1333
1333 1334 topicname = req.form.get('node', [None])[0]
1334 1335 if not topicname:
1335 1336 def topics(**map):
1336 1337 for entries, summary, _doc in helpmod.helptable:
1337 1338 yield {'topic': entries[0], 'summary': summary}
1338 1339
1339 1340 early, other = [], []
1340 1341 primary = lambda s: s.partition('|')[0]
1341 1342 for c, e in commands.table.iteritems():
1342 1343 doc = _getdoc(e)
1343 1344 if 'DEPRECATED' in doc or c.startswith('debug'):
1344 1345 continue
1345 1346 cmd = primary(c)
1346 1347 if cmd.startswith('^'):
1347 1348 early.append((cmd[1:], doc))
1348 1349 else:
1349 1350 other.append((cmd, doc))
1350 1351
1351 1352 early.sort()
1352 1353 other.sort()
1353 1354
1354 1355 def earlycommands(**map):
1355 1356 for c, doc in early:
1356 1357 yield {'topic': c, 'summary': doc}
1357 1358
1358 1359 def othercommands(**map):
1359 1360 for c, doc in other:
1360 1361 yield {'topic': c, 'summary': doc}
1361 1362
1362 1363 return tmpl('helptopics', topics=topics, earlycommands=earlycommands,
1363 1364 othercommands=othercommands, title='Index')
1364 1365
1365 1366 # Render an index of sub-topics.
1366 1367 if topicname in helpmod.subtopics:
1367 1368 topics = []
1368 1369 for entries, summary, _doc in helpmod.subtopics[topicname]:
1369 1370 topics.append({
1370 1371 'topic': '%s.%s' % (topicname, entries[0]),
1371 1372 'basename': entries[0],
1372 1373 'summary': summary,
1373 1374 })
1374 1375
1375 1376 return tmpl('helptopics', topics=topics, title=topicname,
1376 1377 subindex=True)
1377 1378
1378 1379 u = webutil.wsgiui.load()
1379 1380 u.verbose = True
1380 1381
1381 1382 # Render a page from a sub-topic.
1382 1383 if '.' in topicname:
1383 1384 # TODO implement support for rendering sections, like
1384 1385 # `hg help` works.
1385 1386 topic, subtopic = topicname.split('.', 1)
1386 1387 if topic not in helpmod.subtopics:
1387 1388 raise ErrorResponse(HTTP_NOT_FOUND)
1388 1389 else:
1389 1390 topic = topicname
1390 1391 subtopic = None
1391 1392
1392 1393 try:
1393 1394 doc = helpmod.help_(u, commands, topic, subtopic=subtopic)
1394 1395 except error.UnknownCommand:
1395 1396 raise ErrorResponse(HTTP_NOT_FOUND)
1396 1397 return tmpl('help', topic=topicname, doc=doc)
1397 1398
1398 1399 # tell hggettext to extract docstrings from these functions:
1399 1400 i18nfunctions = commands.values()
@@ -1,75 +1,102 b''
1 1 from __future__ import absolute_import
2 2 from __future__ import print_function
3 3
4 4 import unittest
5 5
6 6 from mercurial import (
7 7 mdiff,
8 8 )
9 9 from mercurial.context import (
10 annotateline,
10 11 _annotatepair,
11 12 )
12 13
13 14 class AnnotateTests(unittest.TestCase):
14 15 """Unit tests for annotate code."""
15 16
16 17 def testannotatepair(self):
17 18 self.maxDiff = None # camelcase-required
18 19
19 20 oldfctx = b'old'
20 21 p1fctx, p2fctx, childfctx = b'p1', b'p2', b'c'
21 22 olddata = b'a\nb\n'
22 23 p1data = b'a\nb\nc\n'
23 24 p2data = b'a\nc\nd\n'
24 25 childdata = b'a\nb2\nc\nc2\nd\n'
25 26 diffopts = mdiff.diffopts()
26 27
27 28 def decorate(text, rev):
28 return ([(rev, i) for i in xrange(1, text.count(b'\n') + 1)], text)
29 return ([annotateline(fctx=rev, lineno=i)
30 for i in xrange(1, text.count(b'\n') + 1)],
31 text)
29 32
30 33 # Basic usage
31 34
32 35 oldann = decorate(olddata, oldfctx)
33 36 p1ann = decorate(p1data, p1fctx)
34 37 p1ann = _annotatepair([oldann], p1fctx, p1ann, False, diffopts)
35 self.assertEqual(p1ann[0], [('old', 1), ('old', 2), ('p1', 3)])
38 self.assertEqual(p1ann[0], [
39 annotateline('old', 1),
40 annotateline('old', 2),
41 annotateline('p1', 3),
42 ])
36 43
37 44 p2ann = decorate(p2data, p2fctx)
38 45 p2ann = _annotatepair([oldann], p2fctx, p2ann, False, diffopts)
39 self.assertEqual(p2ann[0], [('old', 1), ('p2', 2), ('p2', 3)])
46 self.assertEqual(p2ann[0], [
47 annotateline('old', 1),
48 annotateline('p2', 2),
49 annotateline('p2', 3),
50 ])
40 51
41 52 # Test with multiple parents (note the difference caused by ordering)
42 53
43 54 childann = decorate(childdata, childfctx)
44 55 childann = _annotatepair([p1ann, p2ann], childfctx, childann, False,
45 56 diffopts)
46 self.assertEqual(childann[0],
47 [('old', 1), ('c', 2), ('p2', 2), ('c', 4), ('p2', 3)]
48 )
57 self.assertEqual(childann[0], [
58 annotateline('old', 1),
59 annotateline('c', 2),
60 annotateline('p2', 2),
61 annotateline('c', 4),
62 annotateline('p2', 3),
63 ])
49 64
50 65 childann = decorate(childdata, childfctx)
51 66 childann = _annotatepair([p2ann, p1ann], childfctx, childann, False,
52 67 diffopts)
53 self.assertEqual(childann[0],
54 [('old', 1), ('c', 2), ('p1', 3), ('c', 4), ('p2', 3)]
55 )
68 self.assertEqual(childann[0], [
69 annotateline('old', 1),
70 annotateline('c', 2),
71 annotateline('p1', 3),
72 annotateline('c', 4),
73 annotateline('p2', 3),
74 ])
56 75
57 76 # Test with skipchild (note the difference caused by ordering)
58 77
59 78 childann = decorate(childdata, childfctx)
60 79 childann = _annotatepair([p1ann, p2ann], childfctx, childann, True,
61 80 diffopts)
62 self.assertEqual(childann[0],
63 [('old', 1), ('old', 2), ('p2', 2), ('p2', 2), ('p2', 3)]
64 )
81 self.assertEqual(childann[0], [
82 annotateline('old', 1),
83 annotateline('old', 2),
84 annotateline('p2', 2),
85 annotateline('p2', 2),
86 annotateline('p2', 3),
87 ])
65 88
66 89 childann = decorate(childdata, childfctx)
67 90 childann = _annotatepair([p2ann, p1ann], childfctx, childann, True,
68 91 diffopts)
69 self.assertEqual(childann[0],
70 [('old', 1), ('old', 2), ('p1', 3), ('p1', 3), ('p2', 3)]
71 )
92 self.assertEqual(childann[0], [
93 annotateline('old', 1),
94 annotateline('old', 2),
95 annotateline('p1', 3),
96 annotateline('p1', 3),
97 annotateline('p2', 3),
98 ])
72 99
73 100 if __name__ == '__main__':
74 101 import silenttestrunner
75 102 silenttestrunner.main(__name__)
General Comments 0
You need to be logged in to leave comments. Login now