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