##// END OF EJS Templates
graft: move commit info building...
David Schleimer -
r18038:f8aee803 default
parent child Browse files
Show More
@@ -1,5982 +1,5983 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 node import hex, bin, nullid, nullrev, short
9 9 from lock import release
10 10 from i18n import _, gettext
11 11 import os, re, difflib, time, tempfile, errno
12 12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
13 13 import patch, help, encoding, templatekw, discovery
14 14 import archival, changegroup, cmdutil, hbisect
15 15 import sshserver, hgweb, hgweb.server, commandserver
16 16 import merge as mergemod
17 17 import minirst, revset, fileset
18 18 import dagparser, context, simplemerge, graphmod
19 19 import random, setdiscovery, treediscovery, dagutil, pvec, localrepo
20 20 import phases, obsolete
21 21
22 22 table = {}
23 23
24 24 command = cmdutil.command(table)
25 25
26 26 # common command options
27 27
28 28 globalopts = [
29 29 ('R', 'repository', '',
30 30 _('repository root directory or name of overlay bundle file'),
31 31 _('REPO')),
32 32 ('', 'cwd', '',
33 33 _('change working directory'), _('DIR')),
34 34 ('y', 'noninteractive', None,
35 35 _('do not prompt, automatically pick the first choice for all prompts')),
36 36 ('q', 'quiet', None, _('suppress output')),
37 37 ('v', 'verbose', None, _('enable additional output')),
38 38 ('', 'config', [],
39 39 _('set/override config option (use \'section.name=value\')'),
40 40 _('CONFIG')),
41 41 ('', 'debug', None, _('enable debugging output')),
42 42 ('', 'debugger', None, _('start debugger')),
43 43 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
44 44 _('ENCODE')),
45 45 ('', 'encodingmode', encoding.encodingmode,
46 46 _('set the charset encoding mode'), _('MODE')),
47 47 ('', 'traceback', None, _('always print a traceback on exception')),
48 48 ('', 'time', None, _('time how long the command takes')),
49 49 ('', 'profile', None, _('print command execution profile')),
50 50 ('', 'version', None, _('output version information and exit')),
51 51 ('h', 'help', None, _('display help and exit')),
52 52 ]
53 53
54 54 dryrunopts = [('n', 'dry-run', None,
55 55 _('do not perform actions, just print output'))]
56 56
57 57 remoteopts = [
58 58 ('e', 'ssh', '',
59 59 _('specify ssh command to use'), _('CMD')),
60 60 ('', 'remotecmd', '',
61 61 _('specify hg command to run on the remote side'), _('CMD')),
62 62 ('', 'insecure', None,
63 63 _('do not verify server certificate (ignoring web.cacerts config)')),
64 64 ]
65 65
66 66 walkopts = [
67 67 ('I', 'include', [],
68 68 _('include names matching the given patterns'), _('PATTERN')),
69 69 ('X', 'exclude', [],
70 70 _('exclude names matching the given patterns'), _('PATTERN')),
71 71 ]
72 72
73 73 commitopts = [
74 74 ('m', 'message', '',
75 75 _('use text as commit message'), _('TEXT')),
76 76 ('l', 'logfile', '',
77 77 _('read commit message from file'), _('FILE')),
78 78 ]
79 79
80 80 commitopts2 = [
81 81 ('d', 'date', '',
82 82 _('record the specified date as commit date'), _('DATE')),
83 83 ('u', 'user', '',
84 84 _('record the specified user as committer'), _('USER')),
85 85 ]
86 86
87 87 templateopts = [
88 88 ('', 'style', '',
89 89 _('display using template map file'), _('STYLE')),
90 90 ('', 'template', '',
91 91 _('display with template'), _('TEMPLATE')),
92 92 ]
93 93
94 94 logopts = [
95 95 ('p', 'patch', None, _('show patch')),
96 96 ('g', 'git', None, _('use git extended diff format')),
97 97 ('l', 'limit', '',
98 98 _('limit number of changes displayed'), _('NUM')),
99 99 ('M', 'no-merges', None, _('do not show merges')),
100 100 ('', 'stat', None, _('output diffstat-style summary of changes')),
101 101 ('G', 'graph', None, _("show the revision DAG")),
102 102 ] + templateopts
103 103
104 104 diffopts = [
105 105 ('a', 'text', None, _('treat all files as text')),
106 106 ('g', 'git', None, _('use git extended diff format')),
107 107 ('', 'nodates', None, _('omit dates from diff headers'))
108 108 ]
109 109
110 110 diffwsopts = [
111 111 ('w', 'ignore-all-space', None,
112 112 _('ignore white space when comparing lines')),
113 113 ('b', 'ignore-space-change', None,
114 114 _('ignore changes in the amount of white space')),
115 115 ('B', 'ignore-blank-lines', None,
116 116 _('ignore changes whose lines are all blank')),
117 117 ]
118 118
119 119 diffopts2 = [
120 120 ('p', 'show-function', None, _('show which function each change is in')),
121 121 ('', 'reverse', None, _('produce a diff that undoes the changes')),
122 122 ] + diffwsopts + [
123 123 ('U', 'unified', '',
124 124 _('number of lines of context to show'), _('NUM')),
125 125 ('', 'stat', None, _('output diffstat-style summary of changes')),
126 126 ]
127 127
128 128 mergetoolopts = [
129 129 ('t', 'tool', '', _('specify merge tool')),
130 130 ]
131 131
132 132 similarityopts = [
133 133 ('s', 'similarity', '',
134 134 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
135 135 ]
136 136
137 137 subrepoopts = [
138 138 ('S', 'subrepos', None,
139 139 _('recurse into subrepositories'))
140 140 ]
141 141
142 142 # Commands start here, listed alphabetically
143 143
144 144 @command('^add',
145 145 walkopts + subrepoopts + dryrunopts,
146 146 _('[OPTION]... [FILE]...'))
147 147 def add(ui, repo, *pats, **opts):
148 148 """add the specified files on the next commit
149 149
150 150 Schedule files to be version controlled and added to the
151 151 repository.
152 152
153 153 The files will be added to the repository at the next commit. To
154 154 undo an add before that, see :hg:`forget`.
155 155
156 156 If no names are given, add all files to the repository.
157 157
158 158 .. container:: verbose
159 159
160 160 An example showing how new (unknown) files are added
161 161 automatically by :hg:`add`::
162 162
163 163 $ ls
164 164 foo.c
165 165 $ hg status
166 166 ? foo.c
167 167 $ hg add
168 168 adding foo.c
169 169 $ hg status
170 170 A foo.c
171 171
172 172 Returns 0 if all files are successfully added.
173 173 """
174 174
175 175 m = scmutil.match(repo[None], pats, opts)
176 176 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
177 177 opts.get('subrepos'), prefix="", explicitonly=False)
178 178 return rejected and 1 or 0
179 179
180 180 @command('addremove',
181 181 similarityopts + walkopts + dryrunopts,
182 182 _('[OPTION]... [FILE]...'))
183 183 def addremove(ui, repo, *pats, **opts):
184 184 """add all new files, delete all missing files
185 185
186 186 Add all new files and remove all missing files from the
187 187 repository.
188 188
189 189 New files are ignored if they match any of the patterns in
190 190 ``.hgignore``. As with add, these changes take effect at the next
191 191 commit.
192 192
193 193 Use the -s/--similarity option to detect renamed files. This
194 194 option takes a percentage between 0 (disabled) and 100 (files must
195 195 be identical) as its parameter. With a parameter greater than 0,
196 196 this compares every removed file with every added file and records
197 197 those similar enough as renames. Detecting renamed files this way
198 198 can be expensive. After using this option, :hg:`status -C` can be
199 199 used to check which files were identified as moved or renamed. If
200 200 not specified, -s/--similarity defaults to 100 and only renames of
201 201 identical files are detected.
202 202
203 203 Returns 0 if all files are successfully added.
204 204 """
205 205 try:
206 206 sim = float(opts.get('similarity') or 100)
207 207 except ValueError:
208 208 raise util.Abort(_('similarity must be a number'))
209 209 if sim < 0 or sim > 100:
210 210 raise util.Abort(_('similarity must be between 0 and 100'))
211 211 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
212 212
213 213 @command('^annotate|blame',
214 214 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
215 215 ('', 'follow', None,
216 216 _('follow copies/renames and list the filename (DEPRECATED)')),
217 217 ('', 'no-follow', None, _("don't follow copies and renames")),
218 218 ('a', 'text', None, _('treat all files as text')),
219 219 ('u', 'user', None, _('list the author (long with -v)')),
220 220 ('f', 'file', None, _('list the filename')),
221 221 ('d', 'date', None, _('list the date (short with -q)')),
222 222 ('n', 'number', None, _('list the revision number (default)')),
223 223 ('c', 'changeset', None, _('list the changeset')),
224 224 ('l', 'line-number', None, _('show line number at the first appearance'))
225 225 ] + diffwsopts + walkopts,
226 226 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
227 227 def annotate(ui, repo, *pats, **opts):
228 228 """show changeset information by line for each file
229 229
230 230 List changes in files, showing the revision id responsible for
231 231 each line
232 232
233 233 This command is useful for discovering when a change was made and
234 234 by whom.
235 235
236 236 Without the -a/--text option, annotate will avoid processing files
237 237 it detects as binary. With -a, annotate will annotate the file
238 238 anyway, although the results will probably be neither useful
239 239 nor desirable.
240 240
241 241 Returns 0 on success.
242 242 """
243 243 if opts.get('follow'):
244 244 # --follow is deprecated and now just an alias for -f/--file
245 245 # to mimic the behavior of Mercurial before version 1.5
246 246 opts['file'] = True
247 247
248 248 datefunc = ui.quiet and util.shortdate or util.datestr
249 249 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
250 250
251 251 if not pats:
252 252 raise util.Abort(_('at least one filename or pattern is required'))
253 253
254 254 hexfn = ui.debugflag and hex or short
255 255
256 256 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
257 257 ('number', ' ', lambda x: str(x[0].rev())),
258 258 ('changeset', ' ', lambda x: hexfn(x[0].node())),
259 259 ('date', ' ', getdate),
260 260 ('file', ' ', lambda x: x[0].path()),
261 261 ('line_number', ':', lambda x: str(x[1])),
262 262 ]
263 263
264 264 if (not opts.get('user') and not opts.get('changeset')
265 265 and not opts.get('date') and not opts.get('file')):
266 266 opts['number'] = True
267 267
268 268 linenumber = opts.get('line_number') is not None
269 269 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
270 270 raise util.Abort(_('at least one of -n/-c is required for -l'))
271 271
272 272 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
273 273 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
274 274
275 275 def bad(x, y):
276 276 raise util.Abort("%s: %s" % (x, y))
277 277
278 278 ctx = scmutil.revsingle(repo, opts.get('rev'))
279 279 m = scmutil.match(ctx, pats, opts)
280 280 m.bad = bad
281 281 follow = not opts.get('no_follow')
282 282 diffopts = patch.diffopts(ui, opts, section='annotate')
283 283 for abs in ctx.walk(m):
284 284 fctx = ctx[abs]
285 285 if not opts.get('text') and util.binary(fctx.data()):
286 286 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
287 287 continue
288 288
289 289 lines = fctx.annotate(follow=follow, linenumber=linenumber,
290 290 diffopts=diffopts)
291 291 pieces = []
292 292
293 293 for f, sep in funcmap:
294 294 l = [f(n) for n, dummy in lines]
295 295 if l:
296 296 sized = [(x, encoding.colwidth(x)) for x in l]
297 297 ml = max([w for x, w in sized])
298 298 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
299 299 for x, w in sized])
300 300
301 301 if pieces:
302 302 for p, l in zip(zip(*pieces), lines):
303 303 ui.write("%s: %s" % ("".join(p), l[1]))
304 304
305 305 if lines and not lines[-1][1].endswith('\n'):
306 306 ui.write('\n')
307 307
308 308 @command('archive',
309 309 [('', 'no-decode', None, _('do not pass files through decoders')),
310 310 ('p', 'prefix', '', _('directory prefix for files in archive'),
311 311 _('PREFIX')),
312 312 ('r', 'rev', '', _('revision to distribute'), _('REV')),
313 313 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
314 314 ] + subrepoopts + walkopts,
315 315 _('[OPTION]... DEST'))
316 316 def archive(ui, repo, dest, **opts):
317 317 '''create an unversioned archive of a repository revision
318 318
319 319 By default, the revision used is the parent of the working
320 320 directory; use -r/--rev to specify a different revision.
321 321
322 322 The archive type is automatically detected based on file
323 323 extension (or override using -t/--type).
324 324
325 325 .. container:: verbose
326 326
327 327 Examples:
328 328
329 329 - create a zip file containing the 1.0 release::
330 330
331 331 hg archive -r 1.0 project-1.0.zip
332 332
333 333 - create a tarball excluding .hg files::
334 334
335 335 hg archive project.tar.gz -X ".hg*"
336 336
337 337 Valid types are:
338 338
339 339 :``files``: a directory full of files (default)
340 340 :``tar``: tar archive, uncompressed
341 341 :``tbz2``: tar archive, compressed using bzip2
342 342 :``tgz``: tar archive, compressed using gzip
343 343 :``uzip``: zip archive, uncompressed
344 344 :``zip``: zip archive, compressed using deflate
345 345
346 346 The exact name of the destination archive or directory is given
347 347 using a format string; see :hg:`help export` for details.
348 348
349 349 Each member added to an archive file has a directory prefix
350 350 prepended. Use -p/--prefix to specify a format string for the
351 351 prefix. The default is the basename of the archive, with suffixes
352 352 removed.
353 353
354 354 Returns 0 on success.
355 355 '''
356 356
357 357 ctx = scmutil.revsingle(repo, opts.get('rev'))
358 358 if not ctx:
359 359 raise util.Abort(_('no working directory: please specify a revision'))
360 360 node = ctx.node()
361 361 dest = cmdutil.makefilename(repo, dest, node)
362 362 if os.path.realpath(dest) == repo.root:
363 363 raise util.Abort(_('repository root cannot be destination'))
364 364
365 365 kind = opts.get('type') or archival.guesskind(dest) or 'files'
366 366 prefix = opts.get('prefix')
367 367
368 368 if dest == '-':
369 369 if kind == 'files':
370 370 raise util.Abort(_('cannot archive plain files to stdout'))
371 371 dest = cmdutil.makefileobj(repo, dest)
372 372 if not prefix:
373 373 prefix = os.path.basename(repo.root) + '-%h'
374 374
375 375 prefix = cmdutil.makefilename(repo, prefix, node)
376 376 matchfn = scmutil.match(ctx, [], opts)
377 377 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
378 378 matchfn, prefix, subrepos=opts.get('subrepos'))
379 379
380 380 @command('backout',
381 381 [('', 'merge', None, _('merge with old dirstate parent after backout')),
382 382 ('', 'parent', '',
383 383 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
384 384 ('r', 'rev', '', _('revision to backout'), _('REV')),
385 385 ] + mergetoolopts + walkopts + commitopts + commitopts2,
386 386 _('[OPTION]... [-r] REV'))
387 387 def backout(ui, repo, node=None, rev=None, **opts):
388 388 '''reverse effect of earlier changeset
389 389
390 390 Prepare a new changeset with the effect of REV undone in the
391 391 current working directory.
392 392
393 393 If REV is the parent of the working directory, then this new changeset
394 394 is committed automatically. Otherwise, hg needs to merge the
395 395 changes and the merged result is left uncommitted.
396 396
397 397 .. note::
398 398 backout cannot be used to fix either an unwanted or
399 399 incorrect merge.
400 400
401 401 .. container:: verbose
402 402
403 403 By default, the pending changeset will have one parent,
404 404 maintaining a linear history. With --merge, the pending
405 405 changeset will instead have two parents: the old parent of the
406 406 working directory and a new child of REV that simply undoes REV.
407 407
408 408 Before version 1.7, the behavior without --merge was equivalent
409 409 to specifying --merge followed by :hg:`update --clean .` to
410 410 cancel the merge and leave the child of REV as a head to be
411 411 merged separately.
412 412
413 413 See :hg:`help dates` for a list of formats valid for -d/--date.
414 414
415 415 Returns 0 on success.
416 416 '''
417 417 if rev and node:
418 418 raise util.Abort(_("please specify just one revision"))
419 419
420 420 if not rev:
421 421 rev = node
422 422
423 423 if not rev:
424 424 raise util.Abort(_("please specify a revision to backout"))
425 425
426 426 date = opts.get('date')
427 427 if date:
428 428 opts['date'] = util.parsedate(date)
429 429
430 430 cmdutil.bailifchanged(repo)
431 431 node = scmutil.revsingle(repo, rev).node()
432 432
433 433 op1, op2 = repo.dirstate.parents()
434 434 a = repo.changelog.ancestor(op1, node)
435 435 if a != node:
436 436 raise util.Abort(_('cannot backout change on a different branch'))
437 437
438 438 p1, p2 = repo.changelog.parents(node)
439 439 if p1 == nullid:
440 440 raise util.Abort(_('cannot backout a change with no parents'))
441 441 if p2 != nullid:
442 442 if not opts.get('parent'):
443 443 raise util.Abort(_('cannot backout a merge changeset'))
444 444 p = repo.lookup(opts['parent'])
445 445 if p not in (p1, p2):
446 446 raise util.Abort(_('%s is not a parent of %s') %
447 447 (short(p), short(node)))
448 448 parent = p
449 449 else:
450 450 if opts.get('parent'):
451 451 raise util.Abort(_('cannot use --parent on non-merge changeset'))
452 452 parent = p1
453 453
454 454 # the backout should appear on the same branch
455 455 wlock = repo.wlock()
456 456 try:
457 457 branch = repo.dirstate.branch()
458 458 hg.clean(repo, node, show_stats=False)
459 459 repo.dirstate.setbranch(branch)
460 460 revert_opts = opts.copy()
461 461 revert_opts['date'] = None
462 462 revert_opts['all'] = True
463 463 revert_opts['rev'] = hex(parent)
464 464 revert_opts['no_backup'] = None
465 465 revert(ui, repo, **revert_opts)
466 466 if not opts.get('merge') and op1 != node:
467 467 try:
468 468 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
469 469 return hg.update(repo, op1)
470 470 finally:
471 471 ui.setconfig('ui', 'forcemerge', '')
472 472
473 473 commit_opts = opts.copy()
474 474 commit_opts['addremove'] = False
475 475 if not commit_opts['message'] and not commit_opts['logfile']:
476 476 # we don't translate commit messages
477 477 commit_opts['message'] = "Backed out changeset %s" % short(node)
478 478 commit_opts['force_editor'] = True
479 479 commit(ui, repo, **commit_opts)
480 480 def nice(node):
481 481 return '%d:%s' % (repo.changelog.rev(node), short(node))
482 482 ui.status(_('changeset %s backs out changeset %s\n') %
483 483 (nice(repo.changelog.tip()), nice(node)))
484 484 if opts.get('merge') and op1 != node:
485 485 hg.clean(repo, op1, show_stats=False)
486 486 ui.status(_('merging with changeset %s\n')
487 487 % nice(repo.changelog.tip()))
488 488 try:
489 489 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
490 490 return hg.merge(repo, hex(repo.changelog.tip()))
491 491 finally:
492 492 ui.setconfig('ui', 'forcemerge', '')
493 493 finally:
494 494 wlock.release()
495 495 return 0
496 496
497 497 @command('bisect',
498 498 [('r', 'reset', False, _('reset bisect state')),
499 499 ('g', 'good', False, _('mark changeset good')),
500 500 ('b', 'bad', False, _('mark changeset bad')),
501 501 ('s', 'skip', False, _('skip testing changeset')),
502 502 ('e', 'extend', False, _('extend the bisect range')),
503 503 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
504 504 ('U', 'noupdate', False, _('do not update to target'))],
505 505 _("[-gbsr] [-U] [-c CMD] [REV]"))
506 506 def bisect(ui, repo, rev=None, extra=None, command=None,
507 507 reset=None, good=None, bad=None, skip=None, extend=None,
508 508 noupdate=None):
509 509 """subdivision search of changesets
510 510
511 511 This command helps to find changesets which introduce problems. To
512 512 use, mark the earliest changeset you know exhibits the problem as
513 513 bad, then mark the latest changeset which is free from the problem
514 514 as good. Bisect will update your working directory to a revision
515 515 for testing (unless the -U/--noupdate option is specified). Once
516 516 you have performed tests, mark the working directory as good or
517 517 bad, and bisect will either update to another candidate changeset
518 518 or announce that it has found the bad revision.
519 519
520 520 As a shortcut, you can also use the revision argument to mark a
521 521 revision as good or bad without checking it out first.
522 522
523 523 If you supply a command, it will be used for automatic bisection.
524 524 The environment variable HG_NODE will contain the ID of the
525 525 changeset being tested. The exit status of the command will be
526 526 used to mark revisions as good or bad: status 0 means good, 125
527 527 means to skip the revision, 127 (command not found) will abort the
528 528 bisection, and any other non-zero exit status means the revision
529 529 is bad.
530 530
531 531 .. container:: verbose
532 532
533 533 Some examples:
534 534
535 535 - start a bisection with known bad revision 12, and good revision 34::
536 536
537 537 hg bisect --bad 34
538 538 hg bisect --good 12
539 539
540 540 - advance the current bisection by marking current revision as good or
541 541 bad::
542 542
543 543 hg bisect --good
544 544 hg bisect --bad
545 545
546 546 - mark the current revision, or a known revision, to be skipped (e.g. if
547 547 that revision is not usable because of another issue)::
548 548
549 549 hg bisect --skip
550 550 hg bisect --skip 23
551 551
552 552 - skip all revisions that do not touch directories ``foo`` or ``bar``
553 553
554 554 hg bisect --skip '!( file("path:foo") & file("path:bar") )'
555 555
556 556 - forget the current bisection::
557 557
558 558 hg bisect --reset
559 559
560 560 - use 'make && make tests' to automatically find the first broken
561 561 revision::
562 562
563 563 hg bisect --reset
564 564 hg bisect --bad 34
565 565 hg bisect --good 12
566 566 hg bisect --command 'make && make tests'
567 567
568 568 - see all changesets whose states are already known in the current
569 569 bisection::
570 570
571 571 hg log -r "bisect(pruned)"
572 572
573 573 - see the changeset currently being bisected (especially useful
574 574 if running with -U/--noupdate)::
575 575
576 576 hg log -r "bisect(current)"
577 577
578 578 - see all changesets that took part in the current bisection::
579 579
580 580 hg log -r "bisect(range)"
581 581
582 582 - with the graphlog extension, you can even get a nice graph::
583 583
584 584 hg log --graph -r "bisect(range)"
585 585
586 586 See :hg:`help revsets` for more about the `bisect()` keyword.
587 587
588 588 Returns 0 on success.
589 589 """
590 590 def extendbisectrange(nodes, good):
591 591 # bisect is incomplete when it ends on a merge node and
592 592 # one of the parent was not checked.
593 593 parents = repo[nodes[0]].parents()
594 594 if len(parents) > 1:
595 595 side = good and state['bad'] or state['good']
596 596 num = len(set(i.node() for i in parents) & set(side))
597 597 if num == 1:
598 598 return parents[0].ancestor(parents[1])
599 599 return None
600 600
601 601 def print_result(nodes, good):
602 602 displayer = cmdutil.show_changeset(ui, repo, {})
603 603 if len(nodes) == 1:
604 604 # narrowed it down to a single revision
605 605 if good:
606 606 ui.write(_("The first good revision is:\n"))
607 607 else:
608 608 ui.write(_("The first bad revision is:\n"))
609 609 displayer.show(repo[nodes[0]])
610 610 extendnode = extendbisectrange(nodes, good)
611 611 if extendnode is not None:
612 612 ui.write(_('Not all ancestors of this changeset have been'
613 613 ' checked.\nUse bisect --extend to continue the '
614 614 'bisection from\nthe common ancestor, %s.\n')
615 615 % extendnode)
616 616 else:
617 617 # multiple possible revisions
618 618 if good:
619 619 ui.write(_("Due to skipped revisions, the first "
620 620 "good revision could be any of:\n"))
621 621 else:
622 622 ui.write(_("Due to skipped revisions, the first "
623 623 "bad revision could be any of:\n"))
624 624 for n in nodes:
625 625 displayer.show(repo[n])
626 626 displayer.close()
627 627
628 628 def check_state(state, interactive=True):
629 629 if not state['good'] or not state['bad']:
630 630 if (good or bad or skip or reset) and interactive:
631 631 return
632 632 if not state['good']:
633 633 raise util.Abort(_('cannot bisect (no known good revisions)'))
634 634 else:
635 635 raise util.Abort(_('cannot bisect (no known bad revisions)'))
636 636 return True
637 637
638 638 # backward compatibility
639 639 if rev in "good bad reset init".split():
640 640 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
641 641 cmd, rev, extra = rev, extra, None
642 642 if cmd == "good":
643 643 good = True
644 644 elif cmd == "bad":
645 645 bad = True
646 646 else:
647 647 reset = True
648 648 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
649 649 raise util.Abort(_('incompatible arguments'))
650 650
651 651 if reset:
652 652 p = repo.join("bisect.state")
653 653 if os.path.exists(p):
654 654 os.unlink(p)
655 655 return
656 656
657 657 state = hbisect.load_state(repo)
658 658
659 659 if command:
660 660 changesets = 1
661 661 try:
662 662 node = state['current'][0]
663 663 except LookupError:
664 664 if noupdate:
665 665 raise util.Abort(_('current bisect revision is unknown - '
666 666 'start a new bisect to fix'))
667 667 node, p2 = repo.dirstate.parents()
668 668 if p2 != nullid:
669 669 raise util.Abort(_('current bisect revision is a merge'))
670 670 try:
671 671 while changesets:
672 672 # update state
673 673 state['current'] = [node]
674 674 hbisect.save_state(repo, state)
675 675 status = util.system(command,
676 676 environ={'HG_NODE': hex(node)},
677 677 out=ui.fout)
678 678 if status == 125:
679 679 transition = "skip"
680 680 elif status == 0:
681 681 transition = "good"
682 682 # status < 0 means process was killed
683 683 elif status == 127:
684 684 raise util.Abort(_("failed to execute %s") % command)
685 685 elif status < 0:
686 686 raise util.Abort(_("%s killed") % command)
687 687 else:
688 688 transition = "bad"
689 689 ctx = scmutil.revsingle(repo, rev, node)
690 690 rev = None # clear for future iterations
691 691 state[transition].append(ctx.node())
692 692 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
693 693 check_state(state, interactive=False)
694 694 # bisect
695 695 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
696 696 # update to next check
697 697 node = nodes[0]
698 698 if not noupdate:
699 699 cmdutil.bailifchanged(repo)
700 700 hg.clean(repo, node, show_stats=False)
701 701 finally:
702 702 state['current'] = [node]
703 703 hbisect.save_state(repo, state)
704 704 print_result(nodes, good)
705 705 return
706 706
707 707 # update state
708 708
709 709 if rev:
710 710 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
711 711 else:
712 712 nodes = [repo.lookup('.')]
713 713
714 714 if good or bad or skip:
715 715 if good:
716 716 state['good'] += nodes
717 717 elif bad:
718 718 state['bad'] += nodes
719 719 elif skip:
720 720 state['skip'] += nodes
721 721 hbisect.save_state(repo, state)
722 722
723 723 if not check_state(state):
724 724 return
725 725
726 726 # actually bisect
727 727 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
728 728 if extend:
729 729 if not changesets:
730 730 extendnode = extendbisectrange(nodes, good)
731 731 if extendnode is not None:
732 732 ui.write(_("Extending search to changeset %d:%s\n"
733 733 % (extendnode.rev(), extendnode)))
734 734 state['current'] = [extendnode.node()]
735 735 hbisect.save_state(repo, state)
736 736 if noupdate:
737 737 return
738 738 cmdutil.bailifchanged(repo)
739 739 return hg.clean(repo, extendnode.node())
740 740 raise util.Abort(_("nothing to extend"))
741 741
742 742 if changesets == 0:
743 743 print_result(nodes, good)
744 744 else:
745 745 assert len(nodes) == 1 # only a single node can be tested next
746 746 node = nodes[0]
747 747 # compute the approximate number of remaining tests
748 748 tests, size = 0, 2
749 749 while size <= changesets:
750 750 tests, size = tests + 1, size * 2
751 751 rev = repo.changelog.rev(node)
752 752 ui.write(_("Testing changeset %d:%s "
753 753 "(%d changesets remaining, ~%d tests)\n")
754 754 % (rev, short(node), changesets, tests))
755 755 state['current'] = [node]
756 756 hbisect.save_state(repo, state)
757 757 if not noupdate:
758 758 cmdutil.bailifchanged(repo)
759 759 return hg.clean(repo, node)
760 760
761 761 @command('bookmarks',
762 762 [('f', 'force', False, _('force')),
763 763 ('r', 'rev', '', _('revision'), _('REV')),
764 764 ('d', 'delete', False, _('delete a given bookmark')),
765 765 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
766 766 ('i', 'inactive', False, _('mark a bookmark inactive'))],
767 767 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
768 768 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
769 769 rename=None, inactive=False):
770 770 '''track a line of development with movable markers
771 771
772 772 Bookmarks are pointers to certain commits that move when committing.
773 773 Bookmarks are local. They can be renamed, copied and deleted. It is
774 774 possible to use :hg:`merge NAME` to merge from a given bookmark, and
775 775 :hg:`update NAME` to update to a given bookmark.
776 776
777 777 You can use :hg:`bookmark NAME` to set a bookmark on the working
778 778 directory's parent revision with the given name. If you specify
779 779 a revision using -r REV (where REV may be an existing bookmark),
780 780 the bookmark is assigned to that revision.
781 781
782 782 Bookmarks can be pushed and pulled between repositories (see :hg:`help
783 783 push` and :hg:`help pull`). This requires both the local and remote
784 784 repositories to support bookmarks. For versions prior to 1.8, this means
785 785 the bookmarks extension must be enabled.
786 786
787 787 With -i/--inactive, the new bookmark will not be made the active
788 788 bookmark. If -r/--rev is given, the new bookmark will not be made
789 789 active even if -i/--inactive is not given. If no NAME is given, the
790 790 current active bookmark will be marked inactive.
791 791 '''
792 792 hexfn = ui.debugflag and hex or short
793 793 marks = repo._bookmarks
794 794 cur = repo.changectx('.').node()
795 795
796 796 def checkformat(mark):
797 797 mark = mark.strip()
798 798 if not mark:
799 799 raise util.Abort(_("bookmark names cannot consist entirely of "
800 800 "whitespace"))
801 801 scmutil.checknewlabel(repo, mark, 'bookmark')
802 802 return mark
803 803
804 804 def checkconflict(repo, mark, force=False):
805 805 if mark in marks and not force:
806 806 raise util.Abort(_("bookmark '%s' already exists "
807 807 "(use -f to force)") % mark)
808 808 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
809 809 and not force):
810 810 raise util.Abort(
811 811 _("a bookmark cannot have the name of an existing branch"))
812 812
813 813 if delete and rename:
814 814 raise util.Abort(_("--delete and --rename are incompatible"))
815 815 if delete and rev:
816 816 raise util.Abort(_("--rev is incompatible with --delete"))
817 817 if rename and rev:
818 818 raise util.Abort(_("--rev is incompatible with --rename"))
819 819 if mark is None and (delete or rev):
820 820 raise util.Abort(_("bookmark name required"))
821 821
822 822 if delete:
823 823 if mark not in marks:
824 824 raise util.Abort(_("bookmark '%s' does not exist") % mark)
825 825 if mark == repo._bookmarkcurrent:
826 826 bookmarks.setcurrent(repo, None)
827 827 del marks[mark]
828 828 marks.write()
829 829
830 830 elif rename:
831 831 if mark is None:
832 832 raise util.Abort(_("new bookmark name required"))
833 833 mark = checkformat(mark)
834 834 if rename not in marks:
835 835 raise util.Abort(_("bookmark '%s' does not exist") % rename)
836 836 checkconflict(repo, mark, force)
837 837 marks[mark] = marks[rename]
838 838 if repo._bookmarkcurrent == rename and not inactive:
839 839 bookmarks.setcurrent(repo, mark)
840 840 del marks[rename]
841 841 marks.write()
842 842
843 843 elif mark is not None:
844 844 mark = checkformat(mark)
845 845 if inactive and mark == repo._bookmarkcurrent:
846 846 bookmarks.setcurrent(repo, None)
847 847 return
848 848 checkconflict(repo, mark, force)
849 849 if rev:
850 850 marks[mark] = scmutil.revsingle(repo, rev).node()
851 851 else:
852 852 marks[mark] = cur
853 853 if not inactive and cur == marks[mark]:
854 854 bookmarks.setcurrent(repo, mark)
855 855 marks.write()
856 856
857 857 # Same message whether trying to deactivate the current bookmark (-i
858 858 # with no NAME) or listing bookmarks
859 859 elif len(marks) == 0:
860 860 ui.status(_("no bookmarks set\n"))
861 861
862 862 elif inactive:
863 863 if not repo._bookmarkcurrent:
864 864 ui.status(_("no active bookmark\n"))
865 865 else:
866 866 bookmarks.setcurrent(repo, None)
867 867
868 868 else: # show bookmarks
869 869 for bmark, n in sorted(marks.iteritems()):
870 870 current = repo._bookmarkcurrent
871 871 if bmark == current and n == cur:
872 872 prefix, label = '*', 'bookmarks.current'
873 873 else:
874 874 prefix, label = ' ', ''
875 875
876 876 if ui.quiet:
877 877 ui.write("%s\n" % bmark, label=label)
878 878 else:
879 879 ui.write(" %s %-25s %d:%s\n" % (
880 880 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
881 881 label=label)
882 882
883 883 @command('branch',
884 884 [('f', 'force', None,
885 885 _('set branch name even if it shadows an existing branch')),
886 886 ('C', 'clean', None, _('reset branch name to parent branch name'))],
887 887 _('[-fC] [NAME]'))
888 888 def branch(ui, repo, label=None, **opts):
889 889 """set or show the current branch name
890 890
891 891 .. note::
892 892 Branch names are permanent and global. Use :hg:`bookmark` to create a
893 893 light-weight bookmark instead. See :hg:`help glossary` for more
894 894 information about named branches and bookmarks.
895 895
896 896 With no argument, show the current branch name. With one argument,
897 897 set the working directory branch name (the branch will not exist
898 898 in the repository until the next commit). Standard practice
899 899 recommends that primary development take place on the 'default'
900 900 branch.
901 901
902 902 Unless -f/--force is specified, branch will not let you set a
903 903 branch name that already exists, even if it's inactive.
904 904
905 905 Use -C/--clean to reset the working directory branch to that of
906 906 the parent of the working directory, negating a previous branch
907 907 change.
908 908
909 909 Use the command :hg:`update` to switch to an existing branch. Use
910 910 :hg:`commit --close-branch` to mark this branch as closed.
911 911
912 912 Returns 0 on success.
913 913 """
914 914 if not opts.get('clean') and not label:
915 915 ui.write("%s\n" % repo.dirstate.branch())
916 916 return
917 917
918 918 wlock = repo.wlock()
919 919 try:
920 920 if opts.get('clean'):
921 921 label = repo[None].p1().branch()
922 922 repo.dirstate.setbranch(label)
923 923 ui.status(_('reset working directory to branch %s\n') % label)
924 924 elif label:
925 925 if not opts.get('force') and label in repo.branchmap():
926 926 if label not in [p.branch() for p in repo.parents()]:
927 927 raise util.Abort(_('a branch of the same name already'
928 928 ' exists'),
929 929 # i18n: "it" refers to an existing branch
930 930 hint=_("use 'hg update' to switch to it"))
931 931 scmutil.checknewlabel(repo, label, 'branch')
932 932 repo.dirstate.setbranch(label)
933 933 ui.status(_('marked working directory as branch %s\n') % label)
934 934 ui.status(_('(branches are permanent and global, '
935 935 'did you want a bookmark?)\n'))
936 936 finally:
937 937 wlock.release()
938 938
939 939 @command('branches',
940 940 [('a', 'active', False, _('show only branches that have unmerged heads')),
941 941 ('c', 'closed', False, _('show normal and closed branches'))],
942 942 _('[-ac]'))
943 943 def branches(ui, repo, active=False, closed=False):
944 944 """list repository named branches
945 945
946 946 List the repository's named branches, indicating which ones are
947 947 inactive. If -c/--closed is specified, also list branches which have
948 948 been marked closed (see :hg:`commit --close-branch`).
949 949
950 950 If -a/--active is specified, only show active branches. A branch
951 951 is considered active if it contains repository heads.
952 952
953 953 Use the command :hg:`update` to switch to an existing branch.
954 954
955 955 Returns 0.
956 956 """
957 957
958 958 hexfunc = ui.debugflag and hex or short
959 959
960 960 activebranches = set([repo[n].branch() for n in repo.heads()])
961 961 branches = []
962 962 for tag, heads in repo.branchmap().iteritems():
963 963 for h in reversed(heads):
964 964 ctx = repo[h]
965 965 isopen = not ctx.closesbranch()
966 966 if isopen:
967 967 tip = ctx
968 968 break
969 969 else:
970 970 tip = repo[heads[-1]]
971 971 isactive = tag in activebranches and isopen
972 972 branches.append((tip, isactive, isopen))
973 973 branches.sort(key=lambda i: (i[1], i[0].rev(), i[0].branch(), i[2]),
974 974 reverse=True)
975 975
976 976 for ctx, isactive, isopen in branches:
977 977 if (not active) or isactive:
978 978 if isactive:
979 979 label = 'branches.active'
980 980 notice = ''
981 981 elif not isopen:
982 982 if not closed:
983 983 continue
984 984 label = 'branches.closed'
985 985 notice = _(' (closed)')
986 986 else:
987 987 label = 'branches.inactive'
988 988 notice = _(' (inactive)')
989 989 if ctx.branch() == repo.dirstate.branch():
990 990 label = 'branches.current'
991 991 rev = str(ctx.rev()).rjust(31 - encoding.colwidth(ctx.branch()))
992 992 rev = ui.label('%s:%s' % (rev, hexfunc(ctx.node())),
993 993 'log.changeset changeset.%s' % ctx.phasestr())
994 994 tag = ui.label(ctx.branch(), label)
995 995 if ui.quiet:
996 996 ui.write("%s\n" % tag)
997 997 else:
998 998 ui.write("%s %s%s\n" % (tag, rev, notice))
999 999
1000 1000 @command('bundle',
1001 1001 [('f', 'force', None, _('run even when the destination is unrelated')),
1002 1002 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1003 1003 _('REV')),
1004 1004 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1005 1005 _('BRANCH')),
1006 1006 ('', 'base', [],
1007 1007 _('a base changeset assumed to be available at the destination'),
1008 1008 _('REV')),
1009 1009 ('a', 'all', None, _('bundle all changesets in the repository')),
1010 1010 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1011 1011 ] + remoteopts,
1012 1012 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1013 1013 def bundle(ui, repo, fname, dest=None, **opts):
1014 1014 """create a changegroup file
1015 1015
1016 1016 Generate a compressed changegroup file collecting changesets not
1017 1017 known to be in another repository.
1018 1018
1019 1019 If you omit the destination repository, then hg assumes the
1020 1020 destination will have all the nodes you specify with --base
1021 1021 parameters. To create a bundle containing all changesets, use
1022 1022 -a/--all (or --base null).
1023 1023
1024 1024 You can change compression method with the -t/--type option.
1025 1025 The available compression methods are: none, bzip2, and
1026 1026 gzip (by default, bundles are compressed using bzip2).
1027 1027
1028 1028 The bundle file can then be transferred using conventional means
1029 1029 and applied to another repository with the unbundle or pull
1030 1030 command. This is useful when direct push and pull are not
1031 1031 available or when exporting an entire repository is undesirable.
1032 1032
1033 1033 Applying bundles preserves all changeset contents including
1034 1034 permissions, copy/rename information, and revision history.
1035 1035
1036 1036 Returns 0 on success, 1 if no changes found.
1037 1037 """
1038 1038 revs = None
1039 1039 if 'rev' in opts:
1040 1040 revs = scmutil.revrange(repo, opts['rev'])
1041 1041
1042 1042 bundletype = opts.get('type', 'bzip2').lower()
1043 1043 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1044 1044 bundletype = btypes.get(bundletype)
1045 1045 if bundletype not in changegroup.bundletypes:
1046 1046 raise util.Abort(_('unknown bundle type specified with --type'))
1047 1047
1048 1048 if opts.get('all'):
1049 1049 base = ['null']
1050 1050 else:
1051 1051 base = scmutil.revrange(repo, opts.get('base'))
1052 1052 if base:
1053 1053 if dest:
1054 1054 raise util.Abort(_("--base is incompatible with specifying "
1055 1055 "a destination"))
1056 1056 common = [repo.lookup(rev) for rev in base]
1057 1057 heads = revs and map(repo.lookup, revs) or revs
1058 1058 cg = repo.getbundle('bundle', heads=heads, common=common)
1059 1059 outgoing = None
1060 1060 else:
1061 1061 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1062 1062 dest, branches = hg.parseurl(dest, opts.get('branch'))
1063 1063 other = hg.peer(repo, opts, dest)
1064 1064 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
1065 1065 heads = revs and map(repo.lookup, revs) or revs
1066 1066 outgoing = discovery.findcommonoutgoing(repo, other,
1067 1067 onlyheads=heads,
1068 1068 force=opts.get('force'),
1069 1069 portable=True)
1070 1070 cg = repo.getlocalbundle('bundle', outgoing)
1071 1071 if not cg:
1072 1072 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1073 1073 return 1
1074 1074
1075 1075 changegroup.writebundle(cg, fname, bundletype)
1076 1076
1077 1077 @command('cat',
1078 1078 [('o', 'output', '',
1079 1079 _('print output to file with formatted name'), _('FORMAT')),
1080 1080 ('r', 'rev', '', _('print the given revision'), _('REV')),
1081 1081 ('', 'decode', None, _('apply any matching decode filter')),
1082 1082 ] + walkopts,
1083 1083 _('[OPTION]... FILE...'))
1084 1084 def cat(ui, repo, file1, *pats, **opts):
1085 1085 """output the current or given revision of files
1086 1086
1087 1087 Print the specified files as they were at the given revision. If
1088 1088 no revision is given, the parent of the working directory is used,
1089 1089 or tip if no revision is checked out.
1090 1090
1091 1091 Output may be to a file, in which case the name of the file is
1092 1092 given using a format string. The formatting rules are the same as
1093 1093 for the export command, with the following additions:
1094 1094
1095 1095 :``%s``: basename of file being printed
1096 1096 :``%d``: dirname of file being printed, or '.' if in repository root
1097 1097 :``%p``: root-relative path name of file being printed
1098 1098
1099 1099 Returns 0 on success.
1100 1100 """
1101 1101 ctx = scmutil.revsingle(repo, opts.get('rev'))
1102 1102 err = 1
1103 1103 m = scmutil.match(ctx, (file1,) + pats, opts)
1104 1104 for abs in ctx.walk(m):
1105 1105 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1106 1106 pathname=abs)
1107 1107 data = ctx[abs].data()
1108 1108 if opts.get('decode'):
1109 1109 data = repo.wwritedata(abs, data)
1110 1110 fp.write(data)
1111 1111 fp.close()
1112 1112 err = 0
1113 1113 return err
1114 1114
1115 1115 @command('^clone',
1116 1116 [('U', 'noupdate', None,
1117 1117 _('the clone will include an empty working copy (only a repository)')),
1118 1118 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1119 1119 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1120 1120 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1121 1121 ('', 'pull', None, _('use pull protocol to copy metadata')),
1122 1122 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1123 1123 ] + remoteopts,
1124 1124 _('[OPTION]... SOURCE [DEST]'))
1125 1125 def clone(ui, source, dest=None, **opts):
1126 1126 """make a copy of an existing repository
1127 1127
1128 1128 Create a copy of an existing repository in a new directory.
1129 1129
1130 1130 If no destination directory name is specified, it defaults to the
1131 1131 basename of the source.
1132 1132
1133 1133 The location of the source is added to the new repository's
1134 1134 ``.hg/hgrc`` file, as the default to be used for future pulls.
1135 1135
1136 1136 Only local paths and ``ssh://`` URLs are supported as
1137 1137 destinations. For ``ssh://`` destinations, no working directory or
1138 1138 ``.hg/hgrc`` will be created on the remote side.
1139 1139
1140 1140 To pull only a subset of changesets, specify one or more revisions
1141 1141 identifiers with -r/--rev or branches with -b/--branch. The
1142 1142 resulting clone will contain only the specified changesets and
1143 1143 their ancestors. These options (or 'clone src#rev dest') imply
1144 1144 --pull, even for local source repositories. Note that specifying a
1145 1145 tag will include the tagged changeset but not the changeset
1146 1146 containing the tag.
1147 1147
1148 1148 To check out a particular version, use -u/--update, or
1149 1149 -U/--noupdate to create a clone with no working directory.
1150 1150
1151 1151 .. container:: verbose
1152 1152
1153 1153 For efficiency, hardlinks are used for cloning whenever the
1154 1154 source and destination are on the same filesystem (note this
1155 1155 applies only to the repository data, not to the working
1156 1156 directory). Some filesystems, such as AFS, implement hardlinking
1157 1157 incorrectly, but do not report errors. In these cases, use the
1158 1158 --pull option to avoid hardlinking.
1159 1159
1160 1160 In some cases, you can clone repositories and the working
1161 1161 directory using full hardlinks with ::
1162 1162
1163 1163 $ cp -al REPO REPOCLONE
1164 1164
1165 1165 This is the fastest way to clone, but it is not always safe. The
1166 1166 operation is not atomic (making sure REPO is not modified during
1167 1167 the operation is up to you) and you have to make sure your
1168 1168 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1169 1169 so). Also, this is not compatible with certain extensions that
1170 1170 place their metadata under the .hg directory, such as mq.
1171 1171
1172 1172 Mercurial will update the working directory to the first applicable
1173 1173 revision from this list:
1174 1174
1175 1175 a) null if -U or the source repository has no changesets
1176 1176 b) if -u . and the source repository is local, the first parent of
1177 1177 the source repository's working directory
1178 1178 c) the changeset specified with -u (if a branch name, this means the
1179 1179 latest head of that branch)
1180 1180 d) the changeset specified with -r
1181 1181 e) the tipmost head specified with -b
1182 1182 f) the tipmost head specified with the url#branch source syntax
1183 1183 g) the tipmost head of the default branch
1184 1184 h) tip
1185 1185
1186 1186 Examples:
1187 1187
1188 1188 - clone a remote repository to a new directory named hg/::
1189 1189
1190 1190 hg clone http://selenic.com/hg
1191 1191
1192 1192 - create a lightweight local clone::
1193 1193
1194 1194 hg clone project/ project-feature/
1195 1195
1196 1196 - clone from an absolute path on an ssh server (note double-slash)::
1197 1197
1198 1198 hg clone ssh://user@server//home/projects/alpha/
1199 1199
1200 1200 - do a high-speed clone over a LAN while checking out a
1201 1201 specified version::
1202 1202
1203 1203 hg clone --uncompressed http://server/repo -u 1.5
1204 1204
1205 1205 - create a repository without changesets after a particular revision::
1206 1206
1207 1207 hg clone -r 04e544 experimental/ good/
1208 1208
1209 1209 - clone (and track) a particular named branch::
1210 1210
1211 1211 hg clone http://selenic.com/hg#stable
1212 1212
1213 1213 See :hg:`help urls` for details on specifying URLs.
1214 1214
1215 1215 Returns 0 on success.
1216 1216 """
1217 1217 if opts.get('noupdate') and opts.get('updaterev'):
1218 1218 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1219 1219
1220 1220 r = hg.clone(ui, opts, source, dest,
1221 1221 pull=opts.get('pull'),
1222 1222 stream=opts.get('uncompressed'),
1223 1223 rev=opts.get('rev'),
1224 1224 update=opts.get('updaterev') or not opts.get('noupdate'),
1225 1225 branch=opts.get('branch'))
1226 1226
1227 1227 return r is None
1228 1228
1229 1229 @command('^commit|ci',
1230 1230 [('A', 'addremove', None,
1231 1231 _('mark new/missing files as added/removed before committing')),
1232 1232 ('', 'close-branch', None,
1233 1233 _('mark a branch as closed, hiding it from the branch list')),
1234 1234 ('', 'amend', None, _('amend the parent of the working dir')),
1235 1235 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1236 1236 _('[OPTION]... [FILE]...'))
1237 1237 def commit(ui, repo, *pats, **opts):
1238 1238 """commit the specified files or all outstanding changes
1239 1239
1240 1240 Commit changes to the given files into the repository. Unlike a
1241 1241 centralized SCM, this operation is a local operation. See
1242 1242 :hg:`push` for a way to actively distribute your changes.
1243 1243
1244 1244 If a list of files is omitted, all changes reported by :hg:`status`
1245 1245 will be committed.
1246 1246
1247 1247 If you are committing the result of a merge, do not provide any
1248 1248 filenames or -I/-X filters.
1249 1249
1250 1250 If no commit message is specified, Mercurial starts your
1251 1251 configured editor where you can enter a message. In case your
1252 1252 commit fails, you will find a backup of your message in
1253 1253 ``.hg/last-message.txt``.
1254 1254
1255 1255 The --amend flag can be used to amend the parent of the
1256 1256 working directory with a new commit that contains the changes
1257 1257 in the parent in addition to those currently reported by :hg:`status`,
1258 1258 if there are any. The old commit is stored in a backup bundle in
1259 1259 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1260 1260 on how to restore it).
1261 1261
1262 1262 Message, user and date are taken from the amended commit unless
1263 1263 specified. When a message isn't specified on the command line,
1264 1264 the editor will open with the message of the amended commit.
1265 1265
1266 1266 It is not possible to amend public changesets (see :hg:`help phases`)
1267 1267 or changesets that have children.
1268 1268
1269 1269 See :hg:`help dates` for a list of formats valid for -d/--date.
1270 1270
1271 1271 Returns 0 on success, 1 if nothing changed.
1272 1272 """
1273 1273 if opts.get('subrepos'):
1274 1274 # Let --subrepos on the command line override config setting.
1275 1275 ui.setconfig('ui', 'commitsubrepos', True)
1276 1276
1277 1277 extra = {}
1278 1278 if opts.get('close_branch'):
1279 1279 if repo['.'].node() not in repo.branchheads():
1280 1280 # The topo heads set is included in the branch heads set of the
1281 1281 # current branch, so it's sufficient to test branchheads
1282 1282 raise util.Abort(_('can only close branch heads'))
1283 1283 extra['close'] = 1
1284 1284
1285 1285 branch = repo[None].branch()
1286 1286 bheads = repo.branchheads(branch)
1287 1287
1288 1288 if opts.get('amend'):
1289 1289 if ui.configbool('ui', 'commitsubrepos'):
1290 1290 raise util.Abort(_('cannot amend recursively'))
1291 1291
1292 1292 old = repo['.']
1293 1293 if old.phase() == phases.public:
1294 1294 raise util.Abort(_('cannot amend public changesets'))
1295 1295 if len(old.parents()) > 1:
1296 1296 raise util.Abort(_('cannot amend merge changesets'))
1297 1297 if len(repo[None].parents()) > 1:
1298 1298 raise util.Abort(_('cannot amend while merging'))
1299 1299 if old.children():
1300 1300 raise util.Abort(_('cannot amend changeset with children'))
1301 1301
1302 1302 e = cmdutil.commiteditor
1303 1303 if opts.get('force_editor'):
1304 1304 e = cmdutil.commitforceeditor
1305 1305
1306 1306 def commitfunc(ui, repo, message, match, opts):
1307 1307 editor = e
1308 1308 # message contains text from -m or -l, if it's empty,
1309 1309 # open the editor with the old message
1310 1310 if not message:
1311 1311 message = old.description()
1312 1312 editor = cmdutil.commitforceeditor
1313 1313 return repo.commit(message,
1314 1314 opts.get('user') or old.user(),
1315 1315 opts.get('date') or old.date(),
1316 1316 match,
1317 1317 editor=editor,
1318 1318 extra=extra)
1319 1319
1320 1320 current = repo._bookmarkcurrent
1321 1321 marks = old.bookmarks()
1322 1322 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1323 1323 if node == old.node():
1324 1324 ui.status(_("nothing changed\n"))
1325 1325 return 1
1326 1326 elif marks:
1327 1327 ui.debug('moving bookmarks %r from %s to %s\n' %
1328 1328 (marks, old.hex(), hex(node)))
1329 1329 newmarks = repo._bookmarks
1330 1330 for bm in marks:
1331 1331 newmarks[bm] = node
1332 1332 if bm == current:
1333 1333 bookmarks.setcurrent(repo, bm)
1334 1334 newmarks.write()
1335 1335 else:
1336 1336 e = cmdutil.commiteditor
1337 1337 if opts.get('force_editor'):
1338 1338 e = cmdutil.commitforceeditor
1339 1339
1340 1340 def commitfunc(ui, repo, message, match, opts):
1341 1341 return repo.commit(message, opts.get('user'), opts.get('date'),
1342 1342 match, editor=e, extra=extra)
1343 1343
1344 1344 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1345 1345
1346 1346 if not node:
1347 1347 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1348 1348 if stat[3]:
1349 1349 ui.status(_("nothing changed (%d missing files, see "
1350 1350 "'hg status')\n") % len(stat[3]))
1351 1351 else:
1352 1352 ui.status(_("nothing changed\n"))
1353 1353 return 1
1354 1354
1355 1355 ctx = repo[node]
1356 1356 parents = ctx.parents()
1357 1357
1358 1358 if (not opts.get('amend') and bheads and node not in bheads and not
1359 1359 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1360 1360 ui.status(_('created new head\n'))
1361 1361 # The message is not printed for initial roots. For the other
1362 1362 # changesets, it is printed in the following situations:
1363 1363 #
1364 1364 # Par column: for the 2 parents with ...
1365 1365 # N: null or no parent
1366 1366 # B: parent is on another named branch
1367 1367 # C: parent is a regular non head changeset
1368 1368 # H: parent was a branch head of the current branch
1369 1369 # Msg column: whether we print "created new head" message
1370 1370 # In the following, it is assumed that there already exists some
1371 1371 # initial branch heads of the current branch, otherwise nothing is
1372 1372 # printed anyway.
1373 1373 #
1374 1374 # Par Msg Comment
1375 1375 # N N y additional topo root
1376 1376 #
1377 1377 # B N y additional branch root
1378 1378 # C N y additional topo head
1379 1379 # H N n usual case
1380 1380 #
1381 1381 # B B y weird additional branch root
1382 1382 # C B y branch merge
1383 1383 # H B n merge with named branch
1384 1384 #
1385 1385 # C C y additional head from merge
1386 1386 # C H n merge with a head
1387 1387 #
1388 1388 # H H n head merge: head count decreases
1389 1389
1390 1390 if not opts.get('close_branch'):
1391 1391 for r in parents:
1392 1392 if r.closesbranch() and r.branch() == branch:
1393 1393 ui.status(_('reopening closed branch head %d\n') % r)
1394 1394
1395 1395 if ui.debugflag:
1396 1396 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1397 1397 elif ui.verbose:
1398 1398 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1399 1399
1400 1400 @command('copy|cp',
1401 1401 [('A', 'after', None, _('record a copy that has already occurred')),
1402 1402 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1403 1403 ] + walkopts + dryrunopts,
1404 1404 _('[OPTION]... [SOURCE]... DEST'))
1405 1405 def copy(ui, repo, *pats, **opts):
1406 1406 """mark files as copied for the next commit
1407 1407
1408 1408 Mark dest as having copies of source files. If dest is a
1409 1409 directory, copies are put in that directory. If dest is a file,
1410 1410 the source must be a single file.
1411 1411
1412 1412 By default, this command copies the contents of files as they
1413 1413 exist in the working directory. If invoked with -A/--after, the
1414 1414 operation is recorded, but no copying is performed.
1415 1415
1416 1416 This command takes effect with the next commit. To undo a copy
1417 1417 before that, see :hg:`revert`.
1418 1418
1419 1419 Returns 0 on success, 1 if errors are encountered.
1420 1420 """
1421 1421 wlock = repo.wlock(False)
1422 1422 try:
1423 1423 return cmdutil.copy(ui, repo, pats, opts)
1424 1424 finally:
1425 1425 wlock.release()
1426 1426
1427 1427 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1428 1428 def debugancestor(ui, repo, *args):
1429 1429 """find the ancestor revision of two revisions in a given index"""
1430 1430 if len(args) == 3:
1431 1431 index, rev1, rev2 = args
1432 1432 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1433 1433 lookup = r.lookup
1434 1434 elif len(args) == 2:
1435 1435 if not repo:
1436 1436 raise util.Abort(_("there is no Mercurial repository here "
1437 1437 "(.hg not found)"))
1438 1438 rev1, rev2 = args
1439 1439 r = repo.changelog
1440 1440 lookup = repo.lookup
1441 1441 else:
1442 1442 raise util.Abort(_('either two or three arguments required'))
1443 1443 a = r.ancestor(lookup(rev1), lookup(rev2))
1444 1444 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1445 1445
1446 1446 @command('debugbuilddag',
1447 1447 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1448 1448 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1449 1449 ('n', 'new-file', None, _('add new file at each rev'))],
1450 1450 _('[OPTION]... [TEXT]'))
1451 1451 def debugbuilddag(ui, repo, text=None,
1452 1452 mergeable_file=False,
1453 1453 overwritten_file=False,
1454 1454 new_file=False):
1455 1455 """builds a repo with a given DAG from scratch in the current empty repo
1456 1456
1457 1457 The description of the DAG is read from stdin if not given on the
1458 1458 command line.
1459 1459
1460 1460 Elements:
1461 1461
1462 1462 - "+n" is a linear run of n nodes based on the current default parent
1463 1463 - "." is a single node based on the current default parent
1464 1464 - "$" resets the default parent to null (implied at the start);
1465 1465 otherwise the default parent is always the last node created
1466 1466 - "<p" sets the default parent to the backref p
1467 1467 - "*p" is a fork at parent p, which is a backref
1468 1468 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1469 1469 - "/p2" is a merge of the preceding node and p2
1470 1470 - ":tag" defines a local tag for the preceding node
1471 1471 - "@branch" sets the named branch for subsequent nodes
1472 1472 - "#...\\n" is a comment up to the end of the line
1473 1473
1474 1474 Whitespace between the above elements is ignored.
1475 1475
1476 1476 A backref is either
1477 1477
1478 1478 - a number n, which references the node curr-n, where curr is the current
1479 1479 node, or
1480 1480 - the name of a local tag you placed earlier using ":tag", or
1481 1481 - empty to denote the default parent.
1482 1482
1483 1483 All string valued-elements are either strictly alphanumeric, or must
1484 1484 be enclosed in double quotes ("..."), with "\\" as escape character.
1485 1485 """
1486 1486
1487 1487 if text is None:
1488 1488 ui.status(_("reading DAG from stdin\n"))
1489 1489 text = ui.fin.read()
1490 1490
1491 1491 cl = repo.changelog
1492 1492 if len(cl) > 0:
1493 1493 raise util.Abort(_('repository is not empty'))
1494 1494
1495 1495 # determine number of revs in DAG
1496 1496 total = 0
1497 1497 for type, data in dagparser.parsedag(text):
1498 1498 if type == 'n':
1499 1499 total += 1
1500 1500
1501 1501 if mergeable_file:
1502 1502 linesperrev = 2
1503 1503 # make a file with k lines per rev
1504 1504 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1505 1505 initialmergedlines.append("")
1506 1506
1507 1507 tags = []
1508 1508
1509 1509 lock = tr = None
1510 1510 try:
1511 1511 lock = repo.lock()
1512 1512 tr = repo.transaction("builddag")
1513 1513
1514 1514 at = -1
1515 1515 atbranch = 'default'
1516 1516 nodeids = []
1517 1517 id = 0
1518 1518 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1519 1519 for type, data in dagparser.parsedag(text):
1520 1520 if type == 'n':
1521 1521 ui.note(('node %s\n' % str(data)))
1522 1522 id, ps = data
1523 1523
1524 1524 files = []
1525 1525 fctxs = {}
1526 1526
1527 1527 p2 = None
1528 1528 if mergeable_file:
1529 1529 fn = "mf"
1530 1530 p1 = repo[ps[0]]
1531 1531 if len(ps) > 1:
1532 1532 p2 = repo[ps[1]]
1533 1533 pa = p1.ancestor(p2)
1534 1534 base, local, other = [x[fn].data() for x in pa, p1, p2]
1535 1535 m3 = simplemerge.Merge3Text(base, local, other)
1536 1536 ml = [l.strip() for l in m3.merge_lines()]
1537 1537 ml.append("")
1538 1538 elif at > 0:
1539 1539 ml = p1[fn].data().split("\n")
1540 1540 else:
1541 1541 ml = initialmergedlines
1542 1542 ml[id * linesperrev] += " r%i" % id
1543 1543 mergedtext = "\n".join(ml)
1544 1544 files.append(fn)
1545 1545 fctxs[fn] = context.memfilectx(fn, mergedtext)
1546 1546
1547 1547 if overwritten_file:
1548 1548 fn = "of"
1549 1549 files.append(fn)
1550 1550 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1551 1551
1552 1552 if new_file:
1553 1553 fn = "nf%i" % id
1554 1554 files.append(fn)
1555 1555 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1556 1556 if len(ps) > 1:
1557 1557 if not p2:
1558 1558 p2 = repo[ps[1]]
1559 1559 for fn in p2:
1560 1560 if fn.startswith("nf"):
1561 1561 files.append(fn)
1562 1562 fctxs[fn] = p2[fn]
1563 1563
1564 1564 def fctxfn(repo, cx, path):
1565 1565 return fctxs.get(path)
1566 1566
1567 1567 if len(ps) == 0 or ps[0] < 0:
1568 1568 pars = [None, None]
1569 1569 elif len(ps) == 1:
1570 1570 pars = [nodeids[ps[0]], None]
1571 1571 else:
1572 1572 pars = [nodeids[p] for p in ps]
1573 1573 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1574 1574 date=(id, 0),
1575 1575 user="debugbuilddag",
1576 1576 extra={'branch': atbranch})
1577 1577 nodeid = repo.commitctx(cx)
1578 1578 nodeids.append(nodeid)
1579 1579 at = id
1580 1580 elif type == 'l':
1581 1581 id, name = data
1582 1582 ui.note(('tag %s\n' % name))
1583 1583 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1584 1584 elif type == 'a':
1585 1585 ui.note(('branch %s\n' % data))
1586 1586 atbranch = data
1587 1587 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1588 1588 tr.close()
1589 1589
1590 1590 if tags:
1591 1591 repo.opener.write("localtags", "".join(tags))
1592 1592 finally:
1593 1593 ui.progress(_('building'), None)
1594 1594 release(tr, lock)
1595 1595
1596 1596 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1597 1597 def debugbundle(ui, bundlepath, all=None, **opts):
1598 1598 """lists the contents of a bundle"""
1599 1599 f = hg.openpath(ui, bundlepath)
1600 1600 try:
1601 1601 gen = changegroup.readbundle(f, bundlepath)
1602 1602 if all:
1603 1603 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1604 1604
1605 1605 def showchunks(named):
1606 1606 ui.write("\n%s\n" % named)
1607 1607 chain = None
1608 1608 while True:
1609 1609 chunkdata = gen.deltachunk(chain)
1610 1610 if not chunkdata:
1611 1611 break
1612 1612 node = chunkdata['node']
1613 1613 p1 = chunkdata['p1']
1614 1614 p2 = chunkdata['p2']
1615 1615 cs = chunkdata['cs']
1616 1616 deltabase = chunkdata['deltabase']
1617 1617 delta = chunkdata['delta']
1618 1618 ui.write("%s %s %s %s %s %s\n" %
1619 1619 (hex(node), hex(p1), hex(p2),
1620 1620 hex(cs), hex(deltabase), len(delta)))
1621 1621 chain = node
1622 1622
1623 1623 chunkdata = gen.changelogheader()
1624 1624 showchunks("changelog")
1625 1625 chunkdata = gen.manifestheader()
1626 1626 showchunks("manifest")
1627 1627 while True:
1628 1628 chunkdata = gen.filelogheader()
1629 1629 if not chunkdata:
1630 1630 break
1631 1631 fname = chunkdata['filename']
1632 1632 showchunks(fname)
1633 1633 else:
1634 1634 chunkdata = gen.changelogheader()
1635 1635 chain = None
1636 1636 while True:
1637 1637 chunkdata = gen.deltachunk(chain)
1638 1638 if not chunkdata:
1639 1639 break
1640 1640 node = chunkdata['node']
1641 1641 ui.write("%s\n" % hex(node))
1642 1642 chain = node
1643 1643 finally:
1644 1644 f.close()
1645 1645
1646 1646 @command('debugcheckstate', [], '')
1647 1647 def debugcheckstate(ui, repo):
1648 1648 """validate the correctness of the current dirstate"""
1649 1649 parent1, parent2 = repo.dirstate.parents()
1650 1650 m1 = repo[parent1].manifest()
1651 1651 m2 = repo[parent2].manifest()
1652 1652 errors = 0
1653 1653 for f in repo.dirstate:
1654 1654 state = repo.dirstate[f]
1655 1655 if state in "nr" and f not in m1:
1656 1656 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1657 1657 errors += 1
1658 1658 if state in "a" and f in m1:
1659 1659 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1660 1660 errors += 1
1661 1661 if state in "m" and f not in m1 and f not in m2:
1662 1662 ui.warn(_("%s in state %s, but not in either manifest\n") %
1663 1663 (f, state))
1664 1664 errors += 1
1665 1665 for f in m1:
1666 1666 state = repo.dirstate[f]
1667 1667 if state not in "nrm":
1668 1668 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1669 1669 errors += 1
1670 1670 if errors:
1671 1671 error = _(".hg/dirstate inconsistent with current parent's manifest")
1672 1672 raise util.Abort(error)
1673 1673
1674 1674 @command('debugcommands', [], _('[COMMAND]'))
1675 1675 def debugcommands(ui, cmd='', *args):
1676 1676 """list all available commands and options"""
1677 1677 for cmd, vals in sorted(table.iteritems()):
1678 1678 cmd = cmd.split('|')[0].strip('^')
1679 1679 opts = ', '.join([i[1] for i in vals[1]])
1680 1680 ui.write('%s: %s\n' % (cmd, opts))
1681 1681
1682 1682 @command('debugcomplete',
1683 1683 [('o', 'options', None, _('show the command options'))],
1684 1684 _('[-o] CMD'))
1685 1685 def debugcomplete(ui, cmd='', **opts):
1686 1686 """returns the completion list associated with the given command"""
1687 1687
1688 1688 if opts.get('options'):
1689 1689 options = []
1690 1690 otables = [globalopts]
1691 1691 if cmd:
1692 1692 aliases, entry = cmdutil.findcmd(cmd, table, False)
1693 1693 otables.append(entry[1])
1694 1694 for t in otables:
1695 1695 for o in t:
1696 1696 if "(DEPRECATED)" in o[3]:
1697 1697 continue
1698 1698 if o[0]:
1699 1699 options.append('-%s' % o[0])
1700 1700 options.append('--%s' % o[1])
1701 1701 ui.write("%s\n" % "\n".join(options))
1702 1702 return
1703 1703
1704 1704 cmdlist = cmdutil.findpossible(cmd, table)
1705 1705 if ui.verbose:
1706 1706 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1707 1707 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1708 1708
1709 1709 @command('debugdag',
1710 1710 [('t', 'tags', None, _('use tags as labels')),
1711 1711 ('b', 'branches', None, _('annotate with branch names')),
1712 1712 ('', 'dots', None, _('use dots for runs')),
1713 1713 ('s', 'spaces', None, _('separate elements by spaces'))],
1714 1714 _('[OPTION]... [FILE [REV]...]'))
1715 1715 def debugdag(ui, repo, file_=None, *revs, **opts):
1716 1716 """format the changelog or an index DAG as a concise textual description
1717 1717
1718 1718 If you pass a revlog index, the revlog's DAG is emitted. If you list
1719 1719 revision numbers, they get labeled in the output as rN.
1720 1720
1721 1721 Otherwise, the changelog DAG of the current repo is emitted.
1722 1722 """
1723 1723 spaces = opts.get('spaces')
1724 1724 dots = opts.get('dots')
1725 1725 if file_:
1726 1726 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1727 1727 revs = set((int(r) for r in revs))
1728 1728 def events():
1729 1729 for r in rlog:
1730 1730 yield 'n', (r, list(set(p for p in rlog.parentrevs(r)
1731 1731 if p != -1)))
1732 1732 if r in revs:
1733 1733 yield 'l', (r, "r%i" % r)
1734 1734 elif repo:
1735 1735 cl = repo.changelog
1736 1736 tags = opts.get('tags')
1737 1737 branches = opts.get('branches')
1738 1738 if tags:
1739 1739 labels = {}
1740 1740 for l, n in repo.tags().items():
1741 1741 labels.setdefault(cl.rev(n), []).append(l)
1742 1742 def events():
1743 1743 b = "default"
1744 1744 for r in cl:
1745 1745 if branches:
1746 1746 newb = cl.read(cl.node(r))[5]['branch']
1747 1747 if newb != b:
1748 1748 yield 'a', newb
1749 1749 b = newb
1750 1750 yield 'n', (r, list(set(p for p in cl.parentrevs(r)
1751 1751 if p != -1)))
1752 1752 if tags:
1753 1753 ls = labels.get(r)
1754 1754 if ls:
1755 1755 for l in ls:
1756 1756 yield 'l', (r, l)
1757 1757 else:
1758 1758 raise util.Abort(_('need repo for changelog dag'))
1759 1759
1760 1760 for line in dagparser.dagtextlines(events(),
1761 1761 addspaces=spaces,
1762 1762 wraplabels=True,
1763 1763 wrapannotations=True,
1764 1764 wrapnonlinear=dots,
1765 1765 usedots=dots,
1766 1766 maxlinewidth=70):
1767 1767 ui.write(line)
1768 1768 ui.write("\n")
1769 1769
1770 1770 @command('debugdata',
1771 1771 [('c', 'changelog', False, _('open changelog')),
1772 1772 ('m', 'manifest', False, _('open manifest'))],
1773 1773 _('-c|-m|FILE REV'))
1774 1774 def debugdata(ui, repo, file_, rev = None, **opts):
1775 1775 """dump the contents of a data file revision"""
1776 1776 if opts.get('changelog') or opts.get('manifest'):
1777 1777 file_, rev = None, file_
1778 1778 elif rev is None:
1779 1779 raise error.CommandError('debugdata', _('invalid arguments'))
1780 1780 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1781 1781 try:
1782 1782 ui.write(r.revision(r.lookup(rev)))
1783 1783 except KeyError:
1784 1784 raise util.Abort(_('invalid revision identifier %s') % rev)
1785 1785
1786 1786 @command('debugdate',
1787 1787 [('e', 'extended', None, _('try extended date formats'))],
1788 1788 _('[-e] DATE [RANGE]'))
1789 1789 def debugdate(ui, date, range=None, **opts):
1790 1790 """parse and display a date"""
1791 1791 if opts["extended"]:
1792 1792 d = util.parsedate(date, util.extendeddateformats)
1793 1793 else:
1794 1794 d = util.parsedate(date)
1795 1795 ui.write(("internal: %s %s\n") % d)
1796 1796 ui.write(("standard: %s\n") % util.datestr(d))
1797 1797 if range:
1798 1798 m = util.matchdate(range)
1799 1799 ui.write(("match: %s\n") % m(d[0]))
1800 1800
1801 1801 @command('debugdiscovery',
1802 1802 [('', 'old', None, _('use old-style discovery')),
1803 1803 ('', 'nonheads', None,
1804 1804 _('use old-style discovery with non-heads included')),
1805 1805 ] + remoteopts,
1806 1806 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1807 1807 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1808 1808 """runs the changeset discovery protocol in isolation"""
1809 1809 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
1810 1810 opts.get('branch'))
1811 1811 remote = hg.peer(repo, opts, remoteurl)
1812 1812 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1813 1813
1814 1814 # make sure tests are repeatable
1815 1815 random.seed(12323)
1816 1816
1817 1817 def doit(localheads, remoteheads, remote=remote):
1818 1818 if opts.get('old'):
1819 1819 if localheads:
1820 1820 raise util.Abort('cannot use localheads with old style '
1821 1821 'discovery')
1822 1822 if not util.safehasattr(remote, 'branches'):
1823 1823 # enable in-client legacy support
1824 1824 remote = localrepo.locallegacypeer(remote.local())
1825 1825 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1826 1826 force=True)
1827 1827 common = set(common)
1828 1828 if not opts.get('nonheads'):
1829 1829 ui.write(("unpruned common: %s\n") % " ".join([short(n)
1830 1830 for n in common]))
1831 1831 dag = dagutil.revlogdag(repo.changelog)
1832 1832 all = dag.ancestorset(dag.internalizeall(common))
1833 1833 common = dag.externalizeall(dag.headsetofconnecteds(all))
1834 1834 else:
1835 1835 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1836 1836 common = set(common)
1837 1837 rheads = set(hds)
1838 1838 lheads = set(repo.heads())
1839 1839 ui.write(("common heads: %s\n") % " ".join([short(n) for n in common]))
1840 1840 if lheads <= common:
1841 1841 ui.write(("local is subset\n"))
1842 1842 elif rheads <= common:
1843 1843 ui.write(("remote is subset\n"))
1844 1844
1845 1845 serverlogs = opts.get('serverlog')
1846 1846 if serverlogs:
1847 1847 for filename in serverlogs:
1848 1848 logfile = open(filename, 'r')
1849 1849 try:
1850 1850 line = logfile.readline()
1851 1851 while line:
1852 1852 parts = line.strip().split(';')
1853 1853 op = parts[1]
1854 1854 if op == 'cg':
1855 1855 pass
1856 1856 elif op == 'cgss':
1857 1857 doit(parts[2].split(' '), parts[3].split(' '))
1858 1858 elif op == 'unb':
1859 1859 doit(parts[3].split(' '), parts[2].split(' '))
1860 1860 line = logfile.readline()
1861 1861 finally:
1862 1862 logfile.close()
1863 1863
1864 1864 else:
1865 1865 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1866 1866 opts.get('remote_head'))
1867 1867 localrevs = opts.get('local_head')
1868 1868 doit(localrevs, remoterevs)
1869 1869
1870 1870 @command('debugfileset',
1871 1871 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
1872 1872 _('[-r REV] FILESPEC'))
1873 1873 def debugfileset(ui, repo, expr, **opts):
1874 1874 '''parse and apply a fileset specification'''
1875 1875 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
1876 1876 if ui.verbose:
1877 1877 tree = fileset.parse(expr)[0]
1878 1878 ui.note(tree, "\n")
1879 1879
1880 1880 for f in fileset.getfileset(ctx, expr):
1881 1881 ui.write("%s\n" % f)
1882 1882
1883 1883 @command('debugfsinfo', [], _('[PATH]'))
1884 1884 def debugfsinfo(ui, path = "."):
1885 1885 """show information detected about current filesystem"""
1886 1886 util.writefile('.debugfsinfo', '')
1887 1887 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
1888 1888 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
1889 1889 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
1890 1890 and 'yes' or 'no'))
1891 1891 os.unlink('.debugfsinfo')
1892 1892
1893 1893 @command('debuggetbundle',
1894 1894 [('H', 'head', [], _('id of head node'), _('ID')),
1895 1895 ('C', 'common', [], _('id of common node'), _('ID')),
1896 1896 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1897 1897 _('REPO FILE [-H|-C ID]...'))
1898 1898 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1899 1899 """retrieves a bundle from a repo
1900 1900
1901 1901 Every ID must be a full-length hex node id string. Saves the bundle to the
1902 1902 given file.
1903 1903 """
1904 1904 repo = hg.peer(ui, opts, repopath)
1905 1905 if not repo.capable('getbundle'):
1906 1906 raise util.Abort("getbundle() not supported by target repository")
1907 1907 args = {}
1908 1908 if common:
1909 1909 args['common'] = [bin(s) for s in common]
1910 1910 if head:
1911 1911 args['heads'] = [bin(s) for s in head]
1912 1912 bundle = repo.getbundle('debug', **args)
1913 1913
1914 1914 bundletype = opts.get('type', 'bzip2').lower()
1915 1915 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1916 1916 bundletype = btypes.get(bundletype)
1917 1917 if bundletype not in changegroup.bundletypes:
1918 1918 raise util.Abort(_('unknown bundle type specified with --type'))
1919 1919 changegroup.writebundle(bundle, bundlepath, bundletype)
1920 1920
1921 1921 @command('debugignore', [], '')
1922 1922 def debugignore(ui, repo, *values, **opts):
1923 1923 """display the combined ignore pattern"""
1924 1924 ignore = repo.dirstate._ignore
1925 1925 includepat = getattr(ignore, 'includepat', None)
1926 1926 if includepat is not None:
1927 1927 ui.write("%s\n" % includepat)
1928 1928 else:
1929 1929 raise util.Abort(_("no ignore patterns found"))
1930 1930
1931 1931 @command('debugindex',
1932 1932 [('c', 'changelog', False, _('open changelog')),
1933 1933 ('m', 'manifest', False, _('open manifest')),
1934 1934 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1935 1935 _('[-f FORMAT] -c|-m|FILE'))
1936 1936 def debugindex(ui, repo, file_ = None, **opts):
1937 1937 """dump the contents of an index file"""
1938 1938 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1939 1939 format = opts.get('format', 0)
1940 1940 if format not in (0, 1):
1941 1941 raise util.Abort(_("unknown format %d") % format)
1942 1942
1943 1943 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1944 1944 if generaldelta:
1945 1945 basehdr = ' delta'
1946 1946 else:
1947 1947 basehdr = ' base'
1948 1948
1949 1949 if format == 0:
1950 1950 ui.write(" rev offset length " + basehdr + " linkrev"
1951 1951 " nodeid p1 p2\n")
1952 1952 elif format == 1:
1953 1953 ui.write(" rev flag offset length"
1954 1954 " size " + basehdr + " link p1 p2"
1955 1955 " nodeid\n")
1956 1956
1957 1957 for i in r:
1958 1958 node = r.node(i)
1959 1959 if generaldelta:
1960 1960 base = r.deltaparent(i)
1961 1961 else:
1962 1962 base = r.chainbase(i)
1963 1963 if format == 0:
1964 1964 try:
1965 1965 pp = r.parents(node)
1966 1966 except Exception:
1967 1967 pp = [nullid, nullid]
1968 1968 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1969 1969 i, r.start(i), r.length(i), base, r.linkrev(i),
1970 1970 short(node), short(pp[0]), short(pp[1])))
1971 1971 elif format == 1:
1972 1972 pr = r.parentrevs(i)
1973 1973 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1974 1974 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1975 1975 base, r.linkrev(i), pr[0], pr[1], short(node)))
1976 1976
1977 1977 @command('debugindexdot', [], _('FILE'))
1978 1978 def debugindexdot(ui, repo, file_):
1979 1979 """dump an index DAG as a graphviz dot file"""
1980 1980 r = None
1981 1981 if repo:
1982 1982 filelog = repo.file(file_)
1983 1983 if len(filelog):
1984 1984 r = filelog
1985 1985 if not r:
1986 1986 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1987 1987 ui.write(("digraph G {\n"))
1988 1988 for i in r:
1989 1989 node = r.node(i)
1990 1990 pp = r.parents(node)
1991 1991 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1992 1992 if pp[1] != nullid:
1993 1993 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1994 1994 ui.write("}\n")
1995 1995
1996 1996 @command('debuginstall', [], '')
1997 1997 def debuginstall(ui):
1998 1998 '''test Mercurial installation
1999 1999
2000 2000 Returns 0 on success.
2001 2001 '''
2002 2002
2003 2003 def writetemp(contents):
2004 2004 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2005 2005 f = os.fdopen(fd, "wb")
2006 2006 f.write(contents)
2007 2007 f.close()
2008 2008 return name
2009 2009
2010 2010 problems = 0
2011 2011
2012 2012 # encoding
2013 2013 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2014 2014 try:
2015 2015 encoding.fromlocal("test")
2016 2016 except util.Abort, inst:
2017 2017 ui.write(" %s\n" % inst)
2018 2018 ui.write(_(" (check that your locale is properly set)\n"))
2019 2019 problems += 1
2020 2020
2021 2021 # Python lib
2022 2022 ui.status(_("checking Python lib (%s)...\n")
2023 2023 % os.path.dirname(os.__file__))
2024 2024
2025 2025 # compiled modules
2026 2026 ui.status(_("checking installed modules (%s)...\n")
2027 2027 % os.path.dirname(__file__))
2028 2028 try:
2029 2029 import bdiff, mpatch, base85, osutil
2030 2030 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2031 2031 except Exception, inst:
2032 2032 ui.write(" %s\n" % inst)
2033 2033 ui.write(_(" One or more extensions could not be found"))
2034 2034 ui.write(_(" (check that you compiled the extensions)\n"))
2035 2035 problems += 1
2036 2036
2037 2037 # templates
2038 2038 import templater
2039 2039 p = templater.templatepath()
2040 2040 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2041 2041 try:
2042 2042 templater.templater(templater.templatepath("map-cmdline.default"))
2043 2043 except Exception, inst:
2044 2044 ui.write(" %s\n" % inst)
2045 2045 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2046 2046 problems += 1
2047 2047
2048 2048 # editor
2049 2049 ui.status(_("checking commit editor...\n"))
2050 2050 editor = ui.geteditor()
2051 2051 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
2052 2052 if not cmdpath:
2053 2053 if editor == 'vi':
2054 2054 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2055 2055 ui.write(_(" (specify a commit editor in your configuration"
2056 2056 " file)\n"))
2057 2057 else:
2058 2058 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2059 2059 ui.write(_(" (specify a commit editor in your configuration"
2060 2060 " file)\n"))
2061 2061 problems += 1
2062 2062
2063 2063 # check username
2064 2064 ui.status(_("checking username...\n"))
2065 2065 try:
2066 2066 ui.username()
2067 2067 except util.Abort, e:
2068 2068 ui.write(" %s\n" % e)
2069 2069 ui.write(_(" (specify a username in your configuration file)\n"))
2070 2070 problems += 1
2071 2071
2072 2072 if not problems:
2073 2073 ui.status(_("no problems detected\n"))
2074 2074 else:
2075 2075 ui.write(_("%s problems detected,"
2076 2076 " please check your install!\n") % problems)
2077 2077
2078 2078 return problems
2079 2079
2080 2080 @command('debugknown', [], _('REPO ID...'))
2081 2081 def debugknown(ui, repopath, *ids, **opts):
2082 2082 """test whether node ids are known to a repo
2083 2083
2084 2084 Every ID must be a full-length hex node id string. Returns a list of 0s
2085 2085 and 1s indicating unknown/known.
2086 2086 """
2087 2087 repo = hg.peer(ui, opts, repopath)
2088 2088 if not repo.capable('known'):
2089 2089 raise util.Abort("known() not supported by target repository")
2090 2090 flags = repo.known([bin(s) for s in ids])
2091 2091 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2092 2092
2093 2093 @command('debugobsolete',
2094 2094 [('', 'flags', 0, _('markers flag')),
2095 2095 ] + commitopts2,
2096 2096 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2097 2097 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2098 2098 """create arbitrary obsolete marker"""
2099 2099 def parsenodeid(s):
2100 2100 try:
2101 2101 # We do not use revsingle/revrange functions here to accept
2102 2102 # arbitrary node identifiers, possibly not present in the
2103 2103 # local repository.
2104 2104 n = bin(s)
2105 2105 if len(n) != len(nullid):
2106 2106 raise TypeError()
2107 2107 return n
2108 2108 except TypeError:
2109 2109 raise util.Abort('changeset references must be full hexadecimal '
2110 2110 'node identifiers')
2111 2111
2112 2112 if precursor is not None:
2113 2113 metadata = {}
2114 2114 if 'date' in opts:
2115 2115 metadata['date'] = opts['date']
2116 2116 metadata['user'] = opts['user'] or ui.username()
2117 2117 succs = tuple(parsenodeid(succ) for succ in successors)
2118 2118 l = repo.lock()
2119 2119 try:
2120 2120 tr = repo.transaction('debugobsolete')
2121 2121 try:
2122 2122 repo.obsstore.create(tr, parsenodeid(precursor), succs,
2123 2123 opts['flags'], metadata)
2124 2124 tr.close()
2125 2125 finally:
2126 2126 tr.release()
2127 2127 finally:
2128 2128 l.release()
2129 2129 else:
2130 2130 for m in obsolete.allmarkers(repo):
2131 2131 ui.write(hex(m.precnode()))
2132 2132 for repl in m.succnodes():
2133 2133 ui.write(' ')
2134 2134 ui.write(hex(repl))
2135 2135 ui.write(' %X ' % m._data[2])
2136 2136 ui.write(m.metadata())
2137 2137 ui.write('\n')
2138 2138
2139 2139 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
2140 2140 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2141 2141 '''access the pushkey key/value protocol
2142 2142
2143 2143 With two args, list the keys in the given namespace.
2144 2144
2145 2145 With five args, set a key to new if it currently is set to old.
2146 2146 Reports success or failure.
2147 2147 '''
2148 2148
2149 2149 target = hg.peer(ui, {}, repopath)
2150 2150 if keyinfo:
2151 2151 key, old, new = keyinfo
2152 2152 r = target.pushkey(namespace, key, old, new)
2153 2153 ui.status(str(r) + '\n')
2154 2154 return not r
2155 2155 else:
2156 2156 for k, v in target.listkeys(namespace).iteritems():
2157 2157 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2158 2158 v.encode('string-escape')))
2159 2159
2160 2160 @command('debugpvec', [], _('A B'))
2161 2161 def debugpvec(ui, repo, a, b=None):
2162 2162 ca = scmutil.revsingle(repo, a)
2163 2163 cb = scmutil.revsingle(repo, b)
2164 2164 pa = pvec.ctxpvec(ca)
2165 2165 pb = pvec.ctxpvec(cb)
2166 2166 if pa == pb:
2167 2167 rel = "="
2168 2168 elif pa > pb:
2169 2169 rel = ">"
2170 2170 elif pa < pb:
2171 2171 rel = "<"
2172 2172 elif pa | pb:
2173 2173 rel = "|"
2174 2174 ui.write(_("a: %s\n") % pa)
2175 2175 ui.write(_("b: %s\n") % pb)
2176 2176 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2177 2177 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2178 2178 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2179 2179 pa.distance(pb), rel))
2180 2180
2181 2181 @command('debugrebuildstate',
2182 2182 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2183 2183 _('[-r REV] [REV]'))
2184 2184 def debugrebuildstate(ui, repo, rev="tip"):
2185 2185 """rebuild the dirstate as it would look like for the given revision"""
2186 2186 ctx = scmutil.revsingle(repo, rev)
2187 2187 wlock = repo.wlock()
2188 2188 try:
2189 2189 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2190 2190 finally:
2191 2191 wlock.release()
2192 2192
2193 2193 @command('debugrename',
2194 2194 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2195 2195 _('[-r REV] FILE'))
2196 2196 def debugrename(ui, repo, file1, *pats, **opts):
2197 2197 """dump rename information"""
2198 2198
2199 2199 ctx = scmutil.revsingle(repo, opts.get('rev'))
2200 2200 m = scmutil.match(ctx, (file1,) + pats, opts)
2201 2201 for abs in ctx.walk(m):
2202 2202 fctx = ctx[abs]
2203 2203 o = fctx.filelog().renamed(fctx.filenode())
2204 2204 rel = m.rel(abs)
2205 2205 if o:
2206 2206 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2207 2207 else:
2208 2208 ui.write(_("%s not renamed\n") % rel)
2209 2209
2210 2210 @command('debugrevlog',
2211 2211 [('c', 'changelog', False, _('open changelog')),
2212 2212 ('m', 'manifest', False, _('open manifest')),
2213 2213 ('d', 'dump', False, _('dump index data'))],
2214 2214 _('-c|-m|FILE'))
2215 2215 def debugrevlog(ui, repo, file_ = None, **opts):
2216 2216 """show data and statistics about a revlog"""
2217 2217 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2218 2218
2219 2219 if opts.get("dump"):
2220 2220 numrevs = len(r)
2221 2221 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2222 2222 " rawsize totalsize compression heads\n")
2223 2223 ts = 0
2224 2224 heads = set()
2225 2225 for rev in xrange(numrevs):
2226 2226 dbase = r.deltaparent(rev)
2227 2227 if dbase == -1:
2228 2228 dbase = rev
2229 2229 cbase = r.chainbase(rev)
2230 2230 p1, p2 = r.parentrevs(rev)
2231 2231 rs = r.rawsize(rev)
2232 2232 ts = ts + rs
2233 2233 heads -= set(r.parentrevs(rev))
2234 2234 heads.add(rev)
2235 2235 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
2236 2236 (rev, p1, p2, r.start(rev), r.end(rev),
2237 2237 r.start(dbase), r.start(cbase),
2238 2238 r.start(p1), r.start(p2),
2239 2239 rs, ts, ts / r.end(rev), len(heads)))
2240 2240 return 0
2241 2241
2242 2242 v = r.version
2243 2243 format = v & 0xFFFF
2244 2244 flags = []
2245 2245 gdelta = False
2246 2246 if v & revlog.REVLOGNGINLINEDATA:
2247 2247 flags.append('inline')
2248 2248 if v & revlog.REVLOGGENERALDELTA:
2249 2249 gdelta = True
2250 2250 flags.append('generaldelta')
2251 2251 if not flags:
2252 2252 flags = ['(none)']
2253 2253
2254 2254 nummerges = 0
2255 2255 numfull = 0
2256 2256 numprev = 0
2257 2257 nump1 = 0
2258 2258 nump2 = 0
2259 2259 numother = 0
2260 2260 nump1prev = 0
2261 2261 nump2prev = 0
2262 2262 chainlengths = []
2263 2263
2264 2264 datasize = [None, 0, 0L]
2265 2265 fullsize = [None, 0, 0L]
2266 2266 deltasize = [None, 0, 0L]
2267 2267
2268 2268 def addsize(size, l):
2269 2269 if l[0] is None or size < l[0]:
2270 2270 l[0] = size
2271 2271 if size > l[1]:
2272 2272 l[1] = size
2273 2273 l[2] += size
2274 2274
2275 2275 numrevs = len(r)
2276 2276 for rev in xrange(numrevs):
2277 2277 p1, p2 = r.parentrevs(rev)
2278 2278 delta = r.deltaparent(rev)
2279 2279 if format > 0:
2280 2280 addsize(r.rawsize(rev), datasize)
2281 2281 if p2 != nullrev:
2282 2282 nummerges += 1
2283 2283 size = r.length(rev)
2284 2284 if delta == nullrev:
2285 2285 chainlengths.append(0)
2286 2286 numfull += 1
2287 2287 addsize(size, fullsize)
2288 2288 else:
2289 2289 chainlengths.append(chainlengths[delta] + 1)
2290 2290 addsize(size, deltasize)
2291 2291 if delta == rev - 1:
2292 2292 numprev += 1
2293 2293 if delta == p1:
2294 2294 nump1prev += 1
2295 2295 elif delta == p2:
2296 2296 nump2prev += 1
2297 2297 elif delta == p1:
2298 2298 nump1 += 1
2299 2299 elif delta == p2:
2300 2300 nump2 += 1
2301 2301 elif delta != nullrev:
2302 2302 numother += 1
2303 2303
2304 2304 # Adjust size min value for empty cases
2305 2305 for size in (datasize, fullsize, deltasize):
2306 2306 if size[0] is None:
2307 2307 size[0] = 0
2308 2308
2309 2309 numdeltas = numrevs - numfull
2310 2310 numoprev = numprev - nump1prev - nump2prev
2311 2311 totalrawsize = datasize[2]
2312 2312 datasize[2] /= numrevs
2313 2313 fulltotal = fullsize[2]
2314 2314 fullsize[2] /= numfull
2315 2315 deltatotal = deltasize[2]
2316 2316 if numrevs - numfull > 0:
2317 2317 deltasize[2] /= numrevs - numfull
2318 2318 totalsize = fulltotal + deltatotal
2319 2319 avgchainlen = sum(chainlengths) / numrevs
2320 2320 compratio = totalrawsize / totalsize
2321 2321
2322 2322 basedfmtstr = '%%%dd\n'
2323 2323 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2324 2324
2325 2325 def dfmtstr(max):
2326 2326 return basedfmtstr % len(str(max))
2327 2327 def pcfmtstr(max, padding=0):
2328 2328 return basepcfmtstr % (len(str(max)), ' ' * padding)
2329 2329
2330 2330 def pcfmt(value, total):
2331 2331 return (value, 100 * float(value) / total)
2332 2332
2333 2333 ui.write(('format : %d\n') % format)
2334 2334 ui.write(('flags : %s\n') % ', '.join(flags))
2335 2335
2336 2336 ui.write('\n')
2337 2337 fmt = pcfmtstr(totalsize)
2338 2338 fmt2 = dfmtstr(totalsize)
2339 2339 ui.write(('revisions : ') + fmt2 % numrevs)
2340 2340 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2341 2341 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2342 2342 ui.write(('revisions : ') + fmt2 % numrevs)
2343 2343 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2344 2344 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2345 2345 ui.write(('revision size : ') + fmt2 % totalsize)
2346 2346 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2347 2347 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2348 2348
2349 2349 ui.write('\n')
2350 2350 fmt = dfmtstr(max(avgchainlen, compratio))
2351 2351 ui.write(('avg chain length : ') + fmt % avgchainlen)
2352 2352 ui.write(('compression ratio : ') + fmt % compratio)
2353 2353
2354 2354 if format > 0:
2355 2355 ui.write('\n')
2356 2356 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
2357 2357 % tuple(datasize))
2358 2358 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
2359 2359 % tuple(fullsize))
2360 2360 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
2361 2361 % tuple(deltasize))
2362 2362
2363 2363 if numdeltas > 0:
2364 2364 ui.write('\n')
2365 2365 fmt = pcfmtstr(numdeltas)
2366 2366 fmt2 = pcfmtstr(numdeltas, 4)
2367 2367 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
2368 2368 if numprev > 0:
2369 2369 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
2370 2370 numprev))
2371 2371 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
2372 2372 numprev))
2373 2373 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
2374 2374 numprev))
2375 2375 if gdelta:
2376 2376 ui.write(('deltas against p1 : ')
2377 2377 + fmt % pcfmt(nump1, numdeltas))
2378 2378 ui.write(('deltas against p2 : ')
2379 2379 + fmt % pcfmt(nump2, numdeltas))
2380 2380 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
2381 2381 numdeltas))
2382 2382
2383 2383 @command('debugrevspec', [], ('REVSPEC'))
2384 2384 def debugrevspec(ui, repo, expr):
2385 2385 """parse and apply a revision specification
2386 2386
2387 2387 Use --verbose to print the parsed tree before and after aliases
2388 2388 expansion.
2389 2389 """
2390 2390 if ui.verbose:
2391 2391 tree = revset.parse(expr)[0]
2392 2392 ui.note(revset.prettyformat(tree), "\n")
2393 2393 newtree = revset.findaliases(ui, tree)
2394 2394 if newtree != tree:
2395 2395 ui.note(revset.prettyformat(newtree), "\n")
2396 2396 func = revset.match(ui, expr)
2397 2397 for c in func(repo, range(len(repo))):
2398 2398 ui.write("%s\n" % c)
2399 2399
2400 2400 @command('debugsetparents', [], _('REV1 [REV2]'))
2401 2401 def debugsetparents(ui, repo, rev1, rev2=None):
2402 2402 """manually set the parents of the current working directory
2403 2403
2404 2404 This is useful for writing repository conversion tools, but should
2405 2405 be used with care.
2406 2406
2407 2407 Returns 0 on success.
2408 2408 """
2409 2409
2410 2410 r1 = scmutil.revsingle(repo, rev1).node()
2411 2411 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2412 2412
2413 2413 wlock = repo.wlock()
2414 2414 try:
2415 2415 repo.setparents(r1, r2)
2416 2416 finally:
2417 2417 wlock.release()
2418 2418
2419 2419 @command('debugstate',
2420 2420 [('', 'nodates', None, _('do not display the saved mtime')),
2421 2421 ('', 'datesort', None, _('sort by saved mtime'))],
2422 2422 _('[OPTION]...'))
2423 2423 def debugstate(ui, repo, nodates=None, datesort=None):
2424 2424 """show the contents of the current dirstate"""
2425 2425 timestr = ""
2426 2426 showdate = not nodates
2427 2427 if datesort:
2428 2428 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2429 2429 else:
2430 2430 keyfunc = None # sort by filename
2431 2431 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2432 2432 if showdate:
2433 2433 if ent[3] == -1:
2434 2434 # Pad or slice to locale representation
2435 2435 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2436 2436 time.localtime(0)))
2437 2437 timestr = 'unset'
2438 2438 timestr = (timestr[:locale_len] +
2439 2439 ' ' * (locale_len - len(timestr)))
2440 2440 else:
2441 2441 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2442 2442 time.localtime(ent[3]))
2443 2443 if ent[1] & 020000:
2444 2444 mode = 'lnk'
2445 2445 else:
2446 2446 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2447 2447 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2448 2448 for f in repo.dirstate.copies():
2449 2449 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2450 2450
2451 2451 @command('debugsub',
2452 2452 [('r', 'rev', '',
2453 2453 _('revision to check'), _('REV'))],
2454 2454 _('[-r REV] [REV]'))
2455 2455 def debugsub(ui, repo, rev=None):
2456 2456 ctx = scmutil.revsingle(repo, rev, None)
2457 2457 for k, v in sorted(ctx.substate.items()):
2458 2458 ui.write(('path %s\n') % k)
2459 2459 ui.write((' source %s\n') % v[0])
2460 2460 ui.write((' revision %s\n') % v[1])
2461 2461
2462 2462 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2463 2463 def debugwalk(ui, repo, *pats, **opts):
2464 2464 """show how files match on given patterns"""
2465 2465 m = scmutil.match(repo[None], pats, opts)
2466 2466 items = list(repo.walk(m))
2467 2467 if not items:
2468 2468 return
2469 2469 f = lambda fn: fn
2470 2470 if ui.configbool('ui', 'slash') and os.sep != '/':
2471 2471 f = lambda fn: util.normpath(fn)
2472 2472 fmt = 'f %%-%ds %%-%ds %%s' % (
2473 2473 max([len(abs) for abs in items]),
2474 2474 max([len(m.rel(abs)) for abs in items]))
2475 2475 for abs in items:
2476 2476 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2477 2477 ui.write("%s\n" % line.rstrip())
2478 2478
2479 2479 @command('debugwireargs',
2480 2480 [('', 'three', '', 'three'),
2481 2481 ('', 'four', '', 'four'),
2482 2482 ('', 'five', '', 'five'),
2483 2483 ] + remoteopts,
2484 2484 _('REPO [OPTIONS]... [ONE [TWO]]'))
2485 2485 def debugwireargs(ui, repopath, *vals, **opts):
2486 2486 repo = hg.peer(ui, opts, repopath)
2487 2487 for opt in remoteopts:
2488 2488 del opts[opt[1]]
2489 2489 args = {}
2490 2490 for k, v in opts.iteritems():
2491 2491 if v:
2492 2492 args[k] = v
2493 2493 # run twice to check that we don't mess up the stream for the next command
2494 2494 res1 = repo.debugwireargs(*vals, **args)
2495 2495 res2 = repo.debugwireargs(*vals, **args)
2496 2496 ui.write("%s\n" % res1)
2497 2497 if res1 != res2:
2498 2498 ui.warn("%s\n" % res2)
2499 2499
2500 2500 @command('^diff',
2501 2501 [('r', 'rev', [], _('revision'), _('REV')),
2502 2502 ('c', 'change', '', _('change made by revision'), _('REV'))
2503 2503 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2504 2504 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2505 2505 def diff(ui, repo, *pats, **opts):
2506 2506 """diff repository (or selected files)
2507 2507
2508 2508 Show differences between revisions for the specified files.
2509 2509
2510 2510 Differences between files are shown using the unified diff format.
2511 2511
2512 2512 .. note::
2513 2513 diff may generate unexpected results for merges, as it will
2514 2514 default to comparing against the working directory's first
2515 2515 parent changeset if no revisions are specified.
2516 2516
2517 2517 When two revision arguments are given, then changes are shown
2518 2518 between those revisions. If only one revision is specified then
2519 2519 that revision is compared to the working directory, and, when no
2520 2520 revisions are specified, the working directory files are compared
2521 2521 to its parent.
2522 2522
2523 2523 Alternatively you can specify -c/--change with a revision to see
2524 2524 the changes in that changeset relative to its first parent.
2525 2525
2526 2526 Without the -a/--text option, diff will avoid generating diffs of
2527 2527 files it detects as binary. With -a, diff will generate a diff
2528 2528 anyway, probably with undesirable results.
2529 2529
2530 2530 Use the -g/--git option to generate diffs in the git extended diff
2531 2531 format. For more information, read :hg:`help diffs`.
2532 2532
2533 2533 .. container:: verbose
2534 2534
2535 2535 Examples:
2536 2536
2537 2537 - compare a file in the current working directory to its parent::
2538 2538
2539 2539 hg diff foo.c
2540 2540
2541 2541 - compare two historical versions of a directory, with rename info::
2542 2542
2543 2543 hg diff --git -r 1.0:1.2 lib/
2544 2544
2545 2545 - get change stats relative to the last change on some date::
2546 2546
2547 2547 hg diff --stat -r "date('may 2')"
2548 2548
2549 2549 - diff all newly-added files that contain a keyword::
2550 2550
2551 2551 hg diff "set:added() and grep(GNU)"
2552 2552
2553 2553 - compare a revision and its parents::
2554 2554
2555 2555 hg diff -c 9353 # compare against first parent
2556 2556 hg diff -r 9353^:9353 # same using revset syntax
2557 2557 hg diff -r 9353^2:9353 # compare against the second parent
2558 2558
2559 2559 Returns 0 on success.
2560 2560 """
2561 2561
2562 2562 revs = opts.get('rev')
2563 2563 change = opts.get('change')
2564 2564 stat = opts.get('stat')
2565 2565 reverse = opts.get('reverse')
2566 2566
2567 2567 if revs and change:
2568 2568 msg = _('cannot specify --rev and --change at the same time')
2569 2569 raise util.Abort(msg)
2570 2570 elif change:
2571 2571 node2 = scmutil.revsingle(repo, change, None).node()
2572 2572 node1 = repo[node2].p1().node()
2573 2573 else:
2574 2574 node1, node2 = scmutil.revpair(repo, revs)
2575 2575
2576 2576 if reverse:
2577 2577 node1, node2 = node2, node1
2578 2578
2579 2579 diffopts = patch.diffopts(ui, opts)
2580 2580 m = scmutil.match(repo[node2], pats, opts)
2581 2581 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2582 2582 listsubrepos=opts.get('subrepos'))
2583 2583
2584 2584 @command('^export',
2585 2585 [('o', 'output', '',
2586 2586 _('print output to file with formatted name'), _('FORMAT')),
2587 2587 ('', 'switch-parent', None, _('diff against the second parent')),
2588 2588 ('r', 'rev', [], _('revisions to export'), _('REV')),
2589 2589 ] + diffopts,
2590 2590 _('[OPTION]... [-o OUTFILESPEC] [-r] REV...'))
2591 2591 def export(ui, repo, *changesets, **opts):
2592 2592 """dump the header and diffs for one or more changesets
2593 2593
2594 2594 Print the changeset header and diffs for one or more revisions.
2595 2595
2596 2596 The information shown in the changeset header is: author, date,
2597 2597 branch name (if non-default), changeset hash, parent(s) and commit
2598 2598 comment.
2599 2599
2600 2600 .. note::
2601 2601 export may generate unexpected diff output for merge
2602 2602 changesets, as it will compare the merge changeset against its
2603 2603 first parent only.
2604 2604
2605 2605 Output may be to a file, in which case the name of the file is
2606 2606 given using a format string. The formatting rules are as follows:
2607 2607
2608 2608 :``%%``: literal "%" character
2609 2609 :``%H``: changeset hash (40 hexadecimal digits)
2610 2610 :``%N``: number of patches being generated
2611 2611 :``%R``: changeset revision number
2612 2612 :``%b``: basename of the exporting repository
2613 2613 :``%h``: short-form changeset hash (12 hexadecimal digits)
2614 2614 :``%m``: first line of the commit message (only alphanumeric characters)
2615 2615 :``%n``: zero-padded sequence number, starting at 1
2616 2616 :``%r``: zero-padded changeset revision number
2617 2617
2618 2618 Without the -a/--text option, export will avoid generating diffs
2619 2619 of files it detects as binary. With -a, export will generate a
2620 2620 diff anyway, probably with undesirable results.
2621 2621
2622 2622 Use the -g/--git option to generate diffs in the git extended diff
2623 2623 format. See :hg:`help diffs` for more information.
2624 2624
2625 2625 With the --switch-parent option, the diff will be against the
2626 2626 second parent. It can be useful to review a merge.
2627 2627
2628 2628 .. container:: verbose
2629 2629
2630 2630 Examples:
2631 2631
2632 2632 - use export and import to transplant a bugfix to the current
2633 2633 branch::
2634 2634
2635 2635 hg export -r 9353 | hg import -
2636 2636
2637 2637 - export all the changesets between two revisions to a file with
2638 2638 rename information::
2639 2639
2640 2640 hg export --git -r 123:150 > changes.txt
2641 2641
2642 2642 - split outgoing changes into a series of patches with
2643 2643 descriptive names::
2644 2644
2645 2645 hg export -r "outgoing()" -o "%n-%m.patch"
2646 2646
2647 2647 Returns 0 on success.
2648 2648 """
2649 2649 changesets += tuple(opts.get('rev', []))
2650 2650 revs = scmutil.revrange(repo, changesets)
2651 2651 if not revs:
2652 2652 raise util.Abort(_("export requires at least one changeset"))
2653 2653 if len(revs) > 1:
2654 2654 ui.note(_('exporting patches:\n'))
2655 2655 else:
2656 2656 ui.note(_('exporting patch:\n'))
2657 2657 cmdutil.export(repo, revs, template=opts.get('output'),
2658 2658 switch_parent=opts.get('switch_parent'),
2659 2659 opts=patch.diffopts(ui, opts))
2660 2660
2661 2661 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2662 2662 def forget(ui, repo, *pats, **opts):
2663 2663 """forget the specified files on the next commit
2664 2664
2665 2665 Mark the specified files so they will no longer be tracked
2666 2666 after the next commit.
2667 2667
2668 2668 This only removes files from the current branch, not from the
2669 2669 entire project history, and it does not delete them from the
2670 2670 working directory.
2671 2671
2672 2672 To undo a forget before the next commit, see :hg:`add`.
2673 2673
2674 2674 .. container:: verbose
2675 2675
2676 2676 Examples:
2677 2677
2678 2678 - forget newly-added binary files::
2679 2679
2680 2680 hg forget "set:added() and binary()"
2681 2681
2682 2682 - forget files that would be excluded by .hgignore::
2683 2683
2684 2684 hg forget "set:hgignore()"
2685 2685
2686 2686 Returns 0 on success.
2687 2687 """
2688 2688
2689 2689 if not pats:
2690 2690 raise util.Abort(_('no files specified'))
2691 2691
2692 2692 m = scmutil.match(repo[None], pats, opts)
2693 2693 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2694 2694 return rejected and 1 or 0
2695 2695
2696 2696 @command(
2697 2697 'graft',
2698 2698 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2699 2699 ('c', 'continue', False, _('resume interrupted graft')),
2700 2700 ('e', 'edit', False, _('invoke editor on commit messages')),
2701 2701 ('', 'log', None, _('append graft info to log message')),
2702 2702 ('D', 'currentdate', False,
2703 2703 _('record the current date as commit date')),
2704 2704 ('U', 'currentuser', False,
2705 2705 _('record the current user as committer'), _('DATE'))]
2706 2706 + commitopts2 + mergetoolopts + dryrunopts,
2707 2707 _('[OPTION]... [-r] REV...'))
2708 2708 def graft(ui, repo, *revs, **opts):
2709 2709 '''copy changes from other branches onto the current branch
2710 2710
2711 2711 This command uses Mercurial's merge logic to copy individual
2712 2712 changes from other branches without merging branches in the
2713 2713 history graph. This is sometimes known as 'backporting' or
2714 2714 'cherry-picking'. By default, graft will copy user, date, and
2715 2715 description from the source changesets.
2716 2716
2717 2717 Changesets that are ancestors of the current revision, that have
2718 2718 already been grafted, or that are merges will be skipped.
2719 2719
2720 2720 If --log is specified, log messages will have a comment appended
2721 2721 of the form::
2722 2722
2723 2723 (grafted from CHANGESETHASH)
2724 2724
2725 2725 If a graft merge results in conflicts, the graft process is
2726 2726 interrupted so that the current merge can be manually resolved.
2727 2727 Once all conflicts are addressed, the graft process can be
2728 2728 continued with the -c/--continue option.
2729 2729
2730 2730 .. note::
2731 2731 The -c/--continue option does not reapply earlier options.
2732 2732
2733 2733 .. container:: verbose
2734 2734
2735 2735 Examples:
2736 2736
2737 2737 - copy a single change to the stable branch and edit its description::
2738 2738
2739 2739 hg update stable
2740 2740 hg graft --edit 9393
2741 2741
2742 2742 - graft a range of changesets with one exception, updating dates::
2743 2743
2744 2744 hg graft -D "2085::2093 and not 2091"
2745 2745
2746 2746 - continue a graft after resolving conflicts::
2747 2747
2748 2748 hg graft -c
2749 2749
2750 2750 - show the source of a grafted changeset::
2751 2751
2752 2752 hg log --debug -r tip
2753 2753
2754 2754 Returns 0 on successful completion.
2755 2755 '''
2756 2756
2757 2757 revs = list(revs)
2758 2758 revs.extend(opts['rev'])
2759 2759
2760 2760 if not opts.get('user') and opts.get('currentuser'):
2761 2761 opts['user'] = ui.username()
2762 2762 if not opts.get('date') and opts.get('currentdate'):
2763 2763 opts['date'] = "%d %d" % util.makedate()
2764 2764
2765 2765 editor = None
2766 2766 if opts.get('edit'):
2767 2767 editor = cmdutil.commitforceeditor
2768 2768
2769 2769 cont = False
2770 2770 if opts['continue']:
2771 2771 cont = True
2772 2772 if revs:
2773 2773 raise util.Abort(_("can't specify --continue and revisions"))
2774 2774 # read in unfinished revisions
2775 2775 try:
2776 2776 nodes = repo.opener.read('graftstate').splitlines()
2777 2777 revs = [repo[node].rev() for node in nodes]
2778 2778 except IOError, inst:
2779 2779 if inst.errno != errno.ENOENT:
2780 2780 raise
2781 2781 raise util.Abort(_("no graft state found, can't continue"))
2782 2782 else:
2783 2783 cmdutil.bailifchanged(repo)
2784 2784 if not revs:
2785 2785 raise util.Abort(_('no revisions specified'))
2786 2786 revs = scmutil.revrange(repo, revs)
2787 2787
2788 2788 # check for merges
2789 2789 for rev in repo.revs('%ld and merge()', revs):
2790 2790 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
2791 2791 revs.remove(rev)
2792 2792 if not revs:
2793 2793 return -1
2794 2794
2795 2795 # check for ancestors of dest branch
2796 2796 for rev in repo.revs('::. and %ld', revs):
2797 2797 ui.warn(_('skipping ancestor revision %s\n') % rev)
2798 2798 revs.remove(rev)
2799 2799 if not revs:
2800 2800 return -1
2801 2801
2802 2802 # analyze revs for earlier grafts
2803 2803 ids = {}
2804 2804 for ctx in repo.set("%ld", revs):
2805 2805 ids[ctx.hex()] = ctx.rev()
2806 2806 n = ctx.extra().get('source')
2807 2807 if n:
2808 2808 ids[n] = ctx.rev()
2809 2809
2810 2810 # check ancestors for earlier grafts
2811 2811 ui.debug('scanning for duplicate grafts\n')
2812 2812 for ctx in repo.set("::. - ::%ld", revs):
2813 2813 n = ctx.extra().get('source')
2814 2814 if n in ids:
2815 2815 r = repo[n].rev()
2816 2816 if r in revs:
2817 2817 ui.warn(_('skipping already grafted revision %s\n') % r)
2818 2818 revs.remove(r)
2819 2819 elif ids[n] in revs:
2820 2820 ui.warn(_('skipping already grafted revision %s '
2821 2821 '(same origin %d)\n') % (ids[n], r))
2822 2822 revs.remove(ids[n])
2823 2823 elif ctx.hex() in ids:
2824 2824 r = ids[ctx.hex()]
2825 2825 ui.warn(_('skipping already grafted revision %s '
2826 2826 '(was grafted from %d)\n') % (r, ctx.rev()))
2827 2827 revs.remove(r)
2828 2828 if not revs:
2829 2829 return -1
2830 2830
2831 2831 wlock = repo.wlock()
2832 2832 try:
2833 2833 for pos, ctx in enumerate(repo.set("%ld", revs)):
2834 2834 current = repo['.']
2835 2835
2836 2836 ui.status(_('grafting revision %s\n') % ctx.rev())
2837 2837 if opts.get('dry_run'):
2838 2838 continue
2839 2839
2840 source = ctx.extra().get('source')
2841 if not source:
2842 source = ctx.hex()
2843 extra = {'source': source}
2844 user = ctx.user()
2845 if opts.get('user'):
2846 user = opts['user']
2847 date = ctx.date()
2848 if opts.get('date'):
2849 date = opts['date']
2850 message = ctx.description()
2851 if opts.get('log'):
2852 message += '\n(grafted from %s)' % ctx.hex()
2853
2840 2854 # we don't merge the first commit when continuing
2841 2855 if not cont:
2842 2856 # perform the graft merge with p1(rev) as 'ancestor'
2843 2857 try:
2844 2858 # ui.forcemerge is an internal variable, do not document
2845 2859 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
2846 2860 stats = mergemod.update(repo, ctx.node(), True, True, False,
2847 2861 ctx.p1().node())
2848 2862 finally:
2849 2863 repo.ui.setconfig('ui', 'forcemerge', '')
2850 2864 # report any conflicts
2851 2865 if stats and stats[3] > 0:
2852 2866 # write out state for --continue
2853 2867 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2854 2868 repo.opener.write('graftstate', ''.join(nodelines))
2855 2869 raise util.Abort(
2856 2870 _("unresolved conflicts, can't continue"),
2857 2871 hint=_('use hg resolve and hg graft --continue'))
2858 2872 else:
2859 2873 cont = False
2860 2874
2861 2875 # drop the second merge parent
2862 2876 repo.setparents(current.node(), nullid)
2863 2877 repo.dirstate.write()
2864 2878 # fix up dirstate for copies and renames
2865 2879 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
2866 2880
2867 2881 # commit
2868 source = ctx.extra().get('source')
2869 if not source:
2870 source = ctx.hex()
2871 extra = {'source': source}
2872 user = ctx.user()
2873 if opts.get('user'):
2874 user = opts['user']
2875 date = ctx.date()
2876 if opts.get('date'):
2877 date = opts['date']
2878 message = ctx.description()
2879 if opts.get('log'):
2880 message += '\n(grafted from %s)' % ctx.hex()
2881 2882 node = repo.commit(text=message, user=user,
2882 2883 date=date, extra=extra, editor=editor)
2883 2884 if node is None:
2884 2885 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
2885 2886 finally:
2886 2887 wlock.release()
2887 2888
2888 2889 # remove state when we complete successfully
2889 2890 if not opts.get('dry_run') and os.path.exists(repo.join('graftstate')):
2890 2891 util.unlinkpath(repo.join('graftstate'))
2891 2892
2892 2893 return 0
2893 2894
2894 2895 @command('grep',
2895 2896 [('0', 'print0', None, _('end fields with NUL')),
2896 2897 ('', 'all', None, _('print all revisions that match')),
2897 2898 ('a', 'text', None, _('treat all files as text')),
2898 2899 ('f', 'follow', None,
2899 2900 _('follow changeset history,'
2900 2901 ' or file history across copies and renames')),
2901 2902 ('i', 'ignore-case', None, _('ignore case when matching')),
2902 2903 ('l', 'files-with-matches', None,
2903 2904 _('print only filenames and revisions that match')),
2904 2905 ('n', 'line-number', None, _('print matching line numbers')),
2905 2906 ('r', 'rev', [],
2906 2907 _('only search files changed within revision range'), _('REV')),
2907 2908 ('u', 'user', None, _('list the author (long with -v)')),
2908 2909 ('d', 'date', None, _('list the date (short with -q)')),
2909 2910 ] + walkopts,
2910 2911 _('[OPTION]... PATTERN [FILE]...'))
2911 2912 def grep(ui, repo, pattern, *pats, **opts):
2912 2913 """search for a pattern in specified files and revisions
2913 2914
2914 2915 Search revisions of files for a regular expression.
2915 2916
2916 2917 This command behaves differently than Unix grep. It only accepts
2917 2918 Python/Perl regexps. It searches repository history, not the
2918 2919 working directory. It always prints the revision number in which a
2919 2920 match appears.
2920 2921
2921 2922 By default, grep only prints output for the first revision of a
2922 2923 file in which it finds a match. To get it to print every revision
2923 2924 that contains a change in match status ("-" for a match that
2924 2925 becomes a non-match, or "+" for a non-match that becomes a match),
2925 2926 use the --all flag.
2926 2927
2927 2928 Returns 0 if a match is found, 1 otherwise.
2928 2929 """
2929 2930 reflags = re.M
2930 2931 if opts.get('ignore_case'):
2931 2932 reflags |= re.I
2932 2933 try:
2933 2934 regexp = re.compile(pattern, reflags)
2934 2935 except re.error, inst:
2935 2936 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2936 2937 return 1
2937 2938 sep, eol = ':', '\n'
2938 2939 if opts.get('print0'):
2939 2940 sep = eol = '\0'
2940 2941
2941 2942 getfile = util.lrucachefunc(repo.file)
2942 2943
2943 2944 def matchlines(body):
2944 2945 begin = 0
2945 2946 linenum = 0
2946 2947 while begin < len(body):
2947 2948 match = regexp.search(body, begin)
2948 2949 if not match:
2949 2950 break
2950 2951 mstart, mend = match.span()
2951 2952 linenum += body.count('\n', begin, mstart) + 1
2952 2953 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2953 2954 begin = body.find('\n', mend) + 1 or len(body) + 1
2954 2955 lend = begin - 1
2955 2956 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2956 2957
2957 2958 class linestate(object):
2958 2959 def __init__(self, line, linenum, colstart, colend):
2959 2960 self.line = line
2960 2961 self.linenum = linenum
2961 2962 self.colstart = colstart
2962 2963 self.colend = colend
2963 2964
2964 2965 def __hash__(self):
2965 2966 return hash((self.linenum, self.line))
2966 2967
2967 2968 def __eq__(self, other):
2968 2969 return self.line == other.line
2969 2970
2970 2971 matches = {}
2971 2972 copies = {}
2972 2973 def grepbody(fn, rev, body):
2973 2974 matches[rev].setdefault(fn, [])
2974 2975 m = matches[rev][fn]
2975 2976 for lnum, cstart, cend, line in matchlines(body):
2976 2977 s = linestate(line, lnum, cstart, cend)
2977 2978 m.append(s)
2978 2979
2979 2980 def difflinestates(a, b):
2980 2981 sm = difflib.SequenceMatcher(None, a, b)
2981 2982 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2982 2983 if tag == 'insert':
2983 2984 for i in xrange(blo, bhi):
2984 2985 yield ('+', b[i])
2985 2986 elif tag == 'delete':
2986 2987 for i in xrange(alo, ahi):
2987 2988 yield ('-', a[i])
2988 2989 elif tag == 'replace':
2989 2990 for i in xrange(alo, ahi):
2990 2991 yield ('-', a[i])
2991 2992 for i in xrange(blo, bhi):
2992 2993 yield ('+', b[i])
2993 2994
2994 2995 def display(fn, ctx, pstates, states):
2995 2996 rev = ctx.rev()
2996 2997 datefunc = ui.quiet and util.shortdate or util.datestr
2997 2998 found = False
2998 2999 filerevmatches = {}
2999 3000 def binary():
3000 3001 flog = getfile(fn)
3001 3002 return util.binary(flog.read(ctx.filenode(fn)))
3002 3003
3003 3004 if opts.get('all'):
3004 3005 iter = difflinestates(pstates, states)
3005 3006 else:
3006 3007 iter = [('', l) for l in states]
3007 3008 for change, l in iter:
3008 3009 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3009 3010 before, match, after = None, None, None
3010 3011
3011 3012 if opts.get('line_number'):
3012 3013 cols.append((str(l.linenum), 'grep.linenumber'))
3013 3014 if opts.get('all'):
3014 3015 cols.append((change, 'grep.change'))
3015 3016 if opts.get('user'):
3016 3017 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3017 3018 if opts.get('date'):
3018 3019 cols.append((datefunc(ctx.date()), 'grep.date'))
3019 3020 if opts.get('files_with_matches'):
3020 3021 c = (fn, rev)
3021 3022 if c in filerevmatches:
3022 3023 continue
3023 3024 filerevmatches[c] = 1
3024 3025 else:
3025 3026 before = l.line[:l.colstart]
3026 3027 match = l.line[l.colstart:l.colend]
3027 3028 after = l.line[l.colend:]
3028 3029 for col, label in cols[:-1]:
3029 3030 ui.write(col, label=label)
3030 3031 ui.write(sep, label='grep.sep')
3031 3032 ui.write(cols[-1][0], label=cols[-1][1])
3032 3033 if before is not None:
3033 3034 ui.write(sep, label='grep.sep')
3034 3035 if not opts.get('text') and binary():
3035 3036 ui.write(" Binary file matches")
3036 3037 else:
3037 3038 ui.write(before)
3038 3039 ui.write(match, label='grep.match')
3039 3040 ui.write(after)
3040 3041 ui.write(eol)
3041 3042 found = True
3042 3043 return found
3043 3044
3044 3045 skip = {}
3045 3046 revfiles = {}
3046 3047 matchfn = scmutil.match(repo[None], pats, opts)
3047 3048 found = False
3048 3049 follow = opts.get('follow')
3049 3050
3050 3051 def prep(ctx, fns):
3051 3052 rev = ctx.rev()
3052 3053 pctx = ctx.p1()
3053 3054 parent = pctx.rev()
3054 3055 matches.setdefault(rev, {})
3055 3056 matches.setdefault(parent, {})
3056 3057 files = revfiles.setdefault(rev, [])
3057 3058 for fn in fns:
3058 3059 flog = getfile(fn)
3059 3060 try:
3060 3061 fnode = ctx.filenode(fn)
3061 3062 except error.LookupError:
3062 3063 continue
3063 3064
3064 3065 copied = flog.renamed(fnode)
3065 3066 copy = follow and copied and copied[0]
3066 3067 if copy:
3067 3068 copies.setdefault(rev, {})[fn] = copy
3068 3069 if fn in skip:
3069 3070 if copy:
3070 3071 skip[copy] = True
3071 3072 continue
3072 3073 files.append(fn)
3073 3074
3074 3075 if fn not in matches[rev]:
3075 3076 grepbody(fn, rev, flog.read(fnode))
3076 3077
3077 3078 pfn = copy or fn
3078 3079 if pfn not in matches[parent]:
3079 3080 try:
3080 3081 fnode = pctx.filenode(pfn)
3081 3082 grepbody(pfn, parent, flog.read(fnode))
3082 3083 except error.LookupError:
3083 3084 pass
3084 3085
3085 3086 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3086 3087 rev = ctx.rev()
3087 3088 parent = ctx.p1().rev()
3088 3089 for fn in sorted(revfiles.get(rev, [])):
3089 3090 states = matches[rev][fn]
3090 3091 copy = copies.get(rev, {}).get(fn)
3091 3092 if fn in skip:
3092 3093 if copy:
3093 3094 skip[copy] = True
3094 3095 continue
3095 3096 pstates = matches.get(parent, {}).get(copy or fn, [])
3096 3097 if pstates or states:
3097 3098 r = display(fn, ctx, pstates, states)
3098 3099 found = found or r
3099 3100 if r and not opts.get('all'):
3100 3101 skip[fn] = True
3101 3102 if copy:
3102 3103 skip[copy] = True
3103 3104 del matches[rev]
3104 3105 del revfiles[rev]
3105 3106
3106 3107 return not found
3107 3108
3108 3109 @command('heads',
3109 3110 [('r', 'rev', '',
3110 3111 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3111 3112 ('t', 'topo', False, _('show topological heads only')),
3112 3113 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3113 3114 ('c', 'closed', False, _('show normal and closed branch heads')),
3114 3115 ] + templateopts,
3115 3116 _('[-ct] [-r STARTREV] [REV]...'))
3116 3117 def heads(ui, repo, *branchrevs, **opts):
3117 3118 """show current repository heads or show branch heads
3118 3119
3119 3120 With no arguments, show all repository branch heads.
3120 3121
3121 3122 Repository "heads" are changesets with no child changesets. They are
3122 3123 where development generally takes place and are the usual targets
3123 3124 for update and merge operations. Branch heads are changesets that have
3124 3125 no child changeset on the same branch.
3125 3126
3126 3127 If one or more REVs are given, only branch heads on the branches
3127 3128 associated with the specified changesets are shown. This means
3128 3129 that you can use :hg:`heads foo` to see the heads on a branch
3129 3130 named ``foo``.
3130 3131
3131 3132 If -c/--closed is specified, also show branch heads marked closed
3132 3133 (see :hg:`commit --close-branch`).
3133 3134
3134 3135 If STARTREV is specified, only those heads that are descendants of
3135 3136 STARTREV will be displayed.
3136 3137
3137 3138 If -t/--topo is specified, named branch mechanics will be ignored and only
3138 3139 changesets without children will be shown.
3139 3140
3140 3141 Returns 0 if matching heads are found, 1 if not.
3141 3142 """
3142 3143
3143 3144 start = None
3144 3145 if 'rev' in opts:
3145 3146 start = scmutil.revsingle(repo, opts['rev'], None).node()
3146 3147
3147 3148 if opts.get('topo'):
3148 3149 heads = [repo[h] for h in repo.heads(start)]
3149 3150 else:
3150 3151 heads = []
3151 3152 for branch in repo.branchmap():
3152 3153 heads += repo.branchheads(branch, start, opts.get('closed'))
3153 3154 heads = [repo[h] for h in heads]
3154 3155
3155 3156 if branchrevs:
3156 3157 branches = set(repo[br].branch() for br in branchrevs)
3157 3158 heads = [h for h in heads if h.branch() in branches]
3158 3159
3159 3160 if opts.get('active') and branchrevs:
3160 3161 dagheads = repo.heads(start)
3161 3162 heads = [h for h in heads if h.node() in dagheads]
3162 3163
3163 3164 if branchrevs:
3164 3165 haveheads = set(h.branch() for h in heads)
3165 3166 if branches - haveheads:
3166 3167 headless = ', '.join(b for b in branches - haveheads)
3167 3168 msg = _('no open branch heads found on branches %s')
3168 3169 if opts.get('rev'):
3169 3170 msg += _(' (started at %s)') % opts['rev']
3170 3171 ui.warn((msg + '\n') % headless)
3171 3172
3172 3173 if not heads:
3173 3174 return 1
3174 3175
3175 3176 heads = sorted(heads, key=lambda x: -x.rev())
3176 3177 displayer = cmdutil.show_changeset(ui, repo, opts)
3177 3178 for ctx in heads:
3178 3179 displayer.show(ctx)
3179 3180 displayer.close()
3180 3181
3181 3182 @command('help',
3182 3183 [('e', 'extension', None, _('show only help for extensions')),
3183 3184 ('c', 'command', None, _('show only help for commands')),
3184 3185 ('k', 'keyword', '', _('show topics matching keyword')),
3185 3186 ],
3186 3187 _('[-ec] [TOPIC]'))
3187 3188 def help_(ui, name=None, unknowncmd=False, full=True, **opts):
3188 3189 """show help for a given topic or a help overview
3189 3190
3190 3191 With no arguments, print a list of commands with short help messages.
3191 3192
3192 3193 Given a topic, extension, or command name, print help for that
3193 3194 topic.
3194 3195
3195 3196 Returns 0 if successful.
3196 3197 """
3197 3198
3198 3199 textwidth = min(ui.termwidth(), 80) - 2
3199 3200
3200 3201 def helpcmd(name):
3201 3202 try:
3202 3203 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
3203 3204 except error.AmbiguousCommand, inst:
3204 3205 # py3k fix: except vars can't be used outside the scope of the
3205 3206 # except block, nor can be used inside a lambda. python issue4617
3206 3207 prefix = inst.args[0]
3207 3208 select = lambda c: c.lstrip('^').startswith(prefix)
3208 3209 rst = helplist(select)
3209 3210 return rst
3210 3211
3211 3212 rst = []
3212 3213
3213 3214 # check if it's an invalid alias and display its error if it is
3214 3215 if getattr(entry[0], 'badalias', False):
3215 3216 if not unknowncmd:
3216 3217 ui.pushbuffer()
3217 3218 entry[0](ui)
3218 3219 rst.append(ui.popbuffer())
3219 3220 return rst
3220 3221
3221 3222 # synopsis
3222 3223 if len(entry) > 2:
3223 3224 if entry[2].startswith('hg'):
3224 3225 rst.append("%s\n" % entry[2])
3225 3226 else:
3226 3227 rst.append('hg %s %s\n' % (aliases[0], entry[2]))
3227 3228 else:
3228 3229 rst.append('hg %s\n' % aliases[0])
3229 3230 # aliases
3230 3231 if full and not ui.quiet and len(aliases) > 1:
3231 3232 rst.append(_("\naliases: %s\n") % ', '.join(aliases[1:]))
3232 3233 rst.append('\n')
3233 3234
3234 3235 # description
3235 3236 doc = gettext(entry[0].__doc__)
3236 3237 if not doc:
3237 3238 doc = _("(no help text available)")
3238 3239 if util.safehasattr(entry[0], 'definition'): # aliased command
3239 3240 if entry[0].definition.startswith('!'): # shell alias
3240 3241 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
3241 3242 else:
3242 3243 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
3243 3244 doc = doc.splitlines(True)
3244 3245 if ui.quiet or not full:
3245 3246 rst.append(doc[0])
3246 3247 else:
3247 3248 rst.extend(doc)
3248 3249 rst.append('\n')
3249 3250
3250 3251 # check if this command shadows a non-trivial (multi-line)
3251 3252 # extension help text
3252 3253 try:
3253 3254 mod = extensions.find(name)
3254 3255 doc = gettext(mod.__doc__) or ''
3255 3256 if '\n' in doc.strip():
3256 3257 msg = _('use "hg help -e %s" to show help for '
3257 3258 'the %s extension') % (name, name)
3258 3259 rst.append('\n%s\n' % msg)
3259 3260 except KeyError:
3260 3261 pass
3261 3262
3262 3263 # options
3263 3264 if not ui.quiet and entry[1]:
3264 3265 rst.append('\n%s\n\n' % _("options:"))
3265 3266 rst.append(help.optrst(entry[1], ui.verbose))
3266 3267
3267 3268 if ui.verbose:
3268 3269 rst.append('\n%s\n\n' % _("global options:"))
3269 3270 rst.append(help.optrst(globalopts, ui.verbose))
3270 3271
3271 3272 if not ui.verbose:
3272 3273 if not full:
3273 3274 rst.append(_('\nuse "hg help %s" to show the full help text\n')
3274 3275 % name)
3275 3276 elif not ui.quiet:
3276 3277 omitted = _('use "hg -v help %s" to show more complete'
3277 3278 ' help and the global options') % name
3278 3279 notomitted = _('use "hg -v help %s" to show'
3279 3280 ' the global options') % name
3280 3281 help.indicateomitted(rst, omitted, notomitted)
3281 3282
3282 3283 return rst
3283 3284
3284 3285
3285 3286 def helplist(select=None):
3286 3287 # list of commands
3287 3288 if name == "shortlist":
3288 3289 header = _('basic commands:\n\n')
3289 3290 else:
3290 3291 header = _('list of commands:\n\n')
3291 3292
3292 3293 h = {}
3293 3294 cmds = {}
3294 3295 for c, e in table.iteritems():
3295 3296 f = c.split("|", 1)[0]
3296 3297 if select and not select(f):
3297 3298 continue
3298 3299 if (not select and name != 'shortlist' and
3299 3300 e[0].__module__ != __name__):
3300 3301 continue
3301 3302 if name == "shortlist" and not f.startswith("^"):
3302 3303 continue
3303 3304 f = f.lstrip("^")
3304 3305 if not ui.debugflag and f.startswith("debug"):
3305 3306 continue
3306 3307 doc = e[0].__doc__
3307 3308 if doc and 'DEPRECATED' in doc and not ui.verbose:
3308 3309 continue
3309 3310 doc = gettext(doc)
3310 3311 if not doc:
3311 3312 doc = _("(no help text available)")
3312 3313 h[f] = doc.splitlines()[0].rstrip()
3313 3314 cmds[f] = c.lstrip("^")
3314 3315
3315 3316 rst = []
3316 3317 if not h:
3317 3318 if not ui.quiet:
3318 3319 rst.append(_('no commands defined\n'))
3319 3320 return rst
3320 3321
3321 3322 if not ui.quiet:
3322 3323 rst.append(header)
3323 3324 fns = sorted(h)
3324 3325 for f in fns:
3325 3326 if ui.verbose:
3326 3327 commands = cmds[f].replace("|",", ")
3327 3328 rst.append(" :%s: %s\n" % (commands, h[f]))
3328 3329 else:
3329 3330 rst.append(' :%s: %s\n' % (f, h[f]))
3330 3331
3331 3332 if not name:
3332 3333 exts = help.listexts(_('enabled extensions:'), extensions.enabled())
3333 3334 if exts:
3334 3335 rst.append('\n')
3335 3336 rst.extend(exts)
3336 3337
3337 3338 rst.append(_("\nadditional help topics:\n\n"))
3338 3339 topics = []
3339 3340 for names, header, doc in help.helptable:
3340 3341 topics.append((names[0], header))
3341 3342 for t, desc in topics:
3342 3343 rst.append(" :%s: %s\n" % (t, desc))
3343 3344
3344 3345 optlist = []
3345 3346 if not ui.quiet:
3346 3347 if ui.verbose:
3347 3348 optlist.append((_("global options:"), globalopts))
3348 3349 if name == 'shortlist':
3349 3350 optlist.append((_('use "hg help" for the full list '
3350 3351 'of commands'), ()))
3351 3352 else:
3352 3353 if name == 'shortlist':
3353 3354 msg = _('use "hg help" for the full list of commands '
3354 3355 'or "hg -v" for details')
3355 3356 elif name and not full:
3356 3357 msg = _('use "hg help %s" to show the full help '
3357 3358 'text') % name
3358 3359 else:
3359 3360 msg = _('use "hg -v help%s" to show builtin aliases and '
3360 3361 'global options') % (name and " " + name or "")
3361 3362 optlist.append((msg, ()))
3362 3363
3363 3364 if optlist:
3364 3365 for title, options in optlist:
3365 3366 rst.append('\n%s\n' % title)
3366 3367 if options:
3367 3368 rst.append('\n%s\n' % help.optrst(options, ui.verbose))
3368 3369 return rst
3369 3370
3370 3371 def helptopic(name):
3371 3372 for names, header, doc in help.helptable:
3372 3373 if name in names:
3373 3374 break
3374 3375 else:
3375 3376 raise error.UnknownCommand(name)
3376 3377
3377 3378 rst = ["%s\n\n" % header]
3378 3379 # description
3379 3380 if not doc:
3380 3381 rst.append(" %s\n" % _("(no help text available)"))
3381 3382 if util.safehasattr(doc, '__call__'):
3382 3383 rst += [" %s\n" % l for l in doc().splitlines()]
3383 3384
3384 3385 if not ui.verbose:
3385 3386 omitted = (_('use "hg help -v %s" to show more complete help') %
3386 3387 name)
3387 3388 help.indicateomitted(rst, omitted)
3388 3389
3389 3390 try:
3390 3391 cmdutil.findcmd(name, table)
3391 3392 rst.append(_('\nuse "hg help -c %s" to see help for '
3392 3393 'the %s command\n') % (name, name))
3393 3394 except error.UnknownCommand:
3394 3395 pass
3395 3396 return rst
3396 3397
3397 3398 def helpext(name):
3398 3399 try:
3399 3400 mod = extensions.find(name)
3400 3401 doc = gettext(mod.__doc__) or _('no help text available')
3401 3402 except KeyError:
3402 3403 mod = None
3403 3404 doc = extensions.disabledext(name)
3404 3405 if not doc:
3405 3406 raise error.UnknownCommand(name)
3406 3407
3407 3408 if '\n' not in doc:
3408 3409 head, tail = doc, ""
3409 3410 else:
3410 3411 head, tail = doc.split('\n', 1)
3411 3412 rst = [_('%s extension - %s\n\n') % (name.split('.')[-1], head)]
3412 3413 if tail:
3413 3414 rst.extend(tail.splitlines(True))
3414 3415 rst.append('\n')
3415 3416
3416 3417 if not ui.verbose:
3417 3418 omitted = (_('use "hg help -v %s" to show more complete help') %
3418 3419 name)
3419 3420 help.indicateomitted(rst, omitted)
3420 3421
3421 3422 if mod:
3422 3423 try:
3423 3424 ct = mod.cmdtable
3424 3425 except AttributeError:
3425 3426 ct = {}
3426 3427 modcmds = set([c.split('|', 1)[0] for c in ct])
3427 3428 rst.extend(helplist(modcmds.__contains__))
3428 3429 else:
3429 3430 rst.append(_('use "hg help extensions" for information on enabling '
3430 3431 'extensions\n'))
3431 3432 return rst
3432 3433
3433 3434 def helpextcmd(name):
3434 3435 cmd, ext, mod = extensions.disabledcmd(ui, name,
3435 3436 ui.configbool('ui', 'strict'))
3436 3437 doc = gettext(mod.__doc__).splitlines()[0]
3437 3438
3438 3439 rst = help.listexts(_("'%s' is provided by the following "
3439 3440 "extension:") % cmd, {ext: doc}, indent=4)
3440 3441 rst.append('\n')
3441 3442 rst.append(_('use "hg help extensions" for information on enabling '
3442 3443 'extensions\n'))
3443 3444 return rst
3444 3445
3445 3446
3446 3447 rst = []
3447 3448 kw = opts.get('keyword')
3448 3449 if kw:
3449 3450 matches = help.topicmatch(kw)
3450 3451 for t, title in (('topics', _('Topics')),
3451 3452 ('commands', _('Commands')),
3452 3453 ('extensions', _('Extensions')),
3453 3454 ('extensioncommands', _('Extension Commands'))):
3454 3455 if matches[t]:
3455 3456 rst.append('%s:\n\n' % title)
3456 3457 rst.extend(minirst.maketable(sorted(matches[t]), 1))
3457 3458 rst.append('\n')
3458 3459 elif name and name != 'shortlist':
3459 3460 i = None
3460 3461 if unknowncmd:
3461 3462 queries = (helpextcmd,)
3462 3463 elif opts.get('extension'):
3463 3464 queries = (helpext,)
3464 3465 elif opts.get('command'):
3465 3466 queries = (helpcmd,)
3466 3467 else:
3467 3468 queries = (helptopic, helpcmd, helpext, helpextcmd)
3468 3469 for f in queries:
3469 3470 try:
3470 3471 rst = f(name)
3471 3472 i = None
3472 3473 break
3473 3474 except error.UnknownCommand, inst:
3474 3475 i = inst
3475 3476 if i:
3476 3477 raise i
3477 3478 else:
3478 3479 # program name
3479 3480 if not ui.quiet:
3480 3481 rst = [_("Mercurial Distributed SCM\n"), '\n']
3481 3482 rst.extend(helplist())
3482 3483
3483 3484 keep = ui.verbose and ['verbose'] or []
3484 3485 text = ''.join(rst)
3485 3486 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3486 3487 if 'verbose' in pruned:
3487 3488 keep.append('omitted')
3488 3489 else:
3489 3490 keep.append('notomitted')
3490 3491 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3491 3492 ui.write(formatted)
3492 3493
3493 3494
3494 3495 @command('identify|id',
3495 3496 [('r', 'rev', '',
3496 3497 _('identify the specified revision'), _('REV')),
3497 3498 ('n', 'num', None, _('show local revision number')),
3498 3499 ('i', 'id', None, _('show global revision id')),
3499 3500 ('b', 'branch', None, _('show branch')),
3500 3501 ('t', 'tags', None, _('show tags')),
3501 3502 ('B', 'bookmarks', None, _('show bookmarks')),
3502 3503 ] + remoteopts,
3503 3504 _('[-nibtB] [-r REV] [SOURCE]'))
3504 3505 def identify(ui, repo, source=None, rev=None,
3505 3506 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3506 3507 """identify the working copy or specified revision
3507 3508
3508 3509 Print a summary identifying the repository state at REV using one or
3509 3510 two parent hash identifiers, followed by a "+" if the working
3510 3511 directory has uncommitted changes, the branch name (if not default),
3511 3512 a list of tags, and a list of bookmarks.
3512 3513
3513 3514 When REV is not given, print a summary of the current state of the
3514 3515 repository.
3515 3516
3516 3517 Specifying a path to a repository root or Mercurial bundle will
3517 3518 cause lookup to operate on that repository/bundle.
3518 3519
3519 3520 .. container:: verbose
3520 3521
3521 3522 Examples:
3522 3523
3523 3524 - generate a build identifier for the working directory::
3524 3525
3525 3526 hg id --id > build-id.dat
3526 3527
3527 3528 - find the revision corresponding to a tag::
3528 3529
3529 3530 hg id -n -r 1.3
3530 3531
3531 3532 - check the most recent revision of a remote repository::
3532 3533
3533 3534 hg id -r tip http://selenic.com/hg/
3534 3535
3535 3536 Returns 0 if successful.
3536 3537 """
3537 3538
3538 3539 if not repo and not source:
3539 3540 raise util.Abort(_("there is no Mercurial repository here "
3540 3541 "(.hg not found)"))
3541 3542
3542 3543 hexfunc = ui.debugflag and hex or short
3543 3544 default = not (num or id or branch or tags or bookmarks)
3544 3545 output = []
3545 3546 revs = []
3546 3547
3547 3548 if source:
3548 3549 source, branches = hg.parseurl(ui.expandpath(source))
3549 3550 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3550 3551 repo = peer.local()
3551 3552 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3552 3553
3553 3554 if not repo:
3554 3555 if num or branch or tags:
3555 3556 raise util.Abort(
3556 3557 _("can't query remote revision number, branch, or tags"))
3557 3558 if not rev and revs:
3558 3559 rev = revs[0]
3559 3560 if not rev:
3560 3561 rev = "tip"
3561 3562
3562 3563 remoterev = peer.lookup(rev)
3563 3564 if default or id:
3564 3565 output = [hexfunc(remoterev)]
3565 3566
3566 3567 def getbms():
3567 3568 bms = []
3568 3569
3569 3570 if 'bookmarks' in peer.listkeys('namespaces'):
3570 3571 hexremoterev = hex(remoterev)
3571 3572 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3572 3573 if bmr == hexremoterev]
3573 3574
3574 3575 return bms
3575 3576
3576 3577 if bookmarks:
3577 3578 output.extend(getbms())
3578 3579 elif default and not ui.quiet:
3579 3580 # multiple bookmarks for a single parent separated by '/'
3580 3581 bm = '/'.join(getbms())
3581 3582 if bm:
3582 3583 output.append(bm)
3583 3584 else:
3584 3585 if not rev:
3585 3586 ctx = repo[None]
3586 3587 parents = ctx.parents()
3587 3588 changed = ""
3588 3589 if default or id or num:
3589 3590 if (util.any(repo.status())
3590 3591 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3591 3592 changed = '+'
3592 3593 if default or id:
3593 3594 output = ["%s%s" %
3594 3595 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3595 3596 if num:
3596 3597 output.append("%s%s" %
3597 3598 ('+'.join([str(p.rev()) for p in parents]), changed))
3598 3599 else:
3599 3600 ctx = scmutil.revsingle(repo, rev)
3600 3601 if default or id:
3601 3602 output = [hexfunc(ctx.node())]
3602 3603 if num:
3603 3604 output.append(str(ctx.rev()))
3604 3605
3605 3606 if default and not ui.quiet:
3606 3607 b = ctx.branch()
3607 3608 if b != 'default':
3608 3609 output.append("(%s)" % b)
3609 3610
3610 3611 # multiple tags for a single parent separated by '/'
3611 3612 t = '/'.join(ctx.tags())
3612 3613 if t:
3613 3614 output.append(t)
3614 3615
3615 3616 # multiple bookmarks for a single parent separated by '/'
3616 3617 bm = '/'.join(ctx.bookmarks())
3617 3618 if bm:
3618 3619 output.append(bm)
3619 3620 else:
3620 3621 if branch:
3621 3622 output.append(ctx.branch())
3622 3623
3623 3624 if tags:
3624 3625 output.extend(ctx.tags())
3625 3626
3626 3627 if bookmarks:
3627 3628 output.extend(ctx.bookmarks())
3628 3629
3629 3630 ui.write("%s\n" % ' '.join(output))
3630 3631
3631 3632 @command('import|patch',
3632 3633 [('p', 'strip', 1,
3633 3634 _('directory strip option for patch. This has the same '
3634 3635 'meaning as the corresponding patch option'), _('NUM')),
3635 3636 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3636 3637 ('e', 'edit', False, _('invoke editor on commit messages')),
3637 3638 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3638 3639 ('', 'no-commit', None,
3639 3640 _("don't commit, just update the working directory")),
3640 3641 ('', 'bypass', None,
3641 3642 _("apply patch without touching the working directory")),
3642 3643 ('', 'exact', None,
3643 3644 _('apply patch to the nodes from which it was generated')),
3644 3645 ('', 'import-branch', None,
3645 3646 _('use any branch information in patch (implied by --exact)'))] +
3646 3647 commitopts + commitopts2 + similarityopts,
3647 3648 _('[OPTION]... PATCH...'))
3648 3649 def import_(ui, repo, patch1=None, *patches, **opts):
3649 3650 """import an ordered set of patches
3650 3651
3651 3652 Import a list of patches and commit them individually (unless
3652 3653 --no-commit is specified).
3653 3654
3654 3655 If there are outstanding changes in the working directory, import
3655 3656 will abort unless given the -f/--force flag.
3656 3657
3657 3658 You can import a patch straight from a mail message. Even patches
3658 3659 as attachments work (to use the body part, it must have type
3659 3660 text/plain or text/x-patch). From and Subject headers of email
3660 3661 message are used as default committer and commit message. All
3661 3662 text/plain body parts before first diff are added to commit
3662 3663 message.
3663 3664
3664 3665 If the imported patch was generated by :hg:`export`, user and
3665 3666 description from patch override values from message headers and
3666 3667 body. Values given on command line with -m/--message and -u/--user
3667 3668 override these.
3668 3669
3669 3670 If --exact is specified, import will set the working directory to
3670 3671 the parent of each patch before applying it, and will abort if the
3671 3672 resulting changeset has a different ID than the one recorded in
3672 3673 the patch. This may happen due to character set problems or other
3673 3674 deficiencies in the text patch format.
3674 3675
3675 3676 Use --bypass to apply and commit patches directly to the
3676 3677 repository, not touching the working directory. Without --exact,
3677 3678 patches will be applied on top of the working directory parent
3678 3679 revision.
3679 3680
3680 3681 With -s/--similarity, hg will attempt to discover renames and
3681 3682 copies in the patch in the same way as :hg:`addremove`.
3682 3683
3683 3684 To read a patch from standard input, use "-" as the patch name. If
3684 3685 a URL is specified, the patch will be downloaded from it.
3685 3686 See :hg:`help dates` for a list of formats valid for -d/--date.
3686 3687
3687 3688 .. container:: verbose
3688 3689
3689 3690 Examples:
3690 3691
3691 3692 - import a traditional patch from a website and detect renames::
3692 3693
3693 3694 hg import -s 80 http://example.com/bugfix.patch
3694 3695
3695 3696 - import a changeset from an hgweb server::
3696 3697
3697 3698 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3698 3699
3699 3700 - import all the patches in an Unix-style mbox::
3700 3701
3701 3702 hg import incoming-patches.mbox
3702 3703
3703 3704 - attempt to exactly restore an exported changeset (not always
3704 3705 possible)::
3705 3706
3706 3707 hg import --exact proposed-fix.patch
3707 3708
3708 3709 Returns 0 on success.
3709 3710 """
3710 3711
3711 3712 if not patch1:
3712 3713 raise util.Abort(_('need at least one patch to import'))
3713 3714
3714 3715 patches = (patch1,) + patches
3715 3716
3716 3717 date = opts.get('date')
3717 3718 if date:
3718 3719 opts['date'] = util.parsedate(date)
3719 3720
3720 3721 editor = cmdutil.commiteditor
3721 3722 if opts.get('edit'):
3722 3723 editor = cmdutil.commitforceeditor
3723 3724
3724 3725 update = not opts.get('bypass')
3725 3726 if not update and opts.get('no_commit'):
3726 3727 raise util.Abort(_('cannot use --no-commit with --bypass'))
3727 3728 try:
3728 3729 sim = float(opts.get('similarity') or 0)
3729 3730 except ValueError:
3730 3731 raise util.Abort(_('similarity must be a number'))
3731 3732 if sim < 0 or sim > 100:
3732 3733 raise util.Abort(_('similarity must be between 0 and 100'))
3733 3734 if sim and not update:
3734 3735 raise util.Abort(_('cannot use --similarity with --bypass'))
3735 3736
3736 3737 if (opts.get('exact') or not opts.get('force')) and update:
3737 3738 cmdutil.bailifchanged(repo)
3738 3739
3739 3740 base = opts["base"]
3740 3741 strip = opts["strip"]
3741 3742 wlock = lock = tr = None
3742 3743 msgs = []
3743 3744
3744 3745 def checkexact(repo, n, nodeid):
3745 3746 if opts.get('exact') and hex(n) != nodeid:
3746 3747 repo.rollback()
3747 3748 raise util.Abort(_('patch is damaged or loses information'))
3748 3749
3749 3750 def tryone(ui, hunk, parents):
3750 3751 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3751 3752 patch.extract(ui, hunk)
3752 3753
3753 3754 if not tmpname:
3754 3755 return (None, None)
3755 3756 msg = _('applied to working directory')
3756 3757
3757 3758 try:
3758 3759 cmdline_message = cmdutil.logmessage(ui, opts)
3759 3760 if cmdline_message:
3760 3761 # pickup the cmdline msg
3761 3762 message = cmdline_message
3762 3763 elif message:
3763 3764 # pickup the patch msg
3764 3765 message = message.strip()
3765 3766 else:
3766 3767 # launch the editor
3767 3768 message = None
3768 3769 ui.debug('message:\n%s\n' % message)
3769 3770
3770 3771 if len(parents) == 1:
3771 3772 parents.append(repo[nullid])
3772 3773 if opts.get('exact'):
3773 3774 if not nodeid or not p1:
3774 3775 raise util.Abort(_('not a Mercurial patch'))
3775 3776 p1 = repo[p1]
3776 3777 p2 = repo[p2 or nullid]
3777 3778 elif p2:
3778 3779 try:
3779 3780 p1 = repo[p1]
3780 3781 p2 = repo[p2]
3781 3782 # Without any options, consider p2 only if the
3782 3783 # patch is being applied on top of the recorded
3783 3784 # first parent.
3784 3785 if p1 != parents[0]:
3785 3786 p1 = parents[0]
3786 3787 p2 = repo[nullid]
3787 3788 except error.RepoError:
3788 3789 p1, p2 = parents
3789 3790 else:
3790 3791 p1, p2 = parents
3791 3792
3792 3793 n = None
3793 3794 if update:
3794 3795 if p1 != parents[0]:
3795 3796 hg.clean(repo, p1.node())
3796 3797 if p2 != parents[1]:
3797 3798 repo.setparents(p1.node(), p2.node())
3798 3799
3799 3800 if opts.get('exact') or opts.get('import_branch'):
3800 3801 repo.dirstate.setbranch(branch or 'default')
3801 3802
3802 3803 files = set()
3803 3804 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3804 3805 eolmode=None, similarity=sim / 100.0)
3805 3806 files = list(files)
3806 3807 if opts.get('no_commit'):
3807 3808 if message:
3808 3809 msgs.append(message)
3809 3810 else:
3810 3811 if opts.get('exact') or p2:
3811 3812 # If you got here, you either use --force and know what
3812 3813 # you are doing or used --exact or a merge patch while
3813 3814 # being updated to its first parent.
3814 3815 m = None
3815 3816 else:
3816 3817 m = scmutil.matchfiles(repo, files or [])
3817 3818 n = repo.commit(message, opts.get('user') or user,
3818 3819 opts.get('date') or date, match=m,
3819 3820 editor=editor)
3820 3821 checkexact(repo, n, nodeid)
3821 3822 else:
3822 3823 if opts.get('exact') or opts.get('import_branch'):
3823 3824 branch = branch or 'default'
3824 3825 else:
3825 3826 branch = p1.branch()
3826 3827 store = patch.filestore()
3827 3828 try:
3828 3829 files = set()
3829 3830 try:
3830 3831 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3831 3832 files, eolmode=None)
3832 3833 except patch.PatchError, e:
3833 3834 raise util.Abort(str(e))
3834 3835 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3835 3836 message,
3836 3837 opts.get('user') or user,
3837 3838 opts.get('date') or date,
3838 3839 branch, files, store,
3839 3840 editor=cmdutil.commiteditor)
3840 3841 repo.savecommitmessage(memctx.description())
3841 3842 n = memctx.commit()
3842 3843 checkexact(repo, n, nodeid)
3843 3844 finally:
3844 3845 store.close()
3845 3846 if n:
3846 3847 # i18n: refers to a short changeset id
3847 3848 msg = _('created %s') % short(n)
3848 3849 return (msg, n)
3849 3850 finally:
3850 3851 os.unlink(tmpname)
3851 3852
3852 3853 try:
3853 3854 try:
3854 3855 wlock = repo.wlock()
3855 3856 if not opts.get('no_commit'):
3856 3857 lock = repo.lock()
3857 3858 tr = repo.transaction('import')
3858 3859 parents = repo.parents()
3859 3860 for patchurl in patches:
3860 3861 if patchurl == '-':
3861 3862 ui.status(_('applying patch from stdin\n'))
3862 3863 patchfile = ui.fin
3863 3864 patchurl = 'stdin' # for error message
3864 3865 else:
3865 3866 patchurl = os.path.join(base, patchurl)
3866 3867 ui.status(_('applying %s\n') % patchurl)
3867 3868 patchfile = hg.openpath(ui, patchurl)
3868 3869
3869 3870 haspatch = False
3870 3871 for hunk in patch.split(patchfile):
3871 3872 (msg, node) = tryone(ui, hunk, parents)
3872 3873 if msg:
3873 3874 haspatch = True
3874 3875 ui.note(msg + '\n')
3875 3876 if update or opts.get('exact'):
3876 3877 parents = repo.parents()
3877 3878 else:
3878 3879 parents = [repo[node]]
3879 3880
3880 3881 if not haspatch:
3881 3882 raise util.Abort(_('%s: no diffs found') % patchurl)
3882 3883
3883 3884 if tr:
3884 3885 tr.close()
3885 3886 if msgs:
3886 3887 repo.savecommitmessage('\n* * *\n'.join(msgs))
3887 3888 except: # re-raises
3888 3889 # wlock.release() indirectly calls dirstate.write(): since
3889 3890 # we're crashing, we do not want to change the working dir
3890 3891 # parent after all, so make sure it writes nothing
3891 3892 repo.dirstate.invalidate()
3892 3893 raise
3893 3894 finally:
3894 3895 if tr:
3895 3896 tr.release()
3896 3897 release(lock, wlock)
3897 3898
3898 3899 @command('incoming|in',
3899 3900 [('f', 'force', None,
3900 3901 _('run even if remote repository is unrelated')),
3901 3902 ('n', 'newest-first', None, _('show newest record first')),
3902 3903 ('', 'bundle', '',
3903 3904 _('file to store the bundles into'), _('FILE')),
3904 3905 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3905 3906 ('B', 'bookmarks', False, _("compare bookmarks")),
3906 3907 ('b', 'branch', [],
3907 3908 _('a specific branch you would like to pull'), _('BRANCH')),
3908 3909 ] + logopts + remoteopts + subrepoopts,
3909 3910 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3910 3911 def incoming(ui, repo, source="default", **opts):
3911 3912 """show new changesets found in source
3912 3913
3913 3914 Show new changesets found in the specified path/URL or the default
3914 3915 pull location. These are the changesets that would have been pulled
3915 3916 if a pull at the time you issued this command.
3916 3917
3917 3918 For remote repository, using --bundle avoids downloading the
3918 3919 changesets twice if the incoming is followed by a pull.
3919 3920
3920 3921 See pull for valid source format details.
3921 3922
3922 3923 Returns 0 if there are incoming changes, 1 otherwise.
3923 3924 """
3924 3925 if opts.get('graph'):
3925 3926 cmdutil.checkunsupportedgraphflags([], opts)
3926 3927 def display(other, chlist, displayer):
3927 3928 revdag = cmdutil.graphrevs(other, chlist, opts)
3928 3929 showparents = [ctx.node() for ctx in repo[None].parents()]
3929 3930 cmdutil.displaygraph(ui, revdag, displayer, showparents,
3930 3931 graphmod.asciiedges)
3931 3932
3932 3933 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3933 3934 return 0
3934 3935
3935 3936 if opts.get('bundle') and opts.get('subrepos'):
3936 3937 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3937 3938
3938 3939 if opts.get('bookmarks'):
3939 3940 source, branches = hg.parseurl(ui.expandpath(source),
3940 3941 opts.get('branch'))
3941 3942 other = hg.peer(repo, opts, source)
3942 3943 if 'bookmarks' not in other.listkeys('namespaces'):
3943 3944 ui.warn(_("remote doesn't support bookmarks\n"))
3944 3945 return 0
3945 3946 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3946 3947 return bookmarks.diff(ui, repo, other)
3947 3948
3948 3949 repo._subtoppath = ui.expandpath(source)
3949 3950 try:
3950 3951 return hg.incoming(ui, repo, source, opts)
3951 3952 finally:
3952 3953 del repo._subtoppath
3953 3954
3954 3955
3955 3956 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3956 3957 def init(ui, dest=".", **opts):
3957 3958 """create a new repository in the given directory
3958 3959
3959 3960 Initialize a new repository in the given directory. If the given
3960 3961 directory does not exist, it will be created.
3961 3962
3962 3963 If no directory is given, the current directory is used.
3963 3964
3964 3965 It is possible to specify an ``ssh://`` URL as the destination.
3965 3966 See :hg:`help urls` for more information.
3966 3967
3967 3968 Returns 0 on success.
3968 3969 """
3969 3970 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3970 3971
3971 3972 @command('locate',
3972 3973 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3973 3974 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3974 3975 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3975 3976 ] + walkopts,
3976 3977 _('[OPTION]... [PATTERN]...'))
3977 3978 def locate(ui, repo, *pats, **opts):
3978 3979 """locate files matching specific patterns
3979 3980
3980 3981 Print files under Mercurial control in the working directory whose
3981 3982 names match the given patterns.
3982 3983
3983 3984 By default, this command searches all directories in the working
3984 3985 directory. To search just the current directory and its
3985 3986 subdirectories, use "--include .".
3986 3987
3987 3988 If no patterns are given to match, this command prints the names
3988 3989 of all files under Mercurial control in the working directory.
3989 3990
3990 3991 If you want to feed the output of this command into the "xargs"
3991 3992 command, use the -0 option to both this command and "xargs". This
3992 3993 will avoid the problem of "xargs" treating single filenames that
3993 3994 contain whitespace as multiple filenames.
3994 3995
3995 3996 Returns 0 if a match is found, 1 otherwise.
3996 3997 """
3997 3998 end = opts.get('print0') and '\0' or '\n'
3998 3999 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3999 4000
4000 4001 ret = 1
4001 4002 m = scmutil.match(repo[rev], pats, opts, default='relglob')
4002 4003 m.bad = lambda x, y: False
4003 4004 for abs in repo[rev].walk(m):
4004 4005 if not rev and abs not in repo.dirstate:
4005 4006 continue
4006 4007 if opts.get('fullpath'):
4007 4008 ui.write(repo.wjoin(abs), end)
4008 4009 else:
4009 4010 ui.write(((pats and m.rel(abs)) or abs), end)
4010 4011 ret = 0
4011 4012
4012 4013 return ret
4013 4014
4014 4015 @command('^log|history',
4015 4016 [('f', 'follow', None,
4016 4017 _('follow changeset history, or file history across copies and renames')),
4017 4018 ('', 'follow-first', None,
4018 4019 _('only follow the first parent of merge changesets (DEPRECATED)')),
4019 4020 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
4020 4021 ('C', 'copies', None, _('show copied files')),
4021 4022 ('k', 'keyword', [],
4022 4023 _('do case-insensitive search for a given text'), _('TEXT')),
4023 4024 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
4024 4025 ('', 'removed', None, _('include revisions where files were removed')),
4025 4026 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4026 4027 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4027 4028 ('', 'only-branch', [],
4028 4029 _('show only changesets within the given named branch (DEPRECATED)'),
4029 4030 _('BRANCH')),
4030 4031 ('b', 'branch', [],
4031 4032 _('show changesets within the given named branch'), _('BRANCH')),
4032 4033 ('P', 'prune', [],
4033 4034 _('do not display revision or any of its ancestors'), _('REV')),
4034 4035 ('', 'hidden', False, _('show hidden changesets (DEPRECATED)')),
4035 4036 ] + logopts + walkopts,
4036 4037 _('[OPTION]... [FILE]'))
4037 4038 def log(ui, repo, *pats, **opts):
4038 4039 """show revision history of entire repository or files
4039 4040
4040 4041 Print the revision history of the specified files or the entire
4041 4042 project.
4042 4043
4043 4044 If no revision range is specified, the default is ``tip:0`` unless
4044 4045 --follow is set, in which case the working directory parent is
4045 4046 used as the starting revision.
4046 4047
4047 4048 File history is shown without following rename or copy history of
4048 4049 files. Use -f/--follow with a filename to follow history across
4049 4050 renames and copies. --follow without a filename will only show
4050 4051 ancestors or descendants of the starting revision.
4051 4052
4052 4053 By default this command prints revision number and changeset id,
4053 4054 tags, non-trivial parents, user, date and time, and a summary for
4054 4055 each commit. When the -v/--verbose switch is used, the list of
4055 4056 changed files and full commit message are shown.
4056 4057
4057 4058 .. note::
4058 4059 log -p/--patch may generate unexpected diff output for merge
4059 4060 changesets, as it will only compare the merge changeset against
4060 4061 its first parent. Also, only files different from BOTH parents
4061 4062 will appear in files:.
4062 4063
4063 4064 .. note::
4064 4065 for performance reasons, log FILE may omit duplicate changes
4065 4066 made on branches and will not show deletions. To see all
4066 4067 changes including duplicates and deletions, use the --removed
4067 4068 switch.
4068 4069
4069 4070 .. container:: verbose
4070 4071
4071 4072 Some examples:
4072 4073
4073 4074 - changesets with full descriptions and file lists::
4074 4075
4075 4076 hg log -v
4076 4077
4077 4078 - changesets ancestral to the working directory::
4078 4079
4079 4080 hg log -f
4080 4081
4081 4082 - last 10 commits on the current branch::
4082 4083
4083 4084 hg log -l 10 -b .
4084 4085
4085 4086 - changesets showing all modifications of a file, including removals::
4086 4087
4087 4088 hg log --removed file.c
4088 4089
4089 4090 - all changesets that touch a directory, with diffs, excluding merges::
4090 4091
4091 4092 hg log -Mp lib/
4092 4093
4093 4094 - all revision numbers that match a keyword::
4094 4095
4095 4096 hg log -k bug --template "{rev}\\n"
4096 4097
4097 4098 - check if a given changeset is included is a tagged release::
4098 4099
4099 4100 hg log -r "a21ccf and ancestor(1.9)"
4100 4101
4101 4102 - find all changesets by some user in a date range::
4102 4103
4103 4104 hg log -k alice -d "may 2008 to jul 2008"
4104 4105
4105 4106 - summary of all changesets after the last tag::
4106 4107
4107 4108 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4108 4109
4109 4110 See :hg:`help dates` for a list of formats valid for -d/--date.
4110 4111
4111 4112 See :hg:`help revisions` and :hg:`help revsets` for more about
4112 4113 specifying revisions.
4113 4114
4114 4115 See :hg:`help templates` for more about pre-packaged styles and
4115 4116 specifying custom templates.
4116 4117
4117 4118 Returns 0 on success.
4118 4119 """
4119 4120 if opts.get('graph'):
4120 4121 return cmdutil.graphlog(ui, repo, *pats, **opts)
4121 4122
4122 4123 matchfn = scmutil.match(repo[None], pats, opts)
4123 4124 limit = cmdutil.loglimit(opts)
4124 4125 count = 0
4125 4126
4126 4127 getrenamed, endrev = None, None
4127 4128 if opts.get('copies'):
4128 4129 if opts.get('rev'):
4129 4130 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
4130 4131 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4131 4132
4132 4133 df = False
4133 4134 if opts.get("date"):
4134 4135 df = util.matchdate(opts["date"])
4135 4136
4136 4137 branches = opts.get('branch', []) + opts.get('only_branch', [])
4137 4138 opts['branch'] = [repo.lookupbranch(b) for b in branches]
4138 4139
4139 4140 displayer = cmdutil.show_changeset(ui, repo, opts, True)
4140 4141 def prep(ctx, fns):
4141 4142 rev = ctx.rev()
4142 4143 parents = [p for p in repo.changelog.parentrevs(rev)
4143 4144 if p != nullrev]
4144 4145 if opts.get('no_merges') and len(parents) == 2:
4145 4146 return
4146 4147 if opts.get('only_merges') and len(parents) != 2:
4147 4148 return
4148 4149 if opts.get('branch') and ctx.branch() not in opts['branch']:
4149 4150 return
4150 4151 if not opts.get('hidden') and ctx.hidden():
4151 4152 return
4152 4153 if df and not df(ctx.date()[0]):
4153 4154 return
4154 4155
4155 4156 lower = encoding.lower
4156 4157 if opts.get('user'):
4157 4158 luser = lower(ctx.user())
4158 4159 for k in [lower(x) for x in opts['user']]:
4159 4160 if (k in luser):
4160 4161 break
4161 4162 else:
4162 4163 return
4163 4164 if opts.get('keyword'):
4164 4165 luser = lower(ctx.user())
4165 4166 ldesc = lower(ctx.description())
4166 4167 lfiles = lower(" ".join(ctx.files()))
4167 4168 for k in [lower(x) for x in opts['keyword']]:
4168 4169 if (k in luser or k in ldesc or k in lfiles):
4169 4170 break
4170 4171 else:
4171 4172 return
4172 4173
4173 4174 copies = None
4174 4175 if getrenamed is not None and rev:
4175 4176 copies = []
4176 4177 for fn in ctx.files():
4177 4178 rename = getrenamed(fn, rev)
4178 4179 if rename:
4179 4180 copies.append((fn, rename[0]))
4180 4181
4181 4182 revmatchfn = None
4182 4183 if opts.get('patch') or opts.get('stat'):
4183 4184 if opts.get('follow') or opts.get('follow_first'):
4184 4185 # note: this might be wrong when following through merges
4185 4186 revmatchfn = scmutil.match(repo[None], fns, default='path')
4186 4187 else:
4187 4188 revmatchfn = matchfn
4188 4189
4189 4190 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4190 4191
4191 4192 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
4192 4193 if count == limit:
4193 4194 break
4194 4195 if displayer.flush(ctx.rev()):
4195 4196 count += 1
4196 4197 displayer.close()
4197 4198
4198 4199 @command('manifest',
4199 4200 [('r', 'rev', '', _('revision to display'), _('REV')),
4200 4201 ('', 'all', False, _("list files from all revisions"))],
4201 4202 _('[-r REV]'))
4202 4203 def manifest(ui, repo, node=None, rev=None, **opts):
4203 4204 """output the current or given revision of the project manifest
4204 4205
4205 4206 Print a list of version controlled files for the given revision.
4206 4207 If no revision is given, the first parent of the working directory
4207 4208 is used, or the null revision if no revision is checked out.
4208 4209
4209 4210 With -v, print file permissions, symlink and executable bits.
4210 4211 With --debug, print file revision hashes.
4211 4212
4212 4213 If option --all is specified, the list of all files from all revisions
4213 4214 is printed. This includes deleted and renamed files.
4214 4215
4215 4216 Returns 0 on success.
4216 4217 """
4217 4218
4218 4219 fm = ui.formatter('manifest', opts)
4219 4220
4220 4221 if opts.get('all'):
4221 4222 if rev or node:
4222 4223 raise util.Abort(_("can't specify a revision with --all"))
4223 4224
4224 4225 res = []
4225 4226 prefix = "data/"
4226 4227 suffix = ".i"
4227 4228 plen = len(prefix)
4228 4229 slen = len(suffix)
4229 4230 lock = repo.lock()
4230 4231 try:
4231 4232 for fn, b, size in repo.store.datafiles():
4232 4233 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4233 4234 res.append(fn[plen:-slen])
4234 4235 finally:
4235 4236 lock.release()
4236 4237 for f in res:
4237 4238 fm.startitem()
4238 4239 fm.write("path", '%s\n', f)
4239 4240 fm.end()
4240 4241 return
4241 4242
4242 4243 if rev and node:
4243 4244 raise util.Abort(_("please specify just one revision"))
4244 4245
4245 4246 if not node:
4246 4247 node = rev
4247 4248
4248 4249 char = {'l': '@', 'x': '*', '': ''}
4249 4250 mode = {'l': '644', 'x': '755', '': '644'}
4250 4251 ctx = scmutil.revsingle(repo, node)
4251 4252 mf = ctx.manifest()
4252 4253 for f in ctx:
4253 4254 fm.startitem()
4254 4255 fl = ctx[f].flags()
4255 4256 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4256 4257 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4257 4258 fm.write('path', '%s\n', f)
4258 4259 fm.end()
4259 4260
4260 4261 @command('^merge',
4261 4262 [('f', 'force', None, _('force a merge with outstanding changes')),
4262 4263 ('r', 'rev', '', _('revision to merge'), _('REV')),
4263 4264 ('P', 'preview', None,
4264 4265 _('review revisions to merge (no merge is performed)'))
4265 4266 ] + mergetoolopts,
4266 4267 _('[-P] [-f] [[-r] REV]'))
4267 4268 def merge(ui, repo, node=None, **opts):
4268 4269 """merge working directory with another revision
4269 4270
4270 4271 The current working directory is updated with all changes made in
4271 4272 the requested revision since the last common predecessor revision.
4272 4273
4273 4274 Files that changed between either parent are marked as changed for
4274 4275 the next commit and a commit must be performed before any further
4275 4276 updates to the repository are allowed. The next commit will have
4276 4277 two parents.
4277 4278
4278 4279 ``--tool`` can be used to specify the merge tool used for file
4279 4280 merges. It overrides the HGMERGE environment variable and your
4280 4281 configuration files. See :hg:`help merge-tools` for options.
4281 4282
4282 4283 If no revision is specified, the working directory's parent is a
4283 4284 head revision, and the current branch contains exactly one other
4284 4285 head, the other head is merged with by default. Otherwise, an
4285 4286 explicit revision with which to merge with must be provided.
4286 4287
4287 4288 :hg:`resolve` must be used to resolve unresolved files.
4288 4289
4289 4290 To undo an uncommitted merge, use :hg:`update --clean .` which
4290 4291 will check out a clean copy of the original merge parent, losing
4291 4292 all changes.
4292 4293
4293 4294 Returns 0 on success, 1 if there are unresolved files.
4294 4295 """
4295 4296
4296 4297 if opts.get('rev') and node:
4297 4298 raise util.Abort(_("please specify just one revision"))
4298 4299 if not node:
4299 4300 node = opts.get('rev')
4300 4301
4301 4302 if node:
4302 4303 node = scmutil.revsingle(repo, node).node()
4303 4304
4304 4305 if not node and repo._bookmarkcurrent:
4305 4306 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4306 4307 curhead = repo[repo._bookmarkcurrent]
4307 4308 if len(bmheads) == 2:
4308 4309 if curhead == bmheads[0]:
4309 4310 node = bmheads[1]
4310 4311 else:
4311 4312 node = bmheads[0]
4312 4313 elif len(bmheads) > 2:
4313 4314 raise util.Abort(_("multiple matching bookmarks to merge - "
4314 4315 "please merge with an explicit rev or bookmark"),
4315 4316 hint=_("run 'hg heads' to see all heads"))
4316 4317 elif len(bmheads) <= 1:
4317 4318 raise util.Abort(_("no matching bookmark to merge - "
4318 4319 "please merge with an explicit rev or bookmark"),
4319 4320 hint=_("run 'hg heads' to see all heads"))
4320 4321
4321 4322 if not node and not repo._bookmarkcurrent:
4322 4323 branch = repo[None].branch()
4323 4324 bheads = repo.branchheads(branch)
4324 4325 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4325 4326
4326 4327 if len(nbhs) > 2:
4327 4328 raise util.Abort(_("branch '%s' has %d heads - "
4328 4329 "please merge with an explicit rev")
4329 4330 % (branch, len(bheads)),
4330 4331 hint=_("run 'hg heads .' to see heads"))
4331 4332
4332 4333 parent = repo.dirstate.p1()
4333 4334 if len(nbhs) <= 1:
4334 4335 if len(bheads) > 1:
4335 4336 raise util.Abort(_("heads are bookmarked - "
4336 4337 "please merge with an explicit rev"),
4337 4338 hint=_("run 'hg heads' to see all heads"))
4338 4339 if len(repo.heads()) > 1:
4339 4340 raise util.Abort(_("branch '%s' has one head - "
4340 4341 "please merge with an explicit rev")
4341 4342 % branch,
4342 4343 hint=_("run 'hg heads' to see all heads"))
4343 4344 msg, hint = _('nothing to merge'), None
4344 4345 if parent != repo.lookup(branch):
4345 4346 hint = _("use 'hg update' instead")
4346 4347 raise util.Abort(msg, hint=hint)
4347 4348
4348 4349 if parent not in bheads:
4349 4350 raise util.Abort(_('working directory not at a head revision'),
4350 4351 hint=_("use 'hg update' or merge with an "
4351 4352 "explicit revision"))
4352 4353 if parent == nbhs[0]:
4353 4354 node = nbhs[-1]
4354 4355 else:
4355 4356 node = nbhs[0]
4356 4357
4357 4358 if opts.get('preview'):
4358 4359 # find nodes that are ancestors of p2 but not of p1
4359 4360 p1 = repo.lookup('.')
4360 4361 p2 = repo.lookup(node)
4361 4362 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4362 4363
4363 4364 displayer = cmdutil.show_changeset(ui, repo, opts)
4364 4365 for node in nodes:
4365 4366 displayer.show(repo[node])
4366 4367 displayer.close()
4367 4368 return 0
4368 4369
4369 4370 try:
4370 4371 # ui.forcemerge is an internal variable, do not document
4371 4372 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4372 4373 return hg.merge(repo, node, force=opts.get('force'))
4373 4374 finally:
4374 4375 ui.setconfig('ui', 'forcemerge', '')
4375 4376
4376 4377 @command('outgoing|out',
4377 4378 [('f', 'force', None, _('run even when the destination is unrelated')),
4378 4379 ('r', 'rev', [],
4379 4380 _('a changeset intended to be included in the destination'), _('REV')),
4380 4381 ('n', 'newest-first', None, _('show newest record first')),
4381 4382 ('B', 'bookmarks', False, _('compare bookmarks')),
4382 4383 ('b', 'branch', [], _('a specific branch you would like to push'),
4383 4384 _('BRANCH')),
4384 4385 ] + logopts + remoteopts + subrepoopts,
4385 4386 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4386 4387 def outgoing(ui, repo, dest=None, **opts):
4387 4388 """show changesets not found in the destination
4388 4389
4389 4390 Show changesets not found in the specified destination repository
4390 4391 or the default push location. These are the changesets that would
4391 4392 be pushed if a push was requested.
4392 4393
4393 4394 See pull for details of valid destination formats.
4394 4395
4395 4396 Returns 0 if there are outgoing changes, 1 otherwise.
4396 4397 """
4397 4398 if opts.get('graph'):
4398 4399 cmdutil.checkunsupportedgraphflags([], opts)
4399 4400 o = hg._outgoing(ui, repo, dest, opts)
4400 4401 if o is None:
4401 4402 return
4402 4403
4403 4404 revdag = cmdutil.graphrevs(repo, o, opts)
4404 4405 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4405 4406 showparents = [ctx.node() for ctx in repo[None].parents()]
4406 4407 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4407 4408 graphmod.asciiedges)
4408 4409 return 0
4409 4410
4410 4411 if opts.get('bookmarks'):
4411 4412 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4412 4413 dest, branches = hg.parseurl(dest, opts.get('branch'))
4413 4414 other = hg.peer(repo, opts, dest)
4414 4415 if 'bookmarks' not in other.listkeys('namespaces'):
4415 4416 ui.warn(_("remote doesn't support bookmarks\n"))
4416 4417 return 0
4417 4418 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4418 4419 return bookmarks.diff(ui, other, repo)
4419 4420
4420 4421 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4421 4422 try:
4422 4423 return hg.outgoing(ui, repo, dest, opts)
4423 4424 finally:
4424 4425 del repo._subtoppath
4425 4426
4426 4427 @command('parents',
4427 4428 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4428 4429 ] + templateopts,
4429 4430 _('[-r REV] [FILE]'))
4430 4431 def parents(ui, repo, file_=None, **opts):
4431 4432 """show the parents of the working directory or revision
4432 4433
4433 4434 Print the working directory's parent revisions. If a revision is
4434 4435 given via -r/--rev, the parent of that revision will be printed.
4435 4436 If a file argument is given, the revision in which the file was
4436 4437 last changed (before the working directory revision or the
4437 4438 argument to --rev if given) is printed.
4438 4439
4439 4440 Returns 0 on success.
4440 4441 """
4441 4442
4442 4443 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4443 4444
4444 4445 if file_:
4445 4446 m = scmutil.match(ctx, (file_,), opts)
4446 4447 if m.anypats() or len(m.files()) != 1:
4447 4448 raise util.Abort(_('can only specify an explicit filename'))
4448 4449 file_ = m.files()[0]
4449 4450 filenodes = []
4450 4451 for cp in ctx.parents():
4451 4452 if not cp:
4452 4453 continue
4453 4454 try:
4454 4455 filenodes.append(cp.filenode(file_))
4455 4456 except error.LookupError:
4456 4457 pass
4457 4458 if not filenodes:
4458 4459 raise util.Abort(_("'%s' not found in manifest!") % file_)
4459 4460 fl = repo.file(file_)
4460 4461 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
4461 4462 else:
4462 4463 p = [cp.node() for cp in ctx.parents()]
4463 4464
4464 4465 displayer = cmdutil.show_changeset(ui, repo, opts)
4465 4466 for n in p:
4466 4467 if n != nullid:
4467 4468 displayer.show(repo[n])
4468 4469 displayer.close()
4469 4470
4470 4471 @command('paths', [], _('[NAME]'))
4471 4472 def paths(ui, repo, search=None):
4472 4473 """show aliases for remote repositories
4473 4474
4474 4475 Show definition of symbolic path name NAME. If no name is given,
4475 4476 show definition of all available names.
4476 4477
4477 4478 Option -q/--quiet suppresses all output when searching for NAME
4478 4479 and shows only the path names when listing all definitions.
4479 4480
4480 4481 Path names are defined in the [paths] section of your
4481 4482 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4482 4483 repository, ``.hg/hgrc`` is used, too.
4483 4484
4484 4485 The path names ``default`` and ``default-push`` have a special
4485 4486 meaning. When performing a push or pull operation, they are used
4486 4487 as fallbacks if no location is specified on the command-line.
4487 4488 When ``default-push`` is set, it will be used for push and
4488 4489 ``default`` will be used for pull; otherwise ``default`` is used
4489 4490 as the fallback for both. When cloning a repository, the clone
4490 4491 source is written as ``default`` in ``.hg/hgrc``. Note that
4491 4492 ``default`` and ``default-push`` apply to all inbound (e.g.
4492 4493 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4493 4494 :hg:`bundle`) operations.
4494 4495
4495 4496 See :hg:`help urls` for more information.
4496 4497
4497 4498 Returns 0 on success.
4498 4499 """
4499 4500 if search:
4500 4501 for name, path in ui.configitems("paths"):
4501 4502 if name == search:
4502 4503 ui.status("%s\n" % util.hidepassword(path))
4503 4504 return
4504 4505 if not ui.quiet:
4505 4506 ui.warn(_("not found!\n"))
4506 4507 return 1
4507 4508 else:
4508 4509 for name, path in ui.configitems("paths"):
4509 4510 if ui.quiet:
4510 4511 ui.write("%s\n" % name)
4511 4512 else:
4512 4513 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4513 4514
4514 4515 @command('phase',
4515 4516 [('p', 'public', False, _('set changeset phase to public')),
4516 4517 ('d', 'draft', False, _('set changeset phase to draft')),
4517 4518 ('s', 'secret', False, _('set changeset phase to secret')),
4518 4519 ('f', 'force', False, _('allow to move boundary backward')),
4519 4520 ('r', 'rev', [], _('target revision'), _('REV')),
4520 4521 ],
4521 4522 _('[-p|-d|-s] [-f] [-r] REV...'))
4522 4523 def phase(ui, repo, *revs, **opts):
4523 4524 """set or show the current phase name
4524 4525
4525 4526 With no argument, show the phase name of specified revisions.
4526 4527
4527 4528 With one of -p/--public, -d/--draft or -s/--secret, change the
4528 4529 phase value of the specified revisions.
4529 4530
4530 4531 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4531 4532 lower phase to an higher phase. Phases are ordered as follows::
4532 4533
4533 4534 public < draft < secret
4534 4535
4535 4536 Return 0 on success, 1 if no phases were changed or some could not
4536 4537 be changed.
4537 4538 """
4538 4539 # search for a unique phase argument
4539 4540 targetphase = None
4540 4541 for idx, name in enumerate(phases.phasenames):
4541 4542 if opts[name]:
4542 4543 if targetphase is not None:
4543 4544 raise util.Abort(_('only one phase can be specified'))
4544 4545 targetphase = idx
4545 4546
4546 4547 # look for specified revision
4547 4548 revs = list(revs)
4548 4549 revs.extend(opts['rev'])
4549 4550 if not revs:
4550 4551 raise util.Abort(_('no revisions specified'))
4551 4552
4552 4553 revs = scmutil.revrange(repo, revs)
4553 4554
4554 4555 lock = None
4555 4556 ret = 0
4556 4557 if targetphase is None:
4557 4558 # display
4558 4559 for r in revs:
4559 4560 ctx = repo[r]
4560 4561 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4561 4562 else:
4562 4563 lock = repo.lock()
4563 4564 try:
4564 4565 # set phase
4565 4566 if not revs:
4566 4567 raise util.Abort(_('empty revision set'))
4567 4568 nodes = [repo[r].node() for r in revs]
4568 4569 olddata = repo._phasecache.getphaserevs(repo)[:]
4569 4570 phases.advanceboundary(repo, targetphase, nodes)
4570 4571 if opts['force']:
4571 4572 phases.retractboundary(repo, targetphase, nodes)
4572 4573 finally:
4573 4574 lock.release()
4574 4575 newdata = repo._phasecache.getphaserevs(repo)
4575 4576 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4576 4577 rejected = [n for n in nodes
4577 4578 if newdata[repo[n].rev()] < targetphase]
4578 4579 if rejected:
4579 4580 ui.warn(_('cannot move %i changesets to a more permissive '
4580 4581 'phase, use --force\n') % len(rejected))
4581 4582 ret = 1
4582 4583 if changes:
4583 4584 msg = _('phase changed for %i changesets\n') % changes
4584 4585 if ret:
4585 4586 ui.status(msg)
4586 4587 else:
4587 4588 ui.note(msg)
4588 4589 else:
4589 4590 ui.warn(_('no phases changed\n'))
4590 4591 ret = 1
4591 4592 return ret
4592 4593
4593 4594 def postincoming(ui, repo, modheads, optupdate, checkout):
4594 4595 if modheads == 0:
4595 4596 return
4596 4597 if optupdate:
4597 4598 movemarkfrom = repo['.'].node()
4598 4599 try:
4599 4600 ret = hg.update(repo, checkout)
4600 4601 except util.Abort, inst:
4601 4602 ui.warn(_("not updating: %s\n") % str(inst))
4602 4603 return 0
4603 4604 if not ret and not checkout:
4604 4605 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4605 4606 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4606 4607 return ret
4607 4608 if modheads > 1:
4608 4609 currentbranchheads = len(repo.branchheads())
4609 4610 if currentbranchheads == modheads:
4610 4611 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4611 4612 elif currentbranchheads > 1:
4612 4613 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4613 4614 "merge)\n"))
4614 4615 else:
4615 4616 ui.status(_("(run 'hg heads' to see heads)\n"))
4616 4617 else:
4617 4618 ui.status(_("(run 'hg update' to get a working copy)\n"))
4618 4619
4619 4620 @command('^pull',
4620 4621 [('u', 'update', None,
4621 4622 _('update to new branch head if changesets were pulled')),
4622 4623 ('f', 'force', None, _('run even when remote repository is unrelated')),
4623 4624 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4624 4625 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4625 4626 ('b', 'branch', [], _('a specific branch you would like to pull'),
4626 4627 _('BRANCH')),
4627 4628 ] + remoteopts,
4628 4629 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4629 4630 def pull(ui, repo, source="default", **opts):
4630 4631 """pull changes from the specified source
4631 4632
4632 4633 Pull changes from a remote repository to a local one.
4633 4634
4634 4635 This finds all changes from the repository at the specified path
4635 4636 or URL and adds them to a local repository (the current one unless
4636 4637 -R is specified). By default, this does not update the copy of the
4637 4638 project in the working directory.
4638 4639
4639 4640 Use :hg:`incoming` if you want to see what would have been added
4640 4641 by a pull at the time you issued this command. If you then decide
4641 4642 to add those changes to the repository, you should use :hg:`pull
4642 4643 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4643 4644
4644 4645 If SOURCE is omitted, the 'default' path will be used.
4645 4646 See :hg:`help urls` for more information.
4646 4647
4647 4648 Returns 0 on success, 1 if an update had unresolved files.
4648 4649 """
4649 4650 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4650 4651 other = hg.peer(repo, opts, source)
4651 4652 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4652 4653 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4653 4654
4654 4655 if opts.get('bookmark'):
4655 4656 if not revs:
4656 4657 revs = []
4657 4658 rb = other.listkeys('bookmarks')
4658 4659 for b in opts['bookmark']:
4659 4660 if b not in rb:
4660 4661 raise util.Abort(_('remote bookmark %s not found!') % b)
4661 4662 revs.append(rb[b])
4662 4663
4663 4664 if revs:
4664 4665 try:
4665 4666 revs = [other.lookup(rev) for rev in revs]
4666 4667 except error.CapabilityError:
4667 4668 err = _("other repository doesn't support revision lookup, "
4668 4669 "so a rev cannot be specified.")
4669 4670 raise util.Abort(err)
4670 4671
4671 4672 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4672 4673 bookmarks.updatefromremote(ui, repo, other, source)
4673 4674 if checkout:
4674 4675 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4675 4676 repo._subtoppath = source
4676 4677 try:
4677 4678 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4678 4679
4679 4680 finally:
4680 4681 del repo._subtoppath
4681 4682
4682 4683 # update specified bookmarks
4683 4684 if opts.get('bookmark'):
4684 4685 marks = repo._bookmarks
4685 4686 for b in opts['bookmark']:
4686 4687 # explicit pull overrides local bookmark if any
4687 4688 ui.status(_("importing bookmark %s\n") % b)
4688 4689 marks[b] = repo[rb[b]].node()
4689 4690 marks.write()
4690 4691
4691 4692 return ret
4692 4693
4693 4694 @command('^push',
4694 4695 [('f', 'force', None, _('force push')),
4695 4696 ('r', 'rev', [],
4696 4697 _('a changeset intended to be included in the destination'),
4697 4698 _('REV')),
4698 4699 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4699 4700 ('b', 'branch', [],
4700 4701 _('a specific branch you would like to push'), _('BRANCH')),
4701 4702 ('', 'new-branch', False, _('allow pushing a new branch')),
4702 4703 ] + remoteopts,
4703 4704 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4704 4705 def push(ui, repo, dest=None, **opts):
4705 4706 """push changes to the specified destination
4706 4707
4707 4708 Push changesets from the local repository to the specified
4708 4709 destination.
4709 4710
4710 4711 This operation is symmetrical to pull: it is identical to a pull
4711 4712 in the destination repository from the current one.
4712 4713
4713 4714 By default, push will not allow creation of new heads at the
4714 4715 destination, since multiple heads would make it unclear which head
4715 4716 to use. In this situation, it is recommended to pull and merge
4716 4717 before pushing.
4717 4718
4718 4719 Use --new-branch if you want to allow push to create a new named
4719 4720 branch that is not present at the destination. This allows you to
4720 4721 only create a new branch without forcing other changes.
4721 4722
4722 4723 Use -f/--force to override the default behavior and push all
4723 4724 changesets on all branches.
4724 4725
4725 4726 If -r/--rev is used, the specified revision and all its ancestors
4726 4727 will be pushed to the remote repository.
4727 4728
4728 4729 If -B/--bookmark is used, the specified bookmarked revision, its
4729 4730 ancestors, and the bookmark will be pushed to the remote
4730 4731 repository.
4731 4732
4732 4733 Please see :hg:`help urls` for important details about ``ssh://``
4733 4734 URLs. If DESTINATION is omitted, a default path will be used.
4734 4735
4735 4736 Returns 0 if push was successful, 1 if nothing to push.
4736 4737 """
4737 4738
4738 4739 if opts.get('bookmark'):
4739 4740 for b in opts['bookmark']:
4740 4741 # translate -B options to -r so changesets get pushed
4741 4742 if b in repo._bookmarks:
4742 4743 opts.setdefault('rev', []).append(b)
4743 4744 else:
4744 4745 # if we try to push a deleted bookmark, translate it to null
4745 4746 # this lets simultaneous -r, -b options continue working
4746 4747 opts.setdefault('rev', []).append("null")
4747 4748
4748 4749 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4749 4750 dest, branches = hg.parseurl(dest, opts.get('branch'))
4750 4751 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4751 4752 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4752 4753 other = hg.peer(repo, opts, dest)
4753 4754 if revs:
4754 4755 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4755 4756
4756 4757 repo._subtoppath = dest
4757 4758 try:
4758 4759 # push subrepos depth-first for coherent ordering
4759 4760 c = repo['']
4760 4761 subs = c.substate # only repos that are committed
4761 4762 for s in sorted(subs):
4762 4763 if c.sub(s).push(opts) == 0:
4763 4764 return False
4764 4765 finally:
4765 4766 del repo._subtoppath
4766 4767 result = repo.push(other, opts.get('force'), revs=revs,
4767 4768 newbranch=opts.get('new_branch'))
4768 4769
4769 4770 result = not result
4770 4771
4771 4772 if opts.get('bookmark'):
4772 4773 rb = other.listkeys('bookmarks')
4773 4774 for b in opts['bookmark']:
4774 4775 # explicit push overrides remote bookmark if any
4775 4776 if b in repo._bookmarks:
4776 4777 ui.status(_("exporting bookmark %s\n") % b)
4777 4778 new = repo[b].hex()
4778 4779 elif b in rb:
4779 4780 ui.status(_("deleting remote bookmark %s\n") % b)
4780 4781 new = '' # delete
4781 4782 else:
4782 4783 ui.warn(_('bookmark %s does not exist on the local '
4783 4784 'or remote repository!\n') % b)
4784 4785 return 2
4785 4786 old = rb.get(b, '')
4786 4787 r = other.pushkey('bookmarks', b, old, new)
4787 4788 if not r:
4788 4789 ui.warn(_('updating bookmark %s failed!\n') % b)
4789 4790 if not result:
4790 4791 result = 2
4791 4792
4792 4793 return result
4793 4794
4794 4795 @command('recover', [])
4795 4796 def recover(ui, repo):
4796 4797 """roll back an interrupted transaction
4797 4798
4798 4799 Recover from an interrupted commit or pull.
4799 4800
4800 4801 This command tries to fix the repository status after an
4801 4802 interrupted operation. It should only be necessary when Mercurial
4802 4803 suggests it.
4803 4804
4804 4805 Returns 0 if successful, 1 if nothing to recover or verify fails.
4805 4806 """
4806 4807 if repo.recover():
4807 4808 return hg.verify(repo)
4808 4809 return 1
4809 4810
4810 4811 @command('^remove|rm',
4811 4812 [('A', 'after', None, _('record delete for missing files')),
4812 4813 ('f', 'force', None,
4813 4814 _('remove (and delete) file even if added or modified')),
4814 4815 ] + walkopts,
4815 4816 _('[OPTION]... FILE...'))
4816 4817 def remove(ui, repo, *pats, **opts):
4817 4818 """remove the specified files on the next commit
4818 4819
4819 4820 Schedule the indicated files for removal from the current branch.
4820 4821
4821 4822 This command schedules the files to be removed at the next commit.
4822 4823 To undo a remove before that, see :hg:`revert`. To undo added
4823 4824 files, see :hg:`forget`.
4824 4825
4825 4826 .. container:: verbose
4826 4827
4827 4828 -A/--after can be used to remove only files that have already
4828 4829 been deleted, -f/--force can be used to force deletion, and -Af
4829 4830 can be used to remove files from the next revision without
4830 4831 deleting them from the working directory.
4831 4832
4832 4833 The following table details the behavior of remove for different
4833 4834 file states (columns) and option combinations (rows). The file
4834 4835 states are Added [A], Clean [C], Modified [M] and Missing [!]
4835 4836 (as reported by :hg:`status`). The actions are Warn, Remove
4836 4837 (from branch) and Delete (from disk):
4837 4838
4838 4839 ======= == == == ==
4839 4840 A C M !
4840 4841 ======= == == == ==
4841 4842 none W RD W R
4842 4843 -f R RD RD R
4843 4844 -A W W W R
4844 4845 -Af R R R R
4845 4846 ======= == == == ==
4846 4847
4847 4848 Note that remove never deletes files in Added [A] state from the
4848 4849 working directory, not even if option --force is specified.
4849 4850
4850 4851 Returns 0 on success, 1 if any warnings encountered.
4851 4852 """
4852 4853
4853 4854 ret = 0
4854 4855 after, force = opts.get('after'), opts.get('force')
4855 4856 if not pats and not after:
4856 4857 raise util.Abort(_('no files specified'))
4857 4858
4858 4859 m = scmutil.match(repo[None], pats, opts)
4859 4860 s = repo.status(match=m, clean=True)
4860 4861 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4861 4862
4862 4863 # warn about failure to delete explicit files/dirs
4863 4864 wctx = repo[None]
4864 4865 for f in m.files():
4865 4866 if f in repo.dirstate or f in wctx.dirs():
4866 4867 continue
4867 4868 if os.path.exists(m.rel(f)):
4868 4869 if os.path.isdir(m.rel(f)):
4869 4870 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
4870 4871 else:
4871 4872 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4872 4873 # missing files will generate a warning elsewhere
4873 4874 ret = 1
4874 4875
4875 4876 if force:
4876 4877 list = modified + deleted + clean + added
4877 4878 elif after:
4878 4879 list = deleted
4879 4880 for f in modified + added + clean:
4880 4881 ui.warn(_('not removing %s: file still exists (use -f'
4881 4882 ' to force removal)\n') % m.rel(f))
4882 4883 ret = 1
4883 4884 else:
4884 4885 list = deleted + clean
4885 4886 for f in modified:
4886 4887 ui.warn(_('not removing %s: file is modified (use -f'
4887 4888 ' to force removal)\n') % m.rel(f))
4888 4889 ret = 1
4889 4890 for f in added:
4890 4891 ui.warn(_('not removing %s: file has been marked for add'
4891 4892 ' (use forget to undo)\n') % m.rel(f))
4892 4893 ret = 1
4893 4894
4894 4895 for f in sorted(list):
4895 4896 if ui.verbose or not m.exact(f):
4896 4897 ui.status(_('removing %s\n') % m.rel(f))
4897 4898
4898 4899 wlock = repo.wlock()
4899 4900 try:
4900 4901 if not after:
4901 4902 for f in list:
4902 4903 if f in added:
4903 4904 continue # we never unlink added files on remove
4904 4905 try:
4905 4906 util.unlinkpath(repo.wjoin(f))
4906 4907 except OSError, inst:
4907 4908 if inst.errno != errno.ENOENT:
4908 4909 raise
4909 4910 repo[None].forget(list)
4910 4911 finally:
4911 4912 wlock.release()
4912 4913
4913 4914 return ret
4914 4915
4915 4916 @command('rename|move|mv',
4916 4917 [('A', 'after', None, _('record a rename that has already occurred')),
4917 4918 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4918 4919 ] + walkopts + dryrunopts,
4919 4920 _('[OPTION]... SOURCE... DEST'))
4920 4921 def rename(ui, repo, *pats, **opts):
4921 4922 """rename files; equivalent of copy + remove
4922 4923
4923 4924 Mark dest as copies of sources; mark sources for deletion. If dest
4924 4925 is a directory, copies are put in that directory. If dest is a
4925 4926 file, there can only be one source.
4926 4927
4927 4928 By default, this command copies the contents of files as they
4928 4929 exist in the working directory. If invoked with -A/--after, the
4929 4930 operation is recorded, but no copying is performed.
4930 4931
4931 4932 This command takes effect at the next commit. To undo a rename
4932 4933 before that, see :hg:`revert`.
4933 4934
4934 4935 Returns 0 on success, 1 if errors are encountered.
4935 4936 """
4936 4937 wlock = repo.wlock(False)
4937 4938 try:
4938 4939 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4939 4940 finally:
4940 4941 wlock.release()
4941 4942
4942 4943 @command('resolve',
4943 4944 [('a', 'all', None, _('select all unresolved files')),
4944 4945 ('l', 'list', None, _('list state of files needing merge')),
4945 4946 ('m', 'mark', None, _('mark files as resolved')),
4946 4947 ('u', 'unmark', None, _('mark files as unresolved')),
4947 4948 ('n', 'no-status', None, _('hide status prefix'))]
4948 4949 + mergetoolopts + walkopts,
4949 4950 _('[OPTION]... [FILE]...'))
4950 4951 def resolve(ui, repo, *pats, **opts):
4951 4952 """redo merges or set/view the merge status of files
4952 4953
4953 4954 Merges with unresolved conflicts are often the result of
4954 4955 non-interactive merging using the ``internal:merge`` configuration
4955 4956 setting, or a command-line merge tool like ``diff3``. The resolve
4956 4957 command is used to manage the files involved in a merge, after
4957 4958 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4958 4959 working directory must have two parents). See :hg:`help
4959 4960 merge-tools` for information on configuring merge tools.
4960 4961
4961 4962 The resolve command can be used in the following ways:
4962 4963
4963 4964 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4964 4965 files, discarding any previous merge attempts. Re-merging is not
4965 4966 performed for files already marked as resolved. Use ``--all/-a``
4966 4967 to select all unresolved files. ``--tool`` can be used to specify
4967 4968 the merge tool used for the given files. It overrides the HGMERGE
4968 4969 environment variable and your configuration files. Previous file
4969 4970 contents are saved with a ``.orig`` suffix.
4970 4971
4971 4972 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4972 4973 (e.g. after having manually fixed-up the files). The default is
4973 4974 to mark all unresolved files.
4974 4975
4975 4976 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4976 4977 default is to mark all resolved files.
4977 4978
4978 4979 - :hg:`resolve -l`: list files which had or still have conflicts.
4979 4980 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4980 4981
4981 4982 Note that Mercurial will not let you commit files with unresolved
4982 4983 merge conflicts. You must use :hg:`resolve -m ...` before you can
4983 4984 commit after a conflicting merge.
4984 4985
4985 4986 Returns 0 on success, 1 if any files fail a resolve attempt.
4986 4987 """
4987 4988
4988 4989 all, mark, unmark, show, nostatus = \
4989 4990 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4990 4991
4991 4992 if (show and (mark or unmark)) or (mark and unmark):
4992 4993 raise util.Abort(_("too many options specified"))
4993 4994 if pats and all:
4994 4995 raise util.Abort(_("can't specify --all and patterns"))
4995 4996 if not (all or pats or show or mark or unmark):
4996 4997 raise util.Abort(_('no files or directories specified; '
4997 4998 'use --all to remerge all files'))
4998 4999
4999 5000 ms = mergemod.mergestate(repo)
5000 5001 m = scmutil.match(repo[None], pats, opts)
5001 5002 ret = 0
5002 5003
5003 5004 for f in ms:
5004 5005 if m(f):
5005 5006 if show:
5006 5007 if nostatus:
5007 5008 ui.write("%s\n" % f)
5008 5009 else:
5009 5010 ui.write("%s %s\n" % (ms[f].upper(), f),
5010 5011 label='resolve.' +
5011 5012 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
5012 5013 elif mark:
5013 5014 ms.mark(f, "r")
5014 5015 elif unmark:
5015 5016 ms.mark(f, "u")
5016 5017 else:
5017 5018 wctx = repo[None]
5018 5019 mctx = wctx.parents()[-1]
5019 5020
5020 5021 # backup pre-resolve (merge uses .orig for its own purposes)
5021 5022 a = repo.wjoin(f)
5022 5023 util.copyfile(a, a + ".resolve")
5023 5024
5024 5025 try:
5025 5026 # resolve file
5026 5027 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
5027 5028 if ms.resolve(f, wctx, mctx):
5028 5029 ret = 1
5029 5030 finally:
5030 5031 ui.setconfig('ui', 'forcemerge', '')
5031 5032 ms.commit()
5032 5033
5033 5034 # replace filemerge's .orig file with our resolve file
5034 5035 util.rename(a + ".resolve", a + ".orig")
5035 5036
5036 5037 ms.commit()
5037 5038 return ret
5038 5039
5039 5040 @command('revert',
5040 5041 [('a', 'all', None, _('revert all changes when no arguments given')),
5041 5042 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5042 5043 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5043 5044 ('C', 'no-backup', None, _('do not save backup copies of files')),
5044 5045 ] + walkopts + dryrunopts,
5045 5046 _('[OPTION]... [-r REV] [NAME]...'))
5046 5047 def revert(ui, repo, *pats, **opts):
5047 5048 """restore files to their checkout state
5048 5049
5049 5050 .. note::
5050 5051
5051 5052 To check out earlier revisions, you should use :hg:`update REV`.
5052 5053 To cancel an uncommitted merge (and lose your changes), use
5053 5054 :hg:`update --clean .`.
5054 5055
5055 5056 With no revision specified, revert the specified files or directories
5056 5057 to the contents they had in the parent of the working directory.
5057 5058 This restores the contents of files to an unmodified
5058 5059 state and unschedules adds, removes, copies, and renames. If the
5059 5060 working directory has two parents, you must explicitly specify a
5060 5061 revision.
5061 5062
5062 5063 Using the -r/--rev or -d/--date options, revert the given files or
5063 5064 directories to their states as of a specific revision. Because
5064 5065 revert does not change the working directory parents, this will
5065 5066 cause these files to appear modified. This can be helpful to "back
5066 5067 out" some or all of an earlier change. See :hg:`backout` for a
5067 5068 related method.
5068 5069
5069 5070 Modified files are saved with a .orig suffix before reverting.
5070 5071 To disable these backups, use --no-backup.
5071 5072
5072 5073 See :hg:`help dates` for a list of formats valid for -d/--date.
5073 5074
5074 5075 Returns 0 on success.
5075 5076 """
5076 5077
5077 5078 if opts.get("date"):
5078 5079 if opts.get("rev"):
5079 5080 raise util.Abort(_("you can't specify a revision and a date"))
5080 5081 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5081 5082
5082 5083 parent, p2 = repo.dirstate.parents()
5083 5084 if not opts.get('rev') and p2 != nullid:
5084 5085 # revert after merge is a trap for new users (issue2915)
5085 5086 raise util.Abort(_('uncommitted merge with no revision specified'),
5086 5087 hint=_('use "hg update" or see "hg help revert"'))
5087 5088
5088 5089 ctx = scmutil.revsingle(repo, opts.get('rev'))
5089 5090
5090 5091 if not pats and not opts.get('all'):
5091 5092 msg = _("no files or directories specified")
5092 5093 if p2 != nullid:
5093 5094 hint = _("uncommitted merge, use --all to discard all changes,"
5094 5095 " or 'hg update -C .' to abort the merge")
5095 5096 raise util.Abort(msg, hint=hint)
5096 5097 dirty = util.any(repo.status())
5097 5098 node = ctx.node()
5098 5099 if node != parent:
5099 5100 if dirty:
5100 5101 hint = _("uncommitted changes, use --all to discard all"
5101 5102 " changes, or 'hg update %s' to update") % ctx.rev()
5102 5103 else:
5103 5104 hint = _("use --all to revert all files,"
5104 5105 " or 'hg update %s' to update") % ctx.rev()
5105 5106 elif dirty:
5106 5107 hint = _("uncommitted changes, use --all to discard all changes")
5107 5108 else:
5108 5109 hint = _("use --all to revert all files")
5109 5110 raise util.Abort(msg, hint=hint)
5110 5111
5111 5112 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5112 5113
5113 5114 @command('rollback', dryrunopts +
5114 5115 [('f', 'force', False, _('ignore safety measures'))])
5115 5116 def rollback(ui, repo, **opts):
5116 5117 """roll back the last transaction (dangerous)
5117 5118
5118 5119 This command should be used with care. There is only one level of
5119 5120 rollback, and there is no way to undo a rollback. It will also
5120 5121 restore the dirstate at the time of the last transaction, losing
5121 5122 any dirstate changes since that time. This command does not alter
5122 5123 the working directory.
5123 5124
5124 5125 Transactions are used to encapsulate the effects of all commands
5125 5126 that create new changesets or propagate existing changesets into a
5126 5127 repository.
5127 5128
5128 5129 .. container:: verbose
5129 5130
5130 5131 For example, the following commands are transactional, and their
5131 5132 effects can be rolled back:
5132 5133
5133 5134 - commit
5134 5135 - import
5135 5136 - pull
5136 5137 - push (with this repository as the destination)
5137 5138 - unbundle
5138 5139
5139 5140 To avoid permanent data loss, rollback will refuse to rollback a
5140 5141 commit transaction if it isn't checked out. Use --force to
5141 5142 override this protection.
5142 5143
5143 5144 This command is not intended for use on public repositories. Once
5144 5145 changes are visible for pull by other users, rolling a transaction
5145 5146 back locally is ineffective (someone else may already have pulled
5146 5147 the changes). Furthermore, a race is possible with readers of the
5147 5148 repository; for example an in-progress pull from the repository
5148 5149 may fail if a rollback is performed.
5149 5150
5150 5151 Returns 0 on success, 1 if no rollback data is available.
5151 5152 """
5152 5153 return repo.rollback(dryrun=opts.get('dry_run'),
5153 5154 force=opts.get('force'))
5154 5155
5155 5156 @command('root', [])
5156 5157 def root(ui, repo):
5157 5158 """print the root (top) of the current working directory
5158 5159
5159 5160 Print the root directory of the current repository.
5160 5161
5161 5162 Returns 0 on success.
5162 5163 """
5163 5164 ui.write(repo.root + "\n")
5164 5165
5165 5166 @command('^serve',
5166 5167 [('A', 'accesslog', '', _('name of access log file to write to'),
5167 5168 _('FILE')),
5168 5169 ('d', 'daemon', None, _('run server in background')),
5169 5170 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5170 5171 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5171 5172 # use string type, then we can check if something was passed
5172 5173 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5173 5174 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5174 5175 _('ADDR')),
5175 5176 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5176 5177 _('PREFIX')),
5177 5178 ('n', 'name', '',
5178 5179 _('name to show in web pages (default: working directory)'), _('NAME')),
5179 5180 ('', 'web-conf', '',
5180 5181 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5181 5182 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5182 5183 _('FILE')),
5183 5184 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5184 5185 ('', 'stdio', None, _('for remote clients')),
5185 5186 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5186 5187 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5187 5188 ('', 'style', '', _('template style to use'), _('STYLE')),
5188 5189 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5189 5190 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5190 5191 _('[OPTION]...'))
5191 5192 def serve(ui, repo, **opts):
5192 5193 """start stand-alone webserver
5193 5194
5194 5195 Start a local HTTP repository browser and pull server. You can use
5195 5196 this for ad-hoc sharing and browsing of repositories. It is
5196 5197 recommended to use a real web server to serve a repository for
5197 5198 longer periods of time.
5198 5199
5199 5200 Please note that the server does not implement access control.
5200 5201 This means that, by default, anybody can read from the server and
5201 5202 nobody can write to it by default. Set the ``web.allow_push``
5202 5203 option to ``*`` to allow everybody to push to the server. You
5203 5204 should use a real web server if you need to authenticate users.
5204 5205
5205 5206 By default, the server logs accesses to stdout and errors to
5206 5207 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5207 5208 files.
5208 5209
5209 5210 To have the server choose a free port number to listen on, specify
5210 5211 a port number of 0; in this case, the server will print the port
5211 5212 number it uses.
5212 5213
5213 5214 Returns 0 on success.
5214 5215 """
5215 5216
5216 5217 if opts["stdio"] and opts["cmdserver"]:
5217 5218 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5218 5219
5219 5220 def checkrepo():
5220 5221 if repo is None:
5221 5222 raise error.RepoError(_("there is no Mercurial repository here"
5222 5223 " (.hg not found)"))
5223 5224
5224 5225 if opts["stdio"]:
5225 5226 checkrepo()
5226 5227 s = sshserver.sshserver(ui, repo)
5227 5228 s.serve_forever()
5228 5229
5229 5230 if opts["cmdserver"]:
5230 5231 checkrepo()
5231 5232 s = commandserver.server(ui, repo, opts["cmdserver"])
5232 5233 return s.serve()
5233 5234
5234 5235 # this way we can check if something was given in the command-line
5235 5236 if opts.get('port'):
5236 5237 opts['port'] = util.getport(opts.get('port'))
5237 5238
5238 5239 baseui = repo and repo.baseui or ui
5239 5240 optlist = ("name templates style address port prefix ipv6"
5240 5241 " accesslog errorlog certificate encoding")
5241 5242 for o in optlist.split():
5242 5243 val = opts.get(o, '')
5243 5244 if val in (None, ''): # should check against default options instead
5244 5245 continue
5245 5246 baseui.setconfig("web", o, val)
5246 5247 if repo and repo.ui != baseui:
5247 5248 repo.ui.setconfig("web", o, val)
5248 5249
5249 5250 o = opts.get('web_conf') or opts.get('webdir_conf')
5250 5251 if not o:
5251 5252 if not repo:
5252 5253 raise error.RepoError(_("there is no Mercurial repository"
5253 5254 " here (.hg not found)"))
5254 5255 o = repo.root
5255 5256
5256 5257 app = hgweb.hgweb(o, baseui=ui)
5257 5258
5258 5259 class service(object):
5259 5260 def init(self):
5260 5261 util.setsignalhandler()
5261 5262 self.httpd = hgweb.server.create_server(ui, app)
5262 5263
5263 5264 if opts['port'] and not ui.verbose:
5264 5265 return
5265 5266
5266 5267 if self.httpd.prefix:
5267 5268 prefix = self.httpd.prefix.strip('/') + '/'
5268 5269 else:
5269 5270 prefix = ''
5270 5271
5271 5272 port = ':%d' % self.httpd.port
5272 5273 if port == ':80':
5273 5274 port = ''
5274 5275
5275 5276 bindaddr = self.httpd.addr
5276 5277 if bindaddr == '0.0.0.0':
5277 5278 bindaddr = '*'
5278 5279 elif ':' in bindaddr: # IPv6
5279 5280 bindaddr = '[%s]' % bindaddr
5280 5281
5281 5282 fqaddr = self.httpd.fqaddr
5282 5283 if ':' in fqaddr:
5283 5284 fqaddr = '[%s]' % fqaddr
5284 5285 if opts['port']:
5285 5286 write = ui.status
5286 5287 else:
5287 5288 write = ui.write
5288 5289 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5289 5290 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5290 5291
5291 5292 def run(self):
5292 5293 self.httpd.serve_forever()
5293 5294
5294 5295 service = service()
5295 5296
5296 5297 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5297 5298
5298 5299 @command('showconfig|debugconfig',
5299 5300 [('u', 'untrusted', None, _('show untrusted configuration options'))],
5300 5301 _('[-u] [NAME]...'))
5301 5302 def showconfig(ui, repo, *values, **opts):
5302 5303 """show combined config settings from all hgrc files
5303 5304
5304 5305 With no arguments, print names and values of all config items.
5305 5306
5306 5307 With one argument of the form section.name, print just the value
5307 5308 of that config item.
5308 5309
5309 5310 With multiple arguments, print names and values of all config
5310 5311 items with matching section names.
5311 5312
5312 5313 With --debug, the source (filename and line number) is printed
5313 5314 for each config item.
5314 5315
5315 5316 Returns 0 on success.
5316 5317 """
5317 5318
5318 5319 for f in scmutil.rcpath():
5319 5320 ui.debug('read config from: %s\n' % f)
5320 5321 untrusted = bool(opts.get('untrusted'))
5321 5322 if values:
5322 5323 sections = [v for v in values if '.' not in v]
5323 5324 items = [v for v in values if '.' in v]
5324 5325 if len(items) > 1 or items and sections:
5325 5326 raise util.Abort(_('only one config item permitted'))
5326 5327 for section, name, value in ui.walkconfig(untrusted=untrusted):
5327 5328 value = str(value).replace('\n', '\\n')
5328 5329 sectname = section + '.' + name
5329 5330 if values:
5330 5331 for v in values:
5331 5332 if v == section:
5332 5333 ui.debug('%s: ' %
5333 5334 ui.configsource(section, name, untrusted))
5334 5335 ui.write('%s=%s\n' % (sectname, value))
5335 5336 elif v == sectname:
5336 5337 ui.debug('%s: ' %
5337 5338 ui.configsource(section, name, untrusted))
5338 5339 ui.write(value, '\n')
5339 5340 else:
5340 5341 ui.debug('%s: ' %
5341 5342 ui.configsource(section, name, untrusted))
5342 5343 ui.write('%s=%s\n' % (sectname, value))
5343 5344
5344 5345 @command('^status|st',
5345 5346 [('A', 'all', None, _('show status of all files')),
5346 5347 ('m', 'modified', None, _('show only modified files')),
5347 5348 ('a', 'added', None, _('show only added files')),
5348 5349 ('r', 'removed', None, _('show only removed files')),
5349 5350 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5350 5351 ('c', 'clean', None, _('show only files without changes')),
5351 5352 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5352 5353 ('i', 'ignored', None, _('show only ignored files')),
5353 5354 ('n', 'no-status', None, _('hide status prefix')),
5354 5355 ('C', 'copies', None, _('show source of copied files')),
5355 5356 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5356 5357 ('', 'rev', [], _('show difference from revision'), _('REV')),
5357 5358 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5358 5359 ] + walkopts + subrepoopts,
5359 5360 _('[OPTION]... [FILE]...'))
5360 5361 def status(ui, repo, *pats, **opts):
5361 5362 """show changed files in the working directory
5362 5363
5363 5364 Show status of files in the repository. If names are given, only
5364 5365 files that match are shown. Files that are clean or ignored or
5365 5366 the source of a copy/move operation, are not listed unless
5366 5367 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5367 5368 Unless options described with "show only ..." are given, the
5368 5369 options -mardu are used.
5369 5370
5370 5371 Option -q/--quiet hides untracked (unknown and ignored) files
5371 5372 unless explicitly requested with -u/--unknown or -i/--ignored.
5372 5373
5373 5374 .. note::
5374 5375 status may appear to disagree with diff if permissions have
5375 5376 changed or a merge has occurred. The standard diff format does
5376 5377 not report permission changes and diff only reports changes
5377 5378 relative to one merge parent.
5378 5379
5379 5380 If one revision is given, it is used as the base revision.
5380 5381 If two revisions are given, the differences between them are
5381 5382 shown. The --change option can also be used as a shortcut to list
5382 5383 the changed files of a revision from its first parent.
5383 5384
5384 5385 The codes used to show the status of files are::
5385 5386
5386 5387 M = modified
5387 5388 A = added
5388 5389 R = removed
5389 5390 C = clean
5390 5391 ! = missing (deleted by non-hg command, but still tracked)
5391 5392 ? = not tracked
5392 5393 I = ignored
5393 5394 = origin of the previous file listed as A (added)
5394 5395
5395 5396 .. container:: verbose
5396 5397
5397 5398 Examples:
5398 5399
5399 5400 - show changes in the working directory relative to a
5400 5401 changeset::
5401 5402
5402 5403 hg status --rev 9353
5403 5404
5404 5405 - show all changes including copies in an existing changeset::
5405 5406
5406 5407 hg status --copies --change 9353
5407 5408
5408 5409 - get a NUL separated list of added files, suitable for xargs::
5409 5410
5410 5411 hg status -an0
5411 5412
5412 5413 Returns 0 on success.
5413 5414 """
5414 5415
5415 5416 revs = opts.get('rev')
5416 5417 change = opts.get('change')
5417 5418
5418 5419 if revs and change:
5419 5420 msg = _('cannot specify --rev and --change at the same time')
5420 5421 raise util.Abort(msg)
5421 5422 elif change:
5422 5423 node2 = scmutil.revsingle(repo, change, None).node()
5423 5424 node1 = repo[node2].p1().node()
5424 5425 else:
5425 5426 node1, node2 = scmutil.revpair(repo, revs)
5426 5427
5427 5428 cwd = (pats and repo.getcwd()) or ''
5428 5429 end = opts.get('print0') and '\0' or '\n'
5429 5430 copy = {}
5430 5431 states = 'modified added removed deleted unknown ignored clean'.split()
5431 5432 show = [k for k in states if opts.get(k)]
5432 5433 if opts.get('all'):
5433 5434 show += ui.quiet and (states[:4] + ['clean']) or states
5434 5435 if not show:
5435 5436 show = ui.quiet and states[:4] or states[:5]
5436 5437
5437 5438 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5438 5439 'ignored' in show, 'clean' in show, 'unknown' in show,
5439 5440 opts.get('subrepos'))
5440 5441 changestates = zip(states, 'MAR!?IC', stat)
5441 5442
5442 5443 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5443 5444 copy = copies.pathcopies(repo[node1], repo[node2])
5444 5445
5445 5446 fm = ui.formatter('status', opts)
5446 5447 fmt = '%s' + end
5447 5448 showchar = not opts.get('no_status')
5448 5449
5449 5450 for state, char, files in changestates:
5450 5451 if state in show:
5451 5452 label = 'status.' + state
5452 5453 for f in files:
5453 5454 fm.startitem()
5454 5455 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5455 5456 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5456 5457 if f in copy:
5457 5458 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5458 5459 label='status.copied')
5459 5460 fm.end()
5460 5461
5461 5462 @command('^summary|sum',
5462 5463 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5463 5464 def summary(ui, repo, **opts):
5464 5465 """summarize working directory state
5465 5466
5466 5467 This generates a brief summary of the working directory state,
5467 5468 including parents, branch, commit status, and available updates.
5468 5469
5469 5470 With the --remote option, this will check the default paths for
5470 5471 incoming and outgoing changes. This can be time-consuming.
5471 5472
5472 5473 Returns 0 on success.
5473 5474 """
5474 5475
5475 5476 ctx = repo[None]
5476 5477 parents = ctx.parents()
5477 5478 pnode = parents[0].node()
5478 5479 marks = []
5479 5480
5480 5481 for p in parents:
5481 5482 # label with log.changeset (instead of log.parent) since this
5482 5483 # shows a working directory parent *changeset*:
5483 5484 # i18n: column positioning for "hg summary"
5484 5485 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5485 5486 label='log.changeset changeset.%s' % p.phasestr())
5486 5487 ui.write(' '.join(p.tags()), label='log.tag')
5487 5488 if p.bookmarks():
5488 5489 marks.extend(p.bookmarks())
5489 5490 if p.rev() == -1:
5490 5491 if not len(repo):
5491 5492 ui.write(_(' (empty repository)'))
5492 5493 else:
5493 5494 ui.write(_(' (no revision checked out)'))
5494 5495 ui.write('\n')
5495 5496 if p.description():
5496 5497 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5497 5498 label='log.summary')
5498 5499
5499 5500 branch = ctx.branch()
5500 5501 bheads = repo.branchheads(branch)
5501 5502 # i18n: column positioning for "hg summary"
5502 5503 m = _('branch: %s\n') % branch
5503 5504 if branch != 'default':
5504 5505 ui.write(m, label='log.branch')
5505 5506 else:
5506 5507 ui.status(m, label='log.branch')
5507 5508
5508 5509 if marks:
5509 5510 current = repo._bookmarkcurrent
5510 5511 # i18n: column positioning for "hg summary"
5511 5512 ui.write(_('bookmarks:'), label='log.bookmark')
5512 5513 if current is not None:
5513 5514 try:
5514 5515 marks.remove(current)
5515 5516 ui.write(' *' + current, label='bookmarks.current')
5516 5517 except ValueError:
5517 5518 # current bookmark not in parent ctx marks
5518 5519 pass
5519 5520 for m in marks:
5520 5521 ui.write(' ' + m, label='log.bookmark')
5521 5522 ui.write('\n', label='log.bookmark')
5522 5523
5523 5524 st = list(repo.status(unknown=True))[:6]
5524 5525
5525 5526 c = repo.dirstate.copies()
5526 5527 copied, renamed = [], []
5527 5528 for d, s in c.iteritems():
5528 5529 if s in st[2]:
5529 5530 st[2].remove(s)
5530 5531 renamed.append(d)
5531 5532 else:
5532 5533 copied.append(d)
5533 5534 if d in st[1]:
5534 5535 st[1].remove(d)
5535 5536 st.insert(3, renamed)
5536 5537 st.insert(4, copied)
5537 5538
5538 5539 ms = mergemod.mergestate(repo)
5539 5540 st.append([f for f in ms if ms[f] == 'u'])
5540 5541
5541 5542 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5542 5543 st.append(subs)
5543 5544
5544 5545 labels = [ui.label(_('%d modified'), 'status.modified'),
5545 5546 ui.label(_('%d added'), 'status.added'),
5546 5547 ui.label(_('%d removed'), 'status.removed'),
5547 5548 ui.label(_('%d renamed'), 'status.copied'),
5548 5549 ui.label(_('%d copied'), 'status.copied'),
5549 5550 ui.label(_('%d deleted'), 'status.deleted'),
5550 5551 ui.label(_('%d unknown'), 'status.unknown'),
5551 5552 ui.label(_('%d ignored'), 'status.ignored'),
5552 5553 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5553 5554 ui.label(_('%d subrepos'), 'status.modified')]
5554 5555 t = []
5555 5556 for s, l in zip(st, labels):
5556 5557 if s:
5557 5558 t.append(l % len(s))
5558 5559
5559 5560 t = ', '.join(t)
5560 5561 cleanworkdir = False
5561 5562
5562 5563 if len(parents) > 1:
5563 5564 t += _(' (merge)')
5564 5565 elif branch != parents[0].branch():
5565 5566 t += _(' (new branch)')
5566 5567 elif (parents[0].closesbranch() and
5567 5568 pnode in repo.branchheads(branch, closed=True)):
5568 5569 t += _(' (head closed)')
5569 5570 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5570 5571 t += _(' (clean)')
5571 5572 cleanworkdir = True
5572 5573 elif pnode not in bheads:
5573 5574 t += _(' (new branch head)')
5574 5575
5575 5576 if cleanworkdir:
5576 5577 # i18n: column positioning for "hg summary"
5577 5578 ui.status(_('commit: %s\n') % t.strip())
5578 5579 else:
5579 5580 # i18n: column positioning for "hg summary"
5580 5581 ui.write(_('commit: %s\n') % t.strip())
5581 5582
5582 5583 # all ancestors of branch heads - all ancestors of parent = new csets
5583 5584 new = [0] * len(repo)
5584 5585 cl = repo.changelog
5585 5586 for a in [cl.rev(n) for n in bheads]:
5586 5587 new[a] = 1
5587 5588 for a in cl.ancestors([cl.rev(n) for n in bheads]):
5588 5589 new[a] = 1
5589 5590 for a in [p.rev() for p in parents]:
5590 5591 if a >= 0:
5591 5592 new[a] = 0
5592 5593 for a in cl.ancestors([p.rev() for p in parents]):
5593 5594 new[a] = 0
5594 5595 new = sum(new)
5595 5596
5596 5597 if new == 0:
5597 5598 # i18n: column positioning for "hg summary"
5598 5599 ui.status(_('update: (current)\n'))
5599 5600 elif pnode not in bheads:
5600 5601 # i18n: column positioning for "hg summary"
5601 5602 ui.write(_('update: %d new changesets (update)\n') % new)
5602 5603 else:
5603 5604 # i18n: column positioning for "hg summary"
5604 5605 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5605 5606 (new, len(bheads)))
5606 5607
5607 5608 if opts.get('remote'):
5608 5609 t = []
5609 5610 source, branches = hg.parseurl(ui.expandpath('default'))
5610 5611 other = hg.peer(repo, {}, source)
5611 5612 revs, checkout = hg.addbranchrevs(repo, other, branches,
5612 5613 opts.get('rev'))
5613 5614 ui.debug('comparing with %s\n' % util.hidepassword(source))
5614 5615 repo.ui.pushbuffer()
5615 5616 commoninc = discovery.findcommonincoming(repo, other)
5616 5617 _common, incoming, _rheads = commoninc
5617 5618 repo.ui.popbuffer()
5618 5619 if incoming:
5619 5620 t.append(_('1 or more incoming'))
5620 5621
5621 5622 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5622 5623 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5623 5624 if source != dest:
5624 5625 other = hg.peer(repo, {}, dest)
5625 5626 commoninc = None
5626 5627 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5627 5628 repo.ui.pushbuffer()
5628 5629 outgoing = discovery.findcommonoutgoing(repo, other,
5629 5630 commoninc=commoninc)
5630 5631 repo.ui.popbuffer()
5631 5632 o = outgoing.missing
5632 5633 if o:
5633 5634 t.append(_('%d outgoing') % len(o))
5634 5635 if 'bookmarks' in other.listkeys('namespaces'):
5635 5636 lmarks = repo.listkeys('bookmarks')
5636 5637 rmarks = other.listkeys('bookmarks')
5637 5638 diff = set(rmarks) - set(lmarks)
5638 5639 if len(diff) > 0:
5639 5640 t.append(_('%d incoming bookmarks') % len(diff))
5640 5641 diff = set(lmarks) - set(rmarks)
5641 5642 if len(diff) > 0:
5642 5643 t.append(_('%d outgoing bookmarks') % len(diff))
5643 5644
5644 5645 if t:
5645 5646 # i18n: column positioning for "hg summary"
5646 5647 ui.write(_('remote: %s\n') % (', '.join(t)))
5647 5648 else:
5648 5649 # i18n: column positioning for "hg summary"
5649 5650 ui.status(_('remote: (synced)\n'))
5650 5651
5651 5652 @command('tag',
5652 5653 [('f', 'force', None, _('force tag')),
5653 5654 ('l', 'local', None, _('make the tag local')),
5654 5655 ('r', 'rev', '', _('revision to tag'), _('REV')),
5655 5656 ('', 'remove', None, _('remove a tag')),
5656 5657 # -l/--local is already there, commitopts cannot be used
5657 5658 ('e', 'edit', None, _('edit commit message')),
5658 5659 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5659 5660 ] + commitopts2,
5660 5661 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5661 5662 def tag(ui, repo, name1, *names, **opts):
5662 5663 """add one or more tags for the current or given revision
5663 5664
5664 5665 Name a particular revision using <name>.
5665 5666
5666 5667 Tags are used to name particular revisions of the repository and are
5667 5668 very useful to compare different revisions, to go back to significant
5668 5669 earlier versions or to mark branch points as releases, etc. Changing
5669 5670 an existing tag is normally disallowed; use -f/--force to override.
5670 5671
5671 5672 If no revision is given, the parent of the working directory is
5672 5673 used, or tip if no revision is checked out.
5673 5674
5674 5675 To facilitate version control, distribution, and merging of tags,
5675 5676 they are stored as a file named ".hgtags" which is managed similarly
5676 5677 to other project files and can be hand-edited if necessary. This
5677 5678 also means that tagging creates a new commit. The file
5678 5679 ".hg/localtags" is used for local tags (not shared among
5679 5680 repositories).
5680 5681
5681 5682 Tag commits are usually made at the head of a branch. If the parent
5682 5683 of the working directory is not a branch head, :hg:`tag` aborts; use
5683 5684 -f/--force to force the tag commit to be based on a non-head
5684 5685 changeset.
5685 5686
5686 5687 See :hg:`help dates` for a list of formats valid for -d/--date.
5687 5688
5688 5689 Since tag names have priority over branch names during revision
5689 5690 lookup, using an existing branch name as a tag name is discouraged.
5690 5691
5691 5692 Returns 0 on success.
5692 5693 """
5693 5694 wlock = lock = None
5694 5695 try:
5695 5696 wlock = repo.wlock()
5696 5697 lock = repo.lock()
5697 5698 rev_ = "."
5698 5699 names = [t.strip() for t in (name1,) + names]
5699 5700 if len(names) != len(set(names)):
5700 5701 raise util.Abort(_('tag names must be unique'))
5701 5702 for n in names:
5702 5703 scmutil.checknewlabel(repo, n, 'tag')
5703 5704 if not n:
5704 5705 raise util.Abort(_('tag names cannot consist entirely of '
5705 5706 'whitespace'))
5706 5707 if opts.get('rev') and opts.get('remove'):
5707 5708 raise util.Abort(_("--rev and --remove are incompatible"))
5708 5709 if opts.get('rev'):
5709 5710 rev_ = opts['rev']
5710 5711 message = opts.get('message')
5711 5712 if opts.get('remove'):
5712 5713 expectedtype = opts.get('local') and 'local' or 'global'
5713 5714 for n in names:
5714 5715 if not repo.tagtype(n):
5715 5716 raise util.Abort(_("tag '%s' does not exist") % n)
5716 5717 if repo.tagtype(n) != expectedtype:
5717 5718 if expectedtype == 'global':
5718 5719 raise util.Abort(_("tag '%s' is not a global tag") % n)
5719 5720 else:
5720 5721 raise util.Abort(_("tag '%s' is not a local tag") % n)
5721 5722 rev_ = nullid
5722 5723 if not message:
5723 5724 # we don't translate commit messages
5724 5725 message = 'Removed tag %s' % ', '.join(names)
5725 5726 elif not opts.get('force'):
5726 5727 for n in names:
5727 5728 if n in repo.tags():
5728 5729 raise util.Abort(_("tag '%s' already exists "
5729 5730 "(use -f to force)") % n)
5730 5731 if not opts.get('local'):
5731 5732 p1, p2 = repo.dirstate.parents()
5732 5733 if p2 != nullid:
5733 5734 raise util.Abort(_('uncommitted merge'))
5734 5735 bheads = repo.branchheads()
5735 5736 if not opts.get('force') and bheads and p1 not in bheads:
5736 5737 raise util.Abort(_('not at a branch head (use -f to force)'))
5737 5738 r = scmutil.revsingle(repo, rev_).node()
5738 5739
5739 5740 if not message:
5740 5741 # we don't translate commit messages
5741 5742 message = ('Added tag %s for changeset %s' %
5742 5743 (', '.join(names), short(r)))
5743 5744
5744 5745 date = opts.get('date')
5745 5746 if date:
5746 5747 date = util.parsedate(date)
5747 5748
5748 5749 if opts.get('edit'):
5749 5750 message = ui.edit(message, ui.username())
5750 5751
5751 5752 # don't allow tagging the null rev
5752 5753 if (not opts.get('remove') and
5753 5754 scmutil.revsingle(repo, rev_).rev() == nullrev):
5754 5755 raise util.Abort(_("null revision specified"))
5755 5756
5756 5757 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5757 5758 finally:
5758 5759 release(lock, wlock)
5759 5760
5760 5761 @command('tags', [], '')
5761 5762 def tags(ui, repo, **opts):
5762 5763 """list repository tags
5763 5764
5764 5765 This lists both regular and local tags. When the -v/--verbose
5765 5766 switch is used, a third column "local" is printed for local tags.
5766 5767
5767 5768 Returns 0 on success.
5768 5769 """
5769 5770
5770 5771 fm = ui.formatter('tags', opts)
5771 5772 hexfunc = ui.debugflag and hex or short
5772 5773 tagtype = ""
5773 5774
5774 5775 for t, n in reversed(repo.tagslist()):
5775 5776 hn = hexfunc(n)
5776 5777 label = 'tags.normal'
5777 5778 tagtype = ''
5778 5779 if repo.tagtype(t) == 'local':
5779 5780 label = 'tags.local'
5780 5781 tagtype = 'local'
5781 5782
5782 5783 fm.startitem()
5783 5784 fm.write('tag', '%s', t, label=label)
5784 5785 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5785 5786 fm.condwrite(not ui.quiet, 'rev id', fmt,
5786 5787 repo.changelog.rev(n), hn, label=label)
5787 5788 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5788 5789 tagtype, label=label)
5789 5790 fm.plain('\n')
5790 5791 fm.end()
5791 5792
5792 5793 @command('tip',
5793 5794 [('p', 'patch', None, _('show patch')),
5794 5795 ('g', 'git', None, _('use git extended diff format')),
5795 5796 ] + templateopts,
5796 5797 _('[-p] [-g]'))
5797 5798 def tip(ui, repo, **opts):
5798 5799 """show the tip revision
5799 5800
5800 5801 The tip revision (usually just called the tip) is the changeset
5801 5802 most recently added to the repository (and therefore the most
5802 5803 recently changed head).
5803 5804
5804 5805 If you have just made a commit, that commit will be the tip. If
5805 5806 you have just pulled changes from another repository, the tip of
5806 5807 that repository becomes the current tip. The "tip" tag is special
5807 5808 and cannot be renamed or assigned to a different changeset.
5808 5809
5809 5810 Returns 0 on success.
5810 5811 """
5811 5812 displayer = cmdutil.show_changeset(ui, repo, opts)
5812 5813 displayer.show(repo[len(repo) - 1])
5813 5814 displayer.close()
5814 5815
5815 5816 @command('unbundle',
5816 5817 [('u', 'update', None,
5817 5818 _('update to new branch head if changesets were unbundled'))],
5818 5819 _('[-u] FILE...'))
5819 5820 def unbundle(ui, repo, fname1, *fnames, **opts):
5820 5821 """apply one or more changegroup files
5821 5822
5822 5823 Apply one or more compressed changegroup files generated by the
5823 5824 bundle command.
5824 5825
5825 5826 Returns 0 on success, 1 if an update has unresolved files.
5826 5827 """
5827 5828 fnames = (fname1,) + fnames
5828 5829
5829 5830 lock = repo.lock()
5830 5831 wc = repo['.']
5831 5832 try:
5832 5833 for fname in fnames:
5833 5834 f = hg.openpath(ui, fname)
5834 5835 gen = changegroup.readbundle(f, fname)
5835 5836 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
5836 5837 finally:
5837 5838 lock.release()
5838 5839 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5839 5840 return postincoming(ui, repo, modheads, opts.get('update'), None)
5840 5841
5841 5842 @command('^update|up|checkout|co',
5842 5843 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5843 5844 ('c', 'check', None,
5844 5845 _('update across branches if no uncommitted changes')),
5845 5846 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5846 5847 ('r', 'rev', '', _('revision'), _('REV'))],
5847 5848 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5848 5849 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5849 5850 """update working directory (or switch revisions)
5850 5851
5851 5852 Update the repository's working directory to the specified
5852 5853 changeset. If no changeset is specified, update to the tip of the
5853 5854 current named branch and move the current bookmark (see :hg:`help
5854 5855 bookmarks`).
5855 5856
5856 5857 Update sets the working directory's parent revision to the specified
5857 5858 changeset (see :hg:`help parents`).
5858 5859
5859 5860 If the changeset is not a descendant or ancestor of the working
5860 5861 directory's parent, the update is aborted. With the -c/--check
5861 5862 option, the working directory is checked for uncommitted changes; if
5862 5863 none are found, the working directory is updated to the specified
5863 5864 changeset.
5864 5865
5865 5866 .. container:: verbose
5866 5867
5867 5868 The following rules apply when the working directory contains
5868 5869 uncommitted changes:
5869 5870
5870 5871 1. If neither -c/--check nor -C/--clean is specified, and if
5871 5872 the requested changeset is an ancestor or descendant of
5872 5873 the working directory's parent, the uncommitted changes
5873 5874 are merged into the requested changeset and the merged
5874 5875 result is left uncommitted. If the requested changeset is
5875 5876 not an ancestor or descendant (that is, it is on another
5876 5877 branch), the update is aborted and the uncommitted changes
5877 5878 are preserved.
5878 5879
5879 5880 2. With the -c/--check option, the update is aborted and the
5880 5881 uncommitted changes are preserved.
5881 5882
5882 5883 3. With the -C/--clean option, uncommitted changes are discarded and
5883 5884 the working directory is updated to the requested changeset.
5884 5885
5885 5886 To cancel an uncommitted merge (and lose your changes), use
5886 5887 :hg:`update --clean .`.
5887 5888
5888 5889 Use null as the changeset to remove the working directory (like
5889 5890 :hg:`clone -U`).
5890 5891
5891 5892 If you want to revert just one file to an older revision, use
5892 5893 :hg:`revert [-r REV] NAME`.
5893 5894
5894 5895 See :hg:`help dates` for a list of formats valid for -d/--date.
5895 5896
5896 5897 Returns 0 on success, 1 if there are unresolved files.
5897 5898 """
5898 5899 if rev and node:
5899 5900 raise util.Abort(_("please specify just one revision"))
5900 5901
5901 5902 if rev is None or rev == '':
5902 5903 rev = node
5903 5904
5904 5905 # with no argument, we also move the current bookmark, if any
5905 5906 movemarkfrom = None
5906 5907 if rev is None:
5907 5908 movemarkfrom = repo['.'].node()
5908 5909
5909 5910 # if we defined a bookmark, we have to remember the original bookmark name
5910 5911 brev = rev
5911 5912 rev = scmutil.revsingle(repo, rev, rev).rev()
5912 5913
5913 5914 if check and clean:
5914 5915 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5915 5916
5916 5917 if date:
5917 5918 if rev is not None:
5918 5919 raise util.Abort(_("you can't specify a revision and a date"))
5919 5920 rev = cmdutil.finddate(ui, repo, date)
5920 5921
5921 5922 if check:
5922 5923 c = repo[None]
5923 5924 if c.dirty(merge=False, branch=False, missing=True):
5924 5925 raise util.Abort(_("uncommitted local changes"))
5925 5926 if rev is None:
5926 5927 rev = repo[repo[None].branch()].rev()
5927 5928 mergemod._checkunknown(repo, repo[None], repo[rev])
5928 5929
5929 5930 if clean:
5930 5931 ret = hg.clean(repo, rev)
5931 5932 else:
5932 5933 ret = hg.update(repo, rev)
5933 5934
5934 5935 if not ret and movemarkfrom:
5935 5936 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5936 5937 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5937 5938 elif brev in repo._bookmarks:
5938 5939 bookmarks.setcurrent(repo, brev)
5939 5940 elif brev:
5940 5941 bookmarks.unsetcurrent(repo)
5941 5942
5942 5943 return ret
5943 5944
5944 5945 @command('verify', [])
5945 5946 def verify(ui, repo):
5946 5947 """verify the integrity of the repository
5947 5948
5948 5949 Verify the integrity of the current repository.
5949 5950
5950 5951 This will perform an extensive check of the repository's
5951 5952 integrity, validating the hashes and checksums of each entry in
5952 5953 the changelog, manifest, and tracked files, as well as the
5953 5954 integrity of their crosslinks and indices.
5954 5955
5955 5956 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
5956 5957 for more information about recovery from corruption of the
5957 5958 repository.
5958 5959
5959 5960 Returns 0 on success, 1 if errors are encountered.
5960 5961 """
5961 5962 return hg.verify(repo)
5962 5963
5963 5964 @command('version', [])
5964 5965 def version_(ui):
5965 5966 """output version and copyright information"""
5966 5967 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5967 5968 % util.version())
5968 5969 ui.status(_(
5969 5970 "(see http://mercurial.selenic.com for more information)\n"
5970 5971 "\nCopyright (C) 2005-2012 Matt Mackall and others\n"
5971 5972 "This is free software; see the source for copying conditions. "
5972 5973 "There is NO\nwarranty; "
5973 5974 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5974 5975 ))
5975 5976
5976 5977 norepo = ("clone init version help debugcommands debugcomplete"
5977 5978 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5978 5979 " debugknown debuggetbundle debugbundle")
5979 5980 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5980 5981 " debugdata debugindex debugindexdot debugrevlog")
5981 5982 inferrepo = ("add addremove annotate cat commit diff grep forget log parents"
5982 5983 " remove resolve status debugwalk")
General Comments 0
You need to be logged in to leave comments. Login now