##// END OF EJS Templates
ui: support declaring path push urls as sub-options...
Gregory Szorc -
r27266:4dccc37b default
parent child Browse files
Show More
@@ -1,6964 +1,6966 b''
1 1 # commands.py - command processing for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from node import hex, bin, nullhex, nullid, nullrev, short
9 9 from lock import release
10 10 from i18n import _
11 11 import os, re, difflib, time, tempfile, errno, shlex
12 12 import sys, socket
13 13 import hg, scmutil, util, revlog, copies, error, bookmarks
14 14 import patch, help, encoding, templatekw, discovery
15 15 import archival, changegroup, cmdutil, hbisect
16 16 import sshserver, hgweb
17 17 import extensions
18 18 import merge as mergemod
19 19 import minirst, revset, fileset
20 20 import dagparser, context, simplemerge, graphmod, copies
21 21 import random, operator
22 22 import setdiscovery, treediscovery, dagutil, pvec, localrepo, destutil
23 23 import phases, obsolete, exchange, bundle2, repair, lock as lockmod
24 24 import ui as uimod
25 25 import streamclone
26 26
27 27 table = {}
28 28
29 29 command = cmdutil.command(table)
30 30
31 31 # Space delimited list of commands that don't require local repositories.
32 32 # This should be populated by passing norepo=True into the @command decorator.
33 33 norepo = ''
34 34 # Space delimited list of commands that optionally require local repositories.
35 35 # This should be populated by passing optionalrepo=True into the @command
36 36 # decorator.
37 37 optionalrepo = ''
38 38 # Space delimited list of commands that will examine arguments looking for
39 39 # a repository. This should be populated by passing inferrepo=True into the
40 40 # @command decorator.
41 41 inferrepo = ''
42 42
43 43 # label constants
44 44 # until 3.5, bookmarks.current was the advertised name, not
45 45 # bookmarks.active, so we must use both to avoid breaking old
46 46 # custom styles
47 47 activebookmarklabel = 'bookmarks.active bookmarks.current'
48 48
49 49 # common command options
50 50
51 51 globalopts = [
52 52 ('R', 'repository', '',
53 53 _('repository root directory or name of overlay bundle file'),
54 54 _('REPO')),
55 55 ('', 'cwd', '',
56 56 _('change working directory'), _('DIR')),
57 57 ('y', 'noninteractive', None,
58 58 _('do not prompt, automatically pick the first choice for all prompts')),
59 59 ('q', 'quiet', None, _('suppress output')),
60 60 ('v', 'verbose', None, _('enable additional output')),
61 61 ('', 'config', [],
62 62 _('set/override config option (use \'section.name=value\')'),
63 63 _('CONFIG')),
64 64 ('', 'debug', None, _('enable debugging output')),
65 65 ('', 'debugger', None, _('start debugger')),
66 66 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
67 67 _('ENCODE')),
68 68 ('', 'encodingmode', encoding.encodingmode,
69 69 _('set the charset encoding mode'), _('MODE')),
70 70 ('', 'traceback', None, _('always print a traceback on exception')),
71 71 ('', 'time', None, _('time how long the command takes')),
72 72 ('', 'profile', None, _('print command execution profile')),
73 73 ('', 'version', None, _('output version information and exit')),
74 74 ('h', 'help', None, _('display help and exit')),
75 75 ('', 'hidden', False, _('consider hidden changesets')),
76 76 ]
77 77
78 78 dryrunopts = [('n', 'dry-run', None,
79 79 _('do not perform actions, just print output'))]
80 80
81 81 remoteopts = [
82 82 ('e', 'ssh', '',
83 83 _('specify ssh command to use'), _('CMD')),
84 84 ('', 'remotecmd', '',
85 85 _('specify hg command to run on the remote side'), _('CMD')),
86 86 ('', 'insecure', None,
87 87 _('do not verify server certificate (ignoring web.cacerts config)')),
88 88 ]
89 89
90 90 walkopts = [
91 91 ('I', 'include', [],
92 92 _('include names matching the given patterns'), _('PATTERN')),
93 93 ('X', 'exclude', [],
94 94 _('exclude names matching the given patterns'), _('PATTERN')),
95 95 ]
96 96
97 97 commitopts = [
98 98 ('m', 'message', '',
99 99 _('use text as commit message'), _('TEXT')),
100 100 ('l', 'logfile', '',
101 101 _('read commit message from file'), _('FILE')),
102 102 ]
103 103
104 104 commitopts2 = [
105 105 ('d', 'date', '',
106 106 _('record the specified date as commit date'), _('DATE')),
107 107 ('u', 'user', '',
108 108 _('record the specified user as committer'), _('USER')),
109 109 ]
110 110
111 111 # hidden for now
112 112 formatteropts = [
113 113 ('T', 'template', '',
114 114 _('display with template (EXPERIMENTAL)'), _('TEMPLATE')),
115 115 ]
116 116
117 117 templateopts = [
118 118 ('', 'style', '',
119 119 _('display using template map file (DEPRECATED)'), _('STYLE')),
120 120 ('T', 'template', '',
121 121 _('display with template'), _('TEMPLATE')),
122 122 ]
123 123
124 124 logopts = [
125 125 ('p', 'patch', None, _('show patch')),
126 126 ('g', 'git', None, _('use git extended diff format')),
127 127 ('l', 'limit', '',
128 128 _('limit number of changes displayed'), _('NUM')),
129 129 ('M', 'no-merges', None, _('do not show merges')),
130 130 ('', 'stat', None, _('output diffstat-style summary of changes')),
131 131 ('G', 'graph', None, _("show the revision DAG")),
132 132 ] + templateopts
133 133
134 134 diffopts = [
135 135 ('a', 'text', None, _('treat all files as text')),
136 136 ('g', 'git', None, _('use git extended diff format')),
137 137 ('', 'nodates', None, _('omit dates from diff headers'))
138 138 ]
139 139
140 140 diffwsopts = [
141 141 ('w', 'ignore-all-space', None,
142 142 _('ignore white space when comparing lines')),
143 143 ('b', 'ignore-space-change', None,
144 144 _('ignore changes in the amount of white space')),
145 145 ('B', 'ignore-blank-lines', None,
146 146 _('ignore changes whose lines are all blank')),
147 147 ]
148 148
149 149 diffopts2 = [
150 150 ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
151 151 ('p', 'show-function', None, _('show which function each change is in')),
152 152 ('', 'reverse', None, _('produce a diff that undoes the changes')),
153 153 ] + diffwsopts + [
154 154 ('U', 'unified', '',
155 155 _('number of lines of context to show'), _('NUM')),
156 156 ('', 'stat', None, _('output diffstat-style summary of changes')),
157 157 ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
158 158 ]
159 159
160 160 mergetoolopts = [
161 161 ('t', 'tool', '', _('specify merge tool')),
162 162 ]
163 163
164 164 similarityopts = [
165 165 ('s', 'similarity', '',
166 166 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
167 167 ]
168 168
169 169 subrepoopts = [
170 170 ('S', 'subrepos', None,
171 171 _('recurse into subrepositories'))
172 172 ]
173 173
174 174 debugrevlogopts = [
175 175 ('c', 'changelog', False, _('open changelog')),
176 176 ('m', 'manifest', False, _('open manifest')),
177 177 ('', 'dir', False, _('open directory manifest')),
178 178 ]
179 179
180 180 # Commands start here, listed alphabetically
181 181
182 182 @command('^add',
183 183 walkopts + subrepoopts + dryrunopts,
184 184 _('[OPTION]... [FILE]...'),
185 185 inferrepo=True)
186 186 def add(ui, repo, *pats, **opts):
187 187 """add the specified files on the next commit
188 188
189 189 Schedule files to be version controlled and added to the
190 190 repository.
191 191
192 192 The files will be added to the repository at the next commit. To
193 193 undo an add before that, see :hg:`forget`.
194 194
195 195 If no names are given, add all files to the repository.
196 196
197 197 .. container:: verbose
198 198
199 199 Examples:
200 200
201 201 - New (unknown) files are added
202 202 automatically by :hg:`add`::
203 203
204 204 $ ls
205 205 foo.c
206 206 $ hg status
207 207 ? foo.c
208 208 $ hg add
209 209 adding foo.c
210 210 $ hg status
211 211 A foo.c
212 212
213 213 - Specific files to be added can be specified::
214 214
215 215 $ ls
216 216 bar.c foo.c
217 217 $ hg status
218 218 ? bar.c
219 219 ? foo.c
220 220 $ hg add bar.c
221 221 $ hg status
222 222 A bar.c
223 223 ? foo.c
224 224
225 225 Returns 0 if all files are successfully added.
226 226 """
227 227
228 228 m = scmutil.match(repo[None], pats, opts)
229 229 rejected = cmdutil.add(ui, repo, m, "", False, **opts)
230 230 return rejected and 1 or 0
231 231
232 232 @command('addremove',
233 233 similarityopts + subrepoopts + walkopts + dryrunopts,
234 234 _('[OPTION]... [FILE]...'),
235 235 inferrepo=True)
236 236 def addremove(ui, repo, *pats, **opts):
237 237 """add all new files, delete all missing files
238 238
239 239 Add all new files and remove all missing files from the
240 240 repository.
241 241
242 242 New files are ignored if they match any of the patterns in
243 243 ``.hgignore``. As with add, these changes take effect at the next
244 244 commit.
245 245
246 246 Use the -s/--similarity option to detect renamed files. This
247 247 option takes a percentage between 0 (disabled) and 100 (files must
248 248 be identical) as its parameter. With a parameter greater than 0,
249 249 this compares every removed file with every added file and records
250 250 those similar enough as renames. Detecting renamed files this way
251 251 can be expensive. After using this option, :hg:`status -C` can be
252 252 used to check which files were identified as moved or renamed. If
253 253 not specified, -s/--similarity defaults to 100 and only renames of
254 254 identical files are detected.
255 255
256 256 .. container:: verbose
257 257
258 258 Examples:
259 259
260 260 - A number of files (bar.c and foo.c) are new,
261 261 while foobar.c has been removed (without using :hg:`remove`)
262 262 from the repository::
263 263
264 264 $ ls
265 265 bar.c foo.c
266 266 $ hg status
267 267 ! foobar.c
268 268 ? bar.c
269 269 ? foo.c
270 270 $ hg addremove
271 271 adding bar.c
272 272 adding foo.c
273 273 removing foobar.c
274 274 $ hg status
275 275 A bar.c
276 276 A foo.c
277 277 R foobar.c
278 278
279 279 - A file foobar.c was moved to foo.c without using :hg:`rename`.
280 280 Afterwards, it was edited slightly::
281 281
282 282 $ ls
283 283 foo.c
284 284 $ hg status
285 285 ! foobar.c
286 286 ? foo.c
287 287 $ hg addremove --similarity 90
288 288 removing foobar.c
289 289 adding foo.c
290 290 recording removal of foobar.c as rename to foo.c (94% similar)
291 291 $ hg status -C
292 292 A foo.c
293 293 foobar.c
294 294 R foobar.c
295 295
296 296 Returns 0 if all files are successfully added.
297 297 """
298 298 try:
299 299 sim = float(opts.get('similarity') or 100)
300 300 except ValueError:
301 301 raise error.Abort(_('similarity must be a number'))
302 302 if sim < 0 or sim > 100:
303 303 raise error.Abort(_('similarity must be between 0 and 100'))
304 304 matcher = scmutil.match(repo[None], pats, opts)
305 305 return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
306 306
307 307 @command('^annotate|blame',
308 308 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
309 309 ('', 'follow', None,
310 310 _('follow copies/renames and list the filename (DEPRECATED)')),
311 311 ('', 'no-follow', None, _("don't follow copies and renames")),
312 312 ('a', 'text', None, _('treat all files as text')),
313 313 ('u', 'user', None, _('list the author (long with -v)')),
314 314 ('f', 'file', None, _('list the filename')),
315 315 ('d', 'date', None, _('list the date (short with -q)')),
316 316 ('n', 'number', None, _('list the revision number (default)')),
317 317 ('c', 'changeset', None, _('list the changeset')),
318 318 ('l', 'line-number', None, _('show line number at the first appearance'))
319 319 ] + diffwsopts + walkopts + formatteropts,
320 320 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
321 321 inferrepo=True)
322 322 def annotate(ui, repo, *pats, **opts):
323 323 """show changeset information by line for each file
324 324
325 325 List changes in files, showing the revision id responsible for
326 326 each line
327 327
328 328 This command is useful for discovering when a change was made and
329 329 by whom.
330 330
331 331 Without the -a/--text option, annotate will avoid processing files
332 332 it detects as binary. With -a, annotate will annotate the file
333 333 anyway, although the results will probably be neither useful
334 334 nor desirable.
335 335
336 336 Returns 0 on success.
337 337 """
338 338 if not pats:
339 339 raise error.Abort(_('at least one filename or pattern is required'))
340 340
341 341 if opts.get('follow'):
342 342 # --follow is deprecated and now just an alias for -f/--file
343 343 # to mimic the behavior of Mercurial before version 1.5
344 344 opts['file'] = True
345 345
346 346 ctx = scmutil.revsingle(repo, opts.get('rev'))
347 347
348 348 fm = ui.formatter('annotate', opts)
349 349 if ui.quiet:
350 350 datefunc = util.shortdate
351 351 else:
352 352 datefunc = util.datestr
353 353 if ctx.rev() is None:
354 354 def hexfn(node):
355 355 if node is None:
356 356 return None
357 357 else:
358 358 return fm.hexfunc(node)
359 359 if opts.get('changeset'):
360 360 # omit "+" suffix which is appended to node hex
361 361 def formatrev(rev):
362 362 if rev is None:
363 363 return '%d' % ctx.p1().rev()
364 364 else:
365 365 return '%d' % rev
366 366 else:
367 367 def formatrev(rev):
368 368 if rev is None:
369 369 return '%d+' % ctx.p1().rev()
370 370 else:
371 371 return '%d ' % rev
372 372 def formathex(hex):
373 373 if hex is None:
374 374 return '%s+' % fm.hexfunc(ctx.p1().node())
375 375 else:
376 376 return '%s ' % hex
377 377 else:
378 378 hexfn = fm.hexfunc
379 379 formatrev = formathex = str
380 380
381 381 opmap = [('user', ' ', lambda x: x[0].user(), ui.shortuser),
382 382 ('number', ' ', lambda x: x[0].rev(), formatrev),
383 383 ('changeset', ' ', lambda x: hexfn(x[0].node()), formathex),
384 384 ('date', ' ', lambda x: x[0].date(), util.cachefunc(datefunc)),
385 385 ('file', ' ', lambda x: x[0].path(), str),
386 386 ('line_number', ':', lambda x: x[1], str),
387 387 ]
388 388 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
389 389
390 390 if (not opts.get('user') and not opts.get('changeset')
391 391 and not opts.get('date') and not opts.get('file')):
392 392 opts['number'] = True
393 393
394 394 linenumber = opts.get('line_number') is not None
395 395 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
396 396 raise error.Abort(_('at least one of -n/-c is required for -l'))
397 397
398 398 if fm:
399 399 def makefunc(get, fmt):
400 400 return get
401 401 else:
402 402 def makefunc(get, fmt):
403 403 return lambda x: fmt(get(x))
404 404 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
405 405 if opts.get(op)]
406 406 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
407 407 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
408 408 if opts.get(op))
409 409
410 410 def bad(x, y):
411 411 raise error.Abort("%s: %s" % (x, y))
412 412
413 413 m = scmutil.match(ctx, pats, opts, badfn=bad)
414 414
415 415 follow = not opts.get('no_follow')
416 416 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
417 417 whitespace=True)
418 418 for abs in ctx.walk(m):
419 419 fctx = ctx[abs]
420 420 if not opts.get('text') and util.binary(fctx.data()):
421 421 fm.plain(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
422 422 continue
423 423
424 424 lines = fctx.annotate(follow=follow, linenumber=linenumber,
425 425 diffopts=diffopts)
426 426 formats = []
427 427 pieces = []
428 428
429 429 for f, sep in funcmap:
430 430 l = [f(n) for n, dummy in lines]
431 431 if l:
432 432 if fm:
433 433 formats.append(['%s' for x in l])
434 434 else:
435 435 sizes = [encoding.colwidth(x) for x in l]
436 436 ml = max(sizes)
437 437 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
438 438 pieces.append(l)
439 439
440 440 for f, p, l in zip(zip(*formats), zip(*pieces), lines):
441 441 fm.startitem()
442 442 fm.write(fields, "".join(f), *p)
443 443 fm.write('line', ": %s", l[1])
444 444
445 445 if lines and not lines[-1][1].endswith('\n'):
446 446 fm.plain('\n')
447 447
448 448 fm.end()
449 449
450 450 @command('archive',
451 451 [('', 'no-decode', None, _('do not pass files through decoders')),
452 452 ('p', 'prefix', '', _('directory prefix for files in archive'),
453 453 _('PREFIX')),
454 454 ('r', 'rev', '', _('revision to distribute'), _('REV')),
455 455 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
456 456 ] + subrepoopts + walkopts,
457 457 _('[OPTION]... DEST'))
458 458 def archive(ui, repo, dest, **opts):
459 459 '''create an unversioned archive of a repository revision
460 460
461 461 By default, the revision used is the parent of the working
462 462 directory; use -r/--rev to specify a different revision.
463 463
464 464 The archive type is automatically detected based on file
465 465 extension (or override using -t/--type).
466 466
467 467 .. container:: verbose
468 468
469 469 Examples:
470 470
471 471 - create a zip file containing the 1.0 release::
472 472
473 473 hg archive -r 1.0 project-1.0.zip
474 474
475 475 - create a tarball excluding .hg files::
476 476
477 477 hg archive project.tar.gz -X ".hg*"
478 478
479 479 Valid types are:
480 480
481 481 :``files``: a directory full of files (default)
482 482 :``tar``: tar archive, uncompressed
483 483 :``tbz2``: tar archive, compressed using bzip2
484 484 :``tgz``: tar archive, compressed using gzip
485 485 :``uzip``: zip archive, uncompressed
486 486 :``zip``: zip archive, compressed using deflate
487 487
488 488 The exact name of the destination archive or directory is given
489 489 using a format string; see :hg:`help export` for details.
490 490
491 491 Each member added to an archive file has a directory prefix
492 492 prepended. Use -p/--prefix to specify a format string for the
493 493 prefix. The default is the basename of the archive, with suffixes
494 494 removed.
495 495
496 496 Returns 0 on success.
497 497 '''
498 498
499 499 ctx = scmutil.revsingle(repo, opts.get('rev'))
500 500 if not ctx:
501 501 raise error.Abort(_('no working directory: please specify a revision'))
502 502 node = ctx.node()
503 503 dest = cmdutil.makefilename(repo, dest, node)
504 504 if os.path.realpath(dest) == repo.root:
505 505 raise error.Abort(_('repository root cannot be destination'))
506 506
507 507 kind = opts.get('type') or archival.guesskind(dest) or 'files'
508 508 prefix = opts.get('prefix')
509 509
510 510 if dest == '-':
511 511 if kind == 'files':
512 512 raise error.Abort(_('cannot archive plain files to stdout'))
513 513 dest = cmdutil.makefileobj(repo, dest)
514 514 if not prefix:
515 515 prefix = os.path.basename(repo.root) + '-%h'
516 516
517 517 prefix = cmdutil.makefilename(repo, prefix, node)
518 518 matchfn = scmutil.match(ctx, [], opts)
519 519 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
520 520 matchfn, prefix, subrepos=opts.get('subrepos'))
521 521
522 522 @command('backout',
523 523 [('', 'merge', None, _('merge with old dirstate parent after backout')),
524 524 ('', 'commit', None, _('commit if no conflicts were encountered')),
525 525 ('', 'parent', '',
526 526 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
527 527 ('r', 'rev', '', _('revision to backout'), _('REV')),
528 528 ('e', 'edit', False, _('invoke editor on commit messages')),
529 529 ] + mergetoolopts + walkopts + commitopts + commitopts2,
530 530 _('[OPTION]... [-r] REV'))
531 531 def backout(ui, repo, node=None, rev=None, commit=False, **opts):
532 532 '''reverse effect of earlier changeset
533 533
534 534 Prepare a new changeset with the effect of REV undone in the
535 535 current working directory.
536 536
537 537 If REV is the parent of the working directory, then this new changeset
538 538 is committed automatically. Otherwise, hg needs to merge the
539 539 changes and the merged result is left uncommitted.
540 540
541 541 .. note::
542 542
543 543 backout cannot be used to fix either an unwanted or
544 544 incorrect merge.
545 545
546 546 .. container:: verbose
547 547
548 548 Examples:
549 549
550 550 - Reverse the effect of the parent of the working directory.
551 551 This backout will be committed immediately::
552 552
553 553 hg backout -r .
554 554
555 555 - Reverse the effect of previous bad revision 23::
556 556
557 557 hg backout -r 23
558 558 hg commit -m "Backout revision 23"
559 559
560 560 - Reverse the effect of previous bad revision 23 and
561 561 commit the backout immediately::
562 562
563 563 hg backout -r 23 --commit
564 564
565 565 By default, the pending changeset will have one parent,
566 566 maintaining a linear history. With --merge, the pending
567 567 changeset will instead have two parents: the old parent of the
568 568 working directory and a new child of REV that simply undoes REV.
569 569
570 570 Before version 1.7, the behavior without --merge was equivalent
571 571 to specifying --merge followed by :hg:`update --clean .` to
572 572 cancel the merge and leave the child of REV as a head to be
573 573 merged separately.
574 574
575 575 See :hg:`help dates` for a list of formats valid for -d/--date.
576 576
577 577 See :hg:`help revert` for a way to restore files to the state
578 578 of another revision.
579 579
580 580 Returns 0 on success, 1 if nothing to backout or there are unresolved
581 581 files.
582 582 '''
583 583 wlock = lock = None
584 584 try:
585 585 wlock = repo.wlock()
586 586 lock = repo.lock()
587 587 return _dobackout(ui, repo, node, rev, commit, **opts)
588 588 finally:
589 589 release(lock, wlock)
590 590
591 591 def _dobackout(ui, repo, node=None, rev=None, commit=False, **opts):
592 592 if rev and node:
593 593 raise error.Abort(_("please specify just one revision"))
594 594
595 595 if not rev:
596 596 rev = node
597 597
598 598 if not rev:
599 599 raise error.Abort(_("please specify a revision to backout"))
600 600
601 601 date = opts.get('date')
602 602 if date:
603 603 opts['date'] = util.parsedate(date)
604 604
605 605 cmdutil.checkunfinished(repo)
606 606 cmdutil.bailifchanged(repo)
607 607 node = scmutil.revsingle(repo, rev).node()
608 608
609 609 op1, op2 = repo.dirstate.parents()
610 610 if not repo.changelog.isancestor(node, op1):
611 611 raise error.Abort(_('cannot backout change that is not an ancestor'))
612 612
613 613 p1, p2 = repo.changelog.parents(node)
614 614 if p1 == nullid:
615 615 raise error.Abort(_('cannot backout a change with no parents'))
616 616 if p2 != nullid:
617 617 if not opts.get('parent'):
618 618 raise error.Abort(_('cannot backout a merge changeset'))
619 619 p = repo.lookup(opts['parent'])
620 620 if p not in (p1, p2):
621 621 raise error.Abort(_('%s is not a parent of %s') %
622 622 (short(p), short(node)))
623 623 parent = p
624 624 else:
625 625 if opts.get('parent'):
626 626 raise error.Abort(_('cannot use --parent on non-merge changeset'))
627 627 parent = p1
628 628
629 629 # the backout should appear on the same branch
630 630 try:
631 631 branch = repo.dirstate.branch()
632 632 bheads = repo.branchheads(branch)
633 633 rctx = scmutil.revsingle(repo, hex(parent))
634 634 if not opts.get('merge') and op1 != node:
635 635 dsguard = cmdutil.dirstateguard(repo, 'backout')
636 636 try:
637 637 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
638 638 'backout')
639 639 stats = mergemod.update(repo, parent, True, True, False,
640 640 node, False)
641 641 repo.setparents(op1, op2)
642 642 dsguard.close()
643 643 hg._showstats(repo, stats)
644 644 if stats[3]:
645 645 repo.ui.status(_("use 'hg resolve' to retry unresolved "
646 646 "file merges\n"))
647 647 return 1
648 648 elif not commit:
649 649 msg = _("changeset %s backed out, "
650 650 "don't forget to commit.\n")
651 651 ui.status(msg % short(node))
652 652 return 0
653 653 finally:
654 654 ui.setconfig('ui', 'forcemerge', '', '')
655 655 lockmod.release(dsguard)
656 656 else:
657 657 hg.clean(repo, node, show_stats=False)
658 658 repo.dirstate.setbranch(branch)
659 659 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
660 660
661 661
662 662 def commitfunc(ui, repo, message, match, opts):
663 663 editform = 'backout'
664 664 e = cmdutil.getcommiteditor(editform=editform, **opts)
665 665 if not message:
666 666 # we don't translate commit messages
667 667 message = "Backed out changeset %s" % short(node)
668 668 e = cmdutil.getcommiteditor(edit=True, editform=editform)
669 669 return repo.commit(message, opts.get('user'), opts.get('date'),
670 670 match, editor=e)
671 671 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
672 672 if not newnode:
673 673 ui.status(_("nothing changed\n"))
674 674 return 1
675 675 cmdutil.commitstatus(repo, newnode, branch, bheads)
676 676
677 677 def nice(node):
678 678 return '%d:%s' % (repo.changelog.rev(node), short(node))
679 679 ui.status(_('changeset %s backs out changeset %s\n') %
680 680 (nice(repo.changelog.tip()), nice(node)))
681 681 if opts.get('merge') and op1 != node:
682 682 hg.clean(repo, op1, show_stats=False)
683 683 ui.status(_('merging with changeset %s\n')
684 684 % nice(repo.changelog.tip()))
685 685 try:
686 686 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
687 687 'backout')
688 688 return hg.merge(repo, hex(repo.changelog.tip()))
689 689 finally:
690 690 ui.setconfig('ui', 'forcemerge', '', '')
691 691 finally:
692 692 # TODO: get rid of this meaningless try/finally enclosing.
693 693 # this is kept only to reduce changes in a patch.
694 694 pass
695 695 return 0
696 696
697 697 @command('bisect',
698 698 [('r', 'reset', False, _('reset bisect state')),
699 699 ('g', 'good', False, _('mark changeset good')),
700 700 ('b', 'bad', False, _('mark changeset bad')),
701 701 ('s', 'skip', False, _('skip testing changeset')),
702 702 ('e', 'extend', False, _('extend the bisect range')),
703 703 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
704 704 ('U', 'noupdate', False, _('do not update to target'))],
705 705 _("[-gbsr] [-U] [-c CMD] [REV]"))
706 706 def bisect(ui, repo, rev=None, extra=None, command=None,
707 707 reset=None, good=None, bad=None, skip=None, extend=None,
708 708 noupdate=None):
709 709 """subdivision search of changesets
710 710
711 711 This command helps to find changesets which introduce problems. To
712 712 use, mark the earliest changeset you know exhibits the problem as
713 713 bad, then mark the latest changeset which is free from the problem
714 714 as good. Bisect will update your working directory to a revision
715 715 for testing (unless the -U/--noupdate option is specified). Once
716 716 you have performed tests, mark the working directory as good or
717 717 bad, and bisect will either update to another candidate changeset
718 718 or announce that it has found the bad revision.
719 719
720 720 As a shortcut, you can also use the revision argument to mark a
721 721 revision as good or bad without checking it out first.
722 722
723 723 If you supply a command, it will be used for automatic bisection.
724 724 The environment variable HG_NODE will contain the ID of the
725 725 changeset being tested. The exit status of the command will be
726 726 used to mark revisions as good or bad: status 0 means good, 125
727 727 means to skip the revision, 127 (command not found) will abort the
728 728 bisection, and any other non-zero exit status means the revision
729 729 is bad.
730 730
731 731 .. container:: verbose
732 732
733 733 Some examples:
734 734
735 735 - start a bisection with known bad revision 34, and good revision 12::
736 736
737 737 hg bisect --bad 34
738 738 hg bisect --good 12
739 739
740 740 - advance the current bisection by marking current revision as good or
741 741 bad::
742 742
743 743 hg bisect --good
744 744 hg bisect --bad
745 745
746 746 - mark the current revision, or a known revision, to be skipped (e.g. if
747 747 that revision is not usable because of another issue)::
748 748
749 749 hg bisect --skip
750 750 hg bisect --skip 23
751 751
752 752 - skip all revisions that do not touch directories ``foo`` or ``bar``::
753 753
754 754 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
755 755
756 756 - forget the current bisection::
757 757
758 758 hg bisect --reset
759 759
760 760 - use 'make && make tests' to automatically find the first broken
761 761 revision::
762 762
763 763 hg bisect --reset
764 764 hg bisect --bad 34
765 765 hg bisect --good 12
766 766 hg bisect --command "make && make tests"
767 767
768 768 - see all changesets whose states are already known in the current
769 769 bisection::
770 770
771 771 hg log -r "bisect(pruned)"
772 772
773 773 - see the changeset currently being bisected (especially useful
774 774 if running with -U/--noupdate)::
775 775
776 776 hg log -r "bisect(current)"
777 777
778 778 - see all changesets that took part in the current bisection::
779 779
780 780 hg log -r "bisect(range)"
781 781
782 782 - you can even get a nice graph::
783 783
784 784 hg log --graph -r "bisect(range)"
785 785
786 786 See :hg:`help revsets` for more about the `bisect()` keyword.
787 787
788 788 Returns 0 on success.
789 789 """
790 790 def extendbisectrange(nodes, good):
791 791 # bisect is incomplete when it ends on a merge node and
792 792 # one of the parent was not checked.
793 793 parents = repo[nodes[0]].parents()
794 794 if len(parents) > 1:
795 795 if good:
796 796 side = state['bad']
797 797 else:
798 798 side = state['good']
799 799 num = len(set(i.node() for i in parents) & set(side))
800 800 if num == 1:
801 801 return parents[0].ancestor(parents[1])
802 802 return None
803 803
804 804 def print_result(nodes, good):
805 805 displayer = cmdutil.show_changeset(ui, repo, {})
806 806 if len(nodes) == 1:
807 807 # narrowed it down to a single revision
808 808 if good:
809 809 ui.write(_("The first good revision is:\n"))
810 810 else:
811 811 ui.write(_("The first bad revision is:\n"))
812 812 displayer.show(repo[nodes[0]])
813 813 extendnode = extendbisectrange(nodes, good)
814 814 if extendnode is not None:
815 815 ui.write(_('Not all ancestors of this changeset have been'
816 816 ' checked.\nUse bisect --extend to continue the '
817 817 'bisection from\nthe common ancestor, %s.\n')
818 818 % extendnode)
819 819 else:
820 820 # multiple possible revisions
821 821 if good:
822 822 ui.write(_("Due to skipped revisions, the first "
823 823 "good revision could be any of:\n"))
824 824 else:
825 825 ui.write(_("Due to skipped revisions, the first "
826 826 "bad revision could be any of:\n"))
827 827 for n in nodes:
828 828 displayer.show(repo[n])
829 829 displayer.close()
830 830
831 831 def check_state(state, interactive=True):
832 832 if not state['good'] or not state['bad']:
833 833 if (good or bad or skip or reset) and interactive:
834 834 return
835 835 if not state['good']:
836 836 raise error.Abort(_('cannot bisect (no known good revisions)'))
837 837 else:
838 838 raise error.Abort(_('cannot bisect (no known bad revisions)'))
839 839 return True
840 840
841 841 # backward compatibility
842 842 if rev in "good bad reset init".split():
843 843 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
844 844 cmd, rev, extra = rev, extra, None
845 845 if cmd == "good":
846 846 good = True
847 847 elif cmd == "bad":
848 848 bad = True
849 849 else:
850 850 reset = True
851 851 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
852 852 raise error.Abort(_('incompatible arguments'))
853 853
854 854 cmdutil.checkunfinished(repo)
855 855
856 856 if reset:
857 857 p = repo.join("bisect.state")
858 858 if os.path.exists(p):
859 859 os.unlink(p)
860 860 return
861 861
862 862 state = hbisect.load_state(repo)
863 863
864 864 if command:
865 865 changesets = 1
866 866 if noupdate:
867 867 try:
868 868 node = state['current'][0]
869 869 except LookupError:
870 870 raise error.Abort(_('current bisect revision is unknown - '
871 871 'start a new bisect to fix'))
872 872 else:
873 873 node, p2 = repo.dirstate.parents()
874 874 if p2 != nullid:
875 875 raise error.Abort(_('current bisect revision is a merge'))
876 876 try:
877 877 while changesets:
878 878 # update state
879 879 state['current'] = [node]
880 880 hbisect.save_state(repo, state)
881 881 status = ui.system(command, environ={'HG_NODE': hex(node)})
882 882 if status == 125:
883 883 transition = "skip"
884 884 elif status == 0:
885 885 transition = "good"
886 886 # status < 0 means process was killed
887 887 elif status == 127:
888 888 raise error.Abort(_("failed to execute %s") % command)
889 889 elif status < 0:
890 890 raise error.Abort(_("%s killed") % command)
891 891 else:
892 892 transition = "bad"
893 893 ctx = scmutil.revsingle(repo, rev, node)
894 894 rev = None # clear for future iterations
895 895 state[transition].append(ctx.node())
896 896 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
897 897 check_state(state, interactive=False)
898 898 # bisect
899 899 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
900 900 # update to next check
901 901 node = nodes[0]
902 902 if not noupdate:
903 903 cmdutil.bailifchanged(repo)
904 904 hg.clean(repo, node, show_stats=False)
905 905 finally:
906 906 state['current'] = [node]
907 907 hbisect.save_state(repo, state)
908 908 print_result(nodes, bgood)
909 909 return
910 910
911 911 # update state
912 912
913 913 if rev:
914 914 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
915 915 else:
916 916 nodes = [repo.lookup('.')]
917 917
918 918 if good or bad or skip:
919 919 if good:
920 920 state['good'] += nodes
921 921 elif bad:
922 922 state['bad'] += nodes
923 923 elif skip:
924 924 state['skip'] += nodes
925 925 hbisect.save_state(repo, state)
926 926
927 927 if not check_state(state):
928 928 return
929 929
930 930 # actually bisect
931 931 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
932 932 if extend:
933 933 if not changesets:
934 934 extendnode = extendbisectrange(nodes, good)
935 935 if extendnode is not None:
936 936 ui.write(_("Extending search to changeset %d:%s\n")
937 937 % (extendnode.rev(), extendnode))
938 938 state['current'] = [extendnode.node()]
939 939 hbisect.save_state(repo, state)
940 940 if noupdate:
941 941 return
942 942 cmdutil.bailifchanged(repo)
943 943 return hg.clean(repo, extendnode.node())
944 944 raise error.Abort(_("nothing to extend"))
945 945
946 946 if changesets == 0:
947 947 print_result(nodes, good)
948 948 else:
949 949 assert len(nodes) == 1 # only a single node can be tested next
950 950 node = nodes[0]
951 951 # compute the approximate number of remaining tests
952 952 tests, size = 0, 2
953 953 while size <= changesets:
954 954 tests, size = tests + 1, size * 2
955 955 rev = repo.changelog.rev(node)
956 956 ui.write(_("Testing changeset %d:%s "
957 957 "(%d changesets remaining, ~%d tests)\n")
958 958 % (rev, short(node), changesets, tests))
959 959 state['current'] = [node]
960 960 hbisect.save_state(repo, state)
961 961 if not noupdate:
962 962 cmdutil.bailifchanged(repo)
963 963 return hg.clean(repo, node)
964 964
965 965 @command('bookmarks|bookmark',
966 966 [('f', 'force', False, _('force')),
967 967 ('r', 'rev', '', _('revision'), _('REV')),
968 968 ('d', 'delete', False, _('delete a given bookmark')),
969 969 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
970 970 ('i', 'inactive', False, _('mark a bookmark inactive')),
971 971 ] + formatteropts,
972 972 _('hg bookmarks [OPTIONS]... [NAME]...'))
973 973 def bookmark(ui, repo, *names, **opts):
974 974 '''create a new bookmark or list existing bookmarks
975 975
976 976 Bookmarks are labels on changesets to help track lines of development.
977 977 Bookmarks are unversioned and can be moved, renamed and deleted.
978 978 Deleting or moving a bookmark has no effect on the associated changesets.
979 979
980 980 Creating or updating to a bookmark causes it to be marked as 'active'.
981 981 The active bookmark is indicated with a '*'.
982 982 When a commit is made, the active bookmark will advance to the new commit.
983 983 A plain :hg:`update` will also advance an active bookmark, if possible.
984 984 Updating away from a bookmark will cause it to be deactivated.
985 985
986 986 Bookmarks can be pushed and pulled between repositories (see
987 987 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
988 988 diverged, a new 'divergent bookmark' of the form 'name@path' will
989 989 be created. Using :hg:`merge` will resolve the divergence.
990 990
991 991 A bookmark named '@' has the special property that :hg:`clone` will
992 992 check it out by default if it exists.
993 993
994 994 .. container:: verbose
995 995
996 996 Examples:
997 997
998 998 - create an active bookmark for a new line of development::
999 999
1000 1000 hg book new-feature
1001 1001
1002 1002 - create an inactive bookmark as a place marker::
1003 1003
1004 1004 hg book -i reviewed
1005 1005
1006 1006 - create an inactive bookmark on another changeset::
1007 1007
1008 1008 hg book -r .^ tested
1009 1009
1010 1010 - rename bookmark turkey to dinner::
1011 1011
1012 1012 hg book -m turkey dinner
1013 1013
1014 1014 - move the '@' bookmark from another branch::
1015 1015
1016 1016 hg book -f @
1017 1017 '''
1018 1018 force = opts.get('force')
1019 1019 rev = opts.get('rev')
1020 1020 delete = opts.get('delete')
1021 1021 rename = opts.get('rename')
1022 1022 inactive = opts.get('inactive')
1023 1023
1024 1024 def checkformat(mark):
1025 1025 mark = mark.strip()
1026 1026 if not mark:
1027 1027 raise error.Abort(_("bookmark names cannot consist entirely of "
1028 1028 "whitespace"))
1029 1029 scmutil.checknewlabel(repo, mark, 'bookmark')
1030 1030 return mark
1031 1031
1032 1032 def checkconflict(repo, mark, cur, force=False, target=None):
1033 1033 if mark in marks and not force:
1034 1034 if target:
1035 1035 if marks[mark] == target and target == cur:
1036 1036 # re-activating a bookmark
1037 1037 return
1038 1038 anc = repo.changelog.ancestors([repo[target].rev()])
1039 1039 bmctx = repo[marks[mark]]
1040 1040 divs = [repo[b].node() for b in marks
1041 1041 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
1042 1042
1043 1043 # allow resolving a single divergent bookmark even if moving
1044 1044 # the bookmark across branches when a revision is specified
1045 1045 # that contains a divergent bookmark
1046 1046 if bmctx.rev() not in anc and target in divs:
1047 1047 bookmarks.deletedivergent(repo, [target], mark)
1048 1048 return
1049 1049
1050 1050 deletefrom = [b for b in divs
1051 1051 if repo[b].rev() in anc or b == target]
1052 1052 bookmarks.deletedivergent(repo, deletefrom, mark)
1053 1053 if bookmarks.validdest(repo, bmctx, repo[target]):
1054 1054 ui.status(_("moving bookmark '%s' forward from %s\n") %
1055 1055 (mark, short(bmctx.node())))
1056 1056 return
1057 1057 raise error.Abort(_("bookmark '%s' already exists "
1058 1058 "(use -f to force)") % mark)
1059 1059 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
1060 1060 and not force):
1061 1061 raise error.Abort(
1062 1062 _("a bookmark cannot have the name of an existing branch"))
1063 1063
1064 1064 if delete and rename:
1065 1065 raise error.Abort(_("--delete and --rename are incompatible"))
1066 1066 if delete and rev:
1067 1067 raise error.Abort(_("--rev is incompatible with --delete"))
1068 1068 if rename and rev:
1069 1069 raise error.Abort(_("--rev is incompatible with --rename"))
1070 1070 if not names and (delete or rev):
1071 1071 raise error.Abort(_("bookmark name required"))
1072 1072
1073 1073 if delete or rename or names or inactive:
1074 1074 wlock = lock = tr = None
1075 1075 try:
1076 1076 wlock = repo.wlock()
1077 1077 lock = repo.lock()
1078 1078 cur = repo.changectx('.').node()
1079 1079 marks = repo._bookmarks
1080 1080 if delete:
1081 1081 tr = repo.transaction('bookmark')
1082 1082 for mark in names:
1083 1083 if mark not in marks:
1084 1084 raise error.Abort(_("bookmark '%s' does not exist") %
1085 1085 mark)
1086 1086 if mark == repo._activebookmark:
1087 1087 bookmarks.deactivate(repo)
1088 1088 del marks[mark]
1089 1089
1090 1090 elif rename:
1091 1091 tr = repo.transaction('bookmark')
1092 1092 if not names:
1093 1093 raise error.Abort(_("new bookmark name required"))
1094 1094 elif len(names) > 1:
1095 1095 raise error.Abort(_("only one new bookmark name allowed"))
1096 1096 mark = checkformat(names[0])
1097 1097 if rename not in marks:
1098 1098 raise error.Abort(_("bookmark '%s' does not exist")
1099 1099 % rename)
1100 1100 checkconflict(repo, mark, cur, force)
1101 1101 marks[mark] = marks[rename]
1102 1102 if repo._activebookmark == rename and not inactive:
1103 1103 bookmarks.activate(repo, mark)
1104 1104 del marks[rename]
1105 1105 elif names:
1106 1106 tr = repo.transaction('bookmark')
1107 1107 newact = None
1108 1108 for mark in names:
1109 1109 mark = checkformat(mark)
1110 1110 if newact is None:
1111 1111 newact = mark
1112 1112 if inactive and mark == repo._activebookmark:
1113 1113 bookmarks.deactivate(repo)
1114 1114 return
1115 1115 tgt = cur
1116 1116 if rev:
1117 1117 tgt = scmutil.revsingle(repo, rev).node()
1118 1118 checkconflict(repo, mark, cur, force, tgt)
1119 1119 marks[mark] = tgt
1120 1120 if not inactive and cur == marks[newact] and not rev:
1121 1121 bookmarks.activate(repo, newact)
1122 1122 elif cur != tgt and newact == repo._activebookmark:
1123 1123 bookmarks.deactivate(repo)
1124 1124 elif inactive:
1125 1125 if len(marks) == 0:
1126 1126 ui.status(_("no bookmarks set\n"))
1127 1127 elif not repo._activebookmark:
1128 1128 ui.status(_("no active bookmark\n"))
1129 1129 else:
1130 1130 bookmarks.deactivate(repo)
1131 1131 if tr is not None:
1132 1132 marks.recordchange(tr)
1133 1133 tr.close()
1134 1134 finally:
1135 1135 lockmod.release(tr, lock, wlock)
1136 1136 else: # show bookmarks
1137 1137 fm = ui.formatter('bookmarks', opts)
1138 1138 hexfn = fm.hexfunc
1139 1139 marks = repo._bookmarks
1140 1140 if len(marks) == 0 and not fm:
1141 1141 ui.status(_("no bookmarks set\n"))
1142 1142 for bmark, n in sorted(marks.iteritems()):
1143 1143 active = repo._activebookmark
1144 1144 if bmark == active:
1145 1145 prefix, label = '*', activebookmarklabel
1146 1146 else:
1147 1147 prefix, label = ' ', ''
1148 1148
1149 1149 fm.startitem()
1150 1150 if not ui.quiet:
1151 1151 fm.plain(' %s ' % prefix, label=label)
1152 1152 fm.write('bookmark', '%s', bmark, label=label)
1153 1153 pad = " " * (25 - encoding.colwidth(bmark))
1154 1154 fm.condwrite(not ui.quiet, 'rev node', pad + ' %d:%s',
1155 1155 repo.changelog.rev(n), hexfn(n), label=label)
1156 1156 fm.data(active=(bmark == active))
1157 1157 fm.plain('\n')
1158 1158 fm.end()
1159 1159
1160 1160 @command('branch',
1161 1161 [('f', 'force', None,
1162 1162 _('set branch name even if it shadows an existing branch')),
1163 1163 ('C', 'clean', None, _('reset branch name to parent branch name'))],
1164 1164 _('[-fC] [NAME]'))
1165 1165 def branch(ui, repo, label=None, **opts):
1166 1166 """set or show the current branch name
1167 1167
1168 1168 .. note::
1169 1169
1170 1170 Branch names are permanent and global. Use :hg:`bookmark` to create a
1171 1171 light-weight bookmark instead. See :hg:`help glossary` for more
1172 1172 information about named branches and bookmarks.
1173 1173
1174 1174 With no argument, show the current branch name. With one argument,
1175 1175 set the working directory branch name (the branch will not exist
1176 1176 in the repository until the next commit). Standard practice
1177 1177 recommends that primary development take place on the 'default'
1178 1178 branch.
1179 1179
1180 1180 Unless -f/--force is specified, branch will not let you set a
1181 1181 branch name that already exists.
1182 1182
1183 1183 Use -C/--clean to reset the working directory branch to that of
1184 1184 the parent of the working directory, negating a previous branch
1185 1185 change.
1186 1186
1187 1187 Use the command :hg:`update` to switch to an existing branch. Use
1188 1188 :hg:`commit --close-branch` to mark this branch head as closed.
1189 1189 When all heads of the branch are closed, the branch will be
1190 1190 considered closed.
1191 1191
1192 1192 Returns 0 on success.
1193 1193 """
1194 1194 if label:
1195 1195 label = label.strip()
1196 1196
1197 1197 if not opts.get('clean') and not label:
1198 1198 ui.write("%s\n" % repo.dirstate.branch())
1199 1199 return
1200 1200
1201 1201 wlock = repo.wlock()
1202 1202 try:
1203 1203 if opts.get('clean'):
1204 1204 label = repo[None].p1().branch()
1205 1205 repo.dirstate.setbranch(label)
1206 1206 ui.status(_('reset working directory to branch %s\n') % label)
1207 1207 elif label:
1208 1208 if not opts.get('force') and label in repo.branchmap():
1209 1209 if label not in [p.branch() for p in repo[None].parents()]:
1210 1210 raise error.Abort(_('a branch of the same name already'
1211 1211 ' exists'),
1212 1212 # i18n: "it" refers to an existing branch
1213 1213 hint=_("use 'hg update' to switch to it"))
1214 1214 scmutil.checknewlabel(repo, label, 'branch')
1215 1215 repo.dirstate.setbranch(label)
1216 1216 ui.status(_('marked working directory as branch %s\n') % label)
1217 1217
1218 1218 # find any open named branches aside from default
1219 1219 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1220 1220 if n != "default" and not c]
1221 1221 if not others:
1222 1222 ui.status(_('(branches are permanent and global, '
1223 1223 'did you want a bookmark?)\n'))
1224 1224 finally:
1225 1225 wlock.release()
1226 1226
1227 1227 @command('branches',
1228 1228 [('a', 'active', False,
1229 1229 _('show only branches that have unmerged heads (DEPRECATED)')),
1230 1230 ('c', 'closed', False, _('show normal and closed branches')),
1231 1231 ] + formatteropts,
1232 1232 _('[-ac]'))
1233 1233 def branches(ui, repo, active=False, closed=False, **opts):
1234 1234 """list repository named branches
1235 1235
1236 1236 List the repository's named branches, indicating which ones are
1237 1237 inactive. If -c/--closed is specified, also list branches which have
1238 1238 been marked closed (see :hg:`commit --close-branch`).
1239 1239
1240 1240 Use the command :hg:`update` to switch to an existing branch.
1241 1241
1242 1242 Returns 0.
1243 1243 """
1244 1244
1245 1245 fm = ui.formatter('branches', opts)
1246 1246 hexfunc = fm.hexfunc
1247 1247
1248 1248 allheads = set(repo.heads())
1249 1249 branches = []
1250 1250 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1251 1251 isactive = not isclosed and bool(set(heads) & allheads)
1252 1252 branches.append((tag, repo[tip], isactive, not isclosed))
1253 1253 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1254 1254 reverse=True)
1255 1255
1256 1256 for tag, ctx, isactive, isopen in branches:
1257 1257 if active and not isactive:
1258 1258 continue
1259 1259 if isactive:
1260 1260 label = 'branches.active'
1261 1261 notice = ''
1262 1262 elif not isopen:
1263 1263 if not closed:
1264 1264 continue
1265 1265 label = 'branches.closed'
1266 1266 notice = _(' (closed)')
1267 1267 else:
1268 1268 label = 'branches.inactive'
1269 1269 notice = _(' (inactive)')
1270 1270 current = (tag == repo.dirstate.branch())
1271 1271 if current:
1272 1272 label = 'branches.current'
1273 1273
1274 1274 fm.startitem()
1275 1275 fm.write('branch', '%s', tag, label=label)
1276 1276 rev = ctx.rev()
1277 1277 padsize = max(31 - len(str(rev)) - encoding.colwidth(tag), 0)
1278 1278 fmt = ' ' * padsize + ' %d:%s'
1279 1279 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1280 1280 label='log.changeset changeset.%s' % ctx.phasestr())
1281 1281 fm.data(active=isactive, closed=not isopen, current=current)
1282 1282 if not ui.quiet:
1283 1283 fm.plain(notice)
1284 1284 fm.plain('\n')
1285 1285 fm.end()
1286 1286
1287 1287 @command('bundle',
1288 1288 [('f', 'force', None, _('run even when the destination is unrelated')),
1289 1289 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1290 1290 _('REV')),
1291 1291 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1292 1292 _('BRANCH')),
1293 1293 ('', 'base', [],
1294 1294 _('a base changeset assumed to be available at the destination'),
1295 1295 _('REV')),
1296 1296 ('a', 'all', None, _('bundle all changesets in the repository')),
1297 1297 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1298 1298 ] + remoteopts,
1299 1299 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1300 1300 def bundle(ui, repo, fname, dest=None, **opts):
1301 1301 """create a changegroup file
1302 1302
1303 1303 Generate a compressed changegroup file collecting changesets not
1304 1304 known to be in another repository.
1305 1305
1306 1306 If you omit the destination repository, then hg assumes the
1307 1307 destination will have all the nodes you specify with --base
1308 1308 parameters. To create a bundle containing all changesets, use
1309 1309 -a/--all (or --base null).
1310 1310
1311 1311 You can change bundle format with the -t/--type option. You can
1312 1312 specify a compression, a bundle version or both using a dash
1313 1313 (comp-version). The available compression methods are: none, bzip2,
1314 1314 and gzip (by default, bundles are compressed using bzip2). The
1315 1315 available format are: v1, v2 (default to most suitable).
1316 1316
1317 1317 The bundle file can then be transferred using conventional means
1318 1318 and applied to another repository with the unbundle or pull
1319 1319 command. This is useful when direct push and pull are not
1320 1320 available or when exporting an entire repository is undesirable.
1321 1321
1322 1322 Applying bundles preserves all changeset contents including
1323 1323 permissions, copy/rename information, and revision history.
1324 1324
1325 1325 Returns 0 on success, 1 if no changes found.
1326 1326 """
1327 1327 revs = None
1328 1328 if 'rev' in opts:
1329 1329 revs = scmutil.revrange(repo, opts['rev'])
1330 1330
1331 1331 bundletype = opts.get('type', 'bzip2').lower()
1332 1332 try:
1333 1333 bcompression, cgversion, params = exchange.parsebundlespec(
1334 1334 repo, bundletype, strict=False)
1335 1335 except error.UnsupportedBundleSpecification as e:
1336 1336 raise error.Abort(str(e),
1337 1337 hint=_('see "hg help bundle" for supported '
1338 1338 'values for --type'))
1339 1339
1340 1340 # Packed bundles are a pseudo bundle format for now.
1341 1341 if cgversion == 's1':
1342 1342 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1343 1343 hint=_('use "hg debugcreatestreamclonebundle"'))
1344 1344
1345 1345 if opts.get('all'):
1346 1346 base = ['null']
1347 1347 else:
1348 1348 base = scmutil.revrange(repo, opts.get('base'))
1349 1349 # TODO: get desired bundlecaps from command line.
1350 1350 bundlecaps = None
1351 1351 if base:
1352 1352 if dest:
1353 1353 raise error.Abort(_("--base is incompatible with specifying "
1354 1354 "a destination"))
1355 1355 common = [repo.lookup(rev) for rev in base]
1356 1356 heads = revs and map(repo.lookup, revs) or revs
1357 1357 cg = changegroup.getchangegroup(repo, 'bundle', heads=heads,
1358 1358 common=common, bundlecaps=bundlecaps,
1359 1359 version=cgversion)
1360 1360 outgoing = None
1361 1361 else:
1362 1362 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1363 1363 dest, branches = hg.parseurl(dest, opts.get('branch'))
1364 1364 other = hg.peer(repo, opts, dest)
1365 1365 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1366 1366 heads = revs and map(repo.lookup, revs) or revs
1367 1367 outgoing = discovery.findcommonoutgoing(repo, other,
1368 1368 onlyheads=heads,
1369 1369 force=opts.get('force'),
1370 1370 portable=True)
1371 1371 cg = changegroup.getlocalchangegroup(repo, 'bundle', outgoing,
1372 1372 bundlecaps, version=cgversion)
1373 1373 if not cg:
1374 1374 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1375 1375 return 1
1376 1376
1377 1377 if cgversion == '01': #bundle1
1378 1378 if bcompression is None:
1379 1379 bcompression = 'UN'
1380 1380 bversion = 'HG10' + bcompression
1381 1381 bcompression = None
1382 1382 else:
1383 1383 assert cgversion == '02'
1384 1384 bversion = 'HG20'
1385 1385
1386 1386
1387 1387 changegroup.writebundle(ui, cg, fname, bversion, compression=bcompression)
1388 1388
1389 1389 @command('cat',
1390 1390 [('o', 'output', '',
1391 1391 _('print output to file with formatted name'), _('FORMAT')),
1392 1392 ('r', 'rev', '', _('print the given revision'), _('REV')),
1393 1393 ('', 'decode', None, _('apply any matching decode filter')),
1394 1394 ] + walkopts,
1395 1395 _('[OPTION]... FILE...'),
1396 1396 inferrepo=True)
1397 1397 def cat(ui, repo, file1, *pats, **opts):
1398 1398 """output the current or given revision of files
1399 1399
1400 1400 Print the specified files as they were at the given revision. If
1401 1401 no revision is given, the parent of the working directory is used.
1402 1402
1403 1403 Output may be to a file, in which case the name of the file is
1404 1404 given using a format string. The formatting rules as follows:
1405 1405
1406 1406 :``%%``: literal "%" character
1407 1407 :``%s``: basename of file being printed
1408 1408 :``%d``: dirname of file being printed, or '.' if in repository root
1409 1409 :``%p``: root-relative path name of file being printed
1410 1410 :``%H``: changeset hash (40 hexadecimal digits)
1411 1411 :``%R``: changeset revision number
1412 1412 :``%h``: short-form changeset hash (12 hexadecimal digits)
1413 1413 :``%r``: zero-padded changeset revision number
1414 1414 :``%b``: basename of the exporting repository
1415 1415
1416 1416 Returns 0 on success.
1417 1417 """
1418 1418 ctx = scmutil.revsingle(repo, opts.get('rev'))
1419 1419 m = scmutil.match(ctx, (file1,) + pats, opts)
1420 1420
1421 1421 return cmdutil.cat(ui, repo, ctx, m, '', **opts)
1422 1422
1423 1423 @command('^clone',
1424 1424 [('U', 'noupdate', None, _('the clone will include an empty working '
1425 1425 'directory (only a repository)')),
1426 1426 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1427 1427 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1428 1428 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1429 1429 ('', 'pull', None, _('use pull protocol to copy metadata')),
1430 1430 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1431 1431 ] + remoteopts,
1432 1432 _('[OPTION]... SOURCE [DEST]'),
1433 1433 norepo=True)
1434 1434 def clone(ui, source, dest=None, **opts):
1435 1435 """make a copy of an existing repository
1436 1436
1437 1437 Create a copy of an existing repository in a new directory.
1438 1438
1439 1439 If no destination directory name is specified, it defaults to the
1440 1440 basename of the source.
1441 1441
1442 1442 The location of the source is added to the new repository's
1443 1443 ``.hg/hgrc`` file, as the default to be used for future pulls.
1444 1444
1445 1445 Only local paths and ``ssh://`` URLs are supported as
1446 1446 destinations. For ``ssh://`` destinations, no working directory or
1447 1447 ``.hg/hgrc`` will be created on the remote side.
1448 1448
1449 1449 To pull only a subset of changesets, specify one or more revisions
1450 1450 identifiers with -r/--rev or branches with -b/--branch. The
1451 1451 resulting clone will contain only the specified changesets and
1452 1452 their ancestors. These options (or 'clone src#rev dest') imply
1453 1453 --pull, even for local source repositories. Note that specifying a
1454 1454 tag will include the tagged changeset but not the changeset
1455 1455 containing the tag.
1456 1456
1457 1457 If the source repository has a bookmark called '@' set, that
1458 1458 revision will be checked out in the new repository by default.
1459 1459
1460 1460 To check out a particular version, use -u/--update, or
1461 1461 -U/--noupdate to create a clone with no working directory.
1462 1462
1463 1463 .. container:: verbose
1464 1464
1465 1465 For efficiency, hardlinks are used for cloning whenever the
1466 1466 source and destination are on the same filesystem (note this
1467 1467 applies only to the repository data, not to the working
1468 1468 directory). Some filesystems, such as AFS, implement hardlinking
1469 1469 incorrectly, but do not report errors. In these cases, use the
1470 1470 --pull option to avoid hardlinking.
1471 1471
1472 1472 In some cases, you can clone repositories and the working
1473 1473 directory using full hardlinks with ::
1474 1474
1475 1475 $ cp -al REPO REPOCLONE
1476 1476
1477 1477 This is the fastest way to clone, but it is not always safe. The
1478 1478 operation is not atomic (making sure REPO is not modified during
1479 1479 the operation is up to you) and you have to make sure your
1480 1480 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1481 1481 so). Also, this is not compatible with certain extensions that
1482 1482 place their metadata under the .hg directory, such as mq.
1483 1483
1484 1484 Mercurial will update the working directory to the first applicable
1485 1485 revision from this list:
1486 1486
1487 1487 a) null if -U or the source repository has no changesets
1488 1488 b) if -u . and the source repository is local, the first parent of
1489 1489 the source repository's working directory
1490 1490 c) the changeset specified with -u (if a branch name, this means the
1491 1491 latest head of that branch)
1492 1492 d) the changeset specified with -r
1493 1493 e) the tipmost head specified with -b
1494 1494 f) the tipmost head specified with the url#branch source syntax
1495 1495 g) the revision marked with the '@' bookmark, if present
1496 1496 h) the tipmost head of the default branch
1497 1497 i) tip
1498 1498
1499 1499 Examples:
1500 1500
1501 1501 - clone a remote repository to a new directory named hg/::
1502 1502
1503 1503 hg clone http://selenic.com/hg
1504 1504
1505 1505 - create a lightweight local clone::
1506 1506
1507 1507 hg clone project/ project-feature/
1508 1508
1509 1509 - clone from an absolute path on an ssh server (note double-slash)::
1510 1510
1511 1511 hg clone ssh://user@server//home/projects/alpha/
1512 1512
1513 1513 - do a high-speed clone over a LAN while checking out a
1514 1514 specified version::
1515 1515
1516 1516 hg clone --uncompressed http://server/repo -u 1.5
1517 1517
1518 1518 - create a repository without changesets after a particular revision::
1519 1519
1520 1520 hg clone -r 04e544 experimental/ good/
1521 1521
1522 1522 - clone (and track) a particular named branch::
1523 1523
1524 1524 hg clone http://selenic.com/hg#stable
1525 1525
1526 1526 See :hg:`help urls` for details on specifying URLs.
1527 1527
1528 1528 Returns 0 on success.
1529 1529 """
1530 1530 if opts.get('noupdate') and opts.get('updaterev'):
1531 1531 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1532 1532
1533 1533 r = hg.clone(ui, opts, source, dest,
1534 1534 pull=opts.get('pull'),
1535 1535 stream=opts.get('uncompressed'),
1536 1536 rev=opts.get('rev'),
1537 1537 update=opts.get('updaterev') or not opts.get('noupdate'),
1538 1538 branch=opts.get('branch'),
1539 1539 shareopts=opts.get('shareopts'))
1540 1540
1541 1541 return r is None
1542 1542
1543 1543 @command('^commit|ci',
1544 1544 [('A', 'addremove', None,
1545 1545 _('mark new/missing files as added/removed before committing')),
1546 1546 ('', 'close-branch', None,
1547 1547 _('mark a branch head as closed')),
1548 1548 ('', 'amend', None, _('amend the parent of the working directory')),
1549 1549 ('s', 'secret', None, _('use the secret phase for committing')),
1550 1550 ('e', 'edit', None, _('invoke editor on commit messages')),
1551 1551 ('i', 'interactive', None, _('use interactive mode')),
1552 1552 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1553 1553 _('[OPTION]... [FILE]...'),
1554 1554 inferrepo=True)
1555 1555 def commit(ui, repo, *pats, **opts):
1556 1556 """commit the specified files or all outstanding changes
1557 1557
1558 1558 Commit changes to the given files into the repository. Unlike a
1559 1559 centralized SCM, this operation is a local operation. See
1560 1560 :hg:`push` for a way to actively distribute your changes.
1561 1561
1562 1562 If a list of files is omitted, all changes reported by :hg:`status`
1563 1563 will be committed.
1564 1564
1565 1565 If you are committing the result of a merge, do not provide any
1566 1566 filenames or -I/-X filters.
1567 1567
1568 1568 If no commit message is specified, Mercurial starts your
1569 1569 configured editor where you can enter a message. In case your
1570 1570 commit fails, you will find a backup of your message in
1571 1571 ``.hg/last-message.txt``.
1572 1572
1573 1573 The --close-branch flag can be used to mark the current branch
1574 1574 head closed. When all heads of a branch are closed, the branch
1575 1575 will be considered closed and no longer listed.
1576 1576
1577 1577 The --amend flag can be used to amend the parent of the
1578 1578 working directory with a new commit that contains the changes
1579 1579 in the parent in addition to those currently reported by :hg:`status`,
1580 1580 if there are any. The old commit is stored in a backup bundle in
1581 1581 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1582 1582 on how to restore it).
1583 1583
1584 1584 Message, user and date are taken from the amended commit unless
1585 1585 specified. When a message isn't specified on the command line,
1586 1586 the editor will open with the message of the amended commit.
1587 1587
1588 1588 It is not possible to amend public changesets (see :hg:`help phases`)
1589 1589 or changesets that have children.
1590 1590
1591 1591 See :hg:`help dates` for a list of formats valid for -d/--date.
1592 1592
1593 1593 Returns 0 on success, 1 if nothing changed.
1594 1594
1595 1595 .. container:: verbose
1596 1596
1597 1597 Examples:
1598 1598
1599 1599 - commit all files ending in .py::
1600 1600
1601 1601 hg commit --include "set:**.py"
1602 1602
1603 1603 - commit all non-binary files::
1604 1604
1605 1605 hg commit --exclude "set:binary()"
1606 1606
1607 1607 - amend the current commit and set the date to now::
1608 1608
1609 1609 hg commit --amend --date now
1610 1610 """
1611 1611 wlock = lock = None
1612 1612 try:
1613 1613 wlock = repo.wlock()
1614 1614 lock = repo.lock()
1615 1615 return _docommit(ui, repo, *pats, **opts)
1616 1616 finally:
1617 1617 release(lock, wlock)
1618 1618
1619 1619 def _docommit(ui, repo, *pats, **opts):
1620 1620 if opts.get('interactive'):
1621 1621 opts.pop('interactive')
1622 1622 cmdutil.dorecord(ui, repo, commit, None, False,
1623 1623 cmdutil.recordfilter, *pats, **opts)
1624 1624 return
1625 1625
1626 1626 if opts.get('subrepos'):
1627 1627 if opts.get('amend'):
1628 1628 raise error.Abort(_('cannot amend with --subrepos'))
1629 1629 # Let --subrepos on the command line override config setting.
1630 1630 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1631 1631
1632 1632 cmdutil.checkunfinished(repo, commit=True)
1633 1633
1634 1634 branch = repo[None].branch()
1635 1635 bheads = repo.branchheads(branch)
1636 1636
1637 1637 extra = {}
1638 1638 if opts.get('close_branch'):
1639 1639 extra['close'] = 1
1640 1640
1641 1641 if not bheads:
1642 1642 raise error.Abort(_('can only close branch heads'))
1643 1643 elif opts.get('amend'):
1644 1644 if repo[None].parents()[0].p1().branch() != branch and \
1645 1645 repo[None].parents()[0].p2().branch() != branch:
1646 1646 raise error.Abort(_('can only close branch heads'))
1647 1647
1648 1648 if opts.get('amend'):
1649 1649 if ui.configbool('ui', 'commitsubrepos'):
1650 1650 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1651 1651
1652 1652 old = repo['.']
1653 1653 if not old.mutable():
1654 1654 raise error.Abort(_('cannot amend public changesets'))
1655 1655 if len(repo[None].parents()) > 1:
1656 1656 raise error.Abort(_('cannot amend while merging'))
1657 1657 allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
1658 1658 if not allowunstable and old.children():
1659 1659 raise error.Abort(_('cannot amend changeset with children'))
1660 1660
1661 1661 newextra = extra.copy()
1662 1662 newextra['branch'] = branch
1663 1663 extra = newextra
1664 1664 # commitfunc is used only for temporary amend commit by cmdutil.amend
1665 1665 def commitfunc(ui, repo, message, match, opts):
1666 1666 return repo.commit(message,
1667 1667 opts.get('user') or old.user(),
1668 1668 opts.get('date') or old.date(),
1669 1669 match,
1670 1670 extra=extra)
1671 1671
1672 1672 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1673 1673 if node == old.node():
1674 1674 ui.status(_("nothing changed\n"))
1675 1675 return 1
1676 1676 else:
1677 1677 def commitfunc(ui, repo, message, match, opts):
1678 1678 backup = ui.backupconfig('phases', 'new-commit')
1679 1679 baseui = repo.baseui
1680 1680 basebackup = baseui.backupconfig('phases', 'new-commit')
1681 1681 try:
1682 1682 if opts.get('secret'):
1683 1683 ui.setconfig('phases', 'new-commit', 'secret', 'commit')
1684 1684 # Propagate to subrepos
1685 1685 baseui.setconfig('phases', 'new-commit', 'secret', 'commit')
1686 1686
1687 1687 editform = cmdutil.mergeeditform(repo[None], 'commit.normal')
1688 1688 editor = cmdutil.getcommiteditor(editform=editform, **opts)
1689 1689 return repo.commit(message, opts.get('user'), opts.get('date'),
1690 1690 match,
1691 1691 editor=editor,
1692 1692 extra=extra)
1693 1693 finally:
1694 1694 ui.restoreconfig(backup)
1695 1695 repo.baseui.restoreconfig(basebackup)
1696 1696
1697 1697
1698 1698 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1699 1699
1700 1700 if not node:
1701 1701 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1702 1702 if stat[3]:
1703 1703 ui.status(_("nothing changed (%d missing files, see "
1704 1704 "'hg status')\n") % len(stat[3]))
1705 1705 else:
1706 1706 ui.status(_("nothing changed\n"))
1707 1707 return 1
1708 1708
1709 1709 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1710 1710
1711 1711 @command('config|showconfig|debugconfig',
1712 1712 [('u', 'untrusted', None, _('show untrusted configuration options')),
1713 1713 ('e', 'edit', None, _('edit user config')),
1714 1714 ('l', 'local', None, _('edit repository config')),
1715 1715 ('g', 'global', None, _('edit global config'))],
1716 1716 _('[-u] [NAME]...'),
1717 1717 optionalrepo=True)
1718 1718 def config(ui, repo, *values, **opts):
1719 1719 """show combined config settings from all hgrc files
1720 1720
1721 1721 With no arguments, print names and values of all config items.
1722 1722
1723 1723 With one argument of the form section.name, print just the value
1724 1724 of that config item.
1725 1725
1726 1726 With multiple arguments, print names and values of all config
1727 1727 items with matching section names.
1728 1728
1729 1729 With --edit, start an editor on the user-level config file. With
1730 1730 --global, edit the system-wide config file. With --local, edit the
1731 1731 repository-level config file.
1732 1732
1733 1733 With --debug, the source (filename and line number) is printed
1734 1734 for each config item.
1735 1735
1736 1736 See :hg:`help config` for more information about config files.
1737 1737
1738 1738 Returns 0 on success, 1 if NAME does not exist.
1739 1739
1740 1740 """
1741 1741
1742 1742 if opts.get('edit') or opts.get('local') or opts.get('global'):
1743 1743 if opts.get('local') and opts.get('global'):
1744 1744 raise error.Abort(_("can't use --local and --global together"))
1745 1745
1746 1746 if opts.get('local'):
1747 1747 if not repo:
1748 1748 raise error.Abort(_("can't use --local outside a repository"))
1749 1749 paths = [repo.join('hgrc')]
1750 1750 elif opts.get('global'):
1751 1751 paths = scmutil.systemrcpath()
1752 1752 else:
1753 1753 paths = scmutil.userrcpath()
1754 1754
1755 1755 for f in paths:
1756 1756 if os.path.exists(f):
1757 1757 break
1758 1758 else:
1759 1759 if opts.get('global'):
1760 1760 samplehgrc = uimod.samplehgrcs['global']
1761 1761 elif opts.get('local'):
1762 1762 samplehgrc = uimod.samplehgrcs['local']
1763 1763 else:
1764 1764 samplehgrc = uimod.samplehgrcs['user']
1765 1765
1766 1766 f = paths[0]
1767 1767 fp = open(f, "w")
1768 1768 fp.write(samplehgrc)
1769 1769 fp.close()
1770 1770
1771 1771 editor = ui.geteditor()
1772 1772 ui.system("%s \"%s\"" % (editor, f),
1773 1773 onerr=error.Abort, errprefix=_("edit failed"))
1774 1774 return
1775 1775
1776 1776 for f in scmutil.rcpath():
1777 1777 ui.debug('read config from: %s\n' % f)
1778 1778 untrusted = bool(opts.get('untrusted'))
1779 1779 if values:
1780 1780 sections = [v for v in values if '.' not in v]
1781 1781 items = [v for v in values if '.' in v]
1782 1782 if len(items) > 1 or items and sections:
1783 1783 raise error.Abort(_('only one config item permitted'))
1784 1784 matched = False
1785 1785 for section, name, value in ui.walkconfig(untrusted=untrusted):
1786 1786 value = str(value).replace('\n', '\\n')
1787 1787 sectname = section + '.' + name
1788 1788 if values:
1789 1789 for v in values:
1790 1790 if v == section:
1791 1791 ui.debug('%s: ' %
1792 1792 ui.configsource(section, name, untrusted))
1793 1793 ui.write('%s=%s\n' % (sectname, value))
1794 1794 matched = True
1795 1795 elif v == sectname:
1796 1796 ui.debug('%s: ' %
1797 1797 ui.configsource(section, name, untrusted))
1798 1798 ui.write(value, '\n')
1799 1799 matched = True
1800 1800 else:
1801 1801 ui.debug('%s: ' %
1802 1802 ui.configsource(section, name, untrusted))
1803 1803 ui.write('%s=%s\n' % (sectname, value))
1804 1804 matched = True
1805 1805 if matched:
1806 1806 return 0
1807 1807 return 1
1808 1808
1809 1809 @command('copy|cp',
1810 1810 [('A', 'after', None, _('record a copy that has already occurred')),
1811 1811 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1812 1812 ] + walkopts + dryrunopts,
1813 1813 _('[OPTION]... [SOURCE]... DEST'))
1814 1814 def copy(ui, repo, *pats, **opts):
1815 1815 """mark files as copied for the next commit
1816 1816
1817 1817 Mark dest as having copies of source files. If dest is a
1818 1818 directory, copies are put in that directory. If dest is a file,
1819 1819 the source must be a single file.
1820 1820
1821 1821 By default, this command copies the contents of files as they
1822 1822 exist in the working directory. If invoked with -A/--after, the
1823 1823 operation is recorded, but no copying is performed.
1824 1824
1825 1825 This command takes effect with the next commit. To undo a copy
1826 1826 before that, see :hg:`revert`.
1827 1827
1828 1828 Returns 0 on success, 1 if errors are encountered.
1829 1829 """
1830 1830 wlock = repo.wlock(False)
1831 1831 try:
1832 1832 return cmdutil.copy(ui, repo, pats, opts)
1833 1833 finally:
1834 1834 wlock.release()
1835 1835
1836 1836 @command('debugancestor', [], _('[INDEX] REV1 REV2'), optionalrepo=True)
1837 1837 def debugancestor(ui, repo, *args):
1838 1838 """find the ancestor revision of two revisions in a given index"""
1839 1839 if len(args) == 3:
1840 1840 index, rev1, rev2 = args
1841 1841 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1842 1842 lookup = r.lookup
1843 1843 elif len(args) == 2:
1844 1844 if not repo:
1845 1845 raise error.Abort(_("there is no Mercurial repository here "
1846 1846 "(.hg not found)"))
1847 1847 rev1, rev2 = args
1848 1848 r = repo.changelog
1849 1849 lookup = repo.lookup
1850 1850 else:
1851 1851 raise error.Abort(_('either two or three arguments required'))
1852 1852 a = r.ancestor(lookup(rev1), lookup(rev2))
1853 1853 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1854 1854
1855 1855 @command('debugbuilddag',
1856 1856 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1857 1857 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1858 1858 ('n', 'new-file', None, _('add new file at each rev'))],
1859 1859 _('[OPTION]... [TEXT]'))
1860 1860 def debugbuilddag(ui, repo, text=None,
1861 1861 mergeable_file=False,
1862 1862 overwritten_file=False,
1863 1863 new_file=False):
1864 1864 """builds a repo with a given DAG from scratch in the current empty repo
1865 1865
1866 1866 The description of the DAG is read from stdin if not given on the
1867 1867 command line.
1868 1868
1869 1869 Elements:
1870 1870
1871 1871 - "+n" is a linear run of n nodes based on the current default parent
1872 1872 - "." is a single node based on the current default parent
1873 1873 - "$" resets the default parent to null (implied at the start);
1874 1874 otherwise the default parent is always the last node created
1875 1875 - "<p" sets the default parent to the backref p
1876 1876 - "*p" is a fork at parent p, which is a backref
1877 1877 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1878 1878 - "/p2" is a merge of the preceding node and p2
1879 1879 - ":tag" defines a local tag for the preceding node
1880 1880 - "@branch" sets the named branch for subsequent nodes
1881 1881 - "#...\\n" is a comment up to the end of the line
1882 1882
1883 1883 Whitespace between the above elements is ignored.
1884 1884
1885 1885 A backref is either
1886 1886
1887 1887 - a number n, which references the node curr-n, where curr is the current
1888 1888 node, or
1889 1889 - the name of a local tag you placed earlier using ":tag", or
1890 1890 - empty to denote the default parent.
1891 1891
1892 1892 All string valued-elements are either strictly alphanumeric, or must
1893 1893 be enclosed in double quotes ("..."), with "\\" as escape character.
1894 1894 """
1895 1895
1896 1896 if text is None:
1897 1897 ui.status(_("reading DAG from stdin\n"))
1898 1898 text = ui.fin.read()
1899 1899
1900 1900 cl = repo.changelog
1901 1901 if len(cl) > 0:
1902 1902 raise error.Abort(_('repository is not empty'))
1903 1903
1904 1904 # determine number of revs in DAG
1905 1905 total = 0
1906 1906 for type, data in dagparser.parsedag(text):
1907 1907 if type == 'n':
1908 1908 total += 1
1909 1909
1910 1910 if mergeable_file:
1911 1911 linesperrev = 2
1912 1912 # make a file with k lines per rev
1913 1913 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1914 1914 initialmergedlines.append("")
1915 1915
1916 1916 tags = []
1917 1917
1918 1918 lock = tr = None
1919 1919 try:
1920 1920 lock = repo.lock()
1921 1921 tr = repo.transaction("builddag")
1922 1922
1923 1923 at = -1
1924 1924 atbranch = 'default'
1925 1925 nodeids = []
1926 1926 id = 0
1927 1927 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1928 1928 for type, data in dagparser.parsedag(text):
1929 1929 if type == 'n':
1930 1930 ui.note(('node %s\n' % str(data)))
1931 1931 id, ps = data
1932 1932
1933 1933 files = []
1934 1934 fctxs = {}
1935 1935
1936 1936 p2 = None
1937 1937 if mergeable_file:
1938 1938 fn = "mf"
1939 1939 p1 = repo[ps[0]]
1940 1940 if len(ps) > 1:
1941 1941 p2 = repo[ps[1]]
1942 1942 pa = p1.ancestor(p2)
1943 1943 base, local, other = [x[fn].data() for x in (pa, p1,
1944 1944 p2)]
1945 1945 m3 = simplemerge.Merge3Text(base, local, other)
1946 1946 ml = [l.strip() for l in m3.merge_lines()]
1947 1947 ml.append("")
1948 1948 elif at > 0:
1949 1949 ml = p1[fn].data().split("\n")
1950 1950 else:
1951 1951 ml = initialmergedlines
1952 1952 ml[id * linesperrev] += " r%i" % id
1953 1953 mergedtext = "\n".join(ml)
1954 1954 files.append(fn)
1955 1955 fctxs[fn] = context.memfilectx(repo, fn, mergedtext)
1956 1956
1957 1957 if overwritten_file:
1958 1958 fn = "of"
1959 1959 files.append(fn)
1960 1960 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
1961 1961
1962 1962 if new_file:
1963 1963 fn = "nf%i" % id
1964 1964 files.append(fn)
1965 1965 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
1966 1966 if len(ps) > 1:
1967 1967 if not p2:
1968 1968 p2 = repo[ps[1]]
1969 1969 for fn in p2:
1970 1970 if fn.startswith("nf"):
1971 1971 files.append(fn)
1972 1972 fctxs[fn] = p2[fn]
1973 1973
1974 1974 def fctxfn(repo, cx, path):
1975 1975 return fctxs.get(path)
1976 1976
1977 1977 if len(ps) == 0 or ps[0] < 0:
1978 1978 pars = [None, None]
1979 1979 elif len(ps) == 1:
1980 1980 pars = [nodeids[ps[0]], None]
1981 1981 else:
1982 1982 pars = [nodeids[p] for p in ps]
1983 1983 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1984 1984 date=(id, 0),
1985 1985 user="debugbuilddag",
1986 1986 extra={'branch': atbranch})
1987 1987 nodeid = repo.commitctx(cx)
1988 1988 nodeids.append(nodeid)
1989 1989 at = id
1990 1990 elif type == 'l':
1991 1991 id, name = data
1992 1992 ui.note(('tag %s\n' % name))
1993 1993 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1994 1994 elif type == 'a':
1995 1995 ui.note(('branch %s\n' % data))
1996 1996 atbranch = data
1997 1997 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1998 1998 tr.close()
1999 1999
2000 2000 if tags:
2001 2001 repo.vfs.write("localtags", "".join(tags))
2002 2002 finally:
2003 2003 ui.progress(_('building'), None)
2004 2004 release(tr, lock)
2005 2005
2006 2006 @command('debugbundle',
2007 2007 [('a', 'all', None, _('show all details'))],
2008 2008 _('FILE'),
2009 2009 norepo=True)
2010 2010 def debugbundle(ui, bundlepath, all=None, **opts):
2011 2011 """lists the contents of a bundle"""
2012 2012 f = hg.openpath(ui, bundlepath)
2013 2013 try:
2014 2014 gen = exchange.readbundle(ui, f, bundlepath)
2015 2015 if isinstance(gen, bundle2.unbundle20):
2016 2016 return _debugbundle2(ui, gen, all=all, **opts)
2017 2017 if all:
2018 2018 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
2019 2019
2020 2020 def showchunks(named):
2021 2021 ui.write("\n%s\n" % named)
2022 2022 chain = None
2023 2023 while True:
2024 2024 chunkdata = gen.deltachunk(chain)
2025 2025 if not chunkdata:
2026 2026 break
2027 2027 node = chunkdata['node']
2028 2028 p1 = chunkdata['p1']
2029 2029 p2 = chunkdata['p2']
2030 2030 cs = chunkdata['cs']
2031 2031 deltabase = chunkdata['deltabase']
2032 2032 delta = chunkdata['delta']
2033 2033 ui.write("%s %s %s %s %s %s\n" %
2034 2034 (hex(node), hex(p1), hex(p2),
2035 2035 hex(cs), hex(deltabase), len(delta)))
2036 2036 chain = node
2037 2037
2038 2038 chunkdata = gen.changelogheader()
2039 2039 showchunks("changelog")
2040 2040 chunkdata = gen.manifestheader()
2041 2041 showchunks("manifest")
2042 2042 while True:
2043 2043 chunkdata = gen.filelogheader()
2044 2044 if not chunkdata:
2045 2045 break
2046 2046 fname = chunkdata['filename']
2047 2047 showchunks(fname)
2048 2048 else:
2049 2049 if isinstance(gen, bundle2.unbundle20):
2050 2050 raise error.Abort(_('use debugbundle2 for this file'))
2051 2051 chunkdata = gen.changelogheader()
2052 2052 chain = None
2053 2053 while True:
2054 2054 chunkdata = gen.deltachunk(chain)
2055 2055 if not chunkdata:
2056 2056 break
2057 2057 node = chunkdata['node']
2058 2058 ui.write("%s\n" % hex(node))
2059 2059 chain = node
2060 2060 finally:
2061 2061 f.close()
2062 2062
2063 2063 def _debugbundle2(ui, gen, **opts):
2064 2064 """lists the contents of a bundle2"""
2065 2065 if not isinstance(gen, bundle2.unbundle20):
2066 2066 raise error.Abort(_('not a bundle2 file'))
2067 2067 ui.write(('Stream params: %s\n' % repr(gen.params)))
2068 2068 for part in gen.iterparts():
2069 2069 ui.write('%s -- %r\n' % (part.type, repr(part.params)))
2070 2070 if part.type == 'changegroup':
2071 2071 version = part.params.get('version', '01')
2072 2072 cg = changegroup.packermap[version][1](part, 'UN')
2073 2073 chunkdata = cg.changelogheader()
2074 2074 chain = None
2075 2075 while True:
2076 2076 chunkdata = cg.deltachunk(chain)
2077 2077 if not chunkdata:
2078 2078 break
2079 2079 node = chunkdata['node']
2080 2080 ui.write(" %s\n" % hex(node))
2081 2081 chain = node
2082 2082
2083 2083 @command('debugcreatestreamclonebundle', [], 'FILE')
2084 2084 def debugcreatestreamclonebundle(ui, repo, fname):
2085 2085 """create a stream clone bundle file
2086 2086
2087 2087 Stream bundles are special bundles that are essentially archives of
2088 2088 revlog files. They are commonly used for cloning very quickly.
2089 2089 """
2090 2090 requirements, gen = streamclone.generatebundlev1(repo)
2091 2091 changegroup.writechunks(ui, gen, fname)
2092 2092
2093 2093 ui.write(_('bundle requirements: %s\n') % ', '.join(sorted(requirements)))
2094 2094
2095 2095 @command('debugapplystreamclonebundle', [], 'FILE')
2096 2096 def debugapplystreamclonebundle(ui, repo, fname):
2097 2097 """apply a stream clone bundle file"""
2098 2098 f = hg.openpath(ui, fname)
2099 2099 gen = exchange.readbundle(ui, f, fname)
2100 2100 gen.apply(repo)
2101 2101
2102 2102 @command('debugcheckstate', [], '')
2103 2103 def debugcheckstate(ui, repo):
2104 2104 """validate the correctness of the current dirstate"""
2105 2105 parent1, parent2 = repo.dirstate.parents()
2106 2106 m1 = repo[parent1].manifest()
2107 2107 m2 = repo[parent2].manifest()
2108 2108 errors = 0
2109 2109 for f in repo.dirstate:
2110 2110 state = repo.dirstate[f]
2111 2111 if state in "nr" and f not in m1:
2112 2112 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
2113 2113 errors += 1
2114 2114 if state in "a" and f in m1:
2115 2115 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
2116 2116 errors += 1
2117 2117 if state in "m" and f not in m1 and f not in m2:
2118 2118 ui.warn(_("%s in state %s, but not in either manifest\n") %
2119 2119 (f, state))
2120 2120 errors += 1
2121 2121 for f in m1:
2122 2122 state = repo.dirstate[f]
2123 2123 if state not in "nrm":
2124 2124 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
2125 2125 errors += 1
2126 2126 if errors:
2127 2127 error = _(".hg/dirstate inconsistent with current parent's manifest")
2128 2128 raise error.Abort(error)
2129 2129
2130 2130 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
2131 2131 def debugcommands(ui, cmd='', *args):
2132 2132 """list all available commands and options"""
2133 2133 for cmd, vals in sorted(table.iteritems()):
2134 2134 cmd = cmd.split('|')[0].strip('^')
2135 2135 opts = ', '.join([i[1] for i in vals[1]])
2136 2136 ui.write('%s: %s\n' % (cmd, opts))
2137 2137
2138 2138 @command('debugcomplete',
2139 2139 [('o', 'options', None, _('show the command options'))],
2140 2140 _('[-o] CMD'),
2141 2141 norepo=True)
2142 2142 def debugcomplete(ui, cmd='', **opts):
2143 2143 """returns the completion list associated with the given command"""
2144 2144
2145 2145 if opts.get('options'):
2146 2146 options = []
2147 2147 otables = [globalopts]
2148 2148 if cmd:
2149 2149 aliases, entry = cmdutil.findcmd(cmd, table, False)
2150 2150 otables.append(entry[1])
2151 2151 for t in otables:
2152 2152 for o in t:
2153 2153 if "(DEPRECATED)" in o[3]:
2154 2154 continue
2155 2155 if o[0]:
2156 2156 options.append('-%s' % o[0])
2157 2157 options.append('--%s' % o[1])
2158 2158 ui.write("%s\n" % "\n".join(options))
2159 2159 return
2160 2160
2161 2161 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
2162 2162 if ui.verbose:
2163 2163 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
2164 2164 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
2165 2165
2166 2166 @command('debugdag',
2167 2167 [('t', 'tags', None, _('use tags as labels')),
2168 2168 ('b', 'branches', None, _('annotate with branch names')),
2169 2169 ('', 'dots', None, _('use dots for runs')),
2170 2170 ('s', 'spaces', None, _('separate elements by spaces'))],
2171 2171 _('[OPTION]... [FILE [REV]...]'),
2172 2172 optionalrepo=True)
2173 2173 def debugdag(ui, repo, file_=None, *revs, **opts):
2174 2174 """format the changelog or an index DAG as a concise textual description
2175 2175
2176 2176 If you pass a revlog index, the revlog's DAG is emitted. If you list
2177 2177 revision numbers, they get labeled in the output as rN.
2178 2178
2179 2179 Otherwise, the changelog DAG of the current repo is emitted.
2180 2180 """
2181 2181 spaces = opts.get('spaces')
2182 2182 dots = opts.get('dots')
2183 2183 if file_:
2184 2184 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
2185 2185 revs = set((int(r) for r in revs))
2186 2186 def events():
2187 2187 for r in rlog:
2188 2188 yield 'n', (r, list(p for p in rlog.parentrevs(r)
2189 2189 if p != -1))
2190 2190 if r in revs:
2191 2191 yield 'l', (r, "r%i" % r)
2192 2192 elif repo:
2193 2193 cl = repo.changelog
2194 2194 tags = opts.get('tags')
2195 2195 branches = opts.get('branches')
2196 2196 if tags:
2197 2197 labels = {}
2198 2198 for l, n in repo.tags().items():
2199 2199 labels.setdefault(cl.rev(n), []).append(l)
2200 2200 def events():
2201 2201 b = "default"
2202 2202 for r in cl:
2203 2203 if branches:
2204 2204 newb = cl.read(cl.node(r))[5]['branch']
2205 2205 if newb != b:
2206 2206 yield 'a', newb
2207 2207 b = newb
2208 2208 yield 'n', (r, list(p for p in cl.parentrevs(r)
2209 2209 if p != -1))
2210 2210 if tags:
2211 2211 ls = labels.get(r)
2212 2212 if ls:
2213 2213 for l in ls:
2214 2214 yield 'l', (r, l)
2215 2215 else:
2216 2216 raise error.Abort(_('need repo for changelog dag'))
2217 2217
2218 2218 for line in dagparser.dagtextlines(events(),
2219 2219 addspaces=spaces,
2220 2220 wraplabels=True,
2221 2221 wrapannotations=True,
2222 2222 wrapnonlinear=dots,
2223 2223 usedots=dots,
2224 2224 maxlinewidth=70):
2225 2225 ui.write(line)
2226 2226 ui.write("\n")
2227 2227
2228 2228 @command('debugdata', debugrevlogopts, _('-c|-m|FILE REV'))
2229 2229 def debugdata(ui, repo, file_, rev=None, **opts):
2230 2230 """dump the contents of a data file revision"""
2231 2231 if opts.get('changelog') or opts.get('manifest'):
2232 2232 file_, rev = None, file_
2233 2233 elif rev is None:
2234 2234 raise error.CommandError('debugdata', _('invalid arguments'))
2235 2235 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
2236 2236 try:
2237 2237 ui.write(r.revision(r.lookup(rev)))
2238 2238 except KeyError:
2239 2239 raise error.Abort(_('invalid revision identifier %s') % rev)
2240 2240
2241 2241 @command('debugdate',
2242 2242 [('e', 'extended', None, _('try extended date formats'))],
2243 2243 _('[-e] DATE [RANGE]'),
2244 2244 norepo=True, optionalrepo=True)
2245 2245 def debugdate(ui, date, range=None, **opts):
2246 2246 """parse and display a date"""
2247 2247 if opts["extended"]:
2248 2248 d = util.parsedate(date, util.extendeddateformats)
2249 2249 else:
2250 2250 d = util.parsedate(date)
2251 2251 ui.write(("internal: %s %s\n") % d)
2252 2252 ui.write(("standard: %s\n") % util.datestr(d))
2253 2253 if range:
2254 2254 m = util.matchdate(range)
2255 2255 ui.write(("match: %s\n") % m(d[0]))
2256 2256
2257 2257 @command('debugdiscovery',
2258 2258 [('', 'old', None, _('use old-style discovery')),
2259 2259 ('', 'nonheads', None,
2260 2260 _('use old-style discovery with non-heads included')),
2261 2261 ] + remoteopts,
2262 2262 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
2263 2263 def debugdiscovery(ui, repo, remoteurl="default", **opts):
2264 2264 """runs the changeset discovery protocol in isolation"""
2265 2265 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
2266 2266 opts.get('branch'))
2267 2267 remote = hg.peer(repo, opts, remoteurl)
2268 2268 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
2269 2269
2270 2270 # make sure tests are repeatable
2271 2271 random.seed(12323)
2272 2272
2273 2273 def doit(localheads, remoteheads, remote=remote):
2274 2274 if opts.get('old'):
2275 2275 if localheads:
2276 2276 raise error.Abort('cannot use localheads with old style '
2277 2277 'discovery')
2278 2278 if not util.safehasattr(remote, 'branches'):
2279 2279 # enable in-client legacy support
2280 2280 remote = localrepo.locallegacypeer(remote.local())
2281 2281 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
2282 2282 force=True)
2283 2283 common = set(common)
2284 2284 if not opts.get('nonheads'):
2285 2285 ui.write(("unpruned common: %s\n") %
2286 2286 " ".join(sorted(short(n) for n in common)))
2287 2287 dag = dagutil.revlogdag(repo.changelog)
2288 2288 all = dag.ancestorset(dag.internalizeall(common))
2289 2289 common = dag.externalizeall(dag.headsetofconnecteds(all))
2290 2290 else:
2291 2291 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
2292 2292 common = set(common)
2293 2293 rheads = set(hds)
2294 2294 lheads = set(repo.heads())
2295 2295 ui.write(("common heads: %s\n") %
2296 2296 " ".join(sorted(short(n) for n in common)))
2297 2297 if lheads <= common:
2298 2298 ui.write(("local is subset\n"))
2299 2299 elif rheads <= common:
2300 2300 ui.write(("remote is subset\n"))
2301 2301
2302 2302 serverlogs = opts.get('serverlog')
2303 2303 if serverlogs:
2304 2304 for filename in serverlogs:
2305 2305 logfile = open(filename, 'r')
2306 2306 try:
2307 2307 line = logfile.readline()
2308 2308 while line:
2309 2309 parts = line.strip().split(';')
2310 2310 op = parts[1]
2311 2311 if op == 'cg':
2312 2312 pass
2313 2313 elif op == 'cgss':
2314 2314 doit(parts[2].split(' '), parts[3].split(' '))
2315 2315 elif op == 'unb':
2316 2316 doit(parts[3].split(' '), parts[2].split(' '))
2317 2317 line = logfile.readline()
2318 2318 finally:
2319 2319 logfile.close()
2320 2320
2321 2321 else:
2322 2322 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
2323 2323 opts.get('remote_head'))
2324 2324 localrevs = opts.get('local_head')
2325 2325 doit(localrevs, remoterevs)
2326 2326
2327 2327 @command('debugextensions', formatteropts, [], norepo=True)
2328 2328 def debugextensions(ui, **opts):
2329 2329 '''show information about active extensions'''
2330 2330 exts = extensions.extensions(ui)
2331 2331 fm = ui.formatter('debugextensions', opts)
2332 2332 for extname, extmod in sorted(exts, key=operator.itemgetter(0)):
2333 2333 extsource = extmod.__file__
2334 2334 exttestedwith = getattr(extmod, 'testedwith', None)
2335 2335 if exttestedwith is not None:
2336 2336 exttestedwith = exttestedwith.split()
2337 2337 extbuglink = getattr(extmod, 'buglink', None)
2338 2338
2339 2339 fm.startitem()
2340 2340
2341 2341 if ui.quiet or ui.verbose:
2342 2342 fm.write('name', '%s\n', extname)
2343 2343 else:
2344 2344 fm.write('name', '%s', extname)
2345 2345 if not exttestedwith:
2346 2346 fm.plain(_(' (untested!)\n'))
2347 2347 else:
2348 2348 if exttestedwith == ['internal'] or \
2349 2349 util.version() in exttestedwith:
2350 2350 fm.plain('\n')
2351 2351 else:
2352 2352 lasttestedversion = exttestedwith[-1]
2353 2353 fm.plain(' (%s!)\n' % lasttestedversion)
2354 2354
2355 2355 fm.condwrite(ui.verbose and extsource, 'source',
2356 2356 _(' location: %s\n'), extsource or "")
2357 2357
2358 2358 fm.condwrite(ui.verbose and exttestedwith, 'testedwith',
2359 2359 _(' tested with: %s\n'), ' '.join(exttestedwith or []))
2360 2360
2361 2361 fm.condwrite(ui.verbose and extbuglink, 'buglink',
2362 2362 _(' bug reporting: %s\n'), extbuglink or "")
2363 2363
2364 2364 fm.end()
2365 2365
2366 2366 @command('debugfileset',
2367 2367 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
2368 2368 _('[-r REV] FILESPEC'))
2369 2369 def debugfileset(ui, repo, expr, **opts):
2370 2370 '''parse and apply a fileset specification'''
2371 2371 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
2372 2372 if ui.verbose:
2373 2373 tree = fileset.parse(expr)
2374 2374 ui.note(fileset.prettyformat(tree), "\n")
2375 2375
2376 2376 for f in ctx.getfileset(expr):
2377 2377 ui.write("%s\n" % f)
2378 2378
2379 2379 @command('debugfsinfo', [], _('[PATH]'), norepo=True)
2380 2380 def debugfsinfo(ui, path="."):
2381 2381 """show information detected about current filesystem"""
2382 2382 util.writefile('.debugfsinfo', '')
2383 2383 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
2384 2384 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
2385 2385 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
2386 2386 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
2387 2387 and 'yes' or 'no'))
2388 2388 os.unlink('.debugfsinfo')
2389 2389
2390 2390 @command('debuggetbundle',
2391 2391 [('H', 'head', [], _('id of head node'), _('ID')),
2392 2392 ('C', 'common', [], _('id of common node'), _('ID')),
2393 2393 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
2394 2394 _('REPO FILE [-H|-C ID]...'),
2395 2395 norepo=True)
2396 2396 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
2397 2397 """retrieves a bundle from a repo
2398 2398
2399 2399 Every ID must be a full-length hex node id string. Saves the bundle to the
2400 2400 given file.
2401 2401 """
2402 2402 repo = hg.peer(ui, opts, repopath)
2403 2403 if not repo.capable('getbundle'):
2404 2404 raise error.Abort("getbundle() not supported by target repository")
2405 2405 args = {}
2406 2406 if common:
2407 2407 args['common'] = [bin(s) for s in common]
2408 2408 if head:
2409 2409 args['heads'] = [bin(s) for s in head]
2410 2410 # TODO: get desired bundlecaps from command line.
2411 2411 args['bundlecaps'] = None
2412 2412 bundle = repo.getbundle('debug', **args)
2413 2413
2414 2414 bundletype = opts.get('type', 'bzip2').lower()
2415 2415 btypes = {'none': 'HG10UN',
2416 2416 'bzip2': 'HG10BZ',
2417 2417 'gzip': 'HG10GZ',
2418 2418 'bundle2': 'HG20'}
2419 2419 bundletype = btypes.get(bundletype)
2420 2420 if bundletype not in changegroup.bundletypes:
2421 2421 raise error.Abort(_('unknown bundle type specified with --type'))
2422 2422 changegroup.writebundle(ui, bundle, bundlepath, bundletype)
2423 2423
2424 2424 @command('debugignore', [], '')
2425 2425 def debugignore(ui, repo, *values, **opts):
2426 2426 """display the combined ignore pattern"""
2427 2427 ignore = repo.dirstate._ignore
2428 2428 includepat = getattr(ignore, 'includepat', None)
2429 2429 if includepat is not None:
2430 2430 ui.write("%s\n" % includepat)
2431 2431 else:
2432 2432 raise error.Abort(_("no ignore patterns found"))
2433 2433
2434 2434 @command('debugindex', debugrevlogopts +
2435 2435 [('f', 'format', 0, _('revlog format'), _('FORMAT'))],
2436 2436 _('[-f FORMAT] -c|-m|FILE'),
2437 2437 optionalrepo=True)
2438 2438 def debugindex(ui, repo, file_=None, **opts):
2439 2439 """dump the contents of an index file"""
2440 2440 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
2441 2441 format = opts.get('format', 0)
2442 2442 if format not in (0, 1):
2443 2443 raise error.Abort(_("unknown format %d") % format)
2444 2444
2445 2445 generaldelta = r.version & revlog.REVLOGGENERALDELTA
2446 2446 if generaldelta:
2447 2447 basehdr = ' delta'
2448 2448 else:
2449 2449 basehdr = ' base'
2450 2450
2451 2451 if ui.debugflag:
2452 2452 shortfn = hex
2453 2453 else:
2454 2454 shortfn = short
2455 2455
2456 2456 # There might not be anything in r, so have a sane default
2457 2457 idlen = 12
2458 2458 for i in r:
2459 2459 idlen = len(shortfn(r.node(i)))
2460 2460 break
2461 2461
2462 2462 if format == 0:
2463 2463 ui.write(" rev offset length " + basehdr + " linkrev"
2464 2464 " %s %s p2\n" % ("nodeid".ljust(idlen), "p1".ljust(idlen)))
2465 2465 elif format == 1:
2466 2466 ui.write(" rev flag offset length"
2467 2467 " size " + basehdr + " link p1 p2"
2468 2468 " %s\n" % "nodeid".rjust(idlen))
2469 2469
2470 2470 for i in r:
2471 2471 node = r.node(i)
2472 2472 if generaldelta:
2473 2473 base = r.deltaparent(i)
2474 2474 else:
2475 2475 base = r.chainbase(i)
2476 2476 if format == 0:
2477 2477 try:
2478 2478 pp = r.parents(node)
2479 2479 except Exception:
2480 2480 pp = [nullid, nullid]
2481 2481 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
2482 2482 i, r.start(i), r.length(i), base, r.linkrev(i),
2483 2483 shortfn(node), shortfn(pp[0]), shortfn(pp[1])))
2484 2484 elif format == 1:
2485 2485 pr = r.parentrevs(i)
2486 2486 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
2487 2487 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
2488 2488 base, r.linkrev(i), pr[0], pr[1], shortfn(node)))
2489 2489
2490 2490 @command('debugindexdot', debugrevlogopts,
2491 2491 _('-c|-m|FILE'), optionalrepo=True)
2492 2492 def debugindexdot(ui, repo, file_=None, **opts):
2493 2493 """dump an index DAG as a graphviz dot file"""
2494 2494 r = cmdutil.openrevlog(repo, 'debugindexdot', file_, opts)
2495 2495 ui.write(("digraph G {\n"))
2496 2496 for i in r:
2497 2497 node = r.node(i)
2498 2498 pp = r.parents(node)
2499 2499 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
2500 2500 if pp[1] != nullid:
2501 2501 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
2502 2502 ui.write("}\n")
2503 2503
2504 2504 @command('debugdeltachain',
2505 2505 debugrevlogopts + formatteropts,
2506 2506 _('-c|-m|FILE'),
2507 2507 optionalrepo=True)
2508 2508 def debugdeltachain(ui, repo, file_=None, **opts):
2509 2509 """dump information about delta chains in a revlog
2510 2510
2511 2511 Output can be templatized. Available template keywords are:
2512 2512
2513 2513 rev revision number
2514 2514 chainid delta chain identifier (numbered by unique base)
2515 2515 chainlen delta chain length to this revision
2516 2516 prevrev previous revision in delta chain
2517 2517 deltatype role of delta / how it was computed
2518 2518 compsize compressed size of revision
2519 2519 uncompsize uncompressed size of revision
2520 2520 chainsize total size of compressed revisions in chain
2521 2521 chainratio total chain size divided by uncompressed revision size
2522 2522 (new delta chains typically start at ratio 2.00)
2523 2523 lindist linear distance from base revision in delta chain to end
2524 2524 of this revision
2525 2525 extradist total size of revisions not part of this delta chain from
2526 2526 base of delta chain to end of this revision; a measurement
2527 2527 of how much extra data we need to read/seek across to read
2528 2528 the delta chain for this revision
2529 2529 extraratio extradist divided by chainsize; another representation of
2530 2530 how much unrelated data is needed to load this delta chain
2531 2531 """
2532 2532 r = cmdutil.openrevlog(repo, 'debugdeltachain', file_, opts)
2533 2533 index = r.index
2534 2534 generaldelta = r.version & revlog.REVLOGGENERALDELTA
2535 2535
2536 2536 def revinfo(rev):
2537 2537 iterrev = rev
2538 2538 e = index[iterrev]
2539 2539 chain = []
2540 2540 compsize = e[1]
2541 2541 uncompsize = e[2]
2542 2542 chainsize = 0
2543 2543
2544 2544 if generaldelta:
2545 2545 if e[3] == e[5]:
2546 2546 deltatype = 'p1'
2547 2547 elif e[3] == e[6]:
2548 2548 deltatype = 'p2'
2549 2549 elif e[3] == rev - 1:
2550 2550 deltatype = 'prev'
2551 2551 elif e[3] == rev:
2552 2552 deltatype = 'base'
2553 2553 else:
2554 2554 deltatype = 'other'
2555 2555 else:
2556 2556 if e[3] == rev:
2557 2557 deltatype = 'base'
2558 2558 else:
2559 2559 deltatype = 'prev'
2560 2560
2561 2561 while iterrev != e[3]:
2562 2562 chain.append(iterrev)
2563 2563 chainsize += e[1]
2564 2564 if generaldelta:
2565 2565 iterrev = e[3]
2566 2566 else:
2567 2567 iterrev -= 1
2568 2568 e = index[iterrev]
2569 2569 else:
2570 2570 chainsize += e[1]
2571 2571 chain.append(iterrev)
2572 2572
2573 2573 chain.reverse()
2574 2574 return compsize, uncompsize, deltatype, chain, chainsize
2575 2575
2576 2576 fm = ui.formatter('debugdeltachain', opts)
2577 2577
2578 2578 fm.plain(' rev chain# chainlen prev delta '
2579 2579 'size rawsize chainsize ratio lindist extradist '
2580 2580 'extraratio\n')
2581 2581
2582 2582 chainbases = {}
2583 2583 for rev in r:
2584 2584 comp, uncomp, deltatype, chain, chainsize = revinfo(rev)
2585 2585 chainbase = chain[0]
2586 2586 chainid = chainbases.setdefault(chainbase, len(chainbases) + 1)
2587 2587 basestart = r.start(chainbase)
2588 2588 revstart = r.start(rev)
2589 2589 lineardist = revstart + comp - basestart
2590 2590 extradist = lineardist - chainsize
2591 2591 try:
2592 2592 prevrev = chain[-2]
2593 2593 except IndexError:
2594 2594 prevrev = -1
2595 2595
2596 2596 chainratio = float(chainsize) / float(uncomp)
2597 2597 extraratio = float(extradist) / float(chainsize)
2598 2598
2599 2599 fm.startitem()
2600 2600 fm.write('rev chainid chainlen prevrev deltatype compsize '
2601 2601 'uncompsize chainsize chainratio lindist extradist '
2602 2602 'extraratio',
2603 2603 '%7d %7d %8d %8d %7s %10d %10d %10d %9.5f %9d %9d %10.5f\n',
2604 2604 rev, chainid, len(chain), prevrev, deltatype, comp,
2605 2605 uncomp, chainsize, chainratio, lineardist, extradist,
2606 2606 extraratio,
2607 2607 rev=rev, chainid=chainid, chainlen=len(chain),
2608 2608 prevrev=prevrev, deltatype=deltatype, compsize=comp,
2609 2609 uncompsize=uncomp, chainsize=chainsize,
2610 2610 chainratio=chainratio, lindist=lineardist,
2611 2611 extradist=extradist, extraratio=extraratio)
2612 2612
2613 2613 fm.end()
2614 2614
2615 2615 @command('debuginstall', [], '', norepo=True)
2616 2616 def debuginstall(ui):
2617 2617 '''test Mercurial installation
2618 2618
2619 2619 Returns 0 on success.
2620 2620 '''
2621 2621
2622 2622 def writetemp(contents):
2623 2623 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2624 2624 f = os.fdopen(fd, "wb")
2625 2625 f.write(contents)
2626 2626 f.close()
2627 2627 return name
2628 2628
2629 2629 problems = 0
2630 2630
2631 2631 # encoding
2632 2632 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2633 2633 try:
2634 2634 encoding.fromlocal("test")
2635 2635 except error.Abort as inst:
2636 2636 ui.write(" %s\n" % inst)
2637 2637 ui.write(_(" (check that your locale is properly set)\n"))
2638 2638 problems += 1
2639 2639
2640 2640 # Python
2641 2641 ui.status(_("checking Python executable (%s)\n") % sys.executable)
2642 2642 ui.status(_("checking Python version (%s)\n")
2643 2643 % ("%s.%s.%s" % sys.version_info[:3]))
2644 2644 ui.status(_("checking Python lib (%s)...\n")
2645 2645 % os.path.dirname(os.__file__))
2646 2646
2647 2647 # compiled modules
2648 2648 ui.status(_("checking installed modules (%s)...\n")
2649 2649 % os.path.dirname(__file__))
2650 2650 try:
2651 2651 import bdiff, mpatch, base85, osutil
2652 2652 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2653 2653 except Exception as inst:
2654 2654 ui.write(" %s\n" % inst)
2655 2655 ui.write(_(" One or more extensions could not be found"))
2656 2656 ui.write(_(" (check that you compiled the extensions)\n"))
2657 2657 problems += 1
2658 2658
2659 2659 # templates
2660 2660 import templater
2661 2661 p = templater.templatepaths()
2662 2662 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2663 2663 if p:
2664 2664 m = templater.templatepath("map-cmdline.default")
2665 2665 if m:
2666 2666 # template found, check if it is working
2667 2667 try:
2668 2668 templater.templater(m)
2669 2669 except Exception as inst:
2670 2670 ui.write(" %s\n" % inst)
2671 2671 p = None
2672 2672 else:
2673 2673 ui.write(_(" template 'default' not found\n"))
2674 2674 p = None
2675 2675 else:
2676 2676 ui.write(_(" no template directories found\n"))
2677 2677 if not p:
2678 2678 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2679 2679 problems += 1
2680 2680
2681 2681 # editor
2682 2682 ui.status(_("checking commit editor...\n"))
2683 2683 editor = ui.geteditor()
2684 2684 editor = util.expandpath(editor)
2685 2685 cmdpath = util.findexe(shlex.split(editor)[0])
2686 2686 if not cmdpath:
2687 2687 if editor == 'vi':
2688 2688 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2689 2689 ui.write(_(" (specify a commit editor in your configuration"
2690 2690 " file)\n"))
2691 2691 else:
2692 2692 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2693 2693 ui.write(_(" (specify a commit editor in your configuration"
2694 2694 " file)\n"))
2695 2695 problems += 1
2696 2696
2697 2697 # check username
2698 2698 ui.status(_("checking username...\n"))
2699 2699 try:
2700 2700 ui.username()
2701 2701 except error.Abort as e:
2702 2702 ui.write(" %s\n" % e)
2703 2703 ui.write(_(" (specify a username in your configuration file)\n"))
2704 2704 problems += 1
2705 2705
2706 2706 if not problems:
2707 2707 ui.status(_("no problems detected\n"))
2708 2708 else:
2709 2709 ui.write(_("%s problems detected,"
2710 2710 " please check your install!\n") % problems)
2711 2711
2712 2712 return problems
2713 2713
2714 2714 @command('debugknown', [], _('REPO ID...'), norepo=True)
2715 2715 def debugknown(ui, repopath, *ids, **opts):
2716 2716 """test whether node ids are known to a repo
2717 2717
2718 2718 Every ID must be a full-length hex node id string. Returns a list of 0s
2719 2719 and 1s indicating unknown/known.
2720 2720 """
2721 2721 repo = hg.peer(ui, opts, repopath)
2722 2722 if not repo.capable('known'):
2723 2723 raise error.Abort("known() not supported by target repository")
2724 2724 flags = repo.known([bin(s) for s in ids])
2725 2725 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2726 2726
2727 2727 @command('debuglabelcomplete', [], _('LABEL...'))
2728 2728 def debuglabelcomplete(ui, repo, *args):
2729 2729 '''backwards compatibility with old bash completion scripts (DEPRECATED)'''
2730 2730 debugnamecomplete(ui, repo, *args)
2731 2731
2732 2732 @command('debugmergestate', [], '')
2733 2733 def debugmergestate(ui, repo, *args):
2734 2734 """print merge state
2735 2735
2736 2736 Use --verbose to print out information about whether v1 or v2 merge state
2737 2737 was chosen."""
2738 2738 def _hashornull(h):
2739 2739 if h == nullhex:
2740 2740 return 'null'
2741 2741 else:
2742 2742 return h
2743 2743
2744 2744 def printrecords(version):
2745 2745 ui.write(('* version %s records\n') % version)
2746 2746 if version == 1:
2747 2747 records = v1records
2748 2748 else:
2749 2749 records = v2records
2750 2750
2751 2751 for rtype, record in records:
2752 2752 # pretty print some record types
2753 2753 if rtype == 'L':
2754 2754 ui.write(('local: %s\n') % record)
2755 2755 elif rtype == 'O':
2756 2756 ui.write(('other: %s\n') % record)
2757 2757 elif rtype == 'm':
2758 2758 driver, mdstate = record.split('\0', 1)
2759 2759 ui.write(('merge driver: %s (state "%s")\n')
2760 2760 % (driver, mdstate))
2761 2761 elif rtype in 'FDC':
2762 2762 r = record.split('\0')
2763 2763 f, state, hash, lfile, afile, anode, ofile = r[0:7]
2764 2764 if version == 1:
2765 2765 onode = 'not stored in v1 format'
2766 2766 flags = r[7]
2767 2767 else:
2768 2768 onode, flags = r[7:9]
2769 2769 ui.write(('file: %s (record type "%s", state "%s", hash %s)\n')
2770 2770 % (f, rtype, state, _hashornull(hash)))
2771 2771 ui.write((' local path: %s (flags "%s")\n') % (lfile, flags))
2772 2772 ui.write((' ancestor path: %s (node %s)\n')
2773 2773 % (afile, _hashornull(anode)))
2774 2774 ui.write((' other path: %s (node %s)\n')
2775 2775 % (ofile, _hashornull(onode)))
2776 2776 else:
2777 2777 ui.write(('unrecognized entry: %s\t%s\n')
2778 2778 % (rtype, record.replace('\0', '\t')))
2779 2779
2780 2780 # Avoid mergestate.read() since it may raise an exception for unsupported
2781 2781 # merge state records. We shouldn't be doing this, but this is OK since this
2782 2782 # command is pretty low-level.
2783 2783 ms = mergemod.mergestate(repo)
2784 2784
2785 2785 # sort so that reasonable information is on top
2786 2786 v1records = ms._readrecordsv1()
2787 2787 v2records = ms._readrecordsv2()
2788 2788 order = 'LOm'
2789 2789 def key(r):
2790 2790 idx = order.find(r[0])
2791 2791 if idx == -1:
2792 2792 return (1, r[1])
2793 2793 else:
2794 2794 return (0, idx)
2795 2795 v1records.sort(key=key)
2796 2796 v2records.sort(key=key)
2797 2797
2798 2798 if not v1records and not v2records:
2799 2799 ui.write(('no merge state found\n'))
2800 2800 elif not v2records:
2801 2801 ui.note(('no version 2 merge state\n'))
2802 2802 printrecords(1)
2803 2803 elif ms._v1v2match(v1records, v2records):
2804 2804 ui.note(('v1 and v2 states match: using v2\n'))
2805 2805 printrecords(2)
2806 2806 else:
2807 2807 ui.note(('v1 and v2 states mismatch: using v1\n'))
2808 2808 printrecords(1)
2809 2809 if ui.verbose:
2810 2810 printrecords(2)
2811 2811
2812 2812 @command('debugnamecomplete', [], _('NAME...'))
2813 2813 def debugnamecomplete(ui, repo, *args):
2814 2814 '''complete "names" - tags, open branch names, bookmark names'''
2815 2815
2816 2816 names = set()
2817 2817 # since we previously only listed open branches, we will handle that
2818 2818 # specially (after this for loop)
2819 2819 for name, ns in repo.names.iteritems():
2820 2820 if name != 'branches':
2821 2821 names.update(ns.listnames(repo))
2822 2822 names.update(tag for (tag, heads, tip, closed)
2823 2823 in repo.branchmap().iterbranches() if not closed)
2824 2824 completions = set()
2825 2825 if not args:
2826 2826 args = ['']
2827 2827 for a in args:
2828 2828 completions.update(n for n in names if n.startswith(a))
2829 2829 ui.write('\n'.join(sorted(completions)))
2830 2830 ui.write('\n')
2831 2831
2832 2832 @command('debuglocks',
2833 2833 [('L', 'force-lock', None, _('free the store lock (DANGEROUS)')),
2834 2834 ('W', 'force-wlock', None,
2835 2835 _('free the working state lock (DANGEROUS)'))],
2836 2836 _('[OPTION]...'))
2837 2837 def debuglocks(ui, repo, **opts):
2838 2838 """show or modify state of locks
2839 2839
2840 2840 By default, this command will show which locks are held. This
2841 2841 includes the user and process holding the lock, the amount of time
2842 2842 the lock has been held, and the machine name where the process is
2843 2843 running if it's not local.
2844 2844
2845 2845 Locks protect the integrity of Mercurial's data, so should be
2846 2846 treated with care. System crashes or other interruptions may cause
2847 2847 locks to not be properly released, though Mercurial will usually
2848 2848 detect and remove such stale locks automatically.
2849 2849
2850 2850 However, detecting stale locks may not always be possible (for
2851 2851 instance, on a shared filesystem). Removing locks may also be
2852 2852 blocked by filesystem permissions.
2853 2853
2854 2854 Returns 0 if no locks are held.
2855 2855
2856 2856 """
2857 2857
2858 2858 if opts.get('force_lock'):
2859 2859 repo.svfs.unlink('lock')
2860 2860 if opts.get('force_wlock'):
2861 2861 repo.vfs.unlink('wlock')
2862 2862 if opts.get('force_lock') or opts.get('force_lock'):
2863 2863 return 0
2864 2864
2865 2865 now = time.time()
2866 2866 held = 0
2867 2867
2868 2868 def report(vfs, name, method):
2869 2869 # this causes stale locks to get reaped for more accurate reporting
2870 2870 try:
2871 2871 l = method(False)
2872 2872 except error.LockHeld:
2873 2873 l = None
2874 2874
2875 2875 if l:
2876 2876 l.release()
2877 2877 else:
2878 2878 try:
2879 2879 stat = vfs.lstat(name)
2880 2880 age = now - stat.st_mtime
2881 2881 user = util.username(stat.st_uid)
2882 2882 locker = vfs.readlock(name)
2883 2883 if ":" in locker:
2884 2884 host, pid = locker.split(':')
2885 2885 if host == socket.gethostname():
2886 2886 locker = 'user %s, process %s' % (user, pid)
2887 2887 else:
2888 2888 locker = 'user %s, process %s, host %s' \
2889 2889 % (user, pid, host)
2890 2890 ui.write("%-6s %s (%ds)\n" % (name + ":", locker, age))
2891 2891 return 1
2892 2892 except OSError as e:
2893 2893 if e.errno != errno.ENOENT:
2894 2894 raise
2895 2895
2896 2896 ui.write("%-6s free\n" % (name + ":"))
2897 2897 return 0
2898 2898
2899 2899 held += report(repo.svfs, "lock", repo.lock)
2900 2900 held += report(repo.vfs, "wlock", repo.wlock)
2901 2901
2902 2902 return held
2903 2903
2904 2904 @command('debugobsolete',
2905 2905 [('', 'flags', 0, _('markers flag')),
2906 2906 ('', 'record-parents', False,
2907 2907 _('record parent information for the precursor')),
2908 2908 ('r', 'rev', [], _('display markers relevant to REV')),
2909 2909 ] + commitopts2,
2910 2910 _('[OBSOLETED [REPLACEMENT ...]]'))
2911 2911 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2912 2912 """create arbitrary obsolete marker
2913 2913
2914 2914 With no arguments, displays the list of obsolescence markers."""
2915 2915
2916 2916 def parsenodeid(s):
2917 2917 try:
2918 2918 # We do not use revsingle/revrange functions here to accept
2919 2919 # arbitrary node identifiers, possibly not present in the
2920 2920 # local repository.
2921 2921 n = bin(s)
2922 2922 if len(n) != len(nullid):
2923 2923 raise TypeError()
2924 2924 return n
2925 2925 except TypeError:
2926 2926 raise error.Abort('changeset references must be full hexadecimal '
2927 2927 'node identifiers')
2928 2928
2929 2929 if precursor is not None:
2930 2930 if opts['rev']:
2931 2931 raise error.Abort('cannot select revision when creating marker')
2932 2932 metadata = {}
2933 2933 metadata['user'] = opts['user'] or ui.username()
2934 2934 succs = tuple(parsenodeid(succ) for succ in successors)
2935 2935 l = repo.lock()
2936 2936 try:
2937 2937 tr = repo.transaction('debugobsolete')
2938 2938 try:
2939 2939 date = opts.get('date')
2940 2940 if date:
2941 2941 date = util.parsedate(date)
2942 2942 else:
2943 2943 date = None
2944 2944 prec = parsenodeid(precursor)
2945 2945 parents = None
2946 2946 if opts['record_parents']:
2947 2947 if prec not in repo.unfiltered():
2948 2948 raise error.Abort('cannot used --record-parents on '
2949 2949 'unknown changesets')
2950 2950 parents = repo.unfiltered()[prec].parents()
2951 2951 parents = tuple(p.node() for p in parents)
2952 2952 repo.obsstore.create(tr, prec, succs, opts['flags'],
2953 2953 parents=parents, date=date,
2954 2954 metadata=metadata)
2955 2955 tr.close()
2956 2956 except ValueError as exc:
2957 2957 raise error.Abort(_('bad obsmarker input: %s') % exc)
2958 2958 finally:
2959 2959 tr.release()
2960 2960 finally:
2961 2961 l.release()
2962 2962 else:
2963 2963 if opts['rev']:
2964 2964 revs = scmutil.revrange(repo, opts['rev'])
2965 2965 nodes = [repo[r].node() for r in revs]
2966 2966 markers = list(obsolete.getmarkers(repo, nodes=nodes))
2967 2967 markers.sort(key=lambda x: x._data)
2968 2968 else:
2969 2969 markers = obsolete.getmarkers(repo)
2970 2970
2971 2971 for m in markers:
2972 2972 cmdutil.showmarker(ui, m)
2973 2973
2974 2974 @command('debugpathcomplete',
2975 2975 [('f', 'full', None, _('complete an entire path')),
2976 2976 ('n', 'normal', None, _('show only normal files')),
2977 2977 ('a', 'added', None, _('show only added files')),
2978 2978 ('r', 'removed', None, _('show only removed files'))],
2979 2979 _('FILESPEC...'))
2980 2980 def debugpathcomplete(ui, repo, *specs, **opts):
2981 2981 '''complete part or all of a tracked path
2982 2982
2983 2983 This command supports shells that offer path name completion. It
2984 2984 currently completes only files already known to the dirstate.
2985 2985
2986 2986 Completion extends only to the next path segment unless
2987 2987 --full is specified, in which case entire paths are used.'''
2988 2988
2989 2989 def complete(path, acceptable):
2990 2990 dirstate = repo.dirstate
2991 2991 spec = os.path.normpath(os.path.join(os.getcwd(), path))
2992 2992 rootdir = repo.root + os.sep
2993 2993 if spec != repo.root and not spec.startswith(rootdir):
2994 2994 return [], []
2995 2995 if os.path.isdir(spec):
2996 2996 spec += '/'
2997 2997 spec = spec[len(rootdir):]
2998 2998 fixpaths = os.sep != '/'
2999 2999 if fixpaths:
3000 3000 spec = spec.replace(os.sep, '/')
3001 3001 speclen = len(spec)
3002 3002 fullpaths = opts['full']
3003 3003 files, dirs = set(), set()
3004 3004 adddir, addfile = dirs.add, files.add
3005 3005 for f, st in dirstate.iteritems():
3006 3006 if f.startswith(spec) and st[0] in acceptable:
3007 3007 if fixpaths:
3008 3008 f = f.replace('/', os.sep)
3009 3009 if fullpaths:
3010 3010 addfile(f)
3011 3011 continue
3012 3012 s = f.find(os.sep, speclen)
3013 3013 if s >= 0:
3014 3014 adddir(f[:s])
3015 3015 else:
3016 3016 addfile(f)
3017 3017 return files, dirs
3018 3018
3019 3019 acceptable = ''
3020 3020 if opts['normal']:
3021 3021 acceptable += 'nm'
3022 3022 if opts['added']:
3023 3023 acceptable += 'a'
3024 3024 if opts['removed']:
3025 3025 acceptable += 'r'
3026 3026 cwd = repo.getcwd()
3027 3027 if not specs:
3028 3028 specs = ['.']
3029 3029
3030 3030 files, dirs = set(), set()
3031 3031 for spec in specs:
3032 3032 f, d = complete(spec, acceptable or 'nmar')
3033 3033 files.update(f)
3034 3034 dirs.update(d)
3035 3035 files.update(dirs)
3036 3036 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
3037 3037 ui.write('\n')
3038 3038
3039 3039 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
3040 3040 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
3041 3041 '''access the pushkey key/value protocol
3042 3042
3043 3043 With two args, list the keys in the given namespace.
3044 3044
3045 3045 With five args, set a key to new if it currently is set to old.
3046 3046 Reports success or failure.
3047 3047 '''
3048 3048
3049 3049 target = hg.peer(ui, {}, repopath)
3050 3050 if keyinfo:
3051 3051 key, old, new = keyinfo
3052 3052 r = target.pushkey(namespace, key, old, new)
3053 3053 ui.status(str(r) + '\n')
3054 3054 return not r
3055 3055 else:
3056 3056 for k, v in sorted(target.listkeys(namespace).iteritems()):
3057 3057 ui.write("%s\t%s\n" % (k.encode('string-escape'),
3058 3058 v.encode('string-escape')))
3059 3059
3060 3060 @command('debugpvec', [], _('A B'))
3061 3061 def debugpvec(ui, repo, a, b=None):
3062 3062 ca = scmutil.revsingle(repo, a)
3063 3063 cb = scmutil.revsingle(repo, b)
3064 3064 pa = pvec.ctxpvec(ca)
3065 3065 pb = pvec.ctxpvec(cb)
3066 3066 if pa == pb:
3067 3067 rel = "="
3068 3068 elif pa > pb:
3069 3069 rel = ">"
3070 3070 elif pa < pb:
3071 3071 rel = "<"
3072 3072 elif pa | pb:
3073 3073 rel = "|"
3074 3074 ui.write(_("a: %s\n") % pa)
3075 3075 ui.write(_("b: %s\n") % pb)
3076 3076 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
3077 3077 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
3078 3078 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
3079 3079 pa.distance(pb), rel))
3080 3080
3081 3081 @command('debugrebuilddirstate|debugrebuildstate',
3082 3082 [('r', 'rev', '', _('revision to rebuild to'), _('REV')),
3083 3083 ('', 'minimal', None, _('only rebuild files that are inconsistent with '
3084 3084 'the working copy parent')),
3085 3085 ],
3086 3086 _('[-r REV]'))
3087 3087 def debugrebuilddirstate(ui, repo, rev, **opts):
3088 3088 """rebuild the dirstate as it would look like for the given revision
3089 3089
3090 3090 If no revision is specified the first current parent will be used.
3091 3091
3092 3092 The dirstate will be set to the files of the given revision.
3093 3093 The actual working directory content or existing dirstate
3094 3094 information such as adds or removes is not considered.
3095 3095
3096 3096 ``minimal`` will only rebuild the dirstate status for files that claim to be
3097 3097 tracked but are not in the parent manifest, or that exist in the parent
3098 3098 manifest but are not in the dirstate. It will not change adds, removes, or
3099 3099 modified files that are in the working copy parent.
3100 3100
3101 3101 One use of this command is to make the next :hg:`status` invocation
3102 3102 check the actual file content.
3103 3103 """
3104 3104 ctx = scmutil.revsingle(repo, rev)
3105 3105 wlock = repo.wlock()
3106 3106 try:
3107 3107 dirstate = repo.dirstate
3108 3108 changedfiles = None
3109 3109 # See command doc for what minimal does.
3110 3110 if opts.get('minimal'):
3111 3111 manifestfiles = set(ctx.manifest().keys())
3112 3112 dirstatefiles = set(dirstate)
3113 3113 manifestonly = manifestfiles - dirstatefiles
3114 3114 dsonly = dirstatefiles - manifestfiles
3115 3115 dsnotadded = set(f for f in dsonly if dirstate[f] != 'a')
3116 3116 changedfiles = manifestonly | dsnotadded
3117 3117
3118 3118 dirstate.rebuild(ctx.node(), ctx.manifest(), changedfiles)
3119 3119 finally:
3120 3120 wlock.release()
3121 3121
3122 3122 @command('debugrebuildfncache', [], '')
3123 3123 def debugrebuildfncache(ui, repo):
3124 3124 """rebuild the fncache file"""
3125 3125 repair.rebuildfncache(ui, repo)
3126 3126
3127 3127 @command('debugrename',
3128 3128 [('r', 'rev', '', _('revision to debug'), _('REV'))],
3129 3129 _('[-r REV] FILE'))
3130 3130 def debugrename(ui, repo, file1, *pats, **opts):
3131 3131 """dump rename information"""
3132 3132
3133 3133 ctx = scmutil.revsingle(repo, opts.get('rev'))
3134 3134 m = scmutil.match(ctx, (file1,) + pats, opts)
3135 3135 for abs in ctx.walk(m):
3136 3136 fctx = ctx[abs]
3137 3137 o = fctx.filelog().renamed(fctx.filenode())
3138 3138 rel = m.rel(abs)
3139 3139 if o:
3140 3140 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
3141 3141 else:
3142 3142 ui.write(_("%s not renamed\n") % rel)
3143 3143
3144 3144 @command('debugrevlog', debugrevlogopts +
3145 3145 [('d', 'dump', False, _('dump index data'))],
3146 3146 _('-c|-m|FILE'),
3147 3147 optionalrepo=True)
3148 3148 def debugrevlog(ui, repo, file_=None, **opts):
3149 3149 """show data and statistics about a revlog"""
3150 3150 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
3151 3151
3152 3152 if opts.get("dump"):
3153 3153 numrevs = len(r)
3154 3154 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
3155 3155 " rawsize totalsize compression heads chainlen\n")
3156 3156 ts = 0
3157 3157 heads = set()
3158 3158
3159 3159 for rev in xrange(numrevs):
3160 3160 dbase = r.deltaparent(rev)
3161 3161 if dbase == -1:
3162 3162 dbase = rev
3163 3163 cbase = r.chainbase(rev)
3164 3164 clen = r.chainlen(rev)
3165 3165 p1, p2 = r.parentrevs(rev)
3166 3166 rs = r.rawsize(rev)
3167 3167 ts = ts + rs
3168 3168 heads -= set(r.parentrevs(rev))
3169 3169 heads.add(rev)
3170 3170 ui.write("%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d "
3171 3171 "%11d %5d %8d\n" %
3172 3172 (rev, p1, p2, r.start(rev), r.end(rev),
3173 3173 r.start(dbase), r.start(cbase),
3174 3174 r.start(p1), r.start(p2),
3175 3175 rs, ts, ts / r.end(rev), len(heads), clen))
3176 3176 return 0
3177 3177
3178 3178 v = r.version
3179 3179 format = v & 0xFFFF
3180 3180 flags = []
3181 3181 gdelta = False
3182 3182 if v & revlog.REVLOGNGINLINEDATA:
3183 3183 flags.append('inline')
3184 3184 if v & revlog.REVLOGGENERALDELTA:
3185 3185 gdelta = True
3186 3186 flags.append('generaldelta')
3187 3187 if not flags:
3188 3188 flags = ['(none)']
3189 3189
3190 3190 nummerges = 0
3191 3191 numfull = 0
3192 3192 numprev = 0
3193 3193 nump1 = 0
3194 3194 nump2 = 0
3195 3195 numother = 0
3196 3196 nump1prev = 0
3197 3197 nump2prev = 0
3198 3198 chainlengths = []
3199 3199
3200 3200 datasize = [None, 0, 0L]
3201 3201 fullsize = [None, 0, 0L]
3202 3202 deltasize = [None, 0, 0L]
3203 3203
3204 3204 def addsize(size, l):
3205 3205 if l[0] is None or size < l[0]:
3206 3206 l[0] = size
3207 3207 if size > l[1]:
3208 3208 l[1] = size
3209 3209 l[2] += size
3210 3210
3211 3211 numrevs = len(r)
3212 3212 for rev in xrange(numrevs):
3213 3213 p1, p2 = r.parentrevs(rev)
3214 3214 delta = r.deltaparent(rev)
3215 3215 if format > 0:
3216 3216 addsize(r.rawsize(rev), datasize)
3217 3217 if p2 != nullrev:
3218 3218 nummerges += 1
3219 3219 size = r.length(rev)
3220 3220 if delta == nullrev:
3221 3221 chainlengths.append(0)
3222 3222 numfull += 1
3223 3223 addsize(size, fullsize)
3224 3224 else:
3225 3225 chainlengths.append(chainlengths[delta] + 1)
3226 3226 addsize(size, deltasize)
3227 3227 if delta == rev - 1:
3228 3228 numprev += 1
3229 3229 if delta == p1:
3230 3230 nump1prev += 1
3231 3231 elif delta == p2:
3232 3232 nump2prev += 1
3233 3233 elif delta == p1:
3234 3234 nump1 += 1
3235 3235 elif delta == p2:
3236 3236 nump2 += 1
3237 3237 elif delta != nullrev:
3238 3238 numother += 1
3239 3239
3240 3240 # Adjust size min value for empty cases
3241 3241 for size in (datasize, fullsize, deltasize):
3242 3242 if size[0] is None:
3243 3243 size[0] = 0
3244 3244
3245 3245 numdeltas = numrevs - numfull
3246 3246 numoprev = numprev - nump1prev - nump2prev
3247 3247 totalrawsize = datasize[2]
3248 3248 datasize[2] /= numrevs
3249 3249 fulltotal = fullsize[2]
3250 3250 fullsize[2] /= numfull
3251 3251 deltatotal = deltasize[2]
3252 3252 if numrevs - numfull > 0:
3253 3253 deltasize[2] /= numrevs - numfull
3254 3254 totalsize = fulltotal + deltatotal
3255 3255 avgchainlen = sum(chainlengths) / numrevs
3256 3256 maxchainlen = max(chainlengths)
3257 3257 compratio = 1
3258 3258 if totalsize:
3259 3259 compratio = totalrawsize / totalsize
3260 3260
3261 3261 basedfmtstr = '%%%dd\n'
3262 3262 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
3263 3263
3264 3264 def dfmtstr(max):
3265 3265 return basedfmtstr % len(str(max))
3266 3266 def pcfmtstr(max, padding=0):
3267 3267 return basepcfmtstr % (len(str(max)), ' ' * padding)
3268 3268
3269 3269 def pcfmt(value, total):
3270 3270 if total:
3271 3271 return (value, 100 * float(value) / total)
3272 3272 else:
3273 3273 return value, 100.0
3274 3274
3275 3275 ui.write(('format : %d\n') % format)
3276 3276 ui.write(('flags : %s\n') % ', '.join(flags))
3277 3277
3278 3278 ui.write('\n')
3279 3279 fmt = pcfmtstr(totalsize)
3280 3280 fmt2 = dfmtstr(totalsize)
3281 3281 ui.write(('revisions : ') + fmt2 % numrevs)
3282 3282 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
3283 3283 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
3284 3284 ui.write(('revisions : ') + fmt2 % numrevs)
3285 3285 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
3286 3286 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
3287 3287 ui.write(('revision size : ') + fmt2 % totalsize)
3288 3288 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
3289 3289 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
3290 3290
3291 3291 ui.write('\n')
3292 3292 fmt = dfmtstr(max(avgchainlen, compratio))
3293 3293 ui.write(('avg chain length : ') + fmt % avgchainlen)
3294 3294 ui.write(('max chain length : ') + fmt % maxchainlen)
3295 3295 ui.write(('compression ratio : ') + fmt % compratio)
3296 3296
3297 3297 if format > 0:
3298 3298 ui.write('\n')
3299 3299 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
3300 3300 % tuple(datasize))
3301 3301 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
3302 3302 % tuple(fullsize))
3303 3303 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
3304 3304 % tuple(deltasize))
3305 3305
3306 3306 if numdeltas > 0:
3307 3307 ui.write('\n')
3308 3308 fmt = pcfmtstr(numdeltas)
3309 3309 fmt2 = pcfmtstr(numdeltas, 4)
3310 3310 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
3311 3311 if numprev > 0:
3312 3312 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
3313 3313 numprev))
3314 3314 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
3315 3315 numprev))
3316 3316 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
3317 3317 numprev))
3318 3318 if gdelta:
3319 3319 ui.write(('deltas against p1 : ')
3320 3320 + fmt % pcfmt(nump1, numdeltas))
3321 3321 ui.write(('deltas against p2 : ')
3322 3322 + fmt % pcfmt(nump2, numdeltas))
3323 3323 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
3324 3324 numdeltas))
3325 3325
3326 3326 @command('debugrevspec',
3327 3327 [('', 'optimize', None, _('print parsed tree after optimizing'))],
3328 3328 ('REVSPEC'))
3329 3329 def debugrevspec(ui, repo, expr, **opts):
3330 3330 """parse and apply a revision specification
3331 3331
3332 3332 Use --verbose to print the parsed tree before and after aliases
3333 3333 expansion.
3334 3334 """
3335 3335 if ui.verbose:
3336 3336 tree = revset.parse(expr, lookup=repo.__contains__)
3337 3337 ui.note(revset.prettyformat(tree), "\n")
3338 3338 newtree = revset.findaliases(ui, tree)
3339 3339 if newtree != tree:
3340 3340 ui.note(revset.prettyformat(newtree), "\n")
3341 3341 tree = newtree
3342 3342 newtree = revset.foldconcat(tree)
3343 3343 if newtree != tree:
3344 3344 ui.note(revset.prettyformat(newtree), "\n")
3345 3345 if opts["optimize"]:
3346 3346 weight, optimizedtree = revset.optimize(newtree, True)
3347 3347 ui.note("* optimized:\n", revset.prettyformat(optimizedtree), "\n")
3348 3348 func = revset.match(ui, expr, repo)
3349 3349 revs = func(repo)
3350 3350 if ui.verbose:
3351 3351 ui.note("* set:\n", revset.prettyformatset(revs), "\n")
3352 3352 for c in revs:
3353 3353 ui.write("%s\n" % c)
3354 3354
3355 3355 @command('debugsetparents', [], _('REV1 [REV2]'))
3356 3356 def debugsetparents(ui, repo, rev1, rev2=None):
3357 3357 """manually set the parents of the current working directory
3358 3358
3359 3359 This is useful for writing repository conversion tools, but should
3360 3360 be used with care. For example, neither the working directory nor the
3361 3361 dirstate is updated, so file status may be incorrect after running this
3362 3362 command.
3363 3363
3364 3364 Returns 0 on success.
3365 3365 """
3366 3366
3367 3367 r1 = scmutil.revsingle(repo, rev1).node()
3368 3368 r2 = scmutil.revsingle(repo, rev2, 'null').node()
3369 3369
3370 3370 wlock = repo.wlock()
3371 3371 try:
3372 3372 repo.dirstate.beginparentchange()
3373 3373 repo.setparents(r1, r2)
3374 3374 repo.dirstate.endparentchange()
3375 3375 finally:
3376 3376 wlock.release()
3377 3377
3378 3378 @command('debugdirstate|debugstate',
3379 3379 [('', 'nodates', None, _('do not display the saved mtime')),
3380 3380 ('', 'datesort', None, _('sort by saved mtime'))],
3381 3381 _('[OPTION]...'))
3382 3382 def debugstate(ui, repo, **opts):
3383 3383 """show the contents of the current dirstate"""
3384 3384
3385 3385 nodates = opts.get('nodates')
3386 3386 datesort = opts.get('datesort')
3387 3387
3388 3388 timestr = ""
3389 3389 if datesort:
3390 3390 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
3391 3391 else:
3392 3392 keyfunc = None # sort by filename
3393 3393 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
3394 3394 if ent[3] == -1:
3395 3395 timestr = 'unset '
3396 3396 elif nodates:
3397 3397 timestr = 'set '
3398 3398 else:
3399 3399 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
3400 3400 time.localtime(ent[3]))
3401 3401 if ent[1] & 0o20000:
3402 3402 mode = 'lnk'
3403 3403 else:
3404 3404 mode = '%3o' % (ent[1] & 0o777 & ~util.umask)
3405 3405 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
3406 3406 for f in repo.dirstate.copies():
3407 3407 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
3408 3408
3409 3409 @command('debugsub',
3410 3410 [('r', 'rev', '',
3411 3411 _('revision to check'), _('REV'))],
3412 3412 _('[-r REV] [REV]'))
3413 3413 def debugsub(ui, repo, rev=None):
3414 3414 ctx = scmutil.revsingle(repo, rev, None)
3415 3415 for k, v in sorted(ctx.substate.items()):
3416 3416 ui.write(('path %s\n') % k)
3417 3417 ui.write((' source %s\n') % v[0])
3418 3418 ui.write((' revision %s\n') % v[1])
3419 3419
3420 3420 @command('debugsuccessorssets',
3421 3421 [],
3422 3422 _('[REV]'))
3423 3423 def debugsuccessorssets(ui, repo, *revs):
3424 3424 """show set of successors for revision
3425 3425
3426 3426 A successors set of changeset A is a consistent group of revisions that
3427 3427 succeed A. It contains non-obsolete changesets only.
3428 3428
3429 3429 In most cases a changeset A has a single successors set containing a single
3430 3430 successor (changeset A replaced by A').
3431 3431
3432 3432 A changeset that is made obsolete with no successors are called "pruned".
3433 3433 Such changesets have no successors sets at all.
3434 3434
3435 3435 A changeset that has been "split" will have a successors set containing
3436 3436 more than one successor.
3437 3437
3438 3438 A changeset that has been rewritten in multiple different ways is called
3439 3439 "divergent". Such changesets have multiple successor sets (each of which
3440 3440 may also be split, i.e. have multiple successors).
3441 3441
3442 3442 Results are displayed as follows::
3443 3443
3444 3444 <rev1>
3445 3445 <successors-1A>
3446 3446 <rev2>
3447 3447 <successors-2A>
3448 3448 <successors-2B1> <successors-2B2> <successors-2B3>
3449 3449
3450 3450 Here rev2 has two possible (i.e. divergent) successors sets. The first
3451 3451 holds one element, whereas the second holds three (i.e. the changeset has
3452 3452 been split).
3453 3453 """
3454 3454 # passed to successorssets caching computation from one call to another
3455 3455 cache = {}
3456 3456 ctx2str = str
3457 3457 node2str = short
3458 3458 if ui.debug():
3459 3459 def ctx2str(ctx):
3460 3460 return ctx.hex()
3461 3461 node2str = hex
3462 3462 for rev in scmutil.revrange(repo, revs):
3463 3463 ctx = repo[rev]
3464 3464 ui.write('%s\n'% ctx2str(ctx))
3465 3465 for succsset in obsolete.successorssets(repo, ctx.node(), cache):
3466 3466 if succsset:
3467 3467 ui.write(' ')
3468 3468 ui.write(node2str(succsset[0]))
3469 3469 for node in succsset[1:]:
3470 3470 ui.write(' ')
3471 3471 ui.write(node2str(node))
3472 3472 ui.write('\n')
3473 3473
3474 3474 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'), inferrepo=True)
3475 3475 def debugwalk(ui, repo, *pats, **opts):
3476 3476 """show how files match on given patterns"""
3477 3477 m = scmutil.match(repo[None], pats, opts)
3478 3478 items = list(repo.walk(m))
3479 3479 if not items:
3480 3480 return
3481 3481 f = lambda fn: fn
3482 3482 if ui.configbool('ui', 'slash') and os.sep != '/':
3483 3483 f = lambda fn: util.normpath(fn)
3484 3484 fmt = 'f %%-%ds %%-%ds %%s' % (
3485 3485 max([len(abs) for abs in items]),
3486 3486 max([len(m.rel(abs)) for abs in items]))
3487 3487 for abs in items:
3488 3488 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
3489 3489 ui.write("%s\n" % line.rstrip())
3490 3490
3491 3491 @command('debugwireargs',
3492 3492 [('', 'three', '', 'three'),
3493 3493 ('', 'four', '', 'four'),
3494 3494 ('', 'five', '', 'five'),
3495 3495 ] + remoteopts,
3496 3496 _('REPO [OPTIONS]... [ONE [TWO]]'),
3497 3497 norepo=True)
3498 3498 def debugwireargs(ui, repopath, *vals, **opts):
3499 3499 repo = hg.peer(ui, opts, repopath)
3500 3500 for opt in remoteopts:
3501 3501 del opts[opt[1]]
3502 3502 args = {}
3503 3503 for k, v in opts.iteritems():
3504 3504 if v:
3505 3505 args[k] = v
3506 3506 # run twice to check that we don't mess up the stream for the next command
3507 3507 res1 = repo.debugwireargs(*vals, **args)
3508 3508 res2 = repo.debugwireargs(*vals, **args)
3509 3509 ui.write("%s\n" % res1)
3510 3510 if res1 != res2:
3511 3511 ui.warn("%s\n" % res2)
3512 3512
3513 3513 @command('^diff',
3514 3514 [('r', 'rev', [], _('revision'), _('REV')),
3515 3515 ('c', 'change', '', _('change made by revision'), _('REV'))
3516 3516 ] + diffopts + diffopts2 + walkopts + subrepoopts,
3517 3517 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
3518 3518 inferrepo=True)
3519 3519 def diff(ui, repo, *pats, **opts):
3520 3520 """diff repository (or selected files)
3521 3521
3522 3522 Show differences between revisions for the specified files.
3523 3523
3524 3524 Differences between files are shown using the unified diff format.
3525 3525
3526 3526 .. note::
3527 3527
3528 3528 diff may generate unexpected results for merges, as it will
3529 3529 default to comparing against the working directory's first
3530 3530 parent changeset if no revisions are specified.
3531 3531
3532 3532 When two revision arguments are given, then changes are shown
3533 3533 between those revisions. If only one revision is specified then
3534 3534 that revision is compared to the working directory, and, when no
3535 3535 revisions are specified, the working directory files are compared
3536 3536 to its parent.
3537 3537
3538 3538 Alternatively you can specify -c/--change with a revision to see
3539 3539 the changes in that changeset relative to its first parent.
3540 3540
3541 3541 Without the -a/--text option, diff will avoid generating diffs of
3542 3542 files it detects as binary. With -a, diff will generate a diff
3543 3543 anyway, probably with undesirable results.
3544 3544
3545 3545 Use the -g/--git option to generate diffs in the git extended diff
3546 3546 format. For more information, read :hg:`help diffs`.
3547 3547
3548 3548 .. container:: verbose
3549 3549
3550 3550 Examples:
3551 3551
3552 3552 - compare a file in the current working directory to its parent::
3553 3553
3554 3554 hg diff foo.c
3555 3555
3556 3556 - compare two historical versions of a directory, with rename info::
3557 3557
3558 3558 hg diff --git -r 1.0:1.2 lib/
3559 3559
3560 3560 - get change stats relative to the last change on some date::
3561 3561
3562 3562 hg diff --stat -r "date('may 2')"
3563 3563
3564 3564 - diff all newly-added files that contain a keyword::
3565 3565
3566 3566 hg diff "set:added() and grep(GNU)"
3567 3567
3568 3568 - compare a revision and its parents::
3569 3569
3570 3570 hg diff -c 9353 # compare against first parent
3571 3571 hg diff -r 9353^:9353 # same using revset syntax
3572 3572 hg diff -r 9353^2:9353 # compare against the second parent
3573 3573
3574 3574 Returns 0 on success.
3575 3575 """
3576 3576
3577 3577 revs = opts.get('rev')
3578 3578 change = opts.get('change')
3579 3579 stat = opts.get('stat')
3580 3580 reverse = opts.get('reverse')
3581 3581
3582 3582 if revs and change:
3583 3583 msg = _('cannot specify --rev and --change at the same time')
3584 3584 raise error.Abort(msg)
3585 3585 elif change:
3586 3586 node2 = scmutil.revsingle(repo, change, None).node()
3587 3587 node1 = repo[node2].p1().node()
3588 3588 else:
3589 3589 node1, node2 = scmutil.revpair(repo, revs)
3590 3590
3591 3591 if reverse:
3592 3592 node1, node2 = node2, node1
3593 3593
3594 3594 diffopts = patch.diffallopts(ui, opts)
3595 3595 m = scmutil.match(repo[node2], pats, opts)
3596 3596 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
3597 3597 listsubrepos=opts.get('subrepos'),
3598 3598 root=opts.get('root'))
3599 3599
3600 3600 @command('^export',
3601 3601 [('o', 'output', '',
3602 3602 _('print output to file with formatted name'), _('FORMAT')),
3603 3603 ('', 'switch-parent', None, _('diff against the second parent')),
3604 3604 ('r', 'rev', [], _('revisions to export'), _('REV')),
3605 3605 ] + diffopts,
3606 3606 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
3607 3607 def export(ui, repo, *changesets, **opts):
3608 3608 """dump the header and diffs for one or more changesets
3609 3609
3610 3610 Print the changeset header and diffs for one or more revisions.
3611 3611 If no revision is given, the parent of the working directory is used.
3612 3612
3613 3613 The information shown in the changeset header is: author, date,
3614 3614 branch name (if non-default), changeset hash, parent(s) and commit
3615 3615 comment.
3616 3616
3617 3617 .. note::
3618 3618
3619 3619 export may generate unexpected diff output for merge
3620 3620 changesets, as it will compare the merge changeset against its
3621 3621 first parent only.
3622 3622
3623 3623 Output may be to a file, in which case the name of the file is
3624 3624 given using a format string. The formatting rules are as follows:
3625 3625
3626 3626 :``%%``: literal "%" character
3627 3627 :``%H``: changeset hash (40 hexadecimal digits)
3628 3628 :``%N``: number of patches being generated
3629 3629 :``%R``: changeset revision number
3630 3630 :``%b``: basename of the exporting repository
3631 3631 :``%h``: short-form changeset hash (12 hexadecimal digits)
3632 3632 :``%m``: first line of the commit message (only alphanumeric characters)
3633 3633 :``%n``: zero-padded sequence number, starting at 1
3634 3634 :``%r``: zero-padded changeset revision number
3635 3635
3636 3636 Without the -a/--text option, export will avoid generating diffs
3637 3637 of files it detects as binary. With -a, export will generate a
3638 3638 diff anyway, probably with undesirable results.
3639 3639
3640 3640 Use the -g/--git option to generate diffs in the git extended diff
3641 3641 format. See :hg:`help diffs` for more information.
3642 3642
3643 3643 With the --switch-parent option, the diff will be against the
3644 3644 second parent. It can be useful to review a merge.
3645 3645
3646 3646 .. container:: verbose
3647 3647
3648 3648 Examples:
3649 3649
3650 3650 - use export and import to transplant a bugfix to the current
3651 3651 branch::
3652 3652
3653 3653 hg export -r 9353 | hg import -
3654 3654
3655 3655 - export all the changesets between two revisions to a file with
3656 3656 rename information::
3657 3657
3658 3658 hg export --git -r 123:150 > changes.txt
3659 3659
3660 3660 - split outgoing changes into a series of patches with
3661 3661 descriptive names::
3662 3662
3663 3663 hg export -r "outgoing()" -o "%n-%m.patch"
3664 3664
3665 3665 Returns 0 on success.
3666 3666 """
3667 3667 changesets += tuple(opts.get('rev', []))
3668 3668 if not changesets:
3669 3669 changesets = ['.']
3670 3670 revs = scmutil.revrange(repo, changesets)
3671 3671 if not revs:
3672 3672 raise error.Abort(_("export requires at least one changeset"))
3673 3673 if len(revs) > 1:
3674 3674 ui.note(_('exporting patches:\n'))
3675 3675 else:
3676 3676 ui.note(_('exporting patch:\n'))
3677 3677 cmdutil.export(repo, revs, template=opts.get('output'),
3678 3678 switch_parent=opts.get('switch_parent'),
3679 3679 opts=patch.diffallopts(ui, opts))
3680 3680
3681 3681 @command('files',
3682 3682 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3683 3683 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3684 3684 ] + walkopts + formatteropts + subrepoopts,
3685 3685 _('[OPTION]... [PATTERN]...'))
3686 3686 def files(ui, repo, *pats, **opts):
3687 3687 """list tracked files
3688 3688
3689 3689 Print files under Mercurial control in the working directory or
3690 3690 specified revision whose names match the given patterns (excluding
3691 3691 removed files).
3692 3692
3693 3693 If no patterns are given to match, this command prints the names
3694 3694 of all files under Mercurial control in the working directory.
3695 3695
3696 3696 .. container:: verbose
3697 3697
3698 3698 Examples:
3699 3699
3700 3700 - list all files under the current directory::
3701 3701
3702 3702 hg files .
3703 3703
3704 3704 - shows sizes and flags for current revision::
3705 3705
3706 3706 hg files -vr .
3707 3707
3708 3708 - list all files named README::
3709 3709
3710 3710 hg files -I "**/README"
3711 3711
3712 3712 - list all binary files::
3713 3713
3714 3714 hg files "set:binary()"
3715 3715
3716 3716 - find files containing a regular expression::
3717 3717
3718 3718 hg files "set:grep('bob')"
3719 3719
3720 3720 - search tracked file contents with xargs and grep::
3721 3721
3722 3722 hg files -0 | xargs -0 grep foo
3723 3723
3724 3724 See :hg:`help patterns` and :hg:`help filesets` for more information
3725 3725 on specifying file patterns.
3726 3726
3727 3727 Returns 0 if a match is found, 1 otherwise.
3728 3728
3729 3729 """
3730 3730 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3731 3731
3732 3732 end = '\n'
3733 3733 if opts.get('print0'):
3734 3734 end = '\0'
3735 3735 fm = ui.formatter('files', opts)
3736 3736 fmt = '%s' + end
3737 3737
3738 3738 m = scmutil.match(ctx, pats, opts)
3739 3739 ret = cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
3740 3740
3741 3741 fm.end()
3742 3742
3743 3743 return ret
3744 3744
3745 3745 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
3746 3746 def forget(ui, repo, *pats, **opts):
3747 3747 """forget the specified files on the next commit
3748 3748
3749 3749 Mark the specified files so they will no longer be tracked
3750 3750 after the next commit.
3751 3751
3752 3752 This only removes files from the current branch, not from the
3753 3753 entire project history, and it does not delete them from the
3754 3754 working directory.
3755 3755
3756 3756 To delete the file from the working directory, see :hg:`remove`.
3757 3757
3758 3758 To undo a forget before the next commit, see :hg:`add`.
3759 3759
3760 3760 .. container:: verbose
3761 3761
3762 3762 Examples:
3763 3763
3764 3764 - forget newly-added binary files::
3765 3765
3766 3766 hg forget "set:added() and binary()"
3767 3767
3768 3768 - forget files that would be excluded by .hgignore::
3769 3769
3770 3770 hg forget "set:hgignore()"
3771 3771
3772 3772 Returns 0 on success.
3773 3773 """
3774 3774
3775 3775 if not pats:
3776 3776 raise error.Abort(_('no files specified'))
3777 3777
3778 3778 m = scmutil.match(repo[None], pats, opts)
3779 3779 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
3780 3780 return rejected and 1 or 0
3781 3781
3782 3782 @command(
3783 3783 'graft',
3784 3784 [('r', 'rev', [], _('revisions to graft'), _('REV')),
3785 3785 ('c', 'continue', False, _('resume interrupted graft')),
3786 3786 ('e', 'edit', False, _('invoke editor on commit messages')),
3787 3787 ('', 'log', None, _('append graft info to log message')),
3788 3788 ('f', 'force', False, _('force graft')),
3789 3789 ('D', 'currentdate', False,
3790 3790 _('record the current date as commit date')),
3791 3791 ('U', 'currentuser', False,
3792 3792 _('record the current user as committer'), _('DATE'))]
3793 3793 + commitopts2 + mergetoolopts + dryrunopts,
3794 3794 _('[OPTION]... [-r] REV...'))
3795 3795 def graft(ui, repo, *revs, **opts):
3796 3796 '''copy changes from other branches onto the current branch
3797 3797
3798 3798 This command uses Mercurial's merge logic to copy individual
3799 3799 changes from other branches without merging branches in the
3800 3800 history graph. This is sometimes known as 'backporting' or
3801 3801 'cherry-picking'. By default, graft will copy user, date, and
3802 3802 description from the source changesets.
3803 3803
3804 3804 Changesets that are ancestors of the current revision, that have
3805 3805 already been grafted, or that are merges will be skipped.
3806 3806
3807 3807 If --log is specified, log messages will have a comment appended
3808 3808 of the form::
3809 3809
3810 3810 (grafted from CHANGESETHASH)
3811 3811
3812 3812 If --force is specified, revisions will be grafted even if they
3813 3813 are already ancestors of or have been grafted to the destination.
3814 3814 This is useful when the revisions have since been backed out.
3815 3815
3816 3816 If a graft merge results in conflicts, the graft process is
3817 3817 interrupted so that the current merge can be manually resolved.
3818 3818 Once all conflicts are addressed, the graft process can be
3819 3819 continued with the -c/--continue option.
3820 3820
3821 3821 .. note::
3822 3822
3823 3823 The -c/--continue option does not reapply earlier options, except
3824 3824 for --force.
3825 3825
3826 3826 .. container:: verbose
3827 3827
3828 3828 Examples:
3829 3829
3830 3830 - copy a single change to the stable branch and edit its description::
3831 3831
3832 3832 hg update stable
3833 3833 hg graft --edit 9393
3834 3834
3835 3835 - graft a range of changesets with one exception, updating dates::
3836 3836
3837 3837 hg graft -D "2085::2093 and not 2091"
3838 3838
3839 3839 - continue a graft after resolving conflicts::
3840 3840
3841 3841 hg graft -c
3842 3842
3843 3843 - show the source of a grafted changeset::
3844 3844
3845 3845 hg log --debug -r .
3846 3846
3847 3847 See :hg:`help revisions` and :hg:`help revsets` for more about
3848 3848 specifying revisions.
3849 3849
3850 3850 Returns 0 on successful completion.
3851 3851 '''
3852 3852 wlock = None
3853 3853 try:
3854 3854 wlock = repo.wlock()
3855 3855 return _dograft(ui, repo, *revs, **opts)
3856 3856 finally:
3857 3857 release(wlock)
3858 3858
3859 3859 def _dograft(ui, repo, *revs, **opts):
3860 3860 revs = list(revs)
3861 3861 revs.extend(opts['rev'])
3862 3862
3863 3863 if not opts.get('user') and opts.get('currentuser'):
3864 3864 opts['user'] = ui.username()
3865 3865 if not opts.get('date') and opts.get('currentdate'):
3866 3866 opts['date'] = "%d %d" % util.makedate()
3867 3867
3868 3868 editor = cmdutil.getcommiteditor(editform='graft', **opts)
3869 3869
3870 3870 cont = False
3871 3871 if opts['continue']:
3872 3872 cont = True
3873 3873 if revs:
3874 3874 raise error.Abort(_("can't specify --continue and revisions"))
3875 3875 # read in unfinished revisions
3876 3876 try:
3877 3877 nodes = repo.vfs.read('graftstate').splitlines()
3878 3878 revs = [repo[node].rev() for node in nodes]
3879 3879 except IOError as inst:
3880 3880 if inst.errno != errno.ENOENT:
3881 3881 raise
3882 3882 raise error.Abort(_("no graft state found, can't continue"))
3883 3883 else:
3884 3884 cmdutil.checkunfinished(repo)
3885 3885 cmdutil.bailifchanged(repo)
3886 3886 if not revs:
3887 3887 raise error.Abort(_('no revisions specified'))
3888 3888 revs = scmutil.revrange(repo, revs)
3889 3889
3890 3890 skipped = set()
3891 3891 # check for merges
3892 3892 for rev in repo.revs('%ld and merge()', revs):
3893 3893 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
3894 3894 skipped.add(rev)
3895 3895 revs = [r for r in revs if r not in skipped]
3896 3896 if not revs:
3897 3897 return -1
3898 3898
3899 3899 # Don't check in the --continue case, in effect retaining --force across
3900 3900 # --continues. That's because without --force, any revisions we decided to
3901 3901 # skip would have been filtered out here, so they wouldn't have made their
3902 3902 # way to the graftstate. With --force, any revisions we would have otherwise
3903 3903 # skipped would not have been filtered out, and if they hadn't been applied
3904 3904 # already, they'd have been in the graftstate.
3905 3905 if not (cont or opts.get('force')):
3906 3906 # check for ancestors of dest branch
3907 3907 crev = repo['.'].rev()
3908 3908 ancestors = repo.changelog.ancestors([crev], inclusive=True)
3909 3909 # Cannot use x.remove(y) on smart set, this has to be a list.
3910 3910 # XXX make this lazy in the future
3911 3911 revs = list(revs)
3912 3912 # don't mutate while iterating, create a copy
3913 3913 for rev in list(revs):
3914 3914 if rev in ancestors:
3915 3915 ui.warn(_('skipping ancestor revision %d:%s\n') %
3916 3916 (rev, repo[rev]))
3917 3917 # XXX remove on list is slow
3918 3918 revs.remove(rev)
3919 3919 if not revs:
3920 3920 return -1
3921 3921
3922 3922 # analyze revs for earlier grafts
3923 3923 ids = {}
3924 3924 for ctx in repo.set("%ld", revs):
3925 3925 ids[ctx.hex()] = ctx.rev()
3926 3926 n = ctx.extra().get('source')
3927 3927 if n:
3928 3928 ids[n] = ctx.rev()
3929 3929
3930 3930 # check ancestors for earlier grafts
3931 3931 ui.debug('scanning for duplicate grafts\n')
3932 3932
3933 3933 for rev in repo.changelog.findmissingrevs(revs, [crev]):
3934 3934 ctx = repo[rev]
3935 3935 n = ctx.extra().get('source')
3936 3936 if n in ids:
3937 3937 try:
3938 3938 r = repo[n].rev()
3939 3939 except error.RepoLookupError:
3940 3940 r = None
3941 3941 if r in revs:
3942 3942 ui.warn(_('skipping revision %d:%s '
3943 3943 '(already grafted to %d:%s)\n')
3944 3944 % (r, repo[r], rev, ctx))
3945 3945 revs.remove(r)
3946 3946 elif ids[n] in revs:
3947 3947 if r is None:
3948 3948 ui.warn(_('skipping already grafted revision %d:%s '
3949 3949 '(%d:%s also has unknown origin %s)\n')
3950 3950 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
3951 3951 else:
3952 3952 ui.warn(_('skipping already grafted revision %d:%s '
3953 3953 '(%d:%s also has origin %d:%s)\n')
3954 3954 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
3955 3955 revs.remove(ids[n])
3956 3956 elif ctx.hex() in ids:
3957 3957 r = ids[ctx.hex()]
3958 3958 ui.warn(_('skipping already grafted revision %d:%s '
3959 3959 '(was grafted from %d:%s)\n') %
3960 3960 (r, repo[r], rev, ctx))
3961 3961 revs.remove(r)
3962 3962 if not revs:
3963 3963 return -1
3964 3964
3965 3965 try:
3966 3966 for pos, ctx in enumerate(repo.set("%ld", revs)):
3967 3967 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
3968 3968 ctx.description().split('\n', 1)[0])
3969 3969 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
3970 3970 if names:
3971 3971 desc += ' (%s)' % ' '.join(names)
3972 3972 ui.status(_('grafting %s\n') % desc)
3973 3973 if opts.get('dry_run'):
3974 3974 continue
3975 3975
3976 3976 extra = ctx.extra().copy()
3977 3977 del extra['branch']
3978 3978 source = extra.get('source')
3979 3979 if source:
3980 3980 extra['intermediate-source'] = ctx.hex()
3981 3981 else:
3982 3982 extra['source'] = ctx.hex()
3983 3983 user = ctx.user()
3984 3984 if opts.get('user'):
3985 3985 user = opts['user']
3986 3986 date = ctx.date()
3987 3987 if opts.get('date'):
3988 3988 date = opts['date']
3989 3989 message = ctx.description()
3990 3990 if opts.get('log'):
3991 3991 message += '\n(grafted from %s)' % ctx.hex()
3992 3992
3993 3993 # we don't merge the first commit when continuing
3994 3994 if not cont:
3995 3995 # perform the graft merge with p1(rev) as 'ancestor'
3996 3996 try:
3997 3997 # ui.forcemerge is an internal variable, do not document
3998 3998 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
3999 3999 'graft')
4000 4000 stats = mergemod.graft(repo, ctx, ctx.p1(),
4001 4001 ['local', 'graft'])
4002 4002 finally:
4003 4003 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
4004 4004 # report any conflicts
4005 4005 if stats and stats[3] > 0:
4006 4006 # write out state for --continue
4007 4007 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
4008 4008 repo.vfs.write('graftstate', ''.join(nodelines))
4009 4009 extra = ''
4010 4010 if opts.get('user'):
4011 4011 extra += ' --user %s' % opts['user']
4012 4012 if opts.get('date'):
4013 4013 extra += ' --date %s' % opts['date']
4014 4014 if opts.get('log'):
4015 4015 extra += ' --log'
4016 4016 hint=_('use hg resolve and hg graft --continue%s') % extra
4017 4017 raise error.Abort(
4018 4018 _("unresolved conflicts, can't continue"),
4019 4019 hint=hint)
4020 4020 else:
4021 4021 cont = False
4022 4022
4023 4023 # commit
4024 4024 node = repo.commit(text=message, user=user,
4025 4025 date=date, extra=extra, editor=editor)
4026 4026 if node is None:
4027 4027 ui.warn(
4028 4028 _('note: graft of %d:%s created no changes to commit\n') %
4029 4029 (ctx.rev(), ctx))
4030 4030 finally:
4031 4031 # TODO: get rid of this meaningless try/finally enclosing.
4032 4032 # this is kept only to reduce changes in a patch.
4033 4033 pass
4034 4034
4035 4035 # remove state when we complete successfully
4036 4036 if not opts.get('dry_run'):
4037 4037 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
4038 4038
4039 4039 return 0
4040 4040
4041 4041 @command('grep',
4042 4042 [('0', 'print0', None, _('end fields with NUL')),
4043 4043 ('', 'all', None, _('print all revisions that match')),
4044 4044 ('a', 'text', None, _('treat all files as text')),
4045 4045 ('f', 'follow', None,
4046 4046 _('follow changeset history,'
4047 4047 ' or file history across copies and renames')),
4048 4048 ('i', 'ignore-case', None, _('ignore case when matching')),
4049 4049 ('l', 'files-with-matches', None,
4050 4050 _('print only filenames and revisions that match')),
4051 4051 ('n', 'line-number', None, _('print matching line numbers')),
4052 4052 ('r', 'rev', [],
4053 4053 _('only search files changed within revision range'), _('REV')),
4054 4054 ('u', 'user', None, _('list the author (long with -v)')),
4055 4055 ('d', 'date', None, _('list the date (short with -q)')),
4056 4056 ] + walkopts,
4057 4057 _('[OPTION]... PATTERN [FILE]...'),
4058 4058 inferrepo=True)
4059 4059 def grep(ui, repo, pattern, *pats, **opts):
4060 4060 """search for a pattern in specified files and revisions
4061 4061
4062 4062 Search revisions of files for a regular expression.
4063 4063
4064 4064 This command behaves differently than Unix grep. It only accepts
4065 4065 Python/Perl regexps. It searches repository history, not the
4066 4066 working directory. It always prints the revision number in which a
4067 4067 match appears.
4068 4068
4069 4069 By default, grep only prints output for the first revision of a
4070 4070 file in which it finds a match. To get it to print every revision
4071 4071 that contains a change in match status ("-" for a match that
4072 4072 becomes a non-match, or "+" for a non-match that becomes a match),
4073 4073 use the --all flag.
4074 4074
4075 4075 Returns 0 if a match is found, 1 otherwise.
4076 4076 """
4077 4077 reflags = re.M
4078 4078 if opts.get('ignore_case'):
4079 4079 reflags |= re.I
4080 4080 try:
4081 4081 regexp = util.re.compile(pattern, reflags)
4082 4082 except re.error as inst:
4083 4083 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
4084 4084 return 1
4085 4085 sep, eol = ':', '\n'
4086 4086 if opts.get('print0'):
4087 4087 sep = eol = '\0'
4088 4088
4089 4089 getfile = util.lrucachefunc(repo.file)
4090 4090
4091 4091 def matchlines(body):
4092 4092 begin = 0
4093 4093 linenum = 0
4094 4094 while begin < len(body):
4095 4095 match = regexp.search(body, begin)
4096 4096 if not match:
4097 4097 break
4098 4098 mstart, mend = match.span()
4099 4099 linenum += body.count('\n', begin, mstart) + 1
4100 4100 lstart = body.rfind('\n', begin, mstart) + 1 or begin
4101 4101 begin = body.find('\n', mend) + 1 or len(body) + 1
4102 4102 lend = begin - 1
4103 4103 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
4104 4104
4105 4105 class linestate(object):
4106 4106 def __init__(self, line, linenum, colstart, colend):
4107 4107 self.line = line
4108 4108 self.linenum = linenum
4109 4109 self.colstart = colstart
4110 4110 self.colend = colend
4111 4111
4112 4112 def __hash__(self):
4113 4113 return hash((self.linenum, self.line))
4114 4114
4115 4115 def __eq__(self, other):
4116 4116 return self.line == other.line
4117 4117
4118 4118 def __iter__(self):
4119 4119 yield (self.line[:self.colstart], '')
4120 4120 yield (self.line[self.colstart:self.colend], 'grep.match')
4121 4121 rest = self.line[self.colend:]
4122 4122 while rest != '':
4123 4123 match = regexp.search(rest)
4124 4124 if not match:
4125 4125 yield (rest, '')
4126 4126 break
4127 4127 mstart, mend = match.span()
4128 4128 yield (rest[:mstart], '')
4129 4129 yield (rest[mstart:mend], 'grep.match')
4130 4130 rest = rest[mend:]
4131 4131
4132 4132 matches = {}
4133 4133 copies = {}
4134 4134 def grepbody(fn, rev, body):
4135 4135 matches[rev].setdefault(fn, [])
4136 4136 m = matches[rev][fn]
4137 4137 for lnum, cstart, cend, line in matchlines(body):
4138 4138 s = linestate(line, lnum, cstart, cend)
4139 4139 m.append(s)
4140 4140
4141 4141 def difflinestates(a, b):
4142 4142 sm = difflib.SequenceMatcher(None, a, b)
4143 4143 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
4144 4144 if tag == 'insert':
4145 4145 for i in xrange(blo, bhi):
4146 4146 yield ('+', b[i])
4147 4147 elif tag == 'delete':
4148 4148 for i in xrange(alo, ahi):
4149 4149 yield ('-', a[i])
4150 4150 elif tag == 'replace':
4151 4151 for i in xrange(alo, ahi):
4152 4152 yield ('-', a[i])
4153 4153 for i in xrange(blo, bhi):
4154 4154 yield ('+', b[i])
4155 4155
4156 4156 def display(fn, ctx, pstates, states):
4157 4157 rev = ctx.rev()
4158 4158 if ui.quiet:
4159 4159 datefunc = util.shortdate
4160 4160 else:
4161 4161 datefunc = util.datestr
4162 4162 found = False
4163 4163 @util.cachefunc
4164 4164 def binary():
4165 4165 flog = getfile(fn)
4166 4166 return util.binary(flog.read(ctx.filenode(fn)))
4167 4167
4168 4168 if opts.get('all'):
4169 4169 iter = difflinestates(pstates, states)
4170 4170 else:
4171 4171 iter = [('', l) for l in states]
4172 4172 for change, l in iter:
4173 4173 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
4174 4174
4175 4175 if opts.get('line_number'):
4176 4176 cols.append((str(l.linenum), 'grep.linenumber'))
4177 4177 if opts.get('all'):
4178 4178 cols.append((change, 'grep.change'))
4179 4179 if opts.get('user'):
4180 4180 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
4181 4181 if opts.get('date'):
4182 4182 cols.append((datefunc(ctx.date()), 'grep.date'))
4183 4183 for col, label in cols[:-1]:
4184 4184 ui.write(col, label=label)
4185 4185 ui.write(sep, label='grep.sep')
4186 4186 ui.write(cols[-1][0], label=cols[-1][1])
4187 4187 if not opts.get('files_with_matches'):
4188 4188 ui.write(sep, label='grep.sep')
4189 4189 if not opts.get('text') and binary():
4190 4190 ui.write(" Binary file matches")
4191 4191 else:
4192 4192 for s, label in l:
4193 4193 ui.write(s, label=label)
4194 4194 ui.write(eol)
4195 4195 found = True
4196 4196 if opts.get('files_with_matches'):
4197 4197 break
4198 4198 return found
4199 4199
4200 4200 skip = {}
4201 4201 revfiles = {}
4202 4202 matchfn = scmutil.match(repo[None], pats, opts)
4203 4203 found = False
4204 4204 follow = opts.get('follow')
4205 4205
4206 4206 def prep(ctx, fns):
4207 4207 rev = ctx.rev()
4208 4208 pctx = ctx.p1()
4209 4209 parent = pctx.rev()
4210 4210 matches.setdefault(rev, {})
4211 4211 matches.setdefault(parent, {})
4212 4212 files = revfiles.setdefault(rev, [])
4213 4213 for fn in fns:
4214 4214 flog = getfile(fn)
4215 4215 try:
4216 4216 fnode = ctx.filenode(fn)
4217 4217 except error.LookupError:
4218 4218 continue
4219 4219
4220 4220 copied = flog.renamed(fnode)
4221 4221 copy = follow and copied and copied[0]
4222 4222 if copy:
4223 4223 copies.setdefault(rev, {})[fn] = copy
4224 4224 if fn in skip:
4225 4225 if copy:
4226 4226 skip[copy] = True
4227 4227 continue
4228 4228 files.append(fn)
4229 4229
4230 4230 if fn not in matches[rev]:
4231 4231 grepbody(fn, rev, flog.read(fnode))
4232 4232
4233 4233 pfn = copy or fn
4234 4234 if pfn not in matches[parent]:
4235 4235 try:
4236 4236 fnode = pctx.filenode(pfn)
4237 4237 grepbody(pfn, parent, flog.read(fnode))
4238 4238 except error.LookupError:
4239 4239 pass
4240 4240
4241 4241 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
4242 4242 rev = ctx.rev()
4243 4243 parent = ctx.p1().rev()
4244 4244 for fn in sorted(revfiles.get(rev, [])):
4245 4245 states = matches[rev][fn]
4246 4246 copy = copies.get(rev, {}).get(fn)
4247 4247 if fn in skip:
4248 4248 if copy:
4249 4249 skip[copy] = True
4250 4250 continue
4251 4251 pstates = matches.get(parent, {}).get(copy or fn, [])
4252 4252 if pstates or states:
4253 4253 r = display(fn, ctx, pstates, states)
4254 4254 found = found or r
4255 4255 if r and not opts.get('all'):
4256 4256 skip[fn] = True
4257 4257 if copy:
4258 4258 skip[copy] = True
4259 4259 del matches[rev]
4260 4260 del revfiles[rev]
4261 4261
4262 4262 return not found
4263 4263
4264 4264 @command('heads',
4265 4265 [('r', 'rev', '',
4266 4266 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
4267 4267 ('t', 'topo', False, _('show topological heads only')),
4268 4268 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
4269 4269 ('c', 'closed', False, _('show normal and closed branch heads')),
4270 4270 ] + templateopts,
4271 4271 _('[-ct] [-r STARTREV] [REV]...'))
4272 4272 def heads(ui, repo, *branchrevs, **opts):
4273 4273 """show branch heads
4274 4274
4275 4275 With no arguments, show all open branch heads in the repository.
4276 4276 Branch heads are changesets that have no descendants on the
4277 4277 same branch. They are where development generally takes place and
4278 4278 are the usual targets for update and merge operations.
4279 4279
4280 4280 If one or more REVs are given, only open branch heads on the
4281 4281 branches associated with the specified changesets are shown. This
4282 4282 means that you can use :hg:`heads .` to see the heads on the
4283 4283 currently checked-out branch.
4284 4284
4285 4285 If -c/--closed is specified, also show branch heads marked closed
4286 4286 (see :hg:`commit --close-branch`).
4287 4287
4288 4288 If STARTREV is specified, only those heads that are descendants of
4289 4289 STARTREV will be displayed.
4290 4290
4291 4291 If -t/--topo is specified, named branch mechanics will be ignored and only
4292 4292 topological heads (changesets with no children) will be shown.
4293 4293
4294 4294 Returns 0 if matching heads are found, 1 if not.
4295 4295 """
4296 4296
4297 4297 start = None
4298 4298 if 'rev' in opts:
4299 4299 start = scmutil.revsingle(repo, opts['rev'], None).node()
4300 4300
4301 4301 if opts.get('topo'):
4302 4302 heads = [repo[h] for h in repo.heads(start)]
4303 4303 else:
4304 4304 heads = []
4305 4305 for branch in repo.branchmap():
4306 4306 heads += repo.branchheads(branch, start, opts.get('closed'))
4307 4307 heads = [repo[h] for h in heads]
4308 4308
4309 4309 if branchrevs:
4310 4310 branches = set(repo[br].branch() for br in branchrevs)
4311 4311 heads = [h for h in heads if h.branch() in branches]
4312 4312
4313 4313 if opts.get('active') and branchrevs:
4314 4314 dagheads = repo.heads(start)
4315 4315 heads = [h for h in heads if h.node() in dagheads]
4316 4316
4317 4317 if branchrevs:
4318 4318 haveheads = set(h.branch() for h in heads)
4319 4319 if branches - haveheads:
4320 4320 headless = ', '.join(b for b in branches - haveheads)
4321 4321 msg = _('no open branch heads found on branches %s')
4322 4322 if opts.get('rev'):
4323 4323 msg += _(' (started at %s)') % opts['rev']
4324 4324 ui.warn((msg + '\n') % headless)
4325 4325
4326 4326 if not heads:
4327 4327 return 1
4328 4328
4329 4329 heads = sorted(heads, key=lambda x: -x.rev())
4330 4330 displayer = cmdutil.show_changeset(ui, repo, opts)
4331 4331 for ctx in heads:
4332 4332 displayer.show(ctx)
4333 4333 displayer.close()
4334 4334
4335 4335 @command('help',
4336 4336 [('e', 'extension', None, _('show only help for extensions')),
4337 4337 ('c', 'command', None, _('show only help for commands')),
4338 4338 ('k', 'keyword', None, _('show topics matching keyword')),
4339 4339 ],
4340 4340 _('[-eck] [TOPIC]'),
4341 4341 norepo=True)
4342 4342 def help_(ui, name=None, **opts):
4343 4343 """show help for a given topic or a help overview
4344 4344
4345 4345 With no arguments, print a list of commands with short help messages.
4346 4346
4347 4347 Given a topic, extension, or command name, print help for that
4348 4348 topic.
4349 4349
4350 4350 Returns 0 if successful.
4351 4351 """
4352 4352
4353 4353 textwidth = min(ui.termwidth(), 80) - 2
4354 4354
4355 4355 keep = []
4356 4356 if ui.verbose:
4357 4357 keep.append('verbose')
4358 4358 if sys.platform.startswith('win'):
4359 4359 keep.append('windows')
4360 4360 elif sys.platform == 'OpenVMS':
4361 4361 keep.append('vms')
4362 4362 elif sys.platform == 'plan9':
4363 4363 keep.append('plan9')
4364 4364 else:
4365 4365 keep.append('unix')
4366 4366 keep.append(sys.platform.lower())
4367 4367
4368 4368 section = None
4369 4369 if name and '.' in name:
4370 4370 name, section = name.split('.', 1)
4371 4371 section = section.lower()
4372 4372
4373 4373 text = help.help_(ui, name, **opts)
4374 4374
4375 4375 formatted, pruned = minirst.format(text, textwidth, keep=keep,
4376 4376 section=section)
4377 4377
4378 4378 # We could have been given a weird ".foo" section without a name
4379 4379 # to look for, or we could have simply failed to found "foo.bar"
4380 4380 # because bar isn't a section of foo
4381 4381 if section and not (formatted and name):
4382 4382 raise error.Abort(_("help section not found"))
4383 4383
4384 4384 if 'verbose' in pruned:
4385 4385 keep.append('omitted')
4386 4386 else:
4387 4387 keep.append('notomitted')
4388 4388 formatted, pruned = minirst.format(text, textwidth, keep=keep,
4389 4389 section=section)
4390 4390 ui.write(formatted)
4391 4391
4392 4392
4393 4393 @command('identify|id',
4394 4394 [('r', 'rev', '',
4395 4395 _('identify the specified revision'), _('REV')),
4396 4396 ('n', 'num', None, _('show local revision number')),
4397 4397 ('i', 'id', None, _('show global revision id')),
4398 4398 ('b', 'branch', None, _('show branch')),
4399 4399 ('t', 'tags', None, _('show tags')),
4400 4400 ('B', 'bookmarks', None, _('show bookmarks')),
4401 4401 ] + remoteopts,
4402 4402 _('[-nibtB] [-r REV] [SOURCE]'),
4403 4403 optionalrepo=True)
4404 4404 def identify(ui, repo, source=None, rev=None,
4405 4405 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
4406 4406 """identify the working directory or specified revision
4407 4407
4408 4408 Print a summary identifying the repository state at REV using one or
4409 4409 two parent hash identifiers, followed by a "+" if the working
4410 4410 directory has uncommitted changes, the branch name (if not default),
4411 4411 a list of tags, and a list of bookmarks.
4412 4412
4413 4413 When REV is not given, print a summary of the current state of the
4414 4414 repository.
4415 4415
4416 4416 Specifying a path to a repository root or Mercurial bundle will
4417 4417 cause lookup to operate on that repository/bundle.
4418 4418
4419 4419 .. container:: verbose
4420 4420
4421 4421 Examples:
4422 4422
4423 4423 - generate a build identifier for the working directory::
4424 4424
4425 4425 hg id --id > build-id.dat
4426 4426
4427 4427 - find the revision corresponding to a tag::
4428 4428
4429 4429 hg id -n -r 1.3
4430 4430
4431 4431 - check the most recent revision of a remote repository::
4432 4432
4433 4433 hg id -r tip http://selenic.com/hg/
4434 4434
4435 4435 See :hg:`log` for generating more information about specific revisions,
4436 4436 including full hash identifiers.
4437 4437
4438 4438 Returns 0 if successful.
4439 4439 """
4440 4440
4441 4441 if not repo and not source:
4442 4442 raise error.Abort(_("there is no Mercurial repository here "
4443 4443 "(.hg not found)"))
4444 4444
4445 4445 if ui.debugflag:
4446 4446 hexfunc = hex
4447 4447 else:
4448 4448 hexfunc = short
4449 4449 default = not (num or id or branch or tags or bookmarks)
4450 4450 output = []
4451 4451 revs = []
4452 4452
4453 4453 if source:
4454 4454 source, branches = hg.parseurl(ui.expandpath(source))
4455 4455 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
4456 4456 repo = peer.local()
4457 4457 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
4458 4458
4459 4459 if not repo:
4460 4460 if num or branch or tags:
4461 4461 raise error.Abort(
4462 4462 _("can't query remote revision number, branch, or tags"))
4463 4463 if not rev and revs:
4464 4464 rev = revs[0]
4465 4465 if not rev:
4466 4466 rev = "tip"
4467 4467
4468 4468 remoterev = peer.lookup(rev)
4469 4469 if default or id:
4470 4470 output = [hexfunc(remoterev)]
4471 4471
4472 4472 def getbms():
4473 4473 bms = []
4474 4474
4475 4475 if 'bookmarks' in peer.listkeys('namespaces'):
4476 4476 hexremoterev = hex(remoterev)
4477 4477 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
4478 4478 if bmr == hexremoterev]
4479 4479
4480 4480 return sorted(bms)
4481 4481
4482 4482 if bookmarks:
4483 4483 output.extend(getbms())
4484 4484 elif default and not ui.quiet:
4485 4485 # multiple bookmarks for a single parent separated by '/'
4486 4486 bm = '/'.join(getbms())
4487 4487 if bm:
4488 4488 output.append(bm)
4489 4489 else:
4490 4490 ctx = scmutil.revsingle(repo, rev, None)
4491 4491
4492 4492 if ctx.rev() is None:
4493 4493 ctx = repo[None]
4494 4494 parents = ctx.parents()
4495 4495 taglist = []
4496 4496 for p in parents:
4497 4497 taglist.extend(p.tags())
4498 4498
4499 4499 changed = ""
4500 4500 if default or id or num:
4501 4501 if (any(repo.status())
4502 4502 or any(ctx.sub(s).dirty() for s in ctx.substate)):
4503 4503 changed = '+'
4504 4504 if default or id:
4505 4505 output = ["%s%s" %
4506 4506 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
4507 4507 if num:
4508 4508 output.append("%s%s" %
4509 4509 ('+'.join([str(p.rev()) for p in parents]), changed))
4510 4510 else:
4511 4511 if default or id:
4512 4512 output = [hexfunc(ctx.node())]
4513 4513 if num:
4514 4514 output.append(str(ctx.rev()))
4515 4515 taglist = ctx.tags()
4516 4516
4517 4517 if default and not ui.quiet:
4518 4518 b = ctx.branch()
4519 4519 if b != 'default':
4520 4520 output.append("(%s)" % b)
4521 4521
4522 4522 # multiple tags for a single parent separated by '/'
4523 4523 t = '/'.join(taglist)
4524 4524 if t:
4525 4525 output.append(t)
4526 4526
4527 4527 # multiple bookmarks for a single parent separated by '/'
4528 4528 bm = '/'.join(ctx.bookmarks())
4529 4529 if bm:
4530 4530 output.append(bm)
4531 4531 else:
4532 4532 if branch:
4533 4533 output.append(ctx.branch())
4534 4534
4535 4535 if tags:
4536 4536 output.extend(taglist)
4537 4537
4538 4538 if bookmarks:
4539 4539 output.extend(ctx.bookmarks())
4540 4540
4541 4541 ui.write("%s\n" % ' '.join(output))
4542 4542
4543 4543 @command('import|patch',
4544 4544 [('p', 'strip', 1,
4545 4545 _('directory strip option for patch. This has the same '
4546 4546 'meaning as the corresponding patch option'), _('NUM')),
4547 4547 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
4548 4548 ('e', 'edit', False, _('invoke editor on commit messages')),
4549 4549 ('f', 'force', None,
4550 4550 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
4551 4551 ('', 'no-commit', None,
4552 4552 _("don't commit, just update the working directory")),
4553 4553 ('', 'bypass', None,
4554 4554 _("apply patch without touching the working directory")),
4555 4555 ('', 'partial', None,
4556 4556 _('commit even if some hunks fail')),
4557 4557 ('', 'exact', None,
4558 4558 _('apply patch to the nodes from which it was generated')),
4559 4559 ('', 'prefix', '',
4560 4560 _('apply patch to subdirectory'), _('DIR')),
4561 4561 ('', 'import-branch', None,
4562 4562 _('use any branch information in patch (implied by --exact)'))] +
4563 4563 commitopts + commitopts2 + similarityopts,
4564 4564 _('[OPTION]... PATCH...'))
4565 4565 def import_(ui, repo, patch1=None, *patches, **opts):
4566 4566 """import an ordered set of patches
4567 4567
4568 4568 Import a list of patches and commit them individually (unless
4569 4569 --no-commit is specified).
4570 4570
4571 4571 Because import first applies changes to the working directory,
4572 4572 import will abort if there are outstanding changes.
4573 4573
4574 4574 You can import a patch straight from a mail message. Even patches
4575 4575 as attachments work (to use the body part, it must have type
4576 4576 text/plain or text/x-patch). From and Subject headers of email
4577 4577 message are used as default committer and commit message. All
4578 4578 text/plain body parts before first diff are added to commit
4579 4579 message.
4580 4580
4581 4581 If the imported patch was generated by :hg:`export`, user and
4582 4582 description from patch override values from message headers and
4583 4583 body. Values given on command line with -m/--message and -u/--user
4584 4584 override these.
4585 4585
4586 4586 If --exact is specified, import will set the working directory to
4587 4587 the parent of each patch before applying it, and will abort if the
4588 4588 resulting changeset has a different ID than the one recorded in
4589 4589 the patch. This may happen due to character set problems or other
4590 4590 deficiencies in the text patch format.
4591 4591
4592 4592 Use --bypass to apply and commit patches directly to the
4593 4593 repository, not touching the working directory. Without --exact,
4594 4594 patches will be applied on top of the working directory parent
4595 4595 revision.
4596 4596
4597 4597 With -s/--similarity, hg will attempt to discover renames and
4598 4598 copies in the patch in the same way as :hg:`addremove`.
4599 4599
4600 4600 Use --partial to ensure a changeset will be created from the patch
4601 4601 even if some hunks fail to apply. Hunks that fail to apply will be
4602 4602 written to a <target-file>.rej file. Conflicts can then be resolved
4603 4603 by hand before :hg:`commit --amend` is run to update the created
4604 4604 changeset. This flag exists to let people import patches that
4605 4605 partially apply without losing the associated metadata (author,
4606 4606 date, description, ...). Note that when none of the hunk applies
4607 4607 cleanly, :hg:`import --partial` will create an empty changeset,
4608 4608 importing only the patch metadata.
4609 4609
4610 4610 It is possible to use external patch programs to perform the patch
4611 4611 by setting the ``ui.patch`` configuration option. For the default
4612 4612 internal tool, the fuzz can also be configured via ``patch.fuzz``.
4613 4613 See :hg:`help config` for more information about configuration
4614 4614 files and how to use these options.
4615 4615
4616 4616 To read a patch from standard input, use "-" as the patch name. If
4617 4617 a URL is specified, the patch will be downloaded from it.
4618 4618 See :hg:`help dates` for a list of formats valid for -d/--date.
4619 4619
4620 4620 .. container:: verbose
4621 4621
4622 4622 Examples:
4623 4623
4624 4624 - import a traditional patch from a website and detect renames::
4625 4625
4626 4626 hg import -s 80 http://example.com/bugfix.patch
4627 4627
4628 4628 - import a changeset from an hgweb server::
4629 4629
4630 4630 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
4631 4631
4632 4632 - import all the patches in an Unix-style mbox::
4633 4633
4634 4634 hg import incoming-patches.mbox
4635 4635
4636 4636 - attempt to exactly restore an exported changeset (not always
4637 4637 possible)::
4638 4638
4639 4639 hg import --exact proposed-fix.patch
4640 4640
4641 4641 - use an external tool to apply a patch which is too fuzzy for
4642 4642 the default internal tool.
4643 4643
4644 4644 hg import --config ui.patch="patch --merge" fuzzy.patch
4645 4645
4646 4646 - change the default fuzzing from 2 to a less strict 7
4647 4647
4648 4648 hg import --config ui.fuzz=7 fuzz.patch
4649 4649
4650 4650 Returns 0 on success, 1 on partial success (see --partial).
4651 4651 """
4652 4652
4653 4653 if not patch1:
4654 4654 raise error.Abort(_('need at least one patch to import'))
4655 4655
4656 4656 patches = (patch1,) + patches
4657 4657
4658 4658 date = opts.get('date')
4659 4659 if date:
4660 4660 opts['date'] = util.parsedate(date)
4661 4661
4662 4662 update = not opts.get('bypass')
4663 4663 if not update and opts.get('no_commit'):
4664 4664 raise error.Abort(_('cannot use --no-commit with --bypass'))
4665 4665 try:
4666 4666 sim = float(opts.get('similarity') or 0)
4667 4667 except ValueError:
4668 4668 raise error.Abort(_('similarity must be a number'))
4669 4669 if sim < 0 or sim > 100:
4670 4670 raise error.Abort(_('similarity must be between 0 and 100'))
4671 4671 if sim and not update:
4672 4672 raise error.Abort(_('cannot use --similarity with --bypass'))
4673 4673 if opts.get('exact') and opts.get('edit'):
4674 4674 raise error.Abort(_('cannot use --exact with --edit'))
4675 4675 if opts.get('exact') and opts.get('prefix'):
4676 4676 raise error.Abort(_('cannot use --exact with --prefix'))
4677 4677
4678 4678 base = opts["base"]
4679 4679 wlock = dsguard = lock = tr = None
4680 4680 msgs = []
4681 4681 ret = 0
4682 4682
4683 4683
4684 4684 try:
4685 4685 try:
4686 4686 wlock = repo.wlock()
4687 4687
4688 4688 if update:
4689 4689 cmdutil.checkunfinished(repo)
4690 4690 if (opts.get('exact') or not opts.get('force')) and update:
4691 4691 cmdutil.bailifchanged(repo)
4692 4692
4693 4693 if not opts.get('no_commit'):
4694 4694 lock = repo.lock()
4695 4695 tr = repo.transaction('import')
4696 4696 else:
4697 4697 dsguard = cmdutil.dirstateguard(repo, 'import')
4698 4698 parents = repo[None].parents()
4699 4699 for patchurl in patches:
4700 4700 if patchurl == '-':
4701 4701 ui.status(_('applying patch from stdin\n'))
4702 4702 patchfile = ui.fin
4703 4703 patchurl = 'stdin' # for error message
4704 4704 else:
4705 4705 patchurl = os.path.join(base, patchurl)
4706 4706 ui.status(_('applying %s\n') % patchurl)
4707 4707 patchfile = hg.openpath(ui, patchurl)
4708 4708
4709 4709 haspatch = False
4710 4710 for hunk in patch.split(patchfile):
4711 4711 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
4712 4712 parents, opts,
4713 4713 msgs, hg.clean)
4714 4714 if msg:
4715 4715 haspatch = True
4716 4716 ui.note(msg + '\n')
4717 4717 if update or opts.get('exact'):
4718 4718 parents = repo[None].parents()
4719 4719 else:
4720 4720 parents = [repo[node]]
4721 4721 if rej:
4722 4722 ui.write_err(_("patch applied partially\n"))
4723 4723 ui.write_err(_("(fix the .rej files and run "
4724 4724 "`hg commit --amend`)\n"))
4725 4725 ret = 1
4726 4726 break
4727 4727
4728 4728 if not haspatch:
4729 4729 raise error.Abort(_('%s: no diffs found') % patchurl)
4730 4730
4731 4731 if tr:
4732 4732 tr.close()
4733 4733 if msgs:
4734 4734 repo.savecommitmessage('\n* * *\n'.join(msgs))
4735 4735 if dsguard:
4736 4736 dsguard.close()
4737 4737 return ret
4738 4738 finally:
4739 4739 # TODO: get rid of this meaningless try/finally enclosing.
4740 4740 # this is kept only to reduce changes in a patch.
4741 4741 pass
4742 4742 finally:
4743 4743 if tr:
4744 4744 tr.release()
4745 4745 release(lock, dsguard, wlock)
4746 4746
4747 4747 @command('incoming|in',
4748 4748 [('f', 'force', None,
4749 4749 _('run even if remote repository is unrelated')),
4750 4750 ('n', 'newest-first', None, _('show newest record first')),
4751 4751 ('', 'bundle', '',
4752 4752 _('file to store the bundles into'), _('FILE')),
4753 4753 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4754 4754 ('B', 'bookmarks', False, _("compare bookmarks")),
4755 4755 ('b', 'branch', [],
4756 4756 _('a specific branch you would like to pull'), _('BRANCH')),
4757 4757 ] + logopts + remoteopts + subrepoopts,
4758 4758 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
4759 4759 def incoming(ui, repo, source="default", **opts):
4760 4760 """show new changesets found in source
4761 4761
4762 4762 Show new changesets found in the specified path/URL or the default
4763 4763 pull location. These are the changesets that would have been pulled
4764 4764 if a pull at the time you issued this command.
4765 4765
4766 4766 See pull for valid source format details.
4767 4767
4768 4768 .. container:: verbose
4769 4769
4770 4770 With -B/--bookmarks, the result of bookmark comparison between
4771 4771 local and remote repositories is displayed. With -v/--verbose,
4772 4772 status is also displayed for each bookmark like below::
4773 4773
4774 4774 BM1 01234567890a added
4775 4775 BM2 1234567890ab advanced
4776 4776 BM3 234567890abc diverged
4777 4777 BM4 34567890abcd changed
4778 4778
4779 4779 The action taken locally when pulling depends on the
4780 4780 status of each bookmark:
4781 4781
4782 4782 :``added``: pull will create it
4783 4783 :``advanced``: pull will update it
4784 4784 :``diverged``: pull will create a divergent bookmark
4785 4785 :``changed``: result depends on remote changesets
4786 4786
4787 4787 From the point of view of pulling behavior, bookmark
4788 4788 existing only in the remote repository are treated as ``added``,
4789 4789 even if it is in fact locally deleted.
4790 4790
4791 4791 .. container:: verbose
4792 4792
4793 4793 For remote repository, using --bundle avoids downloading the
4794 4794 changesets twice if the incoming is followed by a pull.
4795 4795
4796 4796 Examples:
4797 4797
4798 4798 - show incoming changes with patches and full description::
4799 4799
4800 4800 hg incoming -vp
4801 4801
4802 4802 - show incoming changes excluding merges, store a bundle::
4803 4803
4804 4804 hg in -vpM --bundle incoming.hg
4805 4805 hg pull incoming.hg
4806 4806
4807 4807 - briefly list changes inside a bundle::
4808 4808
4809 4809 hg in changes.hg -T "{desc|firstline}\\n"
4810 4810
4811 4811 Returns 0 if there are incoming changes, 1 otherwise.
4812 4812 """
4813 4813 if opts.get('graph'):
4814 4814 cmdutil.checkunsupportedgraphflags([], opts)
4815 4815 def display(other, chlist, displayer):
4816 4816 revdag = cmdutil.graphrevs(other, chlist, opts)
4817 4817 cmdutil.displaygraph(ui, repo, revdag, displayer,
4818 4818 graphmod.asciiedges)
4819 4819
4820 4820 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4821 4821 return 0
4822 4822
4823 4823 if opts.get('bundle') and opts.get('subrepos'):
4824 4824 raise error.Abort(_('cannot combine --bundle and --subrepos'))
4825 4825
4826 4826 if opts.get('bookmarks'):
4827 4827 source, branches = hg.parseurl(ui.expandpath(source),
4828 4828 opts.get('branch'))
4829 4829 other = hg.peer(repo, opts, source)
4830 4830 if 'bookmarks' not in other.listkeys('namespaces'):
4831 4831 ui.warn(_("remote doesn't support bookmarks\n"))
4832 4832 return 0
4833 4833 ui.status(_('comparing with %s\n') % util.hidepassword(source))
4834 4834 return bookmarks.incoming(ui, repo, other)
4835 4835
4836 4836 repo._subtoppath = ui.expandpath(source)
4837 4837 try:
4838 4838 return hg.incoming(ui, repo, source, opts)
4839 4839 finally:
4840 4840 del repo._subtoppath
4841 4841
4842 4842
4843 4843 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
4844 4844 norepo=True)
4845 4845 def init(ui, dest=".", **opts):
4846 4846 """create a new repository in the given directory
4847 4847
4848 4848 Initialize a new repository in the given directory. If the given
4849 4849 directory does not exist, it will be created.
4850 4850
4851 4851 If no directory is given, the current directory is used.
4852 4852
4853 4853 It is possible to specify an ``ssh://`` URL as the destination.
4854 4854 See :hg:`help urls` for more information.
4855 4855
4856 4856 Returns 0 on success.
4857 4857 """
4858 4858 hg.peer(ui, opts, ui.expandpath(dest), create=True)
4859 4859
4860 4860 @command('locate',
4861 4861 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
4862 4862 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4863 4863 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
4864 4864 ] + walkopts,
4865 4865 _('[OPTION]... [PATTERN]...'))
4866 4866 def locate(ui, repo, *pats, **opts):
4867 4867 """locate files matching specific patterns (DEPRECATED)
4868 4868
4869 4869 Print files under Mercurial control in the working directory whose
4870 4870 names match the given patterns.
4871 4871
4872 4872 By default, this command searches all directories in the working
4873 4873 directory. To search just the current directory and its
4874 4874 subdirectories, use "--include .".
4875 4875
4876 4876 If no patterns are given to match, this command prints the names
4877 4877 of all files under Mercurial control in the working directory.
4878 4878
4879 4879 If you want to feed the output of this command into the "xargs"
4880 4880 command, use the -0 option to both this command and "xargs". This
4881 4881 will avoid the problem of "xargs" treating single filenames that
4882 4882 contain whitespace as multiple filenames.
4883 4883
4884 4884 See :hg:`help files` for a more versatile command.
4885 4885
4886 4886 Returns 0 if a match is found, 1 otherwise.
4887 4887 """
4888 4888 if opts.get('print0'):
4889 4889 end = '\0'
4890 4890 else:
4891 4891 end = '\n'
4892 4892 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
4893 4893
4894 4894 ret = 1
4895 4895 ctx = repo[rev]
4896 4896 m = scmutil.match(ctx, pats, opts, default='relglob',
4897 4897 badfn=lambda x, y: False)
4898 4898
4899 4899 for abs in ctx.matches(m):
4900 4900 if opts.get('fullpath'):
4901 4901 ui.write(repo.wjoin(abs), end)
4902 4902 else:
4903 4903 ui.write(((pats and m.rel(abs)) or abs), end)
4904 4904 ret = 0
4905 4905
4906 4906 return ret
4907 4907
4908 4908 @command('^log|history',
4909 4909 [('f', 'follow', None,
4910 4910 _('follow changeset history, or file history across copies and renames')),
4911 4911 ('', 'follow-first', None,
4912 4912 _('only follow the first parent of merge changesets (DEPRECATED)')),
4913 4913 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
4914 4914 ('C', 'copies', None, _('show copied files')),
4915 4915 ('k', 'keyword', [],
4916 4916 _('do case-insensitive search for a given text'), _('TEXT')),
4917 4917 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
4918 4918 ('', 'removed', None, _('include revisions where files were removed')),
4919 4919 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4920 4920 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4921 4921 ('', 'only-branch', [],
4922 4922 _('show only changesets within the given named branch (DEPRECATED)'),
4923 4923 _('BRANCH')),
4924 4924 ('b', 'branch', [],
4925 4925 _('show changesets within the given named branch'), _('BRANCH')),
4926 4926 ('P', 'prune', [],
4927 4927 _('do not display revision or any of its ancestors'), _('REV')),
4928 4928 ] + logopts + walkopts,
4929 4929 _('[OPTION]... [FILE]'),
4930 4930 inferrepo=True)
4931 4931 def log(ui, repo, *pats, **opts):
4932 4932 """show revision history of entire repository or files
4933 4933
4934 4934 Print the revision history of the specified files or the entire
4935 4935 project.
4936 4936
4937 4937 If no revision range is specified, the default is ``tip:0`` unless
4938 4938 --follow is set, in which case the working directory parent is
4939 4939 used as the starting revision.
4940 4940
4941 4941 File history is shown without following rename or copy history of
4942 4942 files. Use -f/--follow with a filename to follow history across
4943 4943 renames and copies. --follow without a filename will only show
4944 4944 ancestors or descendants of the starting revision.
4945 4945
4946 4946 By default this command prints revision number and changeset id,
4947 4947 tags, non-trivial parents, user, date and time, and a summary for
4948 4948 each commit. When the -v/--verbose switch is used, the list of
4949 4949 changed files and full commit message are shown.
4950 4950
4951 4951 With --graph the revisions are shown as an ASCII art DAG with the most
4952 4952 recent changeset at the top.
4953 4953 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
4954 4954 and '+' represents a fork where the changeset from the lines below is a
4955 4955 parent of the 'o' merge on the same line.
4956 4956
4957 4957 .. note::
4958 4958
4959 4959 log -p/--patch may generate unexpected diff output for merge
4960 4960 changesets, as it will only compare the merge changeset against
4961 4961 its first parent. Also, only files different from BOTH parents
4962 4962 will appear in files:.
4963 4963
4964 4964 .. note::
4965 4965
4966 4966 for performance reasons, log FILE may omit duplicate changes
4967 4967 made on branches and will not show removals or mode changes. To
4968 4968 see all such changes, use the --removed switch.
4969 4969
4970 4970 .. container:: verbose
4971 4971
4972 4972 Some examples:
4973 4973
4974 4974 - changesets with full descriptions and file lists::
4975 4975
4976 4976 hg log -v
4977 4977
4978 4978 - changesets ancestral to the working directory::
4979 4979
4980 4980 hg log -f
4981 4981
4982 4982 - last 10 commits on the current branch::
4983 4983
4984 4984 hg log -l 10 -b .
4985 4985
4986 4986 - changesets showing all modifications of a file, including removals::
4987 4987
4988 4988 hg log --removed file.c
4989 4989
4990 4990 - all changesets that touch a directory, with diffs, excluding merges::
4991 4991
4992 4992 hg log -Mp lib/
4993 4993
4994 4994 - all revision numbers that match a keyword::
4995 4995
4996 4996 hg log -k bug --template "{rev}\\n"
4997 4997
4998 4998 - the full hash identifier of the working directory parent::
4999 4999
5000 5000 hg log -r . --template "{node}\\n"
5001 5001
5002 5002 - list available log templates::
5003 5003
5004 5004 hg log -T list
5005 5005
5006 5006 - check if a given changeset is included in a tagged release::
5007 5007
5008 5008 hg log -r "a21ccf and ancestor(1.9)"
5009 5009
5010 5010 - find all changesets by some user in a date range::
5011 5011
5012 5012 hg log -k alice -d "may 2008 to jul 2008"
5013 5013
5014 5014 - summary of all changesets after the last tag::
5015 5015
5016 5016 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
5017 5017
5018 5018 See :hg:`help dates` for a list of formats valid for -d/--date.
5019 5019
5020 5020 See :hg:`help revisions` and :hg:`help revsets` for more about
5021 5021 specifying revisions.
5022 5022
5023 5023 See :hg:`help templates` for more about pre-packaged styles and
5024 5024 specifying custom templates.
5025 5025
5026 5026 Returns 0 on success.
5027 5027
5028 5028 """
5029 5029 if opts.get('follow') and opts.get('rev'):
5030 5030 opts['rev'] = [revset.formatspec('reverse(::%lr)', opts.get('rev'))]
5031 5031 del opts['follow']
5032 5032
5033 5033 if opts.get('graph'):
5034 5034 return cmdutil.graphlog(ui, repo, *pats, **opts)
5035 5035
5036 5036 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
5037 5037 limit = cmdutil.loglimit(opts)
5038 5038 count = 0
5039 5039
5040 5040 getrenamed = None
5041 5041 if opts.get('copies'):
5042 5042 endrev = None
5043 5043 if opts.get('rev'):
5044 5044 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
5045 5045 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
5046 5046
5047 5047 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
5048 5048 for rev in revs:
5049 5049 if count == limit:
5050 5050 break
5051 5051 ctx = repo[rev]
5052 5052 copies = None
5053 5053 if getrenamed is not None and rev:
5054 5054 copies = []
5055 5055 for fn in ctx.files():
5056 5056 rename = getrenamed(fn, rev)
5057 5057 if rename:
5058 5058 copies.append((fn, rename[0]))
5059 5059 if filematcher:
5060 5060 revmatchfn = filematcher(ctx.rev())
5061 5061 else:
5062 5062 revmatchfn = None
5063 5063 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
5064 5064 if displayer.flush(ctx):
5065 5065 count += 1
5066 5066
5067 5067 displayer.close()
5068 5068
5069 5069 @command('manifest',
5070 5070 [('r', 'rev', '', _('revision to display'), _('REV')),
5071 5071 ('', 'all', False, _("list files from all revisions"))]
5072 5072 + formatteropts,
5073 5073 _('[-r REV]'))
5074 5074 def manifest(ui, repo, node=None, rev=None, **opts):
5075 5075 """output the current or given revision of the project manifest
5076 5076
5077 5077 Print a list of version controlled files for the given revision.
5078 5078 If no revision is given, the first parent of the working directory
5079 5079 is used, or the null revision if no revision is checked out.
5080 5080
5081 5081 With -v, print file permissions, symlink and executable bits.
5082 5082 With --debug, print file revision hashes.
5083 5083
5084 5084 If option --all is specified, the list of all files from all revisions
5085 5085 is printed. This includes deleted and renamed files.
5086 5086
5087 5087 Returns 0 on success.
5088 5088 """
5089 5089
5090 5090 fm = ui.formatter('manifest', opts)
5091 5091
5092 5092 if opts.get('all'):
5093 5093 if rev or node:
5094 5094 raise error.Abort(_("can't specify a revision with --all"))
5095 5095
5096 5096 res = []
5097 5097 prefix = "data/"
5098 5098 suffix = ".i"
5099 5099 plen = len(prefix)
5100 5100 slen = len(suffix)
5101 5101 lock = repo.lock()
5102 5102 try:
5103 5103 for fn, b, size in repo.store.datafiles():
5104 5104 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
5105 5105 res.append(fn[plen:-slen])
5106 5106 finally:
5107 5107 lock.release()
5108 5108 for f in res:
5109 5109 fm.startitem()
5110 5110 fm.write("path", '%s\n', f)
5111 5111 fm.end()
5112 5112 return
5113 5113
5114 5114 if rev and node:
5115 5115 raise error.Abort(_("please specify just one revision"))
5116 5116
5117 5117 if not node:
5118 5118 node = rev
5119 5119
5120 5120 char = {'l': '@', 'x': '*', '': ''}
5121 5121 mode = {'l': '644', 'x': '755', '': '644'}
5122 5122 ctx = scmutil.revsingle(repo, node)
5123 5123 mf = ctx.manifest()
5124 5124 for f in ctx:
5125 5125 fm.startitem()
5126 5126 fl = ctx[f].flags()
5127 5127 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
5128 5128 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
5129 5129 fm.write('path', '%s\n', f)
5130 5130 fm.end()
5131 5131
5132 5132 @command('^merge',
5133 5133 [('f', 'force', None,
5134 5134 _('force a merge including outstanding changes (DEPRECATED)')),
5135 5135 ('r', 'rev', '', _('revision to merge'), _('REV')),
5136 5136 ('P', 'preview', None,
5137 5137 _('review revisions to merge (no merge is performed)'))
5138 5138 ] + mergetoolopts,
5139 5139 _('[-P] [-f] [[-r] REV]'))
5140 5140 def merge(ui, repo, node=None, **opts):
5141 5141 """merge another revision into working directory
5142 5142
5143 5143 The current working directory is updated with all changes made in
5144 5144 the requested revision since the last common predecessor revision.
5145 5145
5146 5146 Files that changed between either parent are marked as changed for
5147 5147 the next commit and a commit must be performed before any further
5148 5148 updates to the repository are allowed. The next commit will have
5149 5149 two parents.
5150 5150
5151 5151 ``--tool`` can be used to specify the merge tool used for file
5152 5152 merges. It overrides the HGMERGE environment variable and your
5153 5153 configuration files. See :hg:`help merge-tools` for options.
5154 5154
5155 5155 If no revision is specified, the working directory's parent is a
5156 5156 head revision, and the current branch contains exactly one other
5157 5157 head, the other head is merged with by default. Otherwise, an
5158 5158 explicit revision with which to merge with must be provided.
5159 5159
5160 5160 :hg:`resolve` must be used to resolve unresolved files.
5161 5161
5162 5162 To undo an uncommitted merge, use :hg:`update --clean .` which
5163 5163 will check out a clean copy of the original merge parent, losing
5164 5164 all changes.
5165 5165
5166 5166 Returns 0 on success, 1 if there are unresolved files.
5167 5167 """
5168 5168
5169 5169 if opts.get('rev') and node:
5170 5170 raise error.Abort(_("please specify just one revision"))
5171 5171 if not node:
5172 5172 node = opts.get('rev')
5173 5173
5174 5174 if node:
5175 5175 node = scmutil.revsingle(repo, node).node()
5176 5176
5177 5177 if not node:
5178 5178 node = repo[destutil.destmerge(repo)].node()
5179 5179
5180 5180 if opts.get('preview'):
5181 5181 # find nodes that are ancestors of p2 but not of p1
5182 5182 p1 = repo.lookup('.')
5183 5183 p2 = repo.lookup(node)
5184 5184 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
5185 5185
5186 5186 displayer = cmdutil.show_changeset(ui, repo, opts)
5187 5187 for node in nodes:
5188 5188 displayer.show(repo[node])
5189 5189 displayer.close()
5190 5190 return 0
5191 5191
5192 5192 try:
5193 5193 # ui.forcemerge is an internal variable, do not document
5194 5194 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
5195 5195 return hg.merge(repo, node, force=opts.get('force'))
5196 5196 finally:
5197 5197 ui.setconfig('ui', 'forcemerge', '', 'merge')
5198 5198
5199 5199 @command('outgoing|out',
5200 5200 [('f', 'force', None, _('run even when the destination is unrelated')),
5201 5201 ('r', 'rev', [],
5202 5202 _('a changeset intended to be included in the destination'), _('REV')),
5203 5203 ('n', 'newest-first', None, _('show newest record first')),
5204 5204 ('B', 'bookmarks', False, _('compare bookmarks')),
5205 5205 ('b', 'branch', [], _('a specific branch you would like to push'),
5206 5206 _('BRANCH')),
5207 5207 ] + logopts + remoteopts + subrepoopts,
5208 5208 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
5209 5209 def outgoing(ui, repo, dest=None, **opts):
5210 5210 """show changesets not found in the destination
5211 5211
5212 5212 Show changesets not found in the specified destination repository
5213 5213 or the default push location. These are the changesets that would
5214 5214 be pushed if a push was requested.
5215 5215
5216 5216 See pull for details of valid destination formats.
5217 5217
5218 5218 .. container:: verbose
5219 5219
5220 5220 With -B/--bookmarks, the result of bookmark comparison between
5221 5221 local and remote repositories is displayed. With -v/--verbose,
5222 5222 status is also displayed for each bookmark like below::
5223 5223
5224 5224 BM1 01234567890a added
5225 5225 BM2 deleted
5226 5226 BM3 234567890abc advanced
5227 5227 BM4 34567890abcd diverged
5228 5228 BM5 4567890abcde changed
5229 5229
5230 5230 The action taken when pushing depends on the
5231 5231 status of each bookmark:
5232 5232
5233 5233 :``added``: push with ``-B`` will create it
5234 5234 :``deleted``: push with ``-B`` will delete it
5235 5235 :``advanced``: push will update it
5236 5236 :``diverged``: push with ``-B`` will update it
5237 5237 :``changed``: push with ``-B`` will update it
5238 5238
5239 5239 From the point of view of pushing behavior, bookmarks
5240 5240 existing only in the remote repository are treated as
5241 5241 ``deleted``, even if it is in fact added remotely.
5242 5242
5243 5243 Returns 0 if there are outgoing changes, 1 otherwise.
5244 5244 """
5245 5245 if opts.get('graph'):
5246 5246 cmdutil.checkunsupportedgraphflags([], opts)
5247 5247 o, other = hg._outgoing(ui, repo, dest, opts)
5248 5248 if not o:
5249 5249 cmdutil.outgoinghooks(ui, repo, other, opts, o)
5250 5250 return
5251 5251
5252 5252 revdag = cmdutil.graphrevs(repo, o, opts)
5253 5253 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
5254 5254 cmdutil.displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges)
5255 5255 cmdutil.outgoinghooks(ui, repo, other, opts, o)
5256 5256 return 0
5257 5257
5258 5258 if opts.get('bookmarks'):
5259 5259 dest = ui.expandpath(dest or 'default-push', dest or 'default')
5260 5260 dest, branches = hg.parseurl(dest, opts.get('branch'))
5261 5261 other = hg.peer(repo, opts, dest)
5262 5262 if 'bookmarks' not in other.listkeys('namespaces'):
5263 5263 ui.warn(_("remote doesn't support bookmarks\n"))
5264 5264 return 0
5265 5265 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
5266 5266 return bookmarks.outgoing(ui, repo, other)
5267 5267
5268 5268 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
5269 5269 try:
5270 5270 return hg.outgoing(ui, repo, dest, opts)
5271 5271 finally:
5272 5272 del repo._subtoppath
5273 5273
5274 5274 @command('parents',
5275 5275 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
5276 5276 ] + templateopts,
5277 5277 _('[-r REV] [FILE]'),
5278 5278 inferrepo=True)
5279 5279 def parents(ui, repo, file_=None, **opts):
5280 5280 """show the parents of the working directory or revision (DEPRECATED)
5281 5281
5282 5282 Print the working directory's parent revisions. If a revision is
5283 5283 given via -r/--rev, the parent of that revision will be printed.
5284 5284 If a file argument is given, the revision in which the file was
5285 5285 last changed (before the working directory revision or the
5286 5286 argument to --rev if given) is printed.
5287 5287
5288 5288 See :hg:`summary` and :hg:`help revsets` for related information.
5289 5289
5290 5290 Returns 0 on success.
5291 5291 """
5292 5292
5293 5293 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
5294 5294
5295 5295 if file_:
5296 5296 m = scmutil.match(ctx, (file_,), opts)
5297 5297 if m.anypats() or len(m.files()) != 1:
5298 5298 raise error.Abort(_('can only specify an explicit filename'))
5299 5299 file_ = m.files()[0]
5300 5300 filenodes = []
5301 5301 for cp in ctx.parents():
5302 5302 if not cp:
5303 5303 continue
5304 5304 try:
5305 5305 filenodes.append(cp.filenode(file_))
5306 5306 except error.LookupError:
5307 5307 pass
5308 5308 if not filenodes:
5309 5309 raise error.Abort(_("'%s' not found in manifest!") % file_)
5310 5310 p = []
5311 5311 for fn in filenodes:
5312 5312 fctx = repo.filectx(file_, fileid=fn)
5313 5313 p.append(fctx.node())
5314 5314 else:
5315 5315 p = [cp.node() for cp in ctx.parents()]
5316 5316
5317 5317 displayer = cmdutil.show_changeset(ui, repo, opts)
5318 5318 for n in p:
5319 5319 if n != nullid:
5320 5320 displayer.show(repo[n])
5321 5321 displayer.close()
5322 5322
5323 5323 @command('paths', [], _('[NAME]'), optionalrepo=True)
5324 5324 def paths(ui, repo, search=None):
5325 5325 """show aliases for remote repositories
5326 5326
5327 5327 Show definition of symbolic path name NAME. If no name is given,
5328 5328 show definition of all available names.
5329 5329
5330 5330 Option -q/--quiet suppresses all output when searching for NAME
5331 5331 and shows only the path names when listing all definitions.
5332 5332
5333 5333 Path names are defined in the [paths] section of your
5334 5334 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
5335 5335 repository, ``.hg/hgrc`` is used, too.
5336 5336
5337 5337 The path names ``default`` and ``default-push`` have a special
5338 5338 meaning. When performing a push or pull operation, they are used
5339 5339 as fallbacks if no location is specified on the command-line.
5340 5340 When ``default-push`` is set, it will be used for push and
5341 5341 ``default`` will be used for pull; otherwise ``default`` is used
5342 5342 as the fallback for both. When cloning a repository, the clone
5343 5343 source is written as ``default`` in ``.hg/hgrc``. Note that
5344 5344 ``default`` and ``default-push`` apply to all inbound (e.g.
5345 5345 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
5346 5346 :hg:`bundle`) operations.
5347 5347
5348 5348 See :hg:`help urls` for more information.
5349 5349
5350 5350 Returns 0 on success.
5351 5351 """
5352 5352 if search:
5353 5353 for name, path in sorted(ui.paths.iteritems()):
5354 5354 if name == search:
5355 5355 ui.status("%s\n" % util.hidepassword(path.loc))
5356 5356 return
5357 5357 if not ui.quiet:
5358 5358 ui.warn(_("not found!\n"))
5359 5359 return 1
5360 5360 else:
5361 5361 for name, path in sorted(ui.paths.iteritems()):
5362 5362 if ui.quiet:
5363 5363 ui.write("%s\n" % name)
5364 5364 else:
5365 5365 ui.write("%s = %s\n" % (name,
5366 5366 util.hidepassword(path.loc)))
5367 for subopt, value in sorted(path.suboptions.items()):
5368 ui.write('%s:%s = %s\n' % (name, subopt, value))
5367 5369
5368 5370 @command('phase',
5369 5371 [('p', 'public', False, _('set changeset phase to public')),
5370 5372 ('d', 'draft', False, _('set changeset phase to draft')),
5371 5373 ('s', 'secret', False, _('set changeset phase to secret')),
5372 5374 ('f', 'force', False, _('allow to move boundary backward')),
5373 5375 ('r', 'rev', [], _('target revision'), _('REV')),
5374 5376 ],
5375 5377 _('[-p|-d|-s] [-f] [-r] [REV...]'))
5376 5378 def phase(ui, repo, *revs, **opts):
5377 5379 """set or show the current phase name
5378 5380
5379 5381 With no argument, show the phase name of the current revision(s).
5380 5382
5381 5383 With one of -p/--public, -d/--draft or -s/--secret, change the
5382 5384 phase value of the specified revisions.
5383 5385
5384 5386 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
5385 5387 lower phase to an higher phase. Phases are ordered as follows::
5386 5388
5387 5389 public < draft < secret
5388 5390
5389 5391 Returns 0 on success, 1 if some phases could not be changed.
5390 5392
5391 5393 (For more information about the phases concept, see :hg:`help phases`.)
5392 5394 """
5393 5395 # search for a unique phase argument
5394 5396 targetphase = None
5395 5397 for idx, name in enumerate(phases.phasenames):
5396 5398 if opts[name]:
5397 5399 if targetphase is not None:
5398 5400 raise error.Abort(_('only one phase can be specified'))
5399 5401 targetphase = idx
5400 5402
5401 5403 # look for specified revision
5402 5404 revs = list(revs)
5403 5405 revs.extend(opts['rev'])
5404 5406 if not revs:
5405 5407 # display both parents as the second parent phase can influence
5406 5408 # the phase of a merge commit
5407 5409 revs = [c.rev() for c in repo[None].parents()]
5408 5410
5409 5411 revs = scmutil.revrange(repo, revs)
5410 5412
5411 5413 lock = None
5412 5414 ret = 0
5413 5415 if targetphase is None:
5414 5416 # display
5415 5417 for r in revs:
5416 5418 ctx = repo[r]
5417 5419 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
5418 5420 else:
5419 5421 tr = None
5420 5422 lock = repo.lock()
5421 5423 try:
5422 5424 tr = repo.transaction("phase")
5423 5425 # set phase
5424 5426 if not revs:
5425 5427 raise error.Abort(_('empty revision set'))
5426 5428 nodes = [repo[r].node() for r in revs]
5427 5429 # moving revision from public to draft may hide them
5428 5430 # We have to check result on an unfiltered repository
5429 5431 unfi = repo.unfiltered()
5430 5432 getphase = unfi._phasecache.phase
5431 5433 olddata = [getphase(unfi, r) for r in unfi]
5432 5434 phases.advanceboundary(repo, tr, targetphase, nodes)
5433 5435 if opts['force']:
5434 5436 phases.retractboundary(repo, tr, targetphase, nodes)
5435 5437 tr.close()
5436 5438 finally:
5437 5439 if tr is not None:
5438 5440 tr.release()
5439 5441 lock.release()
5440 5442 getphase = unfi._phasecache.phase
5441 5443 newdata = [getphase(unfi, r) for r in unfi]
5442 5444 changes = sum(newdata[r] != olddata[r] for r in unfi)
5443 5445 cl = unfi.changelog
5444 5446 rejected = [n for n in nodes
5445 5447 if newdata[cl.rev(n)] < targetphase]
5446 5448 if rejected:
5447 5449 ui.warn(_('cannot move %i changesets to a higher '
5448 5450 'phase, use --force\n') % len(rejected))
5449 5451 ret = 1
5450 5452 if changes:
5451 5453 msg = _('phase changed for %i changesets\n') % changes
5452 5454 if ret:
5453 5455 ui.status(msg)
5454 5456 else:
5455 5457 ui.note(msg)
5456 5458 else:
5457 5459 ui.warn(_('no phases changed\n'))
5458 5460 return ret
5459 5461
5460 5462 def postincoming(ui, repo, modheads, optupdate, checkout):
5461 5463 if modheads == 0:
5462 5464 return
5463 5465 if optupdate:
5464 5466 try:
5465 5467 brev = checkout
5466 5468 movemarkfrom = None
5467 5469 if not checkout:
5468 5470 updata = destutil.destupdate(repo)
5469 5471 checkout, movemarkfrom, brev = updata
5470 5472 ret = hg.update(repo, checkout)
5471 5473 except error.UpdateAbort as inst:
5472 5474 msg = _("not updating: %s") % str(inst)
5473 5475 hint = inst.hint
5474 5476 raise error.UpdateAbort(msg, hint=hint)
5475 5477 if not ret and not checkout:
5476 5478 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5477 5479 ui.status(_("updating bookmark %s\n") % repo._activebookmark)
5478 5480 return ret
5479 5481 if modheads > 1:
5480 5482 currentbranchheads = len(repo.branchheads())
5481 5483 if currentbranchheads == modheads:
5482 5484 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
5483 5485 elif currentbranchheads > 1:
5484 5486 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
5485 5487 "merge)\n"))
5486 5488 else:
5487 5489 ui.status(_("(run 'hg heads' to see heads)\n"))
5488 5490 else:
5489 5491 ui.status(_("(run 'hg update' to get a working copy)\n"))
5490 5492
5491 5493 @command('^pull',
5492 5494 [('u', 'update', None,
5493 5495 _('update to new branch head if changesets were pulled')),
5494 5496 ('f', 'force', None, _('run even when remote repository is unrelated')),
5495 5497 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
5496 5498 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
5497 5499 ('b', 'branch', [], _('a specific branch you would like to pull'),
5498 5500 _('BRANCH')),
5499 5501 ] + remoteopts,
5500 5502 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
5501 5503 def pull(ui, repo, source="default", **opts):
5502 5504 """pull changes from the specified source
5503 5505
5504 5506 Pull changes from a remote repository to a local one.
5505 5507
5506 5508 This finds all changes from the repository at the specified path
5507 5509 or URL and adds them to a local repository (the current one unless
5508 5510 -R is specified). By default, this does not update the copy of the
5509 5511 project in the working directory.
5510 5512
5511 5513 Use :hg:`incoming` if you want to see what would have been added
5512 5514 by a pull at the time you issued this command. If you then decide
5513 5515 to add those changes to the repository, you should use :hg:`pull
5514 5516 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
5515 5517
5516 5518 If SOURCE is omitted, the 'default' path will be used.
5517 5519 See :hg:`help urls` for more information.
5518 5520
5519 5521 Returns 0 on success, 1 if an update had unresolved files.
5520 5522 """
5521 5523 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
5522 5524 ui.status(_('pulling from %s\n') % util.hidepassword(source))
5523 5525 other = hg.peer(repo, opts, source)
5524 5526 try:
5525 5527 revs, checkout = hg.addbranchrevs(repo, other, branches,
5526 5528 opts.get('rev'))
5527 5529
5528 5530
5529 5531 pullopargs = {}
5530 5532 if opts.get('bookmark'):
5531 5533 if not revs:
5532 5534 revs = []
5533 5535 # The list of bookmark used here is not the one used to actually
5534 5536 # update the bookmark name. This can result in the revision pulled
5535 5537 # not ending up with the name of the bookmark because of a race
5536 5538 # condition on the server. (See issue 4689 for details)
5537 5539 remotebookmarks = other.listkeys('bookmarks')
5538 5540 pullopargs['remotebookmarks'] = remotebookmarks
5539 5541 for b in opts['bookmark']:
5540 5542 if b not in remotebookmarks:
5541 5543 raise error.Abort(_('remote bookmark %s not found!') % b)
5542 5544 revs.append(remotebookmarks[b])
5543 5545
5544 5546 if revs:
5545 5547 try:
5546 5548 # When 'rev' is a bookmark name, we cannot guarantee that it
5547 5549 # will be updated with that name because of a race condition
5548 5550 # server side. (See issue 4689 for details)
5549 5551 oldrevs = revs
5550 5552 revs = [] # actually, nodes
5551 5553 for r in oldrevs:
5552 5554 node = other.lookup(r)
5553 5555 revs.append(node)
5554 5556 if r == checkout:
5555 5557 checkout = node
5556 5558 except error.CapabilityError:
5557 5559 err = _("other repository doesn't support revision lookup, "
5558 5560 "so a rev cannot be specified.")
5559 5561 raise error.Abort(err)
5560 5562
5561 5563 pullopargs.update(opts.get('opargs', {}))
5562 5564 modheads = exchange.pull(repo, other, heads=revs,
5563 5565 force=opts.get('force'),
5564 5566 bookmarks=opts.get('bookmark', ()),
5565 5567 opargs=pullopargs).cgresult
5566 5568 if checkout:
5567 5569 checkout = str(repo.changelog.rev(checkout))
5568 5570 repo._subtoppath = source
5569 5571 try:
5570 5572 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
5571 5573
5572 5574 finally:
5573 5575 del repo._subtoppath
5574 5576
5575 5577 finally:
5576 5578 other.close()
5577 5579 return ret
5578 5580
5579 5581 @command('^push',
5580 5582 [('f', 'force', None, _('force push')),
5581 5583 ('r', 'rev', [],
5582 5584 _('a changeset intended to be included in the destination'),
5583 5585 _('REV')),
5584 5586 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
5585 5587 ('b', 'branch', [],
5586 5588 _('a specific branch you would like to push'), _('BRANCH')),
5587 5589 ('', 'new-branch', False, _('allow pushing a new branch')),
5588 5590 ] + remoteopts,
5589 5591 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
5590 5592 def push(ui, repo, dest=None, **opts):
5591 5593 """push changes to the specified destination
5592 5594
5593 5595 Push changesets from the local repository to the specified
5594 5596 destination.
5595 5597
5596 5598 This operation is symmetrical to pull: it is identical to a pull
5597 5599 in the destination repository from the current one.
5598 5600
5599 5601 By default, push will not allow creation of new heads at the
5600 5602 destination, since multiple heads would make it unclear which head
5601 5603 to use. In this situation, it is recommended to pull and merge
5602 5604 before pushing.
5603 5605
5604 5606 Use --new-branch if you want to allow push to create a new named
5605 5607 branch that is not present at the destination. This allows you to
5606 5608 only create a new branch without forcing other changes.
5607 5609
5608 5610 .. note::
5609 5611
5610 5612 Extra care should be taken with the -f/--force option,
5611 5613 which will push all new heads on all branches, an action which will
5612 5614 almost always cause confusion for collaborators.
5613 5615
5614 5616 If -r/--rev is used, the specified revision and all its ancestors
5615 5617 will be pushed to the remote repository.
5616 5618
5617 5619 If -B/--bookmark is used, the specified bookmarked revision, its
5618 5620 ancestors, and the bookmark will be pushed to the remote
5619 5621 repository.
5620 5622
5621 5623 Please see :hg:`help urls` for important details about ``ssh://``
5622 5624 URLs. If DESTINATION is omitted, a default path will be used.
5623 5625
5624 5626 Returns 0 if push was successful, 1 if nothing to push.
5625 5627 """
5626 5628
5627 5629 if opts.get('bookmark'):
5628 5630 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
5629 5631 for b in opts['bookmark']:
5630 5632 # translate -B options to -r so changesets get pushed
5631 5633 if b in repo._bookmarks:
5632 5634 opts.setdefault('rev', []).append(b)
5633 5635 else:
5634 5636 # if we try to push a deleted bookmark, translate it to null
5635 5637 # this lets simultaneous -r, -b options continue working
5636 5638 opts.setdefault('rev', []).append("null")
5637 5639
5638 5640 path = ui.paths.getpath(dest, default='default')
5639 5641 if not path:
5640 5642 raise error.Abort(_('default repository not configured!'),
5641 5643 hint=_('see the "path" section in "hg help config"'))
5642 5644 dest = path.pushloc or path.loc
5643 5645 branches = (path.branch, opts.get('branch') or [])
5644 5646 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
5645 5647 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
5646 5648 other = hg.peer(repo, opts, dest)
5647 5649
5648 5650 if revs:
5649 5651 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
5650 5652 if not revs:
5651 5653 raise error.Abort(_("specified revisions evaluate to an empty set"),
5652 5654 hint=_("use different revision arguments"))
5653 5655
5654 5656 repo._subtoppath = dest
5655 5657 try:
5656 5658 # push subrepos depth-first for coherent ordering
5657 5659 c = repo['']
5658 5660 subs = c.substate # only repos that are committed
5659 5661 for s in sorted(subs):
5660 5662 result = c.sub(s).push(opts)
5661 5663 if result == 0:
5662 5664 return not result
5663 5665 finally:
5664 5666 del repo._subtoppath
5665 5667 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
5666 5668 newbranch=opts.get('new_branch'),
5667 5669 bookmarks=opts.get('bookmark', ()),
5668 5670 opargs=opts.get('opargs'))
5669 5671
5670 5672 result = not pushop.cgresult
5671 5673
5672 5674 if pushop.bkresult is not None:
5673 5675 if pushop.bkresult == 2:
5674 5676 result = 2
5675 5677 elif not result and pushop.bkresult:
5676 5678 result = 2
5677 5679
5678 5680 return result
5679 5681
5680 5682 @command('recover', [])
5681 5683 def recover(ui, repo):
5682 5684 """roll back an interrupted transaction
5683 5685
5684 5686 Recover from an interrupted commit or pull.
5685 5687
5686 5688 This command tries to fix the repository status after an
5687 5689 interrupted operation. It should only be necessary when Mercurial
5688 5690 suggests it.
5689 5691
5690 5692 Returns 0 if successful, 1 if nothing to recover or verify fails.
5691 5693 """
5692 5694 if repo.recover():
5693 5695 return hg.verify(repo)
5694 5696 return 1
5695 5697
5696 5698 @command('^remove|rm',
5697 5699 [('A', 'after', None, _('record delete for missing files')),
5698 5700 ('f', 'force', None,
5699 5701 _('remove (and delete) file even if added or modified')),
5700 5702 ] + subrepoopts + walkopts,
5701 5703 _('[OPTION]... FILE...'),
5702 5704 inferrepo=True)
5703 5705 def remove(ui, repo, *pats, **opts):
5704 5706 """remove the specified files on the next commit
5705 5707
5706 5708 Schedule the indicated files for removal from the current branch.
5707 5709
5708 5710 This command schedules the files to be removed at the next commit.
5709 5711 To undo a remove before that, see :hg:`revert`. To undo added
5710 5712 files, see :hg:`forget`.
5711 5713
5712 5714 .. container:: verbose
5713 5715
5714 5716 -A/--after can be used to remove only files that have already
5715 5717 been deleted, -f/--force can be used to force deletion, and -Af
5716 5718 can be used to remove files from the next revision without
5717 5719 deleting them from the working directory.
5718 5720
5719 5721 The following table details the behavior of remove for different
5720 5722 file states (columns) and option combinations (rows). The file
5721 5723 states are Added [A], Clean [C], Modified [M] and Missing [!]
5722 5724 (as reported by :hg:`status`). The actions are Warn, Remove
5723 5725 (from branch) and Delete (from disk):
5724 5726
5725 5727 ========= == == == ==
5726 5728 opt/state A C M !
5727 5729 ========= == == == ==
5728 5730 none W RD W R
5729 5731 -f R RD RD R
5730 5732 -A W W W R
5731 5733 -Af R R R R
5732 5734 ========= == == == ==
5733 5735
5734 5736 Note that remove never deletes files in Added [A] state from the
5735 5737 working directory, not even if option --force is specified.
5736 5738
5737 5739 Returns 0 on success, 1 if any warnings encountered.
5738 5740 """
5739 5741
5740 5742 after, force = opts.get('after'), opts.get('force')
5741 5743 if not pats and not after:
5742 5744 raise error.Abort(_('no files specified'))
5743 5745
5744 5746 m = scmutil.match(repo[None], pats, opts)
5745 5747 subrepos = opts.get('subrepos')
5746 5748 return cmdutil.remove(ui, repo, m, "", after, force, subrepos)
5747 5749
5748 5750 @command('rename|move|mv',
5749 5751 [('A', 'after', None, _('record a rename that has already occurred')),
5750 5752 ('f', 'force', None, _('forcibly copy over an existing managed file')),
5751 5753 ] + walkopts + dryrunopts,
5752 5754 _('[OPTION]... SOURCE... DEST'))
5753 5755 def rename(ui, repo, *pats, **opts):
5754 5756 """rename files; equivalent of copy + remove
5755 5757
5756 5758 Mark dest as copies of sources; mark sources for deletion. If dest
5757 5759 is a directory, copies are put in that directory. If dest is a
5758 5760 file, there can only be one source.
5759 5761
5760 5762 By default, this command copies the contents of files as they
5761 5763 exist in the working directory. If invoked with -A/--after, the
5762 5764 operation is recorded, but no copying is performed.
5763 5765
5764 5766 This command takes effect at the next commit. To undo a rename
5765 5767 before that, see :hg:`revert`.
5766 5768
5767 5769 Returns 0 on success, 1 if errors are encountered.
5768 5770 """
5769 5771 wlock = repo.wlock(False)
5770 5772 try:
5771 5773 return cmdutil.copy(ui, repo, pats, opts, rename=True)
5772 5774 finally:
5773 5775 wlock.release()
5774 5776
5775 5777 @command('resolve',
5776 5778 [('a', 'all', None, _('select all unresolved files')),
5777 5779 ('l', 'list', None, _('list state of files needing merge')),
5778 5780 ('m', 'mark', None, _('mark files as resolved')),
5779 5781 ('u', 'unmark', None, _('mark files as unresolved')),
5780 5782 ('n', 'no-status', None, _('hide status prefix'))]
5781 5783 + mergetoolopts + walkopts + formatteropts,
5782 5784 _('[OPTION]... [FILE]...'),
5783 5785 inferrepo=True)
5784 5786 def resolve(ui, repo, *pats, **opts):
5785 5787 """redo merges or set/view the merge status of files
5786 5788
5787 5789 Merges with unresolved conflicts are often the result of
5788 5790 non-interactive merging using the ``internal:merge`` configuration
5789 5791 setting, or a command-line merge tool like ``diff3``. The resolve
5790 5792 command is used to manage the files involved in a merge, after
5791 5793 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
5792 5794 working directory must have two parents). See :hg:`help
5793 5795 merge-tools` for information on configuring merge tools.
5794 5796
5795 5797 The resolve command can be used in the following ways:
5796 5798
5797 5799 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
5798 5800 files, discarding any previous merge attempts. Re-merging is not
5799 5801 performed for files already marked as resolved. Use ``--all/-a``
5800 5802 to select all unresolved files. ``--tool`` can be used to specify
5801 5803 the merge tool used for the given files. It overrides the HGMERGE
5802 5804 environment variable and your configuration files. Previous file
5803 5805 contents are saved with a ``.orig`` suffix.
5804 5806
5805 5807 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
5806 5808 (e.g. after having manually fixed-up the files). The default is
5807 5809 to mark all unresolved files.
5808 5810
5809 5811 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
5810 5812 default is to mark all resolved files.
5811 5813
5812 5814 - :hg:`resolve -l`: list files which had or still have conflicts.
5813 5815 In the printed list, ``U`` = unresolved and ``R`` = resolved.
5814 5816
5815 5817 Note that Mercurial will not let you commit files with unresolved
5816 5818 merge conflicts. You must use :hg:`resolve -m ...` before you can
5817 5819 commit after a conflicting merge.
5818 5820
5819 5821 Returns 0 on success, 1 if any files fail a resolve attempt.
5820 5822 """
5821 5823
5822 5824 all, mark, unmark, show, nostatus = \
5823 5825 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
5824 5826
5825 5827 if (show and (mark or unmark)) or (mark and unmark):
5826 5828 raise error.Abort(_("too many options specified"))
5827 5829 if pats and all:
5828 5830 raise error.Abort(_("can't specify --all and patterns"))
5829 5831 if not (all or pats or show or mark or unmark):
5830 5832 raise error.Abort(_('no files or directories specified'),
5831 5833 hint=('use --all to re-merge all unresolved files'))
5832 5834
5833 5835 if show:
5834 5836 fm = ui.formatter('resolve', opts)
5835 5837 ms = mergemod.mergestate.read(repo)
5836 5838 m = scmutil.match(repo[None], pats, opts)
5837 5839 for f in ms:
5838 5840 if not m(f):
5839 5841 continue
5840 5842 l = 'resolve.' + {'u': 'unresolved', 'r': 'resolved',
5841 5843 'd': 'driverresolved'}[ms[f]]
5842 5844 fm.startitem()
5843 5845 fm.condwrite(not nostatus, 'status', '%s ', ms[f].upper(), label=l)
5844 5846 fm.write('path', '%s\n', f, label=l)
5845 5847 fm.end()
5846 5848 return 0
5847 5849
5848 5850 wlock = repo.wlock()
5849 5851 try:
5850 5852 ms = mergemod.mergestate.read(repo)
5851 5853
5852 5854 if not (ms.active() or repo.dirstate.p2() != nullid):
5853 5855 raise error.Abort(
5854 5856 _('resolve command not applicable when not merging'))
5855 5857
5856 5858 wctx = repo[None]
5857 5859
5858 5860 if ms.mergedriver and ms.mdstate() == 'u':
5859 5861 proceed = mergemod.driverpreprocess(repo, ms, wctx)
5860 5862 ms.commit()
5861 5863 # allow mark and unmark to go through
5862 5864 if not mark and not unmark and not proceed:
5863 5865 return 1
5864 5866
5865 5867 m = scmutil.match(wctx, pats, opts)
5866 5868 ret = 0
5867 5869 didwork = False
5868 5870 runconclude = False
5869 5871
5870 5872 tocomplete = []
5871 5873 for f in ms:
5872 5874 if not m(f):
5873 5875 continue
5874 5876
5875 5877 didwork = True
5876 5878
5877 5879 # don't let driver-resolved files be marked, and run the conclude
5878 5880 # step if asked to resolve
5879 5881 if ms[f] == "d":
5880 5882 exact = m.exact(f)
5881 5883 if mark:
5882 5884 if exact:
5883 5885 ui.warn(_('not marking %s as it is driver-resolved\n')
5884 5886 % f)
5885 5887 elif unmark:
5886 5888 if exact:
5887 5889 ui.warn(_('not unmarking %s as it is driver-resolved\n')
5888 5890 % f)
5889 5891 else:
5890 5892 runconclude = True
5891 5893 continue
5892 5894
5893 5895 if mark:
5894 5896 ms.mark(f, "r")
5895 5897 elif unmark:
5896 5898 ms.mark(f, "u")
5897 5899 else:
5898 5900 # backup pre-resolve (merge uses .orig for its own purposes)
5899 5901 a = repo.wjoin(f)
5900 5902 try:
5901 5903 util.copyfile(a, a + ".resolve")
5902 5904 except (IOError, OSError) as inst:
5903 5905 if inst.errno != errno.ENOENT:
5904 5906 raise
5905 5907
5906 5908 try:
5907 5909 # preresolve file
5908 5910 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
5909 5911 'resolve')
5910 5912 complete, r = ms.preresolve(f, wctx)
5911 5913 if not complete:
5912 5914 tocomplete.append(f)
5913 5915 elif r:
5914 5916 ret = 1
5915 5917 finally:
5916 5918 ui.setconfig('ui', 'forcemerge', '', 'resolve')
5917 5919 ms.commit()
5918 5920
5919 5921 # replace filemerge's .orig file with our resolve file, but only
5920 5922 # for merges that are complete
5921 5923 if complete:
5922 5924 try:
5923 5925 util.rename(a + ".resolve",
5924 5926 cmdutil.origpath(ui, repo, a))
5925 5927 except OSError as inst:
5926 5928 if inst.errno != errno.ENOENT:
5927 5929 raise
5928 5930
5929 5931 for f in tocomplete:
5930 5932 try:
5931 5933 # resolve file
5932 5934 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
5933 5935 'resolve')
5934 5936 r = ms.resolve(f, wctx)
5935 5937 if r:
5936 5938 ret = 1
5937 5939 finally:
5938 5940 ui.setconfig('ui', 'forcemerge', '', 'resolve')
5939 5941 ms.commit()
5940 5942
5941 5943 # replace filemerge's .orig file with our resolve file
5942 5944 a = repo.wjoin(f)
5943 5945 try:
5944 5946 util.rename(a + ".resolve", cmdutil.origpath(ui, repo, a))
5945 5947 except OSError as inst:
5946 5948 if inst.errno != errno.ENOENT:
5947 5949 raise
5948 5950
5949 5951 ms.commit()
5950 5952 ms.recordactions()
5951 5953
5952 5954 if not didwork and pats:
5953 5955 ui.warn(_("arguments do not match paths that need resolving\n"))
5954 5956 elif ms.mergedriver and ms.mdstate() != 's':
5955 5957 # run conclude step when either a driver-resolved file is requested
5956 5958 # or there are no driver-resolved files
5957 5959 # we can't use 'ret' to determine whether any files are unresolved
5958 5960 # because we might not have tried to resolve some
5959 5961 if ((runconclude or not list(ms.driverresolved()))
5960 5962 and not list(ms.unresolved())):
5961 5963 proceed = mergemod.driverconclude(repo, ms, wctx)
5962 5964 ms.commit()
5963 5965 if not proceed:
5964 5966 return 1
5965 5967
5966 5968 finally:
5967 5969 wlock.release()
5968 5970
5969 5971 # Nudge users into finishing an unfinished operation
5970 5972 unresolvedf = list(ms.unresolved())
5971 5973 driverresolvedf = list(ms.driverresolved())
5972 5974 if not unresolvedf and not driverresolvedf:
5973 5975 ui.status(_('(no more unresolved files)\n'))
5974 5976 elif not unresolvedf:
5975 5977 ui.status(_('(no more unresolved files -- '
5976 5978 'run "hg resolve --all" to conclude)\n'))
5977 5979
5978 5980 return ret
5979 5981
5980 5982 @command('revert',
5981 5983 [('a', 'all', None, _('revert all changes when no arguments given')),
5982 5984 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5983 5985 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5984 5986 ('C', 'no-backup', None, _('do not save backup copies of files')),
5985 5987 ('i', 'interactive', None,
5986 5988 _('interactively select the changes (EXPERIMENTAL)')),
5987 5989 ] + walkopts + dryrunopts,
5988 5990 _('[OPTION]... [-r REV] [NAME]...'))
5989 5991 def revert(ui, repo, *pats, **opts):
5990 5992 """restore files to their checkout state
5991 5993
5992 5994 .. note::
5993 5995
5994 5996 To check out earlier revisions, you should use :hg:`update REV`.
5995 5997 To cancel an uncommitted merge (and lose your changes),
5996 5998 use :hg:`update --clean .`.
5997 5999
5998 6000 With no revision specified, revert the specified files or directories
5999 6001 to the contents they had in the parent of the working directory.
6000 6002 This restores the contents of files to an unmodified
6001 6003 state and unschedules adds, removes, copies, and renames. If the
6002 6004 working directory has two parents, you must explicitly specify a
6003 6005 revision.
6004 6006
6005 6007 Using the -r/--rev or -d/--date options, revert the given files or
6006 6008 directories to their states as of a specific revision. Because
6007 6009 revert does not change the working directory parents, this will
6008 6010 cause these files to appear modified. This can be helpful to "back
6009 6011 out" some or all of an earlier change. See :hg:`backout` for a
6010 6012 related method.
6011 6013
6012 6014 Modified files are saved with a .orig suffix before reverting.
6013 6015 To disable these backups, use --no-backup.
6014 6016
6015 6017 See :hg:`help dates` for a list of formats valid for -d/--date.
6016 6018
6017 6019 See :hg:`help backout` for a way to reverse the effect of an
6018 6020 earlier changeset.
6019 6021
6020 6022 Returns 0 on success.
6021 6023 """
6022 6024
6023 6025 if opts.get("date"):
6024 6026 if opts.get("rev"):
6025 6027 raise error.Abort(_("you can't specify a revision and a date"))
6026 6028 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
6027 6029
6028 6030 parent, p2 = repo.dirstate.parents()
6029 6031 if not opts.get('rev') and p2 != nullid:
6030 6032 # revert after merge is a trap for new users (issue2915)
6031 6033 raise error.Abort(_('uncommitted merge with no revision specified'),
6032 6034 hint=_('use "hg update" or see "hg help revert"'))
6033 6035
6034 6036 ctx = scmutil.revsingle(repo, opts.get('rev'))
6035 6037
6036 6038 if (not (pats or opts.get('include') or opts.get('exclude') or
6037 6039 opts.get('all') or opts.get('interactive'))):
6038 6040 msg = _("no files or directories specified")
6039 6041 if p2 != nullid:
6040 6042 hint = _("uncommitted merge, use --all to discard all changes,"
6041 6043 " or 'hg update -C .' to abort the merge")
6042 6044 raise error.Abort(msg, hint=hint)
6043 6045 dirty = any(repo.status())
6044 6046 node = ctx.node()
6045 6047 if node != parent:
6046 6048 if dirty:
6047 6049 hint = _("uncommitted changes, use --all to discard all"
6048 6050 " changes, or 'hg update %s' to update") % ctx.rev()
6049 6051 else:
6050 6052 hint = _("use --all to revert all files,"
6051 6053 " or 'hg update %s' to update") % ctx.rev()
6052 6054 elif dirty:
6053 6055 hint = _("uncommitted changes, use --all to discard all changes")
6054 6056 else:
6055 6057 hint = _("use --all to revert all files")
6056 6058 raise error.Abort(msg, hint=hint)
6057 6059
6058 6060 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
6059 6061
6060 6062 @command('rollback', dryrunopts +
6061 6063 [('f', 'force', False, _('ignore safety measures'))])
6062 6064 def rollback(ui, repo, **opts):
6063 6065 """roll back the last transaction (DANGEROUS) (DEPRECATED)
6064 6066
6065 6067 Please use :hg:`commit --amend` instead of rollback to correct
6066 6068 mistakes in the last commit.
6067 6069
6068 6070 This command should be used with care. There is only one level of
6069 6071 rollback, and there is no way to undo a rollback. It will also
6070 6072 restore the dirstate at the time of the last transaction, losing
6071 6073 any dirstate changes since that time. This command does not alter
6072 6074 the working directory.
6073 6075
6074 6076 Transactions are used to encapsulate the effects of all commands
6075 6077 that create new changesets or propagate existing changesets into a
6076 6078 repository.
6077 6079
6078 6080 .. container:: verbose
6079 6081
6080 6082 For example, the following commands are transactional, and their
6081 6083 effects can be rolled back:
6082 6084
6083 6085 - commit
6084 6086 - import
6085 6087 - pull
6086 6088 - push (with this repository as the destination)
6087 6089 - unbundle
6088 6090
6089 6091 To avoid permanent data loss, rollback will refuse to rollback a
6090 6092 commit transaction if it isn't checked out. Use --force to
6091 6093 override this protection.
6092 6094
6093 6095 This command is not intended for use on public repositories. Once
6094 6096 changes are visible for pull by other users, rolling a transaction
6095 6097 back locally is ineffective (someone else may already have pulled
6096 6098 the changes). Furthermore, a race is possible with readers of the
6097 6099 repository; for example an in-progress pull from the repository
6098 6100 may fail if a rollback is performed.
6099 6101
6100 6102 Returns 0 on success, 1 if no rollback data is available.
6101 6103 """
6102 6104 return repo.rollback(dryrun=opts.get('dry_run'),
6103 6105 force=opts.get('force'))
6104 6106
6105 6107 @command('root', [])
6106 6108 def root(ui, repo):
6107 6109 """print the root (top) of the current working directory
6108 6110
6109 6111 Print the root directory of the current repository.
6110 6112
6111 6113 Returns 0 on success.
6112 6114 """
6113 6115 ui.write(repo.root + "\n")
6114 6116
6115 6117 @command('^serve',
6116 6118 [('A', 'accesslog', '', _('name of access log file to write to'),
6117 6119 _('FILE')),
6118 6120 ('d', 'daemon', None, _('run server in background')),
6119 6121 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('FILE')),
6120 6122 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
6121 6123 # use string type, then we can check if something was passed
6122 6124 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
6123 6125 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
6124 6126 _('ADDR')),
6125 6127 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
6126 6128 _('PREFIX')),
6127 6129 ('n', 'name', '',
6128 6130 _('name to show in web pages (default: working directory)'), _('NAME')),
6129 6131 ('', 'web-conf', '',
6130 6132 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
6131 6133 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
6132 6134 _('FILE')),
6133 6135 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
6134 6136 ('', 'stdio', None, _('for remote clients')),
6135 6137 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
6136 6138 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
6137 6139 ('', 'style', '', _('template style to use'), _('STYLE')),
6138 6140 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
6139 6141 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
6140 6142 _('[OPTION]...'),
6141 6143 optionalrepo=True)
6142 6144 def serve(ui, repo, **opts):
6143 6145 """start stand-alone webserver
6144 6146
6145 6147 Start a local HTTP repository browser and pull server. You can use
6146 6148 this for ad-hoc sharing and browsing of repositories. It is
6147 6149 recommended to use a real web server to serve a repository for
6148 6150 longer periods of time.
6149 6151
6150 6152 Please note that the server does not implement access control.
6151 6153 This means that, by default, anybody can read from the server and
6152 6154 nobody can write to it by default. Set the ``web.allow_push``
6153 6155 option to ``*`` to allow everybody to push to the server. You
6154 6156 should use a real web server if you need to authenticate users.
6155 6157
6156 6158 By default, the server logs accesses to stdout and errors to
6157 6159 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
6158 6160 files.
6159 6161
6160 6162 To have the server choose a free port number to listen on, specify
6161 6163 a port number of 0; in this case, the server will print the port
6162 6164 number it uses.
6163 6165
6164 6166 Returns 0 on success.
6165 6167 """
6166 6168
6167 6169 if opts["stdio"] and opts["cmdserver"]:
6168 6170 raise error.Abort(_("cannot use --stdio with --cmdserver"))
6169 6171
6170 6172 if opts["stdio"]:
6171 6173 if repo is None:
6172 6174 raise error.RepoError(_("there is no Mercurial repository here"
6173 6175 " (.hg not found)"))
6174 6176 s = sshserver.sshserver(ui, repo)
6175 6177 s.serve_forever()
6176 6178
6177 6179 if opts["cmdserver"]:
6178 6180 import commandserver
6179 6181 service = commandserver.createservice(ui, repo, opts)
6180 6182 else:
6181 6183 service = hgweb.createservice(ui, repo, opts)
6182 6184 return cmdutil.service(opts, initfn=service.init, runfn=service.run)
6183 6185
6184 6186 @command('^status|st',
6185 6187 [('A', 'all', None, _('show status of all files')),
6186 6188 ('m', 'modified', None, _('show only modified files')),
6187 6189 ('a', 'added', None, _('show only added files')),
6188 6190 ('r', 'removed', None, _('show only removed files')),
6189 6191 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
6190 6192 ('c', 'clean', None, _('show only files without changes')),
6191 6193 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
6192 6194 ('i', 'ignored', None, _('show only ignored files')),
6193 6195 ('n', 'no-status', None, _('hide status prefix')),
6194 6196 ('C', 'copies', None, _('show source of copied files')),
6195 6197 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
6196 6198 ('', 'rev', [], _('show difference from revision'), _('REV')),
6197 6199 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
6198 6200 ] + walkopts + subrepoopts + formatteropts,
6199 6201 _('[OPTION]... [FILE]...'),
6200 6202 inferrepo=True)
6201 6203 def status(ui, repo, *pats, **opts):
6202 6204 """show changed files in the working directory
6203 6205
6204 6206 Show status of files in the repository. If names are given, only
6205 6207 files that match are shown. Files that are clean or ignored or
6206 6208 the source of a copy/move operation, are not listed unless
6207 6209 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
6208 6210 Unless options described with "show only ..." are given, the
6209 6211 options -mardu are used.
6210 6212
6211 6213 Option -q/--quiet hides untracked (unknown and ignored) files
6212 6214 unless explicitly requested with -u/--unknown or -i/--ignored.
6213 6215
6214 6216 .. note::
6215 6217
6216 6218 status may appear to disagree with diff if permissions have
6217 6219 changed or a merge has occurred. The standard diff format does
6218 6220 not report permission changes and diff only reports changes
6219 6221 relative to one merge parent.
6220 6222
6221 6223 If one revision is given, it is used as the base revision.
6222 6224 If two revisions are given, the differences between them are
6223 6225 shown. The --change option can also be used as a shortcut to list
6224 6226 the changed files of a revision from its first parent.
6225 6227
6226 6228 The codes used to show the status of files are::
6227 6229
6228 6230 M = modified
6229 6231 A = added
6230 6232 R = removed
6231 6233 C = clean
6232 6234 ! = missing (deleted by non-hg command, but still tracked)
6233 6235 ? = not tracked
6234 6236 I = ignored
6235 6237 = origin of the previous file (with --copies)
6236 6238
6237 6239 .. container:: verbose
6238 6240
6239 6241 Examples:
6240 6242
6241 6243 - show changes in the working directory relative to a
6242 6244 changeset::
6243 6245
6244 6246 hg status --rev 9353
6245 6247
6246 6248 - show changes in the working directory relative to the
6247 6249 current directory (see :hg:`help patterns` for more information)::
6248 6250
6249 6251 hg status re:
6250 6252
6251 6253 - show all changes including copies in an existing changeset::
6252 6254
6253 6255 hg status --copies --change 9353
6254 6256
6255 6257 - get a NUL separated list of added files, suitable for xargs::
6256 6258
6257 6259 hg status -an0
6258 6260
6259 6261 Returns 0 on success.
6260 6262 """
6261 6263
6262 6264 revs = opts.get('rev')
6263 6265 change = opts.get('change')
6264 6266
6265 6267 if revs and change:
6266 6268 msg = _('cannot specify --rev and --change at the same time')
6267 6269 raise error.Abort(msg)
6268 6270 elif change:
6269 6271 node2 = scmutil.revsingle(repo, change, None).node()
6270 6272 node1 = repo[node2].p1().node()
6271 6273 else:
6272 6274 node1, node2 = scmutil.revpair(repo, revs)
6273 6275
6274 6276 if pats:
6275 6277 cwd = repo.getcwd()
6276 6278 else:
6277 6279 cwd = ''
6278 6280
6279 6281 if opts.get('print0'):
6280 6282 end = '\0'
6281 6283 else:
6282 6284 end = '\n'
6283 6285 copy = {}
6284 6286 states = 'modified added removed deleted unknown ignored clean'.split()
6285 6287 show = [k for k in states if opts.get(k)]
6286 6288 if opts.get('all'):
6287 6289 show += ui.quiet and (states[:4] + ['clean']) or states
6288 6290 if not show:
6289 6291 if ui.quiet:
6290 6292 show = states[:4]
6291 6293 else:
6292 6294 show = states[:5]
6293 6295
6294 6296 m = scmutil.match(repo[node2], pats, opts)
6295 6297 stat = repo.status(node1, node2, m,
6296 6298 'ignored' in show, 'clean' in show, 'unknown' in show,
6297 6299 opts.get('subrepos'))
6298 6300 changestates = zip(states, 'MAR!?IC', stat)
6299 6301
6300 6302 if (opts.get('all') or opts.get('copies')
6301 6303 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
6302 6304 copy = copies.pathcopies(repo[node1], repo[node2], m)
6303 6305
6304 6306 fm = ui.formatter('status', opts)
6305 6307 fmt = '%s' + end
6306 6308 showchar = not opts.get('no_status')
6307 6309
6308 6310 for state, char, files in changestates:
6309 6311 if state in show:
6310 6312 label = 'status.' + state
6311 6313 for f in files:
6312 6314 fm.startitem()
6313 6315 fm.condwrite(showchar, 'status', '%s ', char, label=label)
6314 6316 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
6315 6317 if f in copy:
6316 6318 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
6317 6319 label='status.copied')
6318 6320 fm.end()
6319 6321
6320 6322 @command('^summary|sum',
6321 6323 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
6322 6324 def summary(ui, repo, **opts):
6323 6325 """summarize working directory state
6324 6326
6325 6327 This generates a brief summary of the working directory state,
6326 6328 including parents, branch, commit status, phase and available updates.
6327 6329
6328 6330 With the --remote option, this will check the default paths for
6329 6331 incoming and outgoing changes. This can be time-consuming.
6330 6332
6331 6333 Returns 0 on success.
6332 6334 """
6333 6335
6334 6336 ctx = repo[None]
6335 6337 parents = ctx.parents()
6336 6338 pnode = parents[0].node()
6337 6339 marks = []
6338 6340
6339 6341 for p in parents:
6340 6342 # label with log.changeset (instead of log.parent) since this
6341 6343 # shows a working directory parent *changeset*:
6342 6344 # i18n: column positioning for "hg summary"
6343 6345 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
6344 6346 label='log.changeset changeset.%s' % p.phasestr())
6345 6347 ui.write(' '.join(p.tags()), label='log.tag')
6346 6348 if p.bookmarks():
6347 6349 marks.extend(p.bookmarks())
6348 6350 if p.rev() == -1:
6349 6351 if not len(repo):
6350 6352 ui.write(_(' (empty repository)'))
6351 6353 else:
6352 6354 ui.write(_(' (no revision checked out)'))
6353 6355 ui.write('\n')
6354 6356 if p.description():
6355 6357 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
6356 6358 label='log.summary')
6357 6359
6358 6360 branch = ctx.branch()
6359 6361 bheads = repo.branchheads(branch)
6360 6362 # i18n: column positioning for "hg summary"
6361 6363 m = _('branch: %s\n') % branch
6362 6364 if branch != 'default':
6363 6365 ui.write(m, label='log.branch')
6364 6366 else:
6365 6367 ui.status(m, label='log.branch')
6366 6368
6367 6369 if marks:
6368 6370 active = repo._activebookmark
6369 6371 # i18n: column positioning for "hg summary"
6370 6372 ui.write(_('bookmarks:'), label='log.bookmark')
6371 6373 if active is not None:
6372 6374 if active in marks:
6373 6375 ui.write(' *' + active, label=activebookmarklabel)
6374 6376 marks.remove(active)
6375 6377 else:
6376 6378 ui.write(' [%s]' % active, label=activebookmarklabel)
6377 6379 for m in marks:
6378 6380 ui.write(' ' + m, label='log.bookmark')
6379 6381 ui.write('\n', label='log.bookmark')
6380 6382
6381 6383 status = repo.status(unknown=True)
6382 6384
6383 6385 c = repo.dirstate.copies()
6384 6386 copied, renamed = [], []
6385 6387 for d, s in c.iteritems():
6386 6388 if s in status.removed:
6387 6389 status.removed.remove(s)
6388 6390 renamed.append(d)
6389 6391 else:
6390 6392 copied.append(d)
6391 6393 if d in status.added:
6392 6394 status.added.remove(d)
6393 6395
6394 6396 try:
6395 6397 ms = mergemod.mergestate.read(repo)
6396 6398 except error.UnsupportedMergeRecords as e:
6397 6399 s = ' '.join(e.recordtypes)
6398 6400 ui.warn(
6399 6401 _('warning: merge state has unsupported record types: %s\n') % s)
6400 6402 unresolved = 0
6401 6403 else:
6402 6404 unresolved = [f for f in ms if ms[f] == 'u']
6403 6405
6404 6406 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
6405 6407
6406 6408 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
6407 6409 (ui.label(_('%d added'), 'status.added'), status.added),
6408 6410 (ui.label(_('%d removed'), 'status.removed'), status.removed),
6409 6411 (ui.label(_('%d renamed'), 'status.copied'), renamed),
6410 6412 (ui.label(_('%d copied'), 'status.copied'), copied),
6411 6413 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
6412 6414 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
6413 6415 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
6414 6416 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
6415 6417 t = []
6416 6418 for l, s in labels:
6417 6419 if s:
6418 6420 t.append(l % len(s))
6419 6421
6420 6422 t = ', '.join(t)
6421 6423 cleanworkdir = False
6422 6424
6423 6425 if repo.vfs.exists('graftstate'):
6424 6426 t += _(' (graft in progress)')
6425 6427 if repo.vfs.exists('updatestate'):
6426 6428 t += _(' (interrupted update)')
6427 6429 elif len(parents) > 1:
6428 6430 t += _(' (merge)')
6429 6431 elif branch != parents[0].branch():
6430 6432 t += _(' (new branch)')
6431 6433 elif (parents[0].closesbranch() and
6432 6434 pnode in repo.branchheads(branch, closed=True)):
6433 6435 t += _(' (head closed)')
6434 6436 elif not (status.modified or status.added or status.removed or renamed or
6435 6437 copied or subs):
6436 6438 t += _(' (clean)')
6437 6439 cleanworkdir = True
6438 6440 elif pnode not in bheads:
6439 6441 t += _(' (new branch head)')
6440 6442
6441 6443 if parents:
6442 6444 pendingphase = max(p.phase() for p in parents)
6443 6445 else:
6444 6446 pendingphase = phases.public
6445 6447
6446 6448 if pendingphase > phases.newcommitphase(ui):
6447 6449 t += ' (%s)' % phases.phasenames[pendingphase]
6448 6450
6449 6451 if cleanworkdir:
6450 6452 # i18n: column positioning for "hg summary"
6451 6453 ui.status(_('commit: %s\n') % t.strip())
6452 6454 else:
6453 6455 # i18n: column positioning for "hg summary"
6454 6456 ui.write(_('commit: %s\n') % t.strip())
6455 6457
6456 6458 # all ancestors of branch heads - all ancestors of parent = new csets
6457 6459 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
6458 6460 bheads))
6459 6461
6460 6462 if new == 0:
6461 6463 # i18n: column positioning for "hg summary"
6462 6464 ui.status(_('update: (current)\n'))
6463 6465 elif pnode not in bheads:
6464 6466 # i18n: column positioning for "hg summary"
6465 6467 ui.write(_('update: %d new changesets (update)\n') % new)
6466 6468 else:
6467 6469 # i18n: column positioning for "hg summary"
6468 6470 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
6469 6471 (new, len(bheads)))
6470 6472
6471 6473 t = []
6472 6474 draft = len(repo.revs('draft()'))
6473 6475 if draft:
6474 6476 t.append(_('%d draft') % draft)
6475 6477 secret = len(repo.revs('secret()'))
6476 6478 if secret:
6477 6479 t.append(_('%d secret') % secret)
6478 6480
6479 6481 if draft or secret:
6480 6482 ui.status(_('phases: %s\n') % ', '.join(t))
6481 6483
6482 6484 cmdutil.summaryhooks(ui, repo)
6483 6485
6484 6486 if opts.get('remote'):
6485 6487 needsincoming, needsoutgoing = True, True
6486 6488 else:
6487 6489 needsincoming, needsoutgoing = False, False
6488 6490 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
6489 6491 if i:
6490 6492 needsincoming = True
6491 6493 if o:
6492 6494 needsoutgoing = True
6493 6495 if not needsincoming and not needsoutgoing:
6494 6496 return
6495 6497
6496 6498 def getincoming():
6497 6499 source, branches = hg.parseurl(ui.expandpath('default'))
6498 6500 sbranch = branches[0]
6499 6501 try:
6500 6502 other = hg.peer(repo, {}, source)
6501 6503 except error.RepoError:
6502 6504 if opts.get('remote'):
6503 6505 raise
6504 6506 return source, sbranch, None, None, None
6505 6507 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
6506 6508 if revs:
6507 6509 revs = [other.lookup(rev) for rev in revs]
6508 6510 ui.debug('comparing with %s\n' % util.hidepassword(source))
6509 6511 repo.ui.pushbuffer()
6510 6512 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
6511 6513 repo.ui.popbuffer()
6512 6514 return source, sbranch, other, commoninc, commoninc[1]
6513 6515
6514 6516 if needsincoming:
6515 6517 source, sbranch, sother, commoninc, incoming = getincoming()
6516 6518 else:
6517 6519 source = sbranch = sother = commoninc = incoming = None
6518 6520
6519 6521 def getoutgoing():
6520 6522 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
6521 6523 dbranch = branches[0]
6522 6524 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
6523 6525 if source != dest:
6524 6526 try:
6525 6527 dother = hg.peer(repo, {}, dest)
6526 6528 except error.RepoError:
6527 6529 if opts.get('remote'):
6528 6530 raise
6529 6531 return dest, dbranch, None, None
6530 6532 ui.debug('comparing with %s\n' % util.hidepassword(dest))
6531 6533 elif sother is None:
6532 6534 # there is no explicit destination peer, but source one is invalid
6533 6535 return dest, dbranch, None, None
6534 6536 else:
6535 6537 dother = sother
6536 6538 if (source != dest or (sbranch is not None and sbranch != dbranch)):
6537 6539 common = None
6538 6540 else:
6539 6541 common = commoninc
6540 6542 if revs:
6541 6543 revs = [repo.lookup(rev) for rev in revs]
6542 6544 repo.ui.pushbuffer()
6543 6545 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
6544 6546 commoninc=common)
6545 6547 repo.ui.popbuffer()
6546 6548 return dest, dbranch, dother, outgoing
6547 6549
6548 6550 if needsoutgoing:
6549 6551 dest, dbranch, dother, outgoing = getoutgoing()
6550 6552 else:
6551 6553 dest = dbranch = dother = outgoing = None
6552 6554
6553 6555 if opts.get('remote'):
6554 6556 t = []
6555 6557 if incoming:
6556 6558 t.append(_('1 or more incoming'))
6557 6559 o = outgoing.missing
6558 6560 if o:
6559 6561 t.append(_('%d outgoing') % len(o))
6560 6562 other = dother or sother
6561 6563 if 'bookmarks' in other.listkeys('namespaces'):
6562 6564 counts = bookmarks.summary(repo, other)
6563 6565 if counts[0] > 0:
6564 6566 t.append(_('%d incoming bookmarks') % counts[0])
6565 6567 if counts[1] > 0:
6566 6568 t.append(_('%d outgoing bookmarks') % counts[1])
6567 6569
6568 6570 if t:
6569 6571 # i18n: column positioning for "hg summary"
6570 6572 ui.write(_('remote: %s\n') % (', '.join(t)))
6571 6573 else:
6572 6574 # i18n: column positioning for "hg summary"
6573 6575 ui.status(_('remote: (synced)\n'))
6574 6576
6575 6577 cmdutil.summaryremotehooks(ui, repo, opts,
6576 6578 ((source, sbranch, sother, commoninc),
6577 6579 (dest, dbranch, dother, outgoing)))
6578 6580
6579 6581 @command('tag',
6580 6582 [('f', 'force', None, _('force tag')),
6581 6583 ('l', 'local', None, _('make the tag local')),
6582 6584 ('r', 'rev', '', _('revision to tag'), _('REV')),
6583 6585 ('', 'remove', None, _('remove a tag')),
6584 6586 # -l/--local is already there, commitopts cannot be used
6585 6587 ('e', 'edit', None, _('invoke editor on commit messages')),
6586 6588 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
6587 6589 ] + commitopts2,
6588 6590 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
6589 6591 def tag(ui, repo, name1, *names, **opts):
6590 6592 """add one or more tags for the current or given revision
6591 6593
6592 6594 Name a particular revision using <name>.
6593 6595
6594 6596 Tags are used to name particular revisions of the repository and are
6595 6597 very useful to compare different revisions, to go back to significant
6596 6598 earlier versions or to mark branch points as releases, etc. Changing
6597 6599 an existing tag is normally disallowed; use -f/--force to override.
6598 6600
6599 6601 If no revision is given, the parent of the working directory is
6600 6602 used.
6601 6603
6602 6604 To facilitate version control, distribution, and merging of tags,
6603 6605 they are stored as a file named ".hgtags" which is managed similarly
6604 6606 to other project files and can be hand-edited if necessary. This
6605 6607 also means that tagging creates a new commit. The file
6606 6608 ".hg/localtags" is used for local tags (not shared among
6607 6609 repositories).
6608 6610
6609 6611 Tag commits are usually made at the head of a branch. If the parent
6610 6612 of the working directory is not a branch head, :hg:`tag` aborts; use
6611 6613 -f/--force to force the tag commit to be based on a non-head
6612 6614 changeset.
6613 6615
6614 6616 See :hg:`help dates` for a list of formats valid for -d/--date.
6615 6617
6616 6618 Since tag names have priority over branch names during revision
6617 6619 lookup, using an existing branch name as a tag name is discouraged.
6618 6620
6619 6621 Returns 0 on success.
6620 6622 """
6621 6623 wlock = lock = None
6622 6624 try:
6623 6625 wlock = repo.wlock()
6624 6626 lock = repo.lock()
6625 6627 rev_ = "."
6626 6628 names = [t.strip() for t in (name1,) + names]
6627 6629 if len(names) != len(set(names)):
6628 6630 raise error.Abort(_('tag names must be unique'))
6629 6631 for n in names:
6630 6632 scmutil.checknewlabel(repo, n, 'tag')
6631 6633 if not n:
6632 6634 raise error.Abort(_('tag names cannot consist entirely of '
6633 6635 'whitespace'))
6634 6636 if opts.get('rev') and opts.get('remove'):
6635 6637 raise error.Abort(_("--rev and --remove are incompatible"))
6636 6638 if opts.get('rev'):
6637 6639 rev_ = opts['rev']
6638 6640 message = opts.get('message')
6639 6641 if opts.get('remove'):
6640 6642 if opts.get('local'):
6641 6643 expectedtype = 'local'
6642 6644 else:
6643 6645 expectedtype = 'global'
6644 6646
6645 6647 for n in names:
6646 6648 if not repo.tagtype(n):
6647 6649 raise error.Abort(_("tag '%s' does not exist") % n)
6648 6650 if repo.tagtype(n) != expectedtype:
6649 6651 if expectedtype == 'global':
6650 6652 raise error.Abort(_("tag '%s' is not a global tag") % n)
6651 6653 else:
6652 6654 raise error.Abort(_("tag '%s' is not a local tag") % n)
6653 6655 rev_ = 'null'
6654 6656 if not message:
6655 6657 # we don't translate commit messages
6656 6658 message = 'Removed tag %s' % ', '.join(names)
6657 6659 elif not opts.get('force'):
6658 6660 for n in names:
6659 6661 if n in repo.tags():
6660 6662 raise error.Abort(_("tag '%s' already exists "
6661 6663 "(use -f to force)") % n)
6662 6664 if not opts.get('local'):
6663 6665 p1, p2 = repo.dirstate.parents()
6664 6666 if p2 != nullid:
6665 6667 raise error.Abort(_('uncommitted merge'))
6666 6668 bheads = repo.branchheads()
6667 6669 if not opts.get('force') and bheads and p1 not in bheads:
6668 6670 raise error.Abort(_('not at a branch head (use -f to force)'))
6669 6671 r = scmutil.revsingle(repo, rev_).node()
6670 6672
6671 6673 if not message:
6672 6674 # we don't translate commit messages
6673 6675 message = ('Added tag %s for changeset %s' %
6674 6676 (', '.join(names), short(r)))
6675 6677
6676 6678 date = opts.get('date')
6677 6679 if date:
6678 6680 date = util.parsedate(date)
6679 6681
6680 6682 if opts.get('remove'):
6681 6683 editform = 'tag.remove'
6682 6684 else:
6683 6685 editform = 'tag.add'
6684 6686 editor = cmdutil.getcommiteditor(editform=editform, **opts)
6685 6687
6686 6688 # don't allow tagging the null rev
6687 6689 if (not opts.get('remove') and
6688 6690 scmutil.revsingle(repo, rev_).rev() == nullrev):
6689 6691 raise error.Abort(_("cannot tag null revision"))
6690 6692
6691 6693 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date,
6692 6694 editor=editor)
6693 6695 finally:
6694 6696 release(lock, wlock)
6695 6697
6696 6698 @command('tags', formatteropts, '')
6697 6699 def tags(ui, repo, **opts):
6698 6700 """list repository tags
6699 6701
6700 6702 This lists both regular and local tags. When the -v/--verbose
6701 6703 switch is used, a third column "local" is printed for local tags.
6702 6704
6703 6705 Returns 0 on success.
6704 6706 """
6705 6707
6706 6708 fm = ui.formatter('tags', opts)
6707 6709 hexfunc = fm.hexfunc
6708 6710 tagtype = ""
6709 6711
6710 6712 for t, n in reversed(repo.tagslist()):
6711 6713 hn = hexfunc(n)
6712 6714 label = 'tags.normal'
6713 6715 tagtype = ''
6714 6716 if repo.tagtype(t) == 'local':
6715 6717 label = 'tags.local'
6716 6718 tagtype = 'local'
6717 6719
6718 6720 fm.startitem()
6719 6721 fm.write('tag', '%s', t, label=label)
6720 6722 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
6721 6723 fm.condwrite(not ui.quiet, 'rev node', fmt,
6722 6724 repo.changelog.rev(n), hn, label=label)
6723 6725 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
6724 6726 tagtype, label=label)
6725 6727 fm.plain('\n')
6726 6728 fm.end()
6727 6729
6728 6730 @command('tip',
6729 6731 [('p', 'patch', None, _('show patch')),
6730 6732 ('g', 'git', None, _('use git extended diff format')),
6731 6733 ] + templateopts,
6732 6734 _('[-p] [-g]'))
6733 6735 def tip(ui, repo, **opts):
6734 6736 """show the tip revision (DEPRECATED)
6735 6737
6736 6738 The tip revision (usually just called the tip) is the changeset
6737 6739 most recently added to the repository (and therefore the most
6738 6740 recently changed head).
6739 6741
6740 6742 If you have just made a commit, that commit will be the tip. If
6741 6743 you have just pulled changes from another repository, the tip of
6742 6744 that repository becomes the current tip. The "tip" tag is special
6743 6745 and cannot be renamed or assigned to a different changeset.
6744 6746
6745 6747 This command is deprecated, please use :hg:`heads` instead.
6746 6748
6747 6749 Returns 0 on success.
6748 6750 """
6749 6751 displayer = cmdutil.show_changeset(ui, repo, opts)
6750 6752 displayer.show(repo['tip'])
6751 6753 displayer.close()
6752 6754
6753 6755 @command('unbundle',
6754 6756 [('u', 'update', None,
6755 6757 _('update to new branch head if changesets were unbundled'))],
6756 6758 _('[-u] FILE...'))
6757 6759 def unbundle(ui, repo, fname1, *fnames, **opts):
6758 6760 """apply one or more changegroup files
6759 6761
6760 6762 Apply one or more compressed changegroup files generated by the
6761 6763 bundle command.
6762 6764
6763 6765 Returns 0 on success, 1 if an update has unresolved files.
6764 6766 """
6765 6767 fnames = (fname1,) + fnames
6766 6768
6767 6769 lock = repo.lock()
6768 6770 try:
6769 6771 for fname in fnames:
6770 6772 f = hg.openpath(ui, fname)
6771 6773 gen = exchange.readbundle(ui, f, fname)
6772 6774 if isinstance(gen, bundle2.unbundle20):
6773 6775 tr = repo.transaction('unbundle')
6774 6776 try:
6775 6777 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
6776 6778 url='bundle:' + fname)
6777 6779 tr.close()
6778 6780 except error.BundleUnknownFeatureError as exc:
6779 6781 raise error.Abort(_('%s: unknown bundle feature, %s')
6780 6782 % (fname, exc),
6781 6783 hint=_("see https://mercurial-scm.org/"
6782 6784 "wiki/BundleFeature for more "
6783 6785 "information"))
6784 6786 finally:
6785 6787 if tr:
6786 6788 tr.release()
6787 6789 changes = [r.get('return', 0)
6788 6790 for r in op.records['changegroup']]
6789 6791 modheads = changegroup.combineresults(changes)
6790 6792 elif isinstance(gen, streamclone.streamcloneapplier):
6791 6793 raise error.Abort(
6792 6794 _('packed bundles cannot be applied with '
6793 6795 '"hg unbundle"'),
6794 6796 hint=_('use "hg debugapplystreamclonebundle"'))
6795 6797 else:
6796 6798 modheads = gen.apply(repo, 'unbundle', 'bundle:' + fname)
6797 6799 finally:
6798 6800 lock.release()
6799 6801
6800 6802 return postincoming(ui, repo, modheads, opts.get('update'), None)
6801 6803
6802 6804 @command('^update|up|checkout|co',
6803 6805 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
6804 6806 ('c', 'check', None,
6805 6807 _('update across branches if no uncommitted changes')),
6806 6808 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
6807 6809 ('r', 'rev', '', _('revision'), _('REV'))
6808 6810 ] + mergetoolopts,
6809 6811 _('[-c] [-C] [-d DATE] [[-r] REV]'))
6810 6812 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
6811 6813 tool=None):
6812 6814 """update working directory (or switch revisions)
6813 6815
6814 6816 Update the repository's working directory to the specified
6815 6817 changeset. If no changeset is specified, update to the tip of the
6816 6818 current named branch and move the active bookmark (see :hg:`help
6817 6819 bookmarks`).
6818 6820
6819 6821 Update sets the working directory's parent revision to the specified
6820 6822 changeset (see :hg:`help parents`).
6821 6823
6822 6824 If the changeset is not a descendant or ancestor of the working
6823 6825 directory's parent, the update is aborted. With the -c/--check
6824 6826 option, the working directory is checked for uncommitted changes; if
6825 6827 none are found, the working directory is updated to the specified
6826 6828 changeset.
6827 6829
6828 6830 .. container:: verbose
6829 6831
6830 6832 The following rules apply when the working directory contains
6831 6833 uncommitted changes:
6832 6834
6833 6835 1. If neither -c/--check nor -C/--clean is specified, and if
6834 6836 the requested changeset is an ancestor or descendant of
6835 6837 the working directory's parent, the uncommitted changes
6836 6838 are merged into the requested changeset and the merged
6837 6839 result is left uncommitted. If the requested changeset is
6838 6840 not an ancestor or descendant (that is, it is on another
6839 6841 branch), the update is aborted and the uncommitted changes
6840 6842 are preserved.
6841 6843
6842 6844 2. With the -c/--check option, the update is aborted and the
6843 6845 uncommitted changes are preserved.
6844 6846
6845 6847 3. With the -C/--clean option, uncommitted changes are discarded and
6846 6848 the working directory is updated to the requested changeset.
6847 6849
6848 6850 To cancel an uncommitted merge (and lose your changes), use
6849 6851 :hg:`update --clean .`.
6850 6852
6851 6853 Use null as the changeset to remove the working directory (like
6852 6854 :hg:`clone -U`).
6853 6855
6854 6856 If you want to revert just one file to an older revision, use
6855 6857 :hg:`revert [-r REV] NAME`.
6856 6858
6857 6859 See :hg:`help dates` for a list of formats valid for -d/--date.
6858 6860
6859 6861 Returns 0 on success, 1 if there are unresolved files.
6860 6862 """
6861 6863 movemarkfrom = None
6862 6864 if rev and node:
6863 6865 raise error.Abort(_("please specify just one revision"))
6864 6866
6865 6867 if rev is None or rev == '':
6866 6868 rev = node
6867 6869
6868 6870 wlock = repo.wlock()
6869 6871 try:
6870 6872 cmdutil.clearunfinished(repo)
6871 6873
6872 6874 if date:
6873 6875 if rev is not None:
6874 6876 raise error.Abort(_("you can't specify a revision and a date"))
6875 6877 rev = cmdutil.finddate(ui, repo, date)
6876 6878
6877 6879 # if we defined a bookmark, we have to remember the original name
6878 6880 brev = rev
6879 6881 rev = scmutil.revsingle(repo, rev, rev).rev()
6880 6882
6881 6883 if check and clean:
6882 6884 raise error.Abort(_("cannot specify both -c/--check and -C/--clean")
6883 6885 )
6884 6886
6885 6887 if check:
6886 6888 cmdutil.bailifchanged(repo, merge=False)
6887 6889 if rev is None:
6888 6890 updata = destutil.destupdate(repo, clean=clean, check=check)
6889 6891 rev, movemarkfrom, brev = updata
6890 6892
6891 6893 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
6892 6894
6893 6895 if clean:
6894 6896 ret = hg.clean(repo, rev)
6895 6897 else:
6896 6898 ret = hg.update(repo, rev)
6897 6899
6898 6900 if not ret and movemarkfrom:
6899 6901 if movemarkfrom == repo['.'].node():
6900 6902 pass # no-op update
6901 6903 elif bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
6902 6904 ui.status(_("updating bookmark %s\n") % repo._activebookmark)
6903 6905 else:
6904 6906 # this can happen with a non-linear update
6905 6907 ui.status(_("(leaving bookmark %s)\n") %
6906 6908 repo._activebookmark)
6907 6909 bookmarks.deactivate(repo)
6908 6910 elif brev in repo._bookmarks:
6909 6911 bookmarks.activate(repo, brev)
6910 6912 ui.status(_("(activating bookmark %s)\n") % brev)
6911 6913 elif brev:
6912 6914 if repo._activebookmark:
6913 6915 ui.status(_("(leaving bookmark %s)\n") %
6914 6916 repo._activebookmark)
6915 6917 bookmarks.deactivate(repo)
6916 6918 finally:
6917 6919 wlock.release()
6918 6920
6919 6921 return ret
6920 6922
6921 6923 @command('verify', [])
6922 6924 def verify(ui, repo):
6923 6925 """verify the integrity of the repository
6924 6926
6925 6927 Verify the integrity of the current repository.
6926 6928
6927 6929 This will perform an extensive check of the repository's
6928 6930 integrity, validating the hashes and checksums of each entry in
6929 6931 the changelog, manifest, and tracked files, as well as the
6930 6932 integrity of their crosslinks and indices.
6931 6933
6932 6934 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
6933 6935 for more information about recovery from corruption of the
6934 6936 repository.
6935 6937
6936 6938 Returns 0 on success, 1 if errors are encountered.
6937 6939 """
6938 6940 return hg.verify(repo)
6939 6941
6940 6942 @command('version', [], norepo=True)
6941 6943 def version_(ui):
6942 6944 """output version and copyright information"""
6943 6945 ui.write(_("Mercurial Distributed SCM (version %s)\n")
6944 6946 % util.version())
6945 6947 ui.status(_(
6946 6948 "(see https://mercurial-scm.org for more information)\n"
6947 6949 "\nCopyright (C) 2005-2015 Matt Mackall and others\n"
6948 6950 "This is free software; see the source for copying conditions. "
6949 6951 "There is NO\nwarranty; "
6950 6952 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
6951 6953 ))
6952 6954
6953 6955 ui.note(_("\nEnabled extensions:\n\n"))
6954 6956 if ui.verbose:
6955 6957 # format names and versions into columns
6956 6958 names = []
6957 6959 vers = []
6958 6960 for name, module in extensions.extensions():
6959 6961 names.append(name)
6960 6962 vers.append(extensions.moduleversion(module))
6961 6963 if names:
6962 6964 maxnamelen = max(len(n) for n in names)
6963 6965 for i, name in enumerate(names):
6964 6966 ui.write(" %-*s %s\n" % (maxnamelen, name, vers[i]))
@@ -1,1901 +1,1915 b''
1 1 The Mercurial system uses a set of configuration files to control
2 2 aspects of its behavior.
3 3
4 4 Troubleshooting
5 5 ===============
6 6
7 7 If you're having problems with your configuration,
8 8 :hg:`config --debug` can help you understand what is introducing
9 9 a setting into your environment.
10 10
11 11 See :hg:`help config.syntax` and :hg:`help config.files`
12 12 for information about how and where to override things.
13 13
14 14 Format
15 15 ======
16 16
17 17 The configuration files use a simple ini-file format. A configuration
18 18 file consists of sections, led by a ``[section]`` header and followed
19 19 by ``name = value`` entries::
20 20
21 21 [ui]
22 22 username = Firstname Lastname <firstname.lastname@example.net>
23 23 verbose = True
24 24
25 25 The above entries will be referred to as ``ui.username`` and
26 26 ``ui.verbose``, respectively. See :hg:`help config.syntax`.
27 27
28 28 Files
29 29 =====
30 30
31 31 Mercurial reads configuration data from several files, if they exist.
32 32 These files do not exist by default and you will have to create the
33 33 appropriate configuration files yourself: global configuration like
34 34 the username setting is typically put into
35 35 ``%USERPROFILE%\mercurial.ini`` or ``$HOME/.hgrc`` and local
36 36 configuration is put into the per-repository ``<repo>/.hg/hgrc`` file.
37 37
38 38 The names of these files depend on the system on which Mercurial is
39 39 installed. ``*.rc`` files from a single directory are read in
40 40 alphabetical order, later ones overriding earlier ones. Where multiple
41 41 paths are given below, settings from earlier paths override later
42 42 ones.
43 43
44 44 .. container:: verbose.unix
45 45
46 46 On Unix, the following files are consulted:
47 47
48 48 - ``<repo>/.hg/hgrc`` (per-repository)
49 49 - ``$HOME/.hgrc`` (per-user)
50 50 - ``<install-root>/etc/mercurial/hgrc`` (per-installation)
51 51 - ``<install-root>/etc/mercurial/hgrc.d/*.rc`` (per-installation)
52 52 - ``/etc/mercurial/hgrc`` (per-system)
53 53 - ``/etc/mercurial/hgrc.d/*.rc`` (per-system)
54 54 - ``<internal>/default.d/*.rc`` (defaults)
55 55
56 56 .. container:: verbose.windows
57 57
58 58 On Windows, the following files are consulted:
59 59
60 60 - ``<repo>/.hg/hgrc`` (per-repository)
61 61 - ``%USERPROFILE%\.hgrc`` (per-user)
62 62 - ``%USERPROFILE%\Mercurial.ini`` (per-user)
63 63 - ``%HOME%\.hgrc`` (per-user)
64 64 - ``%HOME%\Mercurial.ini`` (per-user)
65 65 - ``HKEY_LOCAL_MACHINE\SOFTWARE\Mercurial`` (per-installation)
66 66 - ``<install-dir>\hgrc.d\*.rc`` (per-installation)
67 67 - ``<install-dir>\Mercurial.ini`` (per-installation)
68 68 - ``<internal>/default.d/*.rc`` (defaults)
69 69
70 70 .. note::
71 71
72 72 The registry key ``HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Mercurial``
73 73 is used when running 32-bit Python on 64-bit Windows.
74 74
75 75 .. container:: verbose.plan9
76 76
77 77 On Plan9, the following files are consulted:
78 78
79 79 - ``<repo>/.hg/hgrc`` (per-repository)
80 80 - ``$home/lib/hgrc`` (per-user)
81 81 - ``<install-root>/lib/mercurial/hgrc`` (per-installation)
82 82 - ``<install-root>/lib/mercurial/hgrc.d/*.rc`` (per-installation)
83 83 - ``/lib/mercurial/hgrc`` (per-system)
84 84 - ``/lib/mercurial/hgrc.d/*.rc`` (per-system)
85 85 - ``<internal>/default.d/*.rc`` (defaults)
86 86
87 87 Per-repository configuration options only apply in a
88 88 particular repository. This file is not version-controlled, and
89 89 will not get transferred during a "clone" operation. Options in
90 90 this file override options in all other configuration files. On
91 91 Plan 9 and Unix, most of this file will be ignored if it doesn't
92 92 belong to a trusted user or to a trusted group. See
93 93 :hg:`help config.trusted` for more details.
94 94
95 95 Per-user configuration file(s) are for the user running Mercurial. On
96 96 Windows 9x, ``%HOME%`` is replaced by ``%APPDATA%``. Options in these
97 97 files apply to all Mercurial commands executed by this user in any
98 98 directory. Options in these files override per-system and per-installation
99 99 options.
100 100
101 101 Per-installation configuration files are searched for in the
102 102 directory where Mercurial is installed. ``<install-root>`` is the
103 103 parent directory of the **hg** executable (or symlink) being run. For
104 104 example, if installed in ``/shared/tools/bin/hg``, Mercurial will look
105 105 in ``/shared/tools/etc/mercurial/hgrc``. Options in these files apply
106 106 to all Mercurial commands executed by any user in any directory.
107 107
108 108 Per-installation configuration files are for the system on
109 109 which Mercurial is running. Options in these files apply to all
110 110 Mercurial commands executed by any user in any directory. Registry
111 111 keys contain PATH-like strings, every part of which must reference
112 112 a ``Mercurial.ini`` file or be a directory where ``*.rc`` files will
113 113 be read. Mercurial checks each of these locations in the specified
114 114 order until one or more configuration files are detected.
115 115
116 116 Per-system configuration files are for the system on which Mercurial
117 117 is running. Options in these files apply to all Mercurial commands
118 118 executed by any user in any directory. Options in these files
119 119 override per-installation options.
120 120
121 121 Mercurial comes with some default configuration. The default configuration
122 122 files are installed with Mercurial and will be overwritten on upgrades. Default
123 123 configuration files should never be edited by users or administrators but can
124 124 be overridden in other configuration files. So far the directory only contains
125 125 merge tool configuration but packagers can also put other default configuration
126 126 there.
127 127
128 128 Syntax
129 129 ======
130 130
131 131 A configuration file consists of sections, led by a ``[section]`` header
132 132 and followed by ``name = value`` entries (sometimes called
133 133 ``configuration keys``)::
134 134
135 135 [spam]
136 136 eggs=ham
137 137 green=
138 138 eggs
139 139
140 140 Each line contains one entry. If the lines that follow are indented,
141 141 they are treated as continuations of that entry. Leading whitespace is
142 142 removed from values. Empty lines are skipped. Lines beginning with
143 143 ``#`` or ``;`` are ignored and may be used to provide comments.
144 144
145 145 Configuration keys can be set multiple times, in which case Mercurial
146 146 will use the value that was configured last. As an example::
147 147
148 148 [spam]
149 149 eggs=large
150 150 ham=serrano
151 151 eggs=small
152 152
153 153 This would set the configuration key named ``eggs`` to ``small``.
154 154
155 155 It is also possible to define a section multiple times. A section can
156 156 be redefined on the same and/or on different configuration files. For
157 157 example::
158 158
159 159 [foo]
160 160 eggs=large
161 161 ham=serrano
162 162 eggs=small
163 163
164 164 [bar]
165 165 eggs=ham
166 166 green=
167 167 eggs
168 168
169 169 [foo]
170 170 ham=prosciutto
171 171 eggs=medium
172 172 bread=toasted
173 173
174 174 This would set the ``eggs``, ``ham``, and ``bread`` configuration keys
175 175 of the ``foo`` section to ``medium``, ``prosciutto``, and ``toasted``,
176 176 respectively. As you can see there only thing that matters is the last
177 177 value that was set for each of the configuration keys.
178 178
179 179 If a configuration key is set multiple times in different
180 180 configuration files the final value will depend on the order in which
181 181 the different configuration files are read, with settings from earlier
182 182 paths overriding later ones as described on the ``Files`` section
183 183 above.
184 184
185 185 A line of the form ``%include file`` will include ``file`` into the
186 186 current configuration file. The inclusion is recursive, which means
187 187 that included files can include other files. Filenames are relative to
188 188 the configuration file in which the ``%include`` directive is found.
189 189 Environment variables and ``~user`` constructs are expanded in
190 190 ``file``. This lets you do something like::
191 191
192 192 %include ~/.hgrc.d/$HOST.rc
193 193
194 194 to include a different configuration file on each computer you use.
195 195
196 196 A line with ``%unset name`` will remove ``name`` from the current
197 197 section, if it has been set previously.
198 198
199 199 The values are either free-form text strings, lists of text strings,
200 200 or Boolean values. Boolean values can be set to true using any of "1",
201 201 "yes", "true", or "on" and to false using "0", "no", "false", or "off"
202 202 (all case insensitive).
203 203
204 204 List values are separated by whitespace or comma, except when values are
205 205 placed in double quotation marks::
206 206
207 207 allow_read = "John Doe, PhD", brian, betty
208 208
209 209 Quotation marks can be escaped by prefixing them with a backslash. Only
210 210 quotation marks at the beginning of a word is counted as a quotation
211 211 (e.g., ``foo"bar baz`` is the list of ``foo"bar`` and ``baz``).
212 212
213 213 Sections
214 214 ========
215 215
216 216 This section describes the different sections that may appear in a
217 217 Mercurial configuration file, the purpose of each section, its possible
218 218 keys, and their possible values.
219 219
220 220 ``alias``
221 221 ---------
222 222
223 223 Defines command aliases.
224 224
225 225 Aliases allow you to define your own commands in terms of other
226 226 commands (or aliases), optionally including arguments. Positional
227 227 arguments in the form of ``$1``, ``$2``, etc. in the alias definition
228 228 are expanded by Mercurial before execution. Positional arguments not
229 229 already used by ``$N`` in the definition are put at the end of the
230 230 command to be executed.
231 231
232 232 Alias definitions consist of lines of the form::
233 233
234 234 <alias> = <command> [<argument>]...
235 235
236 236 For example, this definition::
237 237
238 238 latest = log --limit 5
239 239
240 240 creates a new command ``latest`` that shows only the five most recent
241 241 changesets. You can define subsequent aliases using earlier ones::
242 242
243 243 stable5 = latest -b stable
244 244
245 245 .. note::
246 246
247 247 It is possible to create aliases with the same names as
248 248 existing commands, which will then override the original
249 249 definitions. This is almost always a bad idea!
250 250
251 251 An alias can start with an exclamation point (``!``) to make it a
252 252 shell alias. A shell alias is executed with the shell and will let you
253 253 run arbitrary commands. As an example, ::
254 254
255 255 echo = !echo $@
256 256
257 257 will let you do ``hg echo foo`` to have ``foo`` printed in your
258 258 terminal. A better example might be::
259 259
260 260 purge = !$HG status --no-status --unknown -0 | xargs -0 rm
261 261
262 262 which will make ``hg purge`` delete all unknown files in the
263 263 repository in the same manner as the purge extension.
264 264
265 265 Positional arguments like ``$1``, ``$2``, etc. in the alias definition
266 266 expand to the command arguments. Unmatched arguments are
267 267 removed. ``$0`` expands to the alias name and ``$@`` expands to all
268 268 arguments separated by a space. ``"$@"`` (with quotes) expands to all
269 269 arguments quoted individually and separated by a space. These expansions
270 270 happen before the command is passed to the shell.
271 271
272 272 Shell aliases are executed in an environment where ``$HG`` expands to
273 273 the path of the Mercurial that was used to execute the alias. This is
274 274 useful when you want to call further Mercurial commands in a shell
275 275 alias, as was done above for the purge alias. In addition,
276 276 ``$HG_ARGS`` expands to the arguments given to Mercurial. In the ``hg
277 277 echo foo`` call above, ``$HG_ARGS`` would expand to ``echo foo``.
278 278
279 279 .. note::
280 280
281 281 Some global configuration options such as ``-R`` are
282 282 processed before shell aliases and will thus not be passed to
283 283 aliases.
284 284
285 285
286 286 ``annotate``
287 287 ------------
288 288
289 289 Settings used when displaying file annotations. All values are
290 290 Booleans and default to False. See :hg:`help config.diff` for
291 291 related options for the diff command.
292 292
293 293 ``ignorews``
294 294 Ignore white space when comparing lines.
295 295
296 296 ``ignorewsamount``
297 297 Ignore changes in the amount of white space.
298 298
299 299 ``ignoreblanklines``
300 300 Ignore changes whose lines are all blank.
301 301
302 302
303 303 ``auth``
304 304 --------
305 305
306 306 Authentication credentials for HTTP authentication. This section
307 307 allows you to store usernames and passwords for use when logging
308 308 *into* HTTP servers. See :hg:`help config.web` if
309 309 you want to configure *who* can login to your HTTP server.
310 310
311 311 Each line has the following format::
312 312
313 313 <name>.<argument> = <value>
314 314
315 315 where ``<name>`` is used to group arguments into authentication
316 316 entries. Example::
317 317
318 318 foo.prefix = hg.intevation.org/mercurial
319 319 foo.username = foo
320 320 foo.password = bar
321 321 foo.schemes = http https
322 322
323 323 bar.prefix = secure.example.org
324 324 bar.key = path/to/file.key
325 325 bar.cert = path/to/file.cert
326 326 bar.schemes = https
327 327
328 328 Supported arguments:
329 329
330 330 ``prefix``
331 331 Either ``*`` or a URI prefix with or without the scheme part.
332 332 The authentication entry with the longest matching prefix is used
333 333 (where ``*`` matches everything and counts as a match of length
334 334 1). If the prefix doesn't include a scheme, the match is performed
335 335 against the URI with its scheme stripped as well, and the schemes
336 336 argument, q.v., is then subsequently consulted.
337 337
338 338 ``username``
339 339 Optional. Username to authenticate with. If not given, and the
340 340 remote site requires basic or digest authentication, the user will
341 341 be prompted for it. Environment variables are expanded in the
342 342 username letting you do ``foo.username = $USER``. If the URI
343 343 includes a username, only ``[auth]`` entries with a matching
344 344 username or without a username will be considered.
345 345
346 346 ``password``
347 347 Optional. Password to authenticate with. If not given, and the
348 348 remote site requires basic or digest authentication, the user
349 349 will be prompted for it.
350 350
351 351 ``key``
352 352 Optional. PEM encoded client certificate key file. Environment
353 353 variables are expanded in the filename.
354 354
355 355 ``cert``
356 356 Optional. PEM encoded client certificate chain file. Environment
357 357 variables are expanded in the filename.
358 358
359 359 ``schemes``
360 360 Optional. Space separated list of URI schemes to use this
361 361 authentication entry with. Only used if the prefix doesn't include
362 362 a scheme. Supported schemes are http and https. They will match
363 363 static-http and static-https respectively, as well.
364 364 (default: https)
365 365
366 366 If no suitable authentication entry is found, the user is prompted
367 367 for credentials as usual if required by the remote.
368 368
369 369
370 370 ``committemplate``
371 371 ------------------
372 372
373 373 ``changeset``
374 374 String: configuration in this section is used as the template to
375 375 customize the text shown in the editor when committing.
376 376
377 377 In addition to pre-defined template keywords, commit log specific one
378 378 below can be used for customization:
379 379
380 380 ``extramsg``
381 381 String: Extra message (typically 'Leave message empty to abort
382 382 commit.'). This may be changed by some commands or extensions.
383 383
384 384 For example, the template configuration below shows as same text as
385 385 one shown by default::
386 386
387 387 [committemplate]
388 388 changeset = {desc}\n\n
389 389 HG: Enter commit message. Lines beginning with 'HG:' are removed.
390 390 HG: {extramsg}
391 391 HG: --
392 392 HG: user: {author}\n{ifeq(p2rev, "-1", "",
393 393 "HG: branch merge\n")
394 394 }HG: branch '{branch}'\n{if(activebookmark,
395 395 "HG: bookmark '{activebookmark}'\n") }{subrepos %
396 396 "HG: subrepo {subrepo}\n" }{file_adds %
397 397 "HG: added {file}\n" }{file_mods %
398 398 "HG: changed {file}\n" }{file_dels %
399 399 "HG: removed {file}\n" }{if(files, "",
400 400 "HG: no files changed\n")}
401 401
402 402 .. note::
403 403
404 404 For some problematic encodings (see :hg:`help win32mbcs` for
405 405 detail), this customization should be configured carefully, to
406 406 avoid showing broken characters.
407 407
408 408 For example, if a multibyte character ending with backslash (0x5c) is
409 409 followed by the ASCII character 'n' in the customized template,
410 410 the sequence of backslash and 'n' is treated as line-feed unexpectedly
411 411 (and the multibyte character is broken, too).
412 412
413 413 Customized template is used for commands below (``--edit`` may be
414 414 required):
415 415
416 416 - :hg:`backout`
417 417 - :hg:`commit`
418 418 - :hg:`fetch` (for merge commit only)
419 419 - :hg:`graft`
420 420 - :hg:`histedit`
421 421 - :hg:`import`
422 422 - :hg:`qfold`, :hg:`qnew` and :hg:`qrefresh`
423 423 - :hg:`rebase`
424 424 - :hg:`shelve`
425 425 - :hg:`sign`
426 426 - :hg:`tag`
427 427 - :hg:`transplant`
428 428
429 429 Configuring items below instead of ``changeset`` allows showing
430 430 customized message only for specific actions, or showing different
431 431 messages for each action.
432 432
433 433 - ``changeset.backout`` for :hg:`backout`
434 434 - ``changeset.commit.amend.merge`` for :hg:`commit --amend` on merges
435 435 - ``changeset.commit.amend.normal`` for :hg:`commit --amend` on other
436 436 - ``changeset.commit.normal.merge`` for :hg:`commit` on merges
437 437 - ``changeset.commit.normal.normal`` for :hg:`commit` on other
438 438 - ``changeset.fetch`` for :hg:`fetch` (impling merge commit)
439 439 - ``changeset.gpg.sign`` for :hg:`sign`
440 440 - ``changeset.graft`` for :hg:`graft`
441 441 - ``changeset.histedit.edit`` for ``edit`` of :hg:`histedit`
442 442 - ``changeset.histedit.fold`` for ``fold`` of :hg:`histedit`
443 443 - ``changeset.histedit.mess`` for ``mess`` of :hg:`histedit`
444 444 - ``changeset.histedit.pick`` for ``pick`` of :hg:`histedit`
445 445 - ``changeset.import.bypass`` for :hg:`import --bypass`
446 446 - ``changeset.import.normal.merge`` for :hg:`import` on merges
447 447 - ``changeset.import.normal.normal`` for :hg:`import` on other
448 448 - ``changeset.mq.qnew`` for :hg:`qnew`
449 449 - ``changeset.mq.qfold`` for :hg:`qfold`
450 450 - ``changeset.mq.qrefresh`` for :hg:`qrefresh`
451 451 - ``changeset.rebase.collapse`` for :hg:`rebase --collapse`
452 452 - ``changeset.rebase.merge`` for :hg:`rebase` on merges
453 453 - ``changeset.rebase.normal`` for :hg:`rebase` on other
454 454 - ``changeset.shelve.shelve`` for :hg:`shelve`
455 455 - ``changeset.tag.add`` for :hg:`tag` without ``--remove``
456 456 - ``changeset.tag.remove`` for :hg:`tag --remove`
457 457 - ``changeset.transplant.merge`` for :hg:`transplant` on merges
458 458 - ``changeset.transplant.normal`` for :hg:`transplant` on other
459 459
460 460 These dot-separated lists of names are treated as hierarchical ones.
461 461 For example, ``changeset.tag.remove`` customizes the commit message
462 462 only for :hg:`tag --remove`, but ``changeset.tag`` customizes the
463 463 commit message for :hg:`tag` regardless of ``--remove`` option.
464 464
465 465 When the external editor is invoked for a commit, the corresponding
466 466 dot-separated list of names without the ``changeset.`` prefix
467 467 (e.g. ``commit.normal.normal``) is in the ``HGEDITFORM`` environment
468 468 variable.
469 469
470 470 In this section, items other than ``changeset`` can be referred from
471 471 others. For example, the configuration to list committed files up
472 472 below can be referred as ``{listupfiles}``::
473 473
474 474 [committemplate]
475 475 listupfiles = {file_adds %
476 476 "HG: added {file}\n" }{file_mods %
477 477 "HG: changed {file}\n" }{file_dels %
478 478 "HG: removed {file}\n" }{if(files, "",
479 479 "HG: no files changed\n")}
480 480
481 481 ``decode/encode``
482 482 -----------------
483 483
484 484 Filters for transforming files on checkout/checkin. This would
485 485 typically be used for newline processing or other
486 486 localization/canonicalization of files.
487 487
488 488 Filters consist of a filter pattern followed by a filter command.
489 489 Filter patterns are globs by default, rooted at the repository root.
490 490 For example, to match any file ending in ``.txt`` in the root
491 491 directory only, use the pattern ``*.txt``. To match any file ending
492 492 in ``.c`` anywhere in the repository, use the pattern ``**.c``.
493 493 For each file only the first matching filter applies.
494 494
495 495 The filter command can start with a specifier, either ``pipe:`` or
496 496 ``tempfile:``. If no specifier is given, ``pipe:`` is used by default.
497 497
498 498 A ``pipe:`` command must accept data on stdin and return the transformed
499 499 data on stdout.
500 500
501 501 Pipe example::
502 502
503 503 [encode]
504 504 # uncompress gzip files on checkin to improve delta compression
505 505 # note: not necessarily a good idea, just an example
506 506 *.gz = pipe: gunzip
507 507
508 508 [decode]
509 509 # recompress gzip files when writing them to the working dir (we
510 510 # can safely omit "pipe:", because it's the default)
511 511 *.gz = gzip
512 512
513 513 A ``tempfile:`` command is a template. The string ``INFILE`` is replaced
514 514 with the name of a temporary file that contains the data to be
515 515 filtered by the command. The string ``OUTFILE`` is replaced with the name
516 516 of an empty temporary file, where the filtered data must be written by
517 517 the command.
518 518
519 519 .. note::
520 520
521 521 The tempfile mechanism is recommended for Windows systems,
522 522 where the standard shell I/O redirection operators often have
523 523 strange effects and may corrupt the contents of your files.
524 524
525 525 This filter mechanism is used internally by the ``eol`` extension to
526 526 translate line ending characters between Windows (CRLF) and Unix (LF)
527 527 format. We suggest you use the ``eol`` extension for convenience.
528 528
529 529
530 530 ``defaults``
531 531 ------------
532 532
533 533 (defaults are deprecated. Don't use them. Use aliases instead.)
534 534
535 535 Use the ``[defaults]`` section to define command defaults, i.e. the
536 536 default options/arguments to pass to the specified commands.
537 537
538 538 The following example makes :hg:`log` run in verbose mode, and
539 539 :hg:`status` show only the modified files, by default::
540 540
541 541 [defaults]
542 542 log = -v
543 543 status = -m
544 544
545 545 The actual commands, instead of their aliases, must be used when
546 546 defining command defaults. The command defaults will also be applied
547 547 to the aliases of the commands defined.
548 548
549 549
550 550 ``diff``
551 551 --------
552 552
553 553 Settings used when displaying diffs. Everything except for ``unified``
554 554 is a Boolean and defaults to False. See :hg:`help config.annotate`
555 555 for related options for the annotate command.
556 556
557 557 ``git``
558 558 Use git extended diff format.
559 559
560 560 ``nobinary``
561 561 Omit git binary patches.
562 562
563 563 ``nodates``
564 564 Don't include dates in diff headers.
565 565
566 566 ``noprefix``
567 567 Omit 'a/' and 'b/' prefixes from filenames. Ignored in plain mode.
568 568
569 569 ``showfunc``
570 570 Show which function each change is in.
571 571
572 572 ``ignorews``
573 573 Ignore white space when comparing lines.
574 574
575 575 ``ignorewsamount``
576 576 Ignore changes in the amount of white space.
577 577
578 578 ``ignoreblanklines``
579 579 Ignore changes whose lines are all blank.
580 580
581 581 ``unified``
582 582 Number of lines of context to show.
583 583
584 584 ``email``
585 585 ---------
586 586
587 587 Settings for extensions that send email messages.
588 588
589 589 ``from``
590 590 Optional. Email address to use in "From" header and SMTP envelope
591 591 of outgoing messages.
592 592
593 593 ``to``
594 594 Optional. Comma-separated list of recipients' email addresses.
595 595
596 596 ``cc``
597 597 Optional. Comma-separated list of carbon copy recipients'
598 598 email addresses.
599 599
600 600 ``bcc``
601 601 Optional. Comma-separated list of blind carbon copy recipients'
602 602 email addresses.
603 603
604 604 ``method``
605 605 Optional. Method to use to send email messages. If value is ``smtp``
606 606 (default), use SMTP (see the ``[smtp]`` section for configuration).
607 607 Otherwise, use as name of program to run that acts like sendmail
608 608 (takes ``-f`` option for sender, list of recipients on command line,
609 609 message on stdin). Normally, setting this to ``sendmail`` or
610 610 ``/usr/sbin/sendmail`` is enough to use sendmail to send messages.
611 611
612 612 ``charsets``
613 613 Optional. Comma-separated list of character sets considered
614 614 convenient for recipients. Addresses, headers, and parts not
615 615 containing patches of outgoing messages will be encoded in the
616 616 first character set to which conversion from local encoding
617 617 (``$HGENCODING``, ``ui.fallbackencoding``) succeeds. If correct
618 618 conversion fails, the text in question is sent as is.
619 619 (default: '')
620 620
621 621 Order of outgoing email character sets:
622 622
623 623 1. ``us-ascii``: always first, regardless of settings
624 624 2. ``email.charsets``: in order given by user
625 625 3. ``ui.fallbackencoding``: if not in email.charsets
626 626 4. ``$HGENCODING``: if not in email.charsets
627 627 5. ``utf-8``: always last, regardless of settings
628 628
629 629 Email example::
630 630
631 631 [email]
632 632 from = Joseph User <joe.user@example.com>
633 633 method = /usr/sbin/sendmail
634 634 # charsets for western Europeans
635 635 # us-ascii, utf-8 omitted, as they are tried first and last
636 636 charsets = iso-8859-1, iso-8859-15, windows-1252
637 637
638 638
639 639 ``extensions``
640 640 --------------
641 641
642 642 Mercurial has an extension mechanism for adding new features. To
643 643 enable an extension, create an entry for it in this section.
644 644
645 645 If you know that the extension is already in Python's search path,
646 646 you can give the name of the module, followed by ``=``, with nothing
647 647 after the ``=``.
648 648
649 649 Otherwise, give a name that you choose, followed by ``=``, followed by
650 650 the path to the ``.py`` file (including the file name extension) that
651 651 defines the extension.
652 652
653 653 To explicitly disable an extension that is enabled in an hgrc of
654 654 broader scope, prepend its path with ``!``, as in ``foo = !/ext/path``
655 655 or ``foo = !`` when path is not supplied.
656 656
657 657 Example for ``~/.hgrc``::
658 658
659 659 [extensions]
660 660 # (the color extension will get loaded from Mercurial's path)
661 661 color =
662 662 # (this extension will get loaded from the file specified)
663 663 myfeature = ~/.hgext/myfeature.py
664 664
665 665
666 666 ``format``
667 667 ----------
668 668
669 669 ``usegeneraldelta``
670 670 Enable or disable the "generaldelta" repository format which improves
671 671 repository compression by allowing "revlog" to store delta against arbitrary
672 672 revision instead of the previous stored one. This provides significant
673 673 improvement for repositories with branches. Enabled by default. Disabling
674 674 this option ensures that the on-disk format of newly created repository will
675 675 be compatible with Mercurial before version 1.9.
676 676
677 677 ``usestore``
678 678 Enable or disable the "store" repository format which improves
679 679 compatibility with systems that fold case or otherwise mangle
680 680 filenames. Enabled by default. Disabling this option will allow
681 681 you to store longer filenames in some situations at the expense of
682 682 compatibility and ensures that the on-disk format of newly created
683 683 repositories will be compatible with Mercurial before version 0.9.4.
684 684
685 685 ``usefncache``
686 686 Enable or disable the "fncache" repository format which enhances
687 687 the "store" repository format (which has to be enabled to use
688 688 fncache) to allow longer filenames and avoids using Windows
689 689 reserved names, e.g. "nul". Enabled by default. Disabling this
690 690 option ensures that the on-disk format of newly created
691 691 repositories will be compatible with Mercurial before version 1.1.
692 692
693 693 ``dotencode``
694 694 Enable or disable the "dotencode" repository format which enhances
695 695 the "fncache" repository format (which has to be enabled to use
696 696 dotencode) to avoid issues with filenames starting with ._ on
697 697 Mac OS X and spaces on Windows. Enabled by default. Disabling this
698 698 option ensures that the on-disk format of newly created
699 699 repositories will be compatible with Mercurial before version 1.7.
700 700
701 701 ``graph``
702 702 ---------
703 703
704 704 Web graph view configuration. This section let you change graph
705 705 elements display properties by branches, for instance to make the
706 706 ``default`` branch stand out.
707 707
708 708 Each line has the following format::
709 709
710 710 <branch>.<argument> = <value>
711 711
712 712 where ``<branch>`` is the name of the branch being
713 713 customized. Example::
714 714
715 715 [graph]
716 716 # 2px width
717 717 default.width = 2
718 718 # red color
719 719 default.color = FF0000
720 720
721 721 Supported arguments:
722 722
723 723 ``width``
724 724 Set branch edges width in pixels.
725 725
726 726 ``color``
727 727 Set branch edges color in hexadecimal RGB notation.
728 728
729 729 ``hooks``
730 730 ---------
731 731
732 732 Commands or Python functions that get automatically executed by
733 733 various actions such as starting or finishing a commit. Multiple
734 734 hooks can be run for the same action by appending a suffix to the
735 735 action. Overriding a site-wide hook can be done by changing its
736 736 value or setting it to an empty string. Hooks can be prioritized
737 737 by adding a prefix of ``priority`` to the hook name on a new line
738 738 and setting the priority. The default priority is 0.
739 739
740 740 Example ``.hg/hgrc``::
741 741
742 742 [hooks]
743 743 # update working directory after adding changesets
744 744 changegroup.update = hg update
745 745 # do not use the site-wide hook
746 746 incoming =
747 747 incoming.email = /my/email/hook
748 748 incoming.autobuild = /my/build/hook
749 749 # force autobuild hook to run before other incoming hooks
750 750 priority.incoming.autobuild = 1
751 751
752 752 Most hooks are run with environment variables set that give useful
753 753 additional information. For each hook below, the environment
754 754 variables it is passed are listed with names of the form ``$HG_foo``.
755 755
756 756 ``changegroup``
757 757 Run after a changegroup has been added via push, pull or unbundle.
758 758 ID of the first new changeset is in ``$HG_NODE``. URL from which
759 759 changes came is in ``$HG_URL``.
760 760
761 761 ``commit``
762 762 Run after a changeset has been created in the local repository. ID
763 763 of the newly created changeset is in ``$HG_NODE``. Parent changeset
764 764 IDs are in ``$HG_PARENT1`` and ``$HG_PARENT2``.
765 765
766 766 ``incoming``
767 767 Run after a changeset has been pulled, pushed, or unbundled into
768 768 the local repository. The ID of the newly arrived changeset is in
769 769 ``$HG_NODE``. URL that was source of changes came is in ``$HG_URL``.
770 770
771 771 ``outgoing``
772 772 Run after sending changes from local repository to another. ID of
773 773 first changeset sent is in ``$HG_NODE``. Source of operation is in
774 774 ``$HG_SOURCE``; Also see :hg:`help config.preoutgoing` hook.
775 775
776 776 ``post-<command>``
777 777 Run after successful invocations of the associated command. The
778 778 contents of the command line are passed as ``$HG_ARGS`` and the result
779 779 code in ``$HG_RESULT``. Parsed command line arguments are passed as
780 780 ``$HG_PATS`` and ``$HG_OPTS``. These contain string representations of
781 781 the python data internally passed to <command>. ``$HG_OPTS`` is a
782 782 dictionary of options (with unspecified options set to their defaults).
783 783 ``$HG_PATS`` is a list of arguments. Hook failure is ignored.
784 784
785 785 ``pre-<command>``
786 786 Run before executing the associated command. The contents of the
787 787 command line are passed as ``$HG_ARGS``. Parsed command line arguments
788 788 are passed as ``$HG_PATS`` and ``$HG_OPTS``. These contain string
789 789 representations of the data internally passed to <command>. ``$HG_OPTS``
790 790 is a dictionary of options (with unspecified options set to their
791 791 defaults). ``$HG_PATS`` is a list of arguments. If the hook returns
792 792 failure, the command doesn't execute and Mercurial returns the failure
793 793 code.
794 794
795 795 ``prechangegroup``
796 796 Run before a changegroup is added via push, pull or unbundle. Exit
797 797 status 0 allows the changegroup to proceed. Non-zero status will
798 798 cause the push, pull or unbundle to fail. URL from which changes
799 799 will come is in ``$HG_URL``.
800 800
801 801 ``precommit``
802 802 Run before starting a local commit. Exit status 0 allows the
803 803 commit to proceed. Non-zero status will cause the commit to fail.
804 804 Parent changeset IDs are in ``$HG_PARENT1`` and ``$HG_PARENT2``.
805 805
806 806 ``prelistkeys``
807 807 Run before listing pushkeys (like bookmarks) in the
808 808 repository. Non-zero status will cause failure. The key namespace is
809 809 in ``$HG_NAMESPACE``.
810 810
811 811 ``preoutgoing``
812 812 Run before collecting changes to send from the local repository to
813 813 another. Non-zero status will cause failure. This lets you prevent
814 814 pull over HTTP or SSH. Also prevents against local pull, push
815 815 (outbound) or bundle commands, but not effective, since you can
816 816 just copy files instead then. Source of operation is in
817 817 ``$HG_SOURCE``. If "serve", operation is happening on behalf of remote
818 818 SSH or HTTP repository. If "push", "pull" or "bundle", operation
819 819 is happening on behalf of repository on same system.
820 820
821 821 ``prepushkey``
822 822 Run before a pushkey (like a bookmark) is added to the
823 823 repository. Non-zero status will cause the key to be rejected. The
824 824 key namespace is in ``$HG_NAMESPACE``, the key is in ``$HG_KEY``,
825 825 the old value (if any) is in ``$HG_OLD``, and the new value is in
826 826 ``$HG_NEW``.
827 827
828 828 ``pretag``
829 829 Run before creating a tag. Exit status 0 allows the tag to be
830 830 created. Non-zero status will cause the tag to fail. ID of
831 831 changeset to tag is in ``$HG_NODE``. Name of tag is in ``$HG_TAG``. Tag is
832 832 local if ``$HG_LOCAL=1``, in repository if ``$HG_LOCAL=0``.
833 833
834 834 ``pretxnopen``
835 835 Run before any new repository transaction is open. The reason for the
836 836 transaction will be in ``$HG_TXNNAME`` and a unique identifier for the
837 837 transaction will be in ``HG_TXNID``. A non-zero status will prevent the
838 838 transaction from being opened.
839 839
840 840 ``pretxnclose``
841 841 Run right before the transaction is actually finalized. Any
842 842 repository change will be visible to the hook program. This lets you
843 843 validate the transaction content or change it. Exit status 0 allows
844 844 the commit to proceed. Non-zero status will cause the transaction to
845 845 be rolled back. The reason for the transaction opening will be in
846 846 ``$HG_TXNNAME`` and a unique identifier for the transaction will be in
847 847 ``HG_TXNID``. The rest of the available data will vary according the
848 848 transaction type. New changesets will add ``$HG_NODE`` (id of the
849 849 first added changeset), ``$HG_URL`` and ``$HG_SOURCE`` variables,
850 850 bookmarks and phases changes will set ``HG_BOOKMARK_MOVED`` and
851 851 ``HG_PHASES_MOVED`` to ``1``, etc.
852 852
853 853 ``txnclose``
854 854 Run after any repository transaction has been committed. At this
855 855 point, the transaction can no longer be rolled back. The hook will run
856 856 after the lock is released. See :hg:`help config.pretxnclose` docs for
857 857 details about available variables.
858 858
859 859 ``txnabort``
860 860 Run when a transaction is aborted. See :hg:`help config.pretxnclose`
861 861 docs for details about available variables.
862 862
863 863 ``pretxnchangegroup``
864 864 Run after a changegroup has been added via push, pull or unbundle,
865 865 but before the transaction has been committed. Changegroup is
866 866 visible to hook program. This lets you validate incoming changes
867 867 before accepting them. Passed the ID of the first new changeset in
868 868 ``$HG_NODE``. Exit status 0 allows the transaction to commit. Non-zero
869 869 status will cause the transaction to be rolled back and the push,
870 870 pull or unbundle will fail. URL that was source of changes is in
871 871 ``$HG_URL``.
872 872
873 873 ``pretxncommit``
874 874 Run after a changeset has been created but the transaction not yet
875 875 committed. Changeset is visible to hook program. This lets you
876 876 validate commit message and changes. Exit status 0 allows the
877 877 commit to proceed. Non-zero status will cause the transaction to
878 878 be rolled back. ID of changeset is in ``$HG_NODE``. Parent changeset
879 879 IDs are in ``$HG_PARENT1`` and ``$HG_PARENT2``.
880 880
881 881 ``preupdate``
882 882 Run before updating the working directory. Exit status 0 allows
883 883 the update to proceed. Non-zero status will prevent the update.
884 884 Changeset ID of first new parent is in ``$HG_PARENT1``. If merge, ID
885 885 of second new parent is in ``$HG_PARENT2``.
886 886
887 887 ``listkeys``
888 888 Run after listing pushkeys (like bookmarks) in the repository. The
889 889 key namespace is in ``$HG_NAMESPACE``. ``$HG_VALUES`` is a
890 890 dictionary containing the keys and values.
891 891
892 892 ``pushkey``
893 893 Run after a pushkey (like a bookmark) is added to the
894 894 repository. The key namespace is in ``$HG_NAMESPACE``, the key is in
895 895 ``$HG_KEY``, the old value (if any) is in ``$HG_OLD``, and the new
896 896 value is in ``$HG_NEW``.
897 897
898 898 ``tag``
899 899 Run after a tag is created. ID of tagged changeset is in ``$HG_NODE``.
900 900 Name of tag is in ``$HG_TAG``. Tag is local if ``$HG_LOCAL=1``, in
901 901 repository if ``$HG_LOCAL=0``.
902 902
903 903 ``update``
904 904 Run after updating the working directory. Changeset ID of first
905 905 new parent is in ``$HG_PARENT1``. If merge, ID of second new parent is
906 906 in ``$HG_PARENT2``. If the update succeeded, ``$HG_ERROR=0``. If the
907 907 update failed (e.g. because conflicts not resolved), ``$HG_ERROR=1``.
908 908
909 909 .. note::
910 910
911 911 It is generally better to use standard hooks rather than the
912 912 generic pre- and post- command hooks as they are guaranteed to be
913 913 called in the appropriate contexts for influencing transactions.
914 914 Also, hooks like "commit" will be called in all contexts that
915 915 generate a commit (e.g. tag) and not just the commit command.
916 916
917 917 .. note::
918 918
919 919 Environment variables with empty values may not be passed to
920 920 hooks on platforms such as Windows. As an example, ``$HG_PARENT2``
921 921 will have an empty value under Unix-like platforms for non-merge
922 922 changesets, while it will not be available at all under Windows.
923 923
924 924 The syntax for Python hooks is as follows::
925 925
926 926 hookname = python:modulename.submodule.callable
927 927 hookname = python:/path/to/python/module.py:callable
928 928
929 929 Python hooks are run within the Mercurial process. Each hook is
930 930 called with at least three keyword arguments: a ui object (keyword
931 931 ``ui``), a repository object (keyword ``repo``), and a ``hooktype``
932 932 keyword that tells what kind of hook is used. Arguments listed as
933 933 environment variables above are passed as keyword arguments, with no
934 934 ``HG_`` prefix, and names in lower case.
935 935
936 936 If a Python hook returns a "true" value or raises an exception, this
937 937 is treated as a failure.
938 938
939 939
940 940 ``hostfingerprints``
941 941 --------------------
942 942
943 943 Fingerprints of the certificates of known HTTPS servers.
944 944 A HTTPS connection to a server with a fingerprint configured here will
945 945 only succeed if the servers certificate matches the fingerprint.
946 946 This is very similar to how ssh known hosts works.
947 947 The fingerprint is the SHA-1 hash value of the DER encoded certificate.
948 948 The CA chain and web.cacerts is not used for servers with a fingerprint.
949 949
950 950 For example::
951 951
952 952 [hostfingerprints]
953 953 hg.intevation.org = fa:1f:d9:48:f1:e7:74:30:38:8d:d8:58:b6:94:b8:58:28:7d:8b:d0
954 954
955 955 This feature is only supported when using Python 2.6 or later.
956 956
957 957
958 958 ``http_proxy``
959 959 --------------
960 960
961 961 Used to access web-based Mercurial repositories through a HTTP
962 962 proxy.
963 963
964 964 ``host``
965 965 Host name and (optional) port of the proxy server, for example
966 966 "myproxy:8000".
967 967
968 968 ``no``
969 969 Optional. Comma-separated list of host names that should bypass
970 970 the proxy.
971 971
972 972 ``passwd``
973 973 Optional. Password to authenticate with at the proxy server.
974 974
975 975 ``user``
976 976 Optional. User name to authenticate with at the proxy server.
977 977
978 978 ``always``
979 979 Optional. Always use the proxy, even for localhost and any entries
980 980 in ``http_proxy.no``. (default: False)
981 981
982 982 ``merge-patterns``
983 983 ------------------
984 984
985 985 This section specifies merge tools to associate with particular file
986 986 patterns. Tools matched here will take precedence over the default
987 987 merge tool. Patterns are globs by default, rooted at the repository
988 988 root.
989 989
990 990 Example::
991 991
992 992 [merge-patterns]
993 993 **.c = kdiff3
994 994 **.jpg = myimgmerge
995 995
996 996 ``merge-tools``
997 997 ---------------
998 998
999 999 This section configures external merge tools to use for file-level
1000 1000 merges. This section has likely been preconfigured at install time.
1001 1001 Use :hg:`config merge-tools` to check the existing configuration.
1002 1002 Also see :hg:`help merge-tools` for more details.
1003 1003
1004 1004 Example ``~/.hgrc``::
1005 1005
1006 1006 [merge-tools]
1007 1007 # Override stock tool location
1008 1008 kdiff3.executable = ~/bin/kdiff3
1009 1009 # Specify command line
1010 1010 kdiff3.args = $base $local $other -o $output
1011 1011 # Give higher priority
1012 1012 kdiff3.priority = 1
1013 1013
1014 1014 # Changing the priority of preconfigured tool
1015 1015 meld.priority = 0
1016 1016
1017 1017 # Disable a preconfigured tool
1018 1018 vimdiff.disabled = yes
1019 1019
1020 1020 # Define new tool
1021 1021 myHtmlTool.args = -m $local $other $base $output
1022 1022 myHtmlTool.regkey = Software\FooSoftware\HtmlMerge
1023 1023 myHtmlTool.priority = 1
1024 1024
1025 1025 Supported arguments:
1026 1026
1027 1027 ``priority``
1028 1028 The priority in which to evaluate this tool.
1029 1029 (default: 0)
1030 1030
1031 1031 ``executable``
1032 1032 Either just the name of the executable or its pathname. On Windows,
1033 1033 the path can use environment variables with ${ProgramFiles} syntax.
1034 1034 (default: the tool name)
1035 1035
1036 1036 ``args``
1037 1037 The arguments to pass to the tool executable. You can refer to the
1038 1038 files being merged as well as the output file through these
1039 1039 variables: ``$base``, ``$local``, ``$other``, ``$output``. The meaning
1040 1040 of ``$local`` and ``$other`` can vary depending on which action is being
1041 1041 performed. During and update or merge, ``$local`` represents the original
1042 1042 state of the file, while ``$other`` represents the commit you are updating
1043 1043 to or the commit you are merging with. During a rebase ``$local``
1044 1044 represents the destination of the rebase, and ``$other`` represents the
1045 1045 commit being rebased.
1046 1046 (default: ``$local $base $other``)
1047 1047
1048 1048 ``premerge``
1049 1049 Attempt to run internal non-interactive 3-way merge tool before
1050 1050 launching external tool. Options are ``true``, ``false``, ``keep`` or
1051 1051 ``keep-merge3``. The ``keep`` option will leave markers in the file if the
1052 1052 premerge fails. The ``keep-merge3`` will do the same but include information
1053 1053 about the base of the merge in the marker (see internal :merge3 in
1054 1054 :hg:`help merge-tools`).
1055 1055 (default: True)
1056 1056
1057 1057 ``binary``
1058 1058 This tool can merge binary files. (default: False, unless tool
1059 1059 was selected by file pattern match)
1060 1060
1061 1061 ``symlink``
1062 1062 This tool can merge symlinks. (default: False)
1063 1063
1064 1064 ``check``
1065 1065 A list of merge success-checking options:
1066 1066
1067 1067 ``changed``
1068 1068 Ask whether merge was successful when the merged file shows no changes.
1069 1069 ``conflicts``
1070 1070 Check whether there are conflicts even though the tool reported success.
1071 1071 ``prompt``
1072 1072 Always prompt for merge success, regardless of success reported by tool.
1073 1073
1074 1074 ``fixeol``
1075 1075 Attempt to fix up EOL changes caused by the merge tool.
1076 1076 (default: False)
1077 1077
1078 1078 ``gui``
1079 1079 This tool requires a graphical interface to run. (default: False)
1080 1080
1081 1081 ``regkey``
1082 1082 Windows registry key which describes install location of this
1083 1083 tool. Mercurial will search for this key first under
1084 1084 ``HKEY_CURRENT_USER`` and then under ``HKEY_LOCAL_MACHINE``.
1085 1085 (default: None)
1086 1086
1087 1087 ``regkeyalt``
1088 1088 An alternate Windows registry key to try if the first key is not
1089 1089 found. The alternate key uses the same ``regname`` and ``regappend``
1090 1090 semantics of the primary key. The most common use for this key
1091 1091 is to search for 32bit applications on 64bit operating systems.
1092 1092 (default: None)
1093 1093
1094 1094 ``regname``
1095 1095 Name of value to read from specified registry key.
1096 1096 (default: the unnamed (default) value)
1097 1097
1098 1098 ``regappend``
1099 1099 String to append to the value read from the registry, typically
1100 1100 the executable name of the tool.
1101 1101 (default: None)
1102 1102
1103 1103
1104 1104 ``patch``
1105 1105 ---------
1106 1106
1107 1107 Settings used when applying patches, for instance through the 'import'
1108 1108 command or with Mercurial Queues extension.
1109 1109
1110 1110 ``eol``
1111 1111 When set to 'strict' patch content and patched files end of lines
1112 1112 are preserved. When set to ``lf`` or ``crlf``, both files end of
1113 1113 lines are ignored when patching and the result line endings are
1114 1114 normalized to either LF (Unix) or CRLF (Windows). When set to
1115 1115 ``auto``, end of lines are again ignored while patching but line
1116 1116 endings in patched files are normalized to their original setting
1117 1117 on a per-file basis. If target file does not exist or has no end
1118 1118 of line, patch line endings are preserved.
1119 1119 (default: strict)
1120 1120
1121 1121 ``fuzz``
1122 1122 The number of lines of 'fuzz' to allow when applying patches. This
1123 1123 controls how much context the patcher is allowed to ignore when
1124 1124 trying to apply a patch.
1125 1125 (default: 2)
1126 1126
1127 1127 ``paths``
1128 1128 ---------
1129 1129
1130 Assigns symbolic names to repositories. The left side is the
1131 symbolic name, and the right gives the directory or URL that is the
1132 location of the repository. Default paths can be declared by setting
1133 the following entries.
1130 Assigns symbolic names and behavior to repositories.
1131
1132 Options are symbolic names defining the URL or directory that is the
1133 location of the repository. Example::
1134
1135 [paths]
1136 my_server = https://example.com/my_repo
1137 local_path = /home/me/repo
1138
1139 These symbolic names can be used from the command line. To pull
1140 from ``my_server``: :hg:`pull my_server`. To push to ``local_path``:
1141 :hg:`push local_path`.
1142
1143 Options containing colons (``:``) denote sub-options that can influence
1144 behavior for that specific path. Example::
1145
1146 [paths]
1147 my_server = https://example.com/my_path
1148 my_server:pushurl = ssh://example.com/my_path
1149
1150 The following sub-options can be defined:
1151
1152 ``pushurl``
1153 The URL to use for push operations. If not defined, the location
1154 defined by the path's main entry is used.
1155
1156 The following special named paths exist:
1134 1157
1135 1158 ``default``
1136 Directory or URL to use when pulling if no source is specified.
1137 (default: repository from which the current repository was cloned)
1159 The URL or directory to use when no source or remote is specified.
1160
1161 :hg:`clone` will automatically define this path to the location the
1162 repository was cloned from.
1138 1163
1139 1164 ``default-push``
1140 Optional. Directory or URL to use when pushing if no destination
1141 is specified.
1142
1143 Custom paths can be defined by assigning the path to a name that later can be
1144 used from the command line. Example::
1145
1146 [paths]
1147 my_path = http://example.com/path
1148
1149 To push to the path defined in ``my_path`` run the command::
1150
1151 hg push my_path
1152
1165 (deprecated) The URL or directory for the default :hg:`push` location.
1166 ``default:pushurl`` should be used instead.
1153 1167
1154 1168 ``phases``
1155 1169 ----------
1156 1170
1157 1171 Specifies default handling of phases. See :hg:`help phases` for more
1158 1172 information about working with phases.
1159 1173
1160 1174 ``publish``
1161 1175 Controls draft phase behavior when working as a server. When true,
1162 1176 pushed changesets are set to public in both client and server and
1163 1177 pulled or cloned changesets are set to public in the client.
1164 1178 (default: True)
1165 1179
1166 1180 ``new-commit``
1167 1181 Phase of newly-created commits.
1168 1182 (default: draft)
1169 1183
1170 1184 ``checksubrepos``
1171 1185 Check the phase of the current revision of each subrepository. Allowed
1172 1186 values are "ignore", "follow" and "abort". For settings other than
1173 1187 "ignore", the phase of the current revision of each subrepository is
1174 1188 checked before committing the parent repository. If any of those phases is
1175 1189 greater than the phase of the parent repository (e.g. if a subrepo is in a
1176 1190 "secret" phase while the parent repo is in "draft" phase), the commit is
1177 1191 either aborted (if checksubrepos is set to "abort") or the higher phase is
1178 1192 used for the parent repository commit (if set to "follow").
1179 1193 (default: follow)
1180 1194
1181 1195
1182 1196 ``profiling``
1183 1197 -------------
1184 1198
1185 1199 Specifies profiling type, format, and file output. Two profilers are
1186 1200 supported: an instrumenting profiler (named ``ls``), and a sampling
1187 1201 profiler (named ``stat``).
1188 1202
1189 1203 In this section description, 'profiling data' stands for the raw data
1190 1204 collected during profiling, while 'profiling report' stands for a
1191 1205 statistical text report generated from the profiling data. The
1192 1206 profiling is done using lsprof.
1193 1207
1194 1208 ``type``
1195 1209 The type of profiler to use.
1196 1210 (default: ls)
1197 1211
1198 1212 ``ls``
1199 1213 Use Python's built-in instrumenting profiler. This profiler
1200 1214 works on all platforms, but each line number it reports is the
1201 1215 first line of a function. This restriction makes it difficult to
1202 1216 identify the expensive parts of a non-trivial function.
1203 1217 ``stat``
1204 1218 Use a third-party statistical profiler, statprof. This profiler
1205 1219 currently runs only on Unix systems, and is most useful for
1206 1220 profiling commands that run for longer than about 0.1 seconds.
1207 1221
1208 1222 ``format``
1209 1223 Profiling format. Specific to the ``ls`` instrumenting profiler.
1210 1224 (default: text)
1211 1225
1212 1226 ``text``
1213 1227 Generate a profiling report. When saving to a file, it should be
1214 1228 noted that only the report is saved, and the profiling data is
1215 1229 not kept.
1216 1230 ``kcachegrind``
1217 1231 Format profiling data for kcachegrind use: when saving to a
1218 1232 file, the generated file can directly be loaded into
1219 1233 kcachegrind.
1220 1234
1221 1235 ``frequency``
1222 1236 Sampling frequency. Specific to the ``stat`` sampling profiler.
1223 1237 (default: 1000)
1224 1238
1225 1239 ``output``
1226 1240 File path where profiling data or report should be saved. If the
1227 1241 file exists, it is replaced. (default: None, data is printed on
1228 1242 stderr)
1229 1243
1230 1244 ``sort``
1231 1245 Sort field. Specific to the ``ls`` instrumenting profiler.
1232 1246 One of ``callcount``, ``reccallcount``, ``totaltime`` and
1233 1247 ``inlinetime``.
1234 1248 (default: inlinetime)
1235 1249
1236 1250 ``limit``
1237 1251 Number of lines to show. Specific to the ``ls`` instrumenting profiler.
1238 1252 (default: 30)
1239 1253
1240 1254 ``nested``
1241 1255 Show at most this number of lines of drill-down info after each main entry.
1242 1256 This can help explain the difference between Total and Inline.
1243 1257 Specific to the ``ls`` instrumenting profiler.
1244 1258 (default: 5)
1245 1259
1246 1260 ``progress``
1247 1261 ------------
1248 1262
1249 1263 Mercurial commands can draw progress bars that are as informative as
1250 1264 possible. Some progress bars only offer indeterminate information, while others
1251 1265 have a definite end point.
1252 1266
1253 1267 ``delay``
1254 1268 Number of seconds (float) before showing the progress bar. (default: 3)
1255 1269
1256 1270 ``changedelay``
1257 1271 Minimum delay before showing a new topic. When set to less than 3 * refresh,
1258 1272 that value will be used instead. (default: 1)
1259 1273
1260 1274 ``refresh``
1261 1275 Time in seconds between refreshes of the progress bar. (default: 0.1)
1262 1276
1263 1277 ``format``
1264 1278 Format of the progress bar.
1265 1279
1266 1280 Valid entries for the format field are ``topic``, ``bar``, ``number``,
1267 1281 ``unit``, ``estimate``, speed, and item. item defaults to the last 20
1268 1282 characters of the item, but this can be changed by adding either ``-<num>``
1269 1283 which would take the last num characters, or ``+<num>`` for the first num
1270 1284 characters.
1271 1285
1272 1286 (default: Topic bar number estimate)
1273 1287
1274 1288 ``width``
1275 1289 If set, the maximum width of the progress information (that is, min(width,
1276 1290 term width) will be used).
1277 1291
1278 1292 ``clear-complete``
1279 1293 Clear the progress bar after it's done. (default: True)
1280 1294
1281 1295 ``disable``
1282 1296 If true, don't show a progress bar.
1283 1297
1284 1298 ``assume-tty``
1285 1299 If true, ALWAYS show a progress bar, unless disable is given.
1286 1300
1287 1301 ``revsetalias``
1288 1302 ---------------
1289 1303
1290 1304 Alias definitions for revsets. See :hg:`help revsets` for details.
1291 1305
1292 1306 ``server``
1293 1307 ----------
1294 1308
1295 1309 Controls generic server settings.
1296 1310
1297 1311 ``uncompressed``
1298 1312 Whether to allow clients to clone a repository using the
1299 1313 uncompressed streaming protocol. This transfers about 40% more
1300 1314 data than a regular clone, but uses less memory and CPU on both
1301 1315 server and client. Over a LAN (100 Mbps or better) or a very fast
1302 1316 WAN, an uncompressed streaming clone is a lot faster (~10x) than a
1303 1317 regular clone. Over most WAN connections (anything slower than
1304 1318 about 6 Mbps), uncompressed streaming is slower, because of the
1305 1319 extra data transfer overhead. This mode will also temporarily hold
1306 1320 the write lock while determining what data to transfer.
1307 1321 (default: True)
1308 1322
1309 1323 ``preferuncompressed``
1310 1324 When set, clients will try to use the uncompressed streaming
1311 1325 protocol. (default: False)
1312 1326
1313 1327 ``validate``
1314 1328 Whether to validate the completeness of pushed changesets by
1315 1329 checking that all new file revisions specified in manifests are
1316 1330 present. (default: False)
1317 1331
1318 1332 ``maxhttpheaderlen``
1319 1333 Instruct HTTP clients not to send request headers longer than this
1320 1334 many bytes. (default: 1024)
1321 1335
1322 1336 ``bundle1``
1323 1337 Whether to allow clients to push and pull using the legacy bundle1
1324 1338 exchange format. (default: True)
1325 1339
1326 1340 ``bundle1.push``
1327 1341 Whether to allow clients to push using the legacy bundle1 exchange
1328 1342 format. (default: True)
1329 1343
1330 1344 ``bundle1.pull``
1331 1345 Whether to allow clients to pull using the legacy bundle1 exchange
1332 1346 format. (default: True)
1333 1347
1334 1348 Large repositories using the *generaldelta* storage format should
1335 1349 consider setting this option because converting *generaldelta*
1336 1350 repositories to the exchange format required by the bundle1 data
1337 1351 format can consume a lot of CPU.
1338 1352
1339 1353 ``smtp``
1340 1354 --------
1341 1355
1342 1356 Configuration for extensions that need to send email messages.
1343 1357
1344 1358 ``host``
1345 1359 Host name of mail server, e.g. "mail.example.com".
1346 1360
1347 1361 ``port``
1348 1362 Optional. Port to connect to on mail server. (default: 465 if
1349 1363 ``tls`` is smtps; 25 otherwise)
1350 1364
1351 1365 ``tls``
1352 1366 Optional. Method to enable TLS when connecting to mail server: starttls,
1353 1367 smtps or none. (default: none)
1354 1368
1355 1369 ``verifycert``
1356 1370 Optional. Verification for the certificate of mail server, when
1357 1371 ``tls`` is starttls or smtps. "strict", "loose" or False. For
1358 1372 "strict" or "loose", the certificate is verified as same as the
1359 1373 verification for HTTPS connections (see ``[hostfingerprints]`` and
1360 1374 ``[web] cacerts`` also). For "strict", sending email is also
1361 1375 aborted, if there is no configuration for mail server in
1362 1376 ``[hostfingerprints]`` and ``[web] cacerts``. --insecure for
1363 1377 :hg:`email` overwrites this as "loose". (default: strict)
1364 1378
1365 1379 ``username``
1366 1380 Optional. User name for authenticating with the SMTP server.
1367 1381 (default: None)
1368 1382
1369 1383 ``password``
1370 1384 Optional. Password for authenticating with the SMTP server. If not
1371 1385 specified, interactive sessions will prompt the user for a
1372 1386 password; non-interactive sessions will fail. (default: None)
1373 1387
1374 1388 ``local_hostname``
1375 1389 Optional. The hostname that the sender can use to identify
1376 1390 itself to the MTA.
1377 1391
1378 1392
1379 1393 ``subpaths``
1380 1394 ------------
1381 1395
1382 1396 Subrepository source URLs can go stale if a remote server changes name
1383 1397 or becomes temporarily unavailable. This section lets you define
1384 1398 rewrite rules of the form::
1385 1399
1386 1400 <pattern> = <replacement>
1387 1401
1388 1402 where ``pattern`` is a regular expression matching a subrepository
1389 1403 source URL and ``replacement`` is the replacement string used to
1390 1404 rewrite it. Groups can be matched in ``pattern`` and referenced in
1391 1405 ``replacements``. For instance::
1392 1406
1393 1407 http://server/(.*)-hg/ = http://hg.server/\1/
1394 1408
1395 1409 rewrites ``http://server/foo-hg/`` into ``http://hg.server/foo/``.
1396 1410
1397 1411 Relative subrepository paths are first made absolute, and the
1398 1412 rewrite rules are then applied on the full (absolute) path. The rules
1399 1413 are applied in definition order.
1400 1414
1401 1415 ``trusted``
1402 1416 -----------
1403 1417
1404 1418 Mercurial will not use the settings in the
1405 1419 ``.hg/hgrc`` file from a repository if it doesn't belong to a trusted
1406 1420 user or to a trusted group, as various hgrc features allow arbitrary
1407 1421 commands to be run. This issue is often encountered when configuring
1408 1422 hooks or extensions for shared repositories or servers. However,
1409 1423 the web interface will use some safe settings from the ``[web]``
1410 1424 section.
1411 1425
1412 1426 This section specifies what users and groups are trusted. The
1413 1427 current user is always trusted. To trust everybody, list a user or a
1414 1428 group with name ``*``. These settings must be placed in an
1415 1429 *already-trusted file* to take effect, such as ``$HOME/.hgrc`` of the
1416 1430 user or service running Mercurial.
1417 1431
1418 1432 ``users``
1419 1433 Comma-separated list of trusted users.
1420 1434
1421 1435 ``groups``
1422 1436 Comma-separated list of trusted groups.
1423 1437
1424 1438
1425 1439 ``ui``
1426 1440 ------
1427 1441
1428 1442 User interface controls.
1429 1443
1430 1444 ``archivemeta``
1431 1445 Whether to include the .hg_archival.txt file containing meta data
1432 1446 (hashes for the repository base and for tip) in archives created
1433 1447 by the :hg:`archive` command or downloaded via hgweb.
1434 1448 (default: True)
1435 1449
1436 1450 ``askusername``
1437 1451 Whether to prompt for a username when committing. If True, and
1438 1452 neither ``$HGUSER`` nor ``$EMAIL`` has been specified, then the user will
1439 1453 be prompted to enter a username. If no username is entered, the
1440 1454 default ``USER@HOST`` is used instead.
1441 1455 (default: False)
1442 1456
1443 1457 ``clonebundlefallback``
1444 1458 Whether failure to apply an advertised "clone bundle" from a server
1445 1459 should result in fallback to a regular clone.
1446 1460
1447 1461 This is disabled by default because servers advertising "clone
1448 1462 bundles" often do so to reduce server load. If advertised bundles
1449 1463 start mass failing and clients automatically fall back to a regular
1450 1464 clone, this would add significant and unexpected load to the server
1451 1465 since the server is expecting clone operations to be offloaded to
1452 1466 pre-generated bundles. Failing fast (the default behavior) ensures
1453 1467 clients don't overwhelm the server when "clone bundle" application
1454 1468 fails.
1455 1469
1456 1470 (default: False)
1457 1471
1458 1472 ``commitsubrepos``
1459 1473 Whether to commit modified subrepositories when committing the
1460 1474 parent repository. If False and one subrepository has uncommitted
1461 1475 changes, abort the commit.
1462 1476 (default: False)
1463 1477
1464 1478 ``debug``
1465 1479 Print debugging information. (default: False)
1466 1480
1467 1481 ``editor``
1468 1482 The editor to use during a commit. (default: ``$EDITOR`` or ``vi``)
1469 1483
1470 1484 ``fallbackencoding``
1471 1485 Encoding to try if it's not possible to decode the changelog using
1472 1486 UTF-8. (default: ISO-8859-1)
1473 1487
1474 1488 ``graphnodetemplate``
1475 1489 The template used to print changeset nodes in an ASCII revision graph.
1476 1490 (default: ``{graphnode}``)
1477 1491
1478 1492 ``ignore``
1479 1493 A file to read per-user ignore patterns from. This file should be
1480 1494 in the same format as a repository-wide .hgignore file. Filenames
1481 1495 are relative to the repository root. This option supports hook syntax,
1482 1496 so if you want to specify multiple ignore files, you can do so by
1483 1497 setting something like ``ignore.other = ~/.hgignore2``. For details
1484 1498 of the ignore file format, see the ``hgignore(5)`` man page.
1485 1499
1486 1500 ``interactive``
1487 1501 Allow to prompt the user. (default: True)
1488 1502
1489 1503 ``logtemplate``
1490 1504 Template string for commands that print changesets.
1491 1505
1492 1506 ``merge``
1493 1507 The conflict resolution program to use during a manual merge.
1494 1508 For more information on merge tools see :hg:`help merge-tools`.
1495 1509 For configuring merge tools see the ``[merge-tools]`` section.
1496 1510
1497 1511 ``mergemarkers``
1498 1512 Sets the merge conflict marker label styling. The ``detailed``
1499 1513 style uses the ``mergemarkertemplate`` setting to style the labels.
1500 1514 The ``basic`` style just uses 'local' and 'other' as the marker label.
1501 1515 One of ``basic`` or ``detailed``.
1502 1516 (default: ``basic``)
1503 1517
1504 1518 ``mergemarkertemplate``
1505 1519 The template used to print the commit description next to each conflict
1506 1520 marker during merge conflicts. See :hg:`help templates` for the template
1507 1521 format.
1508 1522
1509 1523 Defaults to showing the hash, tags, branches, bookmarks, author, and
1510 1524 the first line of the commit description.
1511 1525
1512 1526 If you use non-ASCII characters in names for tags, branches, bookmarks,
1513 1527 authors, and/or commit descriptions, you must pay attention to encodings of
1514 1528 managed files. At template expansion, non-ASCII characters use the encoding
1515 1529 specified by the ``--encoding`` global option, ``HGENCODING`` or other
1516 1530 environment variables that govern your locale. If the encoding of the merge
1517 1531 markers is different from the encoding of the merged files,
1518 1532 serious problems may occur.
1519 1533
1520 1534 ``origbackuppath``
1521 1535 The path to a directory used to store generated .orig files. If the path is
1522 1536 not a directory, one will be created.
1523 1537
1524 1538 ``patch``
1525 1539 An optional external tool that ``hg import`` and some extensions
1526 1540 will use for applying patches. By default Mercurial uses an
1527 1541 internal patch utility. The external tool must work as the common
1528 1542 Unix ``patch`` program. In particular, it must accept a ``-p``
1529 1543 argument to strip patch headers, a ``-d`` argument to specify the
1530 1544 current directory, a file name to patch, and a patch file to take
1531 1545 from stdin.
1532 1546
1533 1547 It is possible to specify a patch tool together with extra
1534 1548 arguments. For example, setting this option to ``patch --merge``
1535 1549 will use the ``patch`` program with its 2-way merge option.
1536 1550
1537 1551 ``portablefilenames``
1538 1552 Check for portable filenames. Can be ``warn``, ``ignore`` or ``abort``.
1539 1553 (default: ``warn``)
1540 1554 If set to ``warn`` (or ``true``), a warning message is printed on POSIX
1541 1555 platforms, if a file with a non-portable filename is added (e.g. a file
1542 1556 with a name that can't be created on Windows because it contains reserved
1543 1557 parts like ``AUX``, reserved characters like ``:``, or would cause a case
1544 1558 collision with an existing file).
1545 1559 If set to ``ignore`` (or ``false``), no warning is printed.
1546 1560 If set to ``abort``, the command is aborted.
1547 1561 On Windows, this configuration option is ignored and the command aborted.
1548 1562
1549 1563 ``quiet``
1550 1564 Reduce the amount of output printed. (default: False)
1551 1565
1552 1566 ``remotecmd``
1553 1567 Remote command to use for clone/push/pull operations. (default: ``hg``)
1554 1568
1555 1569 ``report_untrusted``
1556 1570 Warn if a ``.hg/hgrc`` file is ignored due to not being owned by a
1557 1571 trusted user or group. (default: True)
1558 1572
1559 1573 ``slash``
1560 1574 Display paths using a slash (``/``) as the path separator. This
1561 1575 only makes a difference on systems where the default path
1562 1576 separator is not the slash character (e.g. Windows uses the
1563 1577 backslash character (``\``)).
1564 1578 (default: False)
1565 1579
1566 1580 ``statuscopies``
1567 1581 Display copies in the status command.
1568 1582
1569 1583 ``ssh``
1570 1584 Command to use for SSH connections. (default: ``ssh``)
1571 1585
1572 1586 ``strict``
1573 1587 Require exact command names, instead of allowing unambiguous
1574 1588 abbreviations. (default: False)
1575 1589
1576 1590 ``style``
1577 1591 Name of style to use for command output.
1578 1592
1579 1593 ``supportcontact``
1580 1594 A URL where users should report a Mercurial traceback. Use this if you are a
1581 1595 large organisation with its own Mercurial deployment process and crash
1582 1596 reports should be addressed to your internal support.
1583 1597
1584 1598 ``timeout``
1585 1599 The timeout used when a lock is held (in seconds), a negative value
1586 1600 means no timeout. (default: 600)
1587 1601
1588 1602 ``traceback``
1589 1603 Mercurial always prints a traceback when an unknown exception
1590 1604 occurs. Setting this to True will make Mercurial print a traceback
1591 1605 on all exceptions, even those recognized by Mercurial (such as
1592 1606 IOError or MemoryError). (default: False)
1593 1607
1594 1608 ``username``
1595 1609 The committer of a changeset created when running "commit".
1596 1610 Typically a person's name and email address, e.g. ``Fred Widget
1597 1611 <fred@example.com>``. Environment variables in the
1598 1612 username are expanded.
1599 1613
1600 1614 (default: ``$EMAIL`` or ``username@hostname``. If the username in
1601 1615 hgrc is empty, e.g. if the system admin set ``username =`` in the
1602 1616 system hgrc, it has to be specified manually or in a different
1603 1617 hgrc file)
1604 1618
1605 1619 ``verbose``
1606 1620 Increase the amount of output printed. (default: False)
1607 1621
1608 1622
1609 1623 ``web``
1610 1624 -------
1611 1625
1612 1626 Web interface configuration. The settings in this section apply to
1613 1627 both the builtin webserver (started by :hg:`serve`) and the script you
1614 1628 run through a webserver (``hgweb.cgi`` and the derivatives for FastCGI
1615 1629 and WSGI).
1616 1630
1617 1631 The Mercurial webserver does no authentication (it does not prompt for
1618 1632 usernames and passwords to validate *who* users are), but it does do
1619 1633 authorization (it grants or denies access for *authenticated users*
1620 1634 based on settings in this section). You must either configure your
1621 1635 webserver to do authentication for you, or disable the authorization
1622 1636 checks.
1623 1637
1624 1638 For a quick setup in a trusted environment, e.g., a private LAN, where
1625 1639 you want it to accept pushes from anybody, you can use the following
1626 1640 command line::
1627 1641
1628 1642 $ hg --config web.allow_push=* --config web.push_ssl=False serve
1629 1643
1630 1644 Note that this will allow anybody to push anything to the server and
1631 1645 that this should not be used for public servers.
1632 1646
1633 1647 The full set of options is:
1634 1648
1635 1649 ``accesslog``
1636 1650 Where to output the access log. (default: stdout)
1637 1651
1638 1652 ``address``
1639 1653 Interface address to bind to. (default: all)
1640 1654
1641 1655 ``allow_archive``
1642 1656 List of archive format (bz2, gz, zip) allowed for downloading.
1643 1657 (default: empty)
1644 1658
1645 1659 ``allowbz2``
1646 1660 (DEPRECATED) Whether to allow .tar.bz2 downloading of repository
1647 1661 revisions.
1648 1662 (default: False)
1649 1663
1650 1664 ``allowgz``
1651 1665 (DEPRECATED) Whether to allow .tar.gz downloading of repository
1652 1666 revisions.
1653 1667 (default: False)
1654 1668
1655 1669 ``allowpull``
1656 1670 Whether to allow pulling from the repository. (default: True)
1657 1671
1658 1672 ``allow_push``
1659 1673 Whether to allow pushing to the repository. If empty or not set,
1660 1674 pushing is not allowed. If the special value ``*``, any remote
1661 1675 user can push, including unauthenticated users. Otherwise, the
1662 1676 remote user must have been authenticated, and the authenticated
1663 1677 user name must be present in this list. The contents of the
1664 1678 allow_push list are examined after the deny_push list.
1665 1679
1666 1680 ``allow_read``
1667 1681 If the user has not already been denied repository access due to
1668 1682 the contents of deny_read, this list determines whether to grant
1669 1683 repository access to the user. If this list is not empty, and the
1670 1684 user is unauthenticated or not present in the list, then access is
1671 1685 denied for the user. If the list is empty or not set, then access
1672 1686 is permitted to all users by default. Setting allow_read to the
1673 1687 special value ``*`` is equivalent to it not being set (i.e. access
1674 1688 is permitted to all users). The contents of the allow_read list are
1675 1689 examined after the deny_read list.
1676 1690
1677 1691 ``allowzip``
1678 1692 (DEPRECATED) Whether to allow .zip downloading of repository
1679 1693 revisions. This feature creates temporary files.
1680 1694 (default: False)
1681 1695
1682 1696 ``archivesubrepos``
1683 1697 Whether to recurse into subrepositories when archiving.
1684 1698 (default: False)
1685 1699
1686 1700 ``baseurl``
1687 1701 Base URL to use when publishing URLs in other locations, so
1688 1702 third-party tools like email notification hooks can construct
1689 1703 URLs. Example: ``http://hgserver/repos/``.
1690 1704
1691 1705 ``cacerts``
1692 1706 Path to file containing a list of PEM encoded certificate
1693 1707 authority certificates. Environment variables and ``~user``
1694 1708 constructs are expanded in the filename. If specified on the
1695 1709 client, then it will verify the identity of remote HTTPS servers
1696 1710 with these certificates.
1697 1711
1698 1712 This feature is only supported when using Python 2.6 or later. If you wish
1699 1713 to use it with earlier versions of Python, install the backported
1700 1714 version of the ssl library that is available from
1701 1715 ``http://pypi.python.org``.
1702 1716
1703 1717 To disable SSL verification temporarily, specify ``--insecure`` from
1704 1718 command line.
1705 1719
1706 1720 You can use OpenSSL's CA certificate file if your platform has
1707 1721 one. On most Linux systems this will be
1708 1722 ``/etc/ssl/certs/ca-certificates.crt``. Otherwise you will have to
1709 1723 generate this file manually. The form must be as follows::
1710 1724
1711 1725 -----BEGIN CERTIFICATE-----
1712 1726 ... (certificate in base64 PEM encoding) ...
1713 1727 -----END CERTIFICATE-----
1714 1728 -----BEGIN CERTIFICATE-----
1715 1729 ... (certificate in base64 PEM encoding) ...
1716 1730 -----END CERTIFICATE-----
1717 1731
1718 1732 ``cache``
1719 1733 Whether to support caching in hgweb. (default: True)
1720 1734
1721 1735 ``certificate``
1722 1736 Certificate to use when running :hg:`serve`.
1723 1737
1724 1738 ``collapse``
1725 1739 With ``descend`` enabled, repositories in subdirectories are shown at
1726 1740 a single level alongside repositories in the current path. With
1727 1741 ``collapse`` also enabled, repositories residing at a deeper level than
1728 1742 the current path are grouped behind navigable directory entries that
1729 1743 lead to the locations of these repositories. In effect, this setting
1730 1744 collapses each collection of repositories found within a subdirectory
1731 1745 into a single entry for that subdirectory. (default: False)
1732 1746
1733 1747 ``comparisoncontext``
1734 1748 Number of lines of context to show in side-by-side file comparison. If
1735 1749 negative or the value ``full``, whole files are shown. (default: 5)
1736 1750
1737 1751 This setting can be overridden by a ``context`` request parameter to the
1738 1752 ``comparison`` command, taking the same values.
1739 1753
1740 1754 ``contact``
1741 1755 Name or email address of the person in charge of the repository.
1742 1756 (default: ui.username or ``$EMAIL`` or "unknown" if unset or empty)
1743 1757
1744 1758 ``deny_push``
1745 1759 Whether to deny pushing to the repository. If empty or not set,
1746 1760 push is not denied. If the special value ``*``, all remote users are
1747 1761 denied push. Otherwise, unauthenticated users are all denied, and
1748 1762 any authenticated user name present in this list is also denied. The
1749 1763 contents of the deny_push list are examined before the allow_push list.
1750 1764
1751 1765 ``deny_read``
1752 1766 Whether to deny reading/viewing of the repository. If this list is
1753 1767 not empty, unauthenticated users are all denied, and any
1754 1768 authenticated user name present in this list is also denied access to
1755 1769 the repository. If set to the special value ``*``, all remote users
1756 1770 are denied access (rarely needed ;). If deny_read is empty or not set,
1757 1771 the determination of repository access depends on the presence and
1758 1772 content of the allow_read list (see description). If both
1759 1773 deny_read and allow_read are empty or not set, then access is
1760 1774 permitted to all users by default. If the repository is being
1761 1775 served via hgwebdir, denied users will not be able to see it in
1762 1776 the list of repositories. The contents of the deny_read list have
1763 1777 priority over (are examined before) the contents of the allow_read
1764 1778 list.
1765 1779
1766 1780 ``descend``
1767 1781 hgwebdir indexes will not descend into subdirectories. Only repositories
1768 1782 directly in the current path will be shown (other repositories are still
1769 1783 available from the index corresponding to their containing path).
1770 1784
1771 1785 ``description``
1772 1786 Textual description of the repository's purpose or contents.
1773 1787 (default: "unknown")
1774 1788
1775 1789 ``encoding``
1776 1790 Character encoding name. (default: the current locale charset)
1777 1791 Example: "UTF-8".
1778 1792
1779 1793 ``errorlog``
1780 1794 Where to output the error log. (default: stderr)
1781 1795
1782 1796 ``guessmime``
1783 1797 Control MIME types for raw download of file content.
1784 1798 Set to True to let hgweb guess the content type from the file
1785 1799 extension. This will serve HTML files as ``text/html`` and might
1786 1800 allow cross-site scripting attacks when serving untrusted
1787 1801 repositories. (default: False)
1788 1802
1789 1803 ``hidden``
1790 1804 Whether to hide the repository in the hgwebdir index.
1791 1805 (default: False)
1792 1806
1793 1807 ``ipv6``
1794 1808 Whether to use IPv6. (default: False)
1795 1809
1796 1810 ``logoimg``
1797 1811 File name of the logo image that some templates display on each page.
1798 1812 The file name is relative to ``staticurl``. That is, the full path to
1799 1813 the logo image is "staticurl/logoimg".
1800 1814 If unset, ``hglogo.png`` will be used.
1801 1815
1802 1816 ``logourl``
1803 1817 Base URL to use for logos. If unset, ``https://mercurial-scm.org/``
1804 1818 will be used.
1805 1819
1806 1820 ``maxchanges``
1807 1821 Maximum number of changes to list on the changelog. (default: 10)
1808 1822
1809 1823 ``maxfiles``
1810 1824 Maximum number of files to list per changeset. (default: 10)
1811 1825
1812 1826 ``maxshortchanges``
1813 1827 Maximum number of changes to list on the shortlog, graph or filelog
1814 1828 pages. (default: 60)
1815 1829
1816 1830 ``name``
1817 1831 Repository name to use in the web interface.
1818 1832 (default: current working directory)
1819 1833
1820 1834 ``port``
1821 1835 Port to listen on. (default: 8000)
1822 1836
1823 1837 ``prefix``
1824 1838 Prefix path to serve from. (default: '' (server root))
1825 1839
1826 1840 ``push_ssl``
1827 1841 Whether to require that inbound pushes be transported over SSL to
1828 1842 prevent password sniffing. (default: True)
1829 1843
1830 1844 ``refreshinterval``
1831 1845 How frequently directory listings re-scan the filesystem for new
1832 1846 repositories, in seconds. This is relevant when wildcards are used
1833 1847 to define paths. Depending on how much filesystem traversal is
1834 1848 required, refreshing may negatively impact performance.
1835 1849
1836 1850 Values less than or equal to 0 always refresh.
1837 1851 (default: 20)
1838 1852
1839 1853 ``staticurl``
1840 1854 Base URL to use for static files. If unset, static files (e.g. the
1841 1855 hgicon.png favicon) will be served by the CGI script itself. Use
1842 1856 this setting to serve them directly with the HTTP server.
1843 1857 Example: ``http://hgserver/static/``.
1844 1858
1845 1859 ``stripes``
1846 1860 How many lines a "zebra stripe" should span in multi-line output.
1847 1861 Set to 0 to disable. (default: 1)
1848 1862
1849 1863 ``style``
1850 1864 Which template map style to use. The available options are the names of
1851 1865 subdirectories in the HTML templates path. (default: ``paper``)
1852 1866 Example: ``monoblue``.
1853 1867
1854 1868 ``templates``
1855 1869 Where to find the HTML templates. The default path to the HTML templates
1856 1870 can be obtained from ``hg debuginstall``.
1857 1871
1858 1872 ``websub``
1859 1873 ----------
1860 1874
1861 1875 Web substitution filter definition. You can use this section to
1862 1876 define a set of regular expression substitution patterns which
1863 1877 let you automatically modify the hgweb server output.
1864 1878
1865 1879 The default hgweb templates only apply these substitution patterns
1866 1880 on the revision description fields. You can apply them anywhere
1867 1881 you want when you create your own templates by adding calls to the
1868 1882 "websub" filter (usually after calling the "escape" filter).
1869 1883
1870 1884 This can be used, for example, to convert issue references to links
1871 1885 to your issue tracker, or to convert "markdown-like" syntax into
1872 1886 HTML (see the examples below).
1873 1887
1874 1888 Each entry in this section names a substitution filter.
1875 1889 The value of each entry defines the substitution expression itself.
1876 1890 The websub expressions follow the old interhg extension syntax,
1877 1891 which in turn imitates the Unix sed replacement syntax::
1878 1892
1879 1893 patternname = s/SEARCH_REGEX/REPLACE_EXPRESSION/[i]
1880 1894
1881 1895 You can use any separator other than "/". The final "i" is optional
1882 1896 and indicates that the search must be case insensitive.
1883 1897
1884 1898 Examples::
1885 1899
1886 1900 [websub]
1887 1901 issues = s|issue(\d+)|<a href="http://bts.example.org/issue\1">issue\1</a>|i
1888 1902 italic = s/\b_(\S+)_\b/<i>\1<\/i>/
1889 1903 bold = s/\*\b(\S+)\b\*/<b>\1<\/b>/
1890 1904
1891 1905 ``worker``
1892 1906 ----------
1893 1907
1894 1908 Parallel master/worker configuration. We currently perform working
1895 1909 directory updates in parallel on Unix-like systems, which greatly
1896 1910 helps performance.
1897 1911
1898 1912 ``numcpus``
1899 1913 Number of CPUs to use for parallel operations. A zero or
1900 1914 negative value is treated as ``use the default``.
1901 1915 (default: 4 or the number of CPUs on the system, whichever is larger)
@@ -1,1179 +1,1243 b''
1 1 # ui.py - user interface bits for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from __future__ import absolute_import
9 9
10 10 import errno
11 11 import getpass
12 12 import inspect
13 13 import os
14 14 import socket
15 15 import sys
16 16 import tempfile
17 17 import traceback
18 18
19 19 from .i18n import _
20 20 from .node import hex
21 21
22 22 from . import (
23 23 config,
24 24 error,
25 25 formatter,
26 26 progress,
27 27 scmutil,
28 28 util,
29 29 )
30 30
31 31 samplehgrcs = {
32 32 'user':
33 33 """# example user config (see "hg help config" for more info)
34 34 [ui]
35 35 # name and email, e.g.
36 36 # username = Jane Doe <jdoe@example.com>
37 37 username =
38 38
39 39 [extensions]
40 40 # uncomment these lines to enable some popular extensions
41 41 # (see "hg help extensions" for more info)
42 42 #
43 43 # pager =
44 44 # progress =
45 45 # color =""",
46 46
47 47 'cloned':
48 48 """# example repository config (see "hg help config" for more info)
49 49 [paths]
50 50 default = %s
51 51
52 52 # path aliases to other clones of this repo in URLs or filesystem paths
53 53 # (see "hg help config.paths" for more info)
54 54 #
55 55 # default-push = ssh://jdoe@example.net/hg/jdoes-fork
56 56 # my-fork = ssh://jdoe@example.net/hg/jdoes-fork
57 57 # my-clone = /home/jdoe/jdoes-clone
58 58
59 59 [ui]
60 60 # name and email (local to this repository, optional), e.g.
61 61 # username = Jane Doe <jdoe@example.com>
62 62 """,
63 63
64 64 'local':
65 65 """# example repository config (see "hg help config" for more info)
66 66 [paths]
67 67 # path aliases to other clones of this repo in URLs or filesystem paths
68 68 # (see "hg help config.paths" for more info)
69 69 #
70 70 # default = http://example.com/hg/example-repo
71 71 # default-push = ssh://jdoe@example.net/hg/jdoes-fork
72 72 # my-fork = ssh://jdoe@example.net/hg/jdoes-fork
73 73 # my-clone = /home/jdoe/jdoes-clone
74 74
75 75 [ui]
76 76 # name and email (local to this repository, optional), e.g.
77 77 # username = Jane Doe <jdoe@example.com>
78 78 """,
79 79
80 80 'global':
81 81 """# example system-wide hg config (see "hg help config" for more info)
82 82
83 83 [extensions]
84 84 # uncomment these lines to enable some popular extensions
85 85 # (see "hg help extensions" for more info)
86 86 #
87 87 # blackbox =
88 88 # progress =
89 89 # color =
90 90 # pager =""",
91 91 }
92 92
93 93 class ui(object):
94 94 def __init__(self, src=None):
95 95 # _buffers: used for temporary capture of output
96 96 self._buffers = []
97 97 # 3-tuple describing how each buffer in the stack behaves.
98 98 # Values are (capture stderr, capture subprocesses, apply labels).
99 99 self._bufferstates = []
100 100 # When a buffer is active, defines whether we are expanding labels.
101 101 # This exists to prevent an extra list lookup.
102 102 self._bufferapplylabels = None
103 103 self.quiet = self.verbose = self.debugflag = self.tracebackflag = False
104 104 self._reportuntrusted = True
105 105 self._ocfg = config.config() # overlay
106 106 self._tcfg = config.config() # trusted
107 107 self._ucfg = config.config() # untrusted
108 108 self._trustusers = set()
109 109 self._trustgroups = set()
110 110 self.callhooks = True
111 111
112 112 if src:
113 113 self.fout = src.fout
114 114 self.ferr = src.ferr
115 115 self.fin = src.fin
116 116
117 117 self._tcfg = src._tcfg.copy()
118 118 self._ucfg = src._ucfg.copy()
119 119 self._ocfg = src._ocfg.copy()
120 120 self._trustusers = src._trustusers.copy()
121 121 self._trustgroups = src._trustgroups.copy()
122 122 self.environ = src.environ
123 123 self.callhooks = src.callhooks
124 124 self.fixconfig()
125 125 else:
126 126 self.fout = sys.stdout
127 127 self.ferr = sys.stderr
128 128 self.fin = sys.stdin
129 129
130 130 # shared read-only environment
131 131 self.environ = os.environ
132 132 # we always trust global config files
133 133 for f in scmutil.rcpath():
134 134 self.readconfig(f, trust=True)
135 135
136 136 def copy(self):
137 137 return self.__class__(self)
138 138
139 139 def formatter(self, topic, opts):
140 140 return formatter.formatter(self, topic, opts)
141 141
142 142 def _trusted(self, fp, f):
143 143 st = util.fstat(fp)
144 144 if util.isowner(st):
145 145 return True
146 146
147 147 tusers, tgroups = self._trustusers, self._trustgroups
148 148 if '*' in tusers or '*' in tgroups:
149 149 return True
150 150
151 151 user = util.username(st.st_uid)
152 152 group = util.groupname(st.st_gid)
153 153 if user in tusers or group in tgroups or user == util.username():
154 154 return True
155 155
156 156 if self._reportuntrusted:
157 157 self.warn(_('not trusting file %s from untrusted '
158 158 'user %s, group %s\n') % (f, user, group))
159 159 return False
160 160
161 161 def readconfig(self, filename, root=None, trust=False,
162 162 sections=None, remap=None):
163 163 try:
164 164 fp = open(filename)
165 165 except IOError:
166 166 if not sections: # ignore unless we were looking for something
167 167 return
168 168 raise
169 169
170 170 cfg = config.config()
171 171 trusted = sections or trust or self._trusted(fp, filename)
172 172
173 173 try:
174 174 cfg.read(filename, fp, sections=sections, remap=remap)
175 175 fp.close()
176 176 except error.ConfigError as inst:
177 177 if trusted:
178 178 raise
179 179 self.warn(_("ignored: %s\n") % str(inst))
180 180
181 181 if self.plain():
182 182 for k in ('debug', 'fallbackencoding', 'quiet', 'slash',
183 183 'logtemplate', 'statuscopies', 'style',
184 184 'traceback', 'verbose'):
185 185 if k in cfg['ui']:
186 186 del cfg['ui'][k]
187 187 for k, v in cfg.items('defaults'):
188 188 del cfg['defaults'][k]
189 189 # Don't remove aliases from the configuration if in the exceptionlist
190 190 if self.plain('alias'):
191 191 for k, v in cfg.items('alias'):
192 192 del cfg['alias'][k]
193 193 if self.plain('revsetalias'):
194 194 for k, v in cfg.items('revsetalias'):
195 195 del cfg['revsetalias'][k]
196 196
197 197 if trusted:
198 198 self._tcfg.update(cfg)
199 199 self._tcfg.update(self._ocfg)
200 200 self._ucfg.update(cfg)
201 201 self._ucfg.update(self._ocfg)
202 202
203 203 if root is None:
204 204 root = os.path.expanduser('~')
205 205 self.fixconfig(root=root)
206 206
207 207 def fixconfig(self, root=None, section=None):
208 208 if section in (None, 'paths'):
209 209 # expand vars and ~
210 210 # translate paths relative to root (or home) into absolute paths
211 211 root = root or os.getcwd()
212 212 for c in self._tcfg, self._ucfg, self._ocfg:
213 213 for n, p in c.items('paths'):
214 214 if not p:
215 215 continue
216 216 if '%%' in p:
217 217 self.warn(_("(deprecated '%%' in path %s=%s from %s)\n")
218 218 % (n, p, self.configsource('paths', n)))
219 219 p = p.replace('%%', '%')
220 220 p = util.expandpath(p)
221 221 if not util.hasscheme(p) and not os.path.isabs(p):
222 222 p = os.path.normpath(os.path.join(root, p))
223 223 c.set("paths", n, p)
224 224
225 225 if section in (None, 'ui'):
226 226 # update ui options
227 227 self.debugflag = self.configbool('ui', 'debug')
228 228 self.verbose = self.debugflag or self.configbool('ui', 'verbose')
229 229 self.quiet = not self.debugflag and self.configbool('ui', 'quiet')
230 230 if self.verbose and self.quiet:
231 231 self.quiet = self.verbose = False
232 232 self._reportuntrusted = self.debugflag or self.configbool("ui",
233 233 "report_untrusted", True)
234 234 self.tracebackflag = self.configbool('ui', 'traceback', False)
235 235
236 236 if section in (None, 'trusted'):
237 237 # update trust information
238 238 self._trustusers.update(self.configlist('trusted', 'users'))
239 239 self._trustgroups.update(self.configlist('trusted', 'groups'))
240 240
241 241 def backupconfig(self, section, item):
242 242 return (self._ocfg.backup(section, item),
243 243 self._tcfg.backup(section, item),
244 244 self._ucfg.backup(section, item),)
245 245 def restoreconfig(self, data):
246 246 self._ocfg.restore(data[0])
247 247 self._tcfg.restore(data[1])
248 248 self._ucfg.restore(data[2])
249 249
250 250 def setconfig(self, section, name, value, source=''):
251 251 for cfg in (self._ocfg, self._tcfg, self._ucfg):
252 252 cfg.set(section, name, value, source)
253 253 self.fixconfig(section=section)
254 254
255 255 def _data(self, untrusted):
256 256 return untrusted and self._ucfg or self._tcfg
257 257
258 258 def configsource(self, section, name, untrusted=False):
259 259 return self._data(untrusted).source(section, name) or 'none'
260 260
261 261 def config(self, section, name, default=None, untrusted=False):
262 262 if isinstance(name, list):
263 263 alternates = name
264 264 else:
265 265 alternates = [name]
266 266
267 267 for n in alternates:
268 268 value = self._data(untrusted).get(section, n, None)
269 269 if value is not None:
270 270 name = n
271 271 break
272 272 else:
273 273 value = default
274 274
275 275 if self.debugflag and not untrusted and self._reportuntrusted:
276 276 for n in alternates:
277 277 uvalue = self._ucfg.get(section, n)
278 278 if uvalue is not None and uvalue != value:
279 279 self.debug("ignoring untrusted configuration option "
280 280 "%s.%s = %s\n" % (section, n, uvalue))
281 281 return value
282 282
283 283 def configsuboptions(self, section, name, default=None, untrusted=False):
284 284 """Get a config option and all sub-options.
285 285
286 286 Some config options have sub-options that are declared with the
287 287 format "key:opt = value". This method is used to return the main
288 288 option and all its declared sub-options.
289 289
290 290 Returns a 2-tuple of ``(option, sub-options)``, where `sub-options``
291 291 is a dict of defined sub-options where keys and values are strings.
292 292 """
293 293 data = self._data(untrusted)
294 294 main = data.get(section, name, default)
295 295 if self.debugflag and not untrusted and self._reportuntrusted:
296 296 uvalue = self._ucfg.get(section, name)
297 297 if uvalue is not None and uvalue != main:
298 298 self.debug('ignoring untrusted configuration option '
299 299 '%s.%s = %s\n' % (section, name, uvalue))
300 300
301 301 sub = {}
302 302 prefix = '%s:' % name
303 303 for k, v in data.items(section):
304 304 if k.startswith(prefix):
305 305 sub[k[len(prefix):]] = v
306 306
307 307 if self.debugflag and not untrusted and self._reportuntrusted:
308 308 for k, v in sub.items():
309 309 uvalue = self._ucfg.get(section, '%s:%s' % (name, k))
310 310 if uvalue is not None and uvalue != v:
311 311 self.debug('ignoring untrusted configuration option '
312 312 '%s:%s.%s = %s\n' % (section, name, k, uvalue))
313 313
314 314 return main, sub
315 315
316 316 def configpath(self, section, name, default=None, untrusted=False):
317 317 'get a path config item, expanded relative to repo root or config file'
318 318 v = self.config(section, name, default, untrusted)
319 319 if v is None:
320 320 return None
321 321 if not os.path.isabs(v) or "://" not in v:
322 322 src = self.configsource(section, name, untrusted)
323 323 if ':' in src:
324 324 base = os.path.dirname(src.rsplit(':')[0])
325 325 v = os.path.join(base, os.path.expanduser(v))
326 326 return v
327 327
328 328 def configbool(self, section, name, default=False, untrusted=False):
329 329 """parse a configuration element as a boolean
330 330
331 331 >>> u = ui(); s = 'foo'
332 332 >>> u.setconfig(s, 'true', 'yes')
333 333 >>> u.configbool(s, 'true')
334 334 True
335 335 >>> u.setconfig(s, 'false', 'no')
336 336 >>> u.configbool(s, 'false')
337 337 False
338 338 >>> u.configbool(s, 'unknown')
339 339 False
340 340 >>> u.configbool(s, 'unknown', True)
341 341 True
342 342 >>> u.setconfig(s, 'invalid', 'somevalue')
343 343 >>> u.configbool(s, 'invalid')
344 344 Traceback (most recent call last):
345 345 ...
346 346 ConfigError: foo.invalid is not a boolean ('somevalue')
347 347 """
348 348
349 349 v = self.config(section, name, None, untrusted)
350 350 if v is None:
351 351 return default
352 352 if isinstance(v, bool):
353 353 return v
354 354 b = util.parsebool(v)
355 355 if b is None:
356 356 raise error.ConfigError(_("%s.%s is not a boolean ('%s')")
357 357 % (section, name, v))
358 358 return b
359 359
360 360 def configint(self, section, name, default=None, untrusted=False):
361 361 """parse a configuration element as an integer
362 362
363 363 >>> u = ui(); s = 'foo'
364 364 >>> u.setconfig(s, 'int1', '42')
365 365 >>> u.configint(s, 'int1')
366 366 42
367 367 >>> u.setconfig(s, 'int2', '-42')
368 368 >>> u.configint(s, 'int2')
369 369 -42
370 370 >>> u.configint(s, 'unknown', 7)
371 371 7
372 372 >>> u.setconfig(s, 'invalid', 'somevalue')
373 373 >>> u.configint(s, 'invalid')
374 374 Traceback (most recent call last):
375 375 ...
376 376 ConfigError: foo.invalid is not an integer ('somevalue')
377 377 """
378 378
379 379 v = self.config(section, name, None, untrusted)
380 380 if v is None:
381 381 return default
382 382 try:
383 383 return int(v)
384 384 except ValueError:
385 385 raise error.ConfigError(_("%s.%s is not an integer ('%s')")
386 386 % (section, name, v))
387 387
388 388 def configbytes(self, section, name, default=0, untrusted=False):
389 389 """parse a configuration element as a quantity in bytes
390 390
391 391 Units can be specified as b (bytes), k or kb (kilobytes), m or
392 392 mb (megabytes), g or gb (gigabytes).
393 393
394 394 >>> u = ui(); s = 'foo'
395 395 >>> u.setconfig(s, 'val1', '42')
396 396 >>> u.configbytes(s, 'val1')
397 397 42
398 398 >>> u.setconfig(s, 'val2', '42.5 kb')
399 399 >>> u.configbytes(s, 'val2')
400 400 43520
401 401 >>> u.configbytes(s, 'unknown', '7 MB')
402 402 7340032
403 403 >>> u.setconfig(s, 'invalid', 'somevalue')
404 404 >>> u.configbytes(s, 'invalid')
405 405 Traceback (most recent call last):
406 406 ...
407 407 ConfigError: foo.invalid is not a byte quantity ('somevalue')
408 408 """
409 409
410 410 value = self.config(section, name)
411 411 if value is None:
412 412 if not isinstance(default, str):
413 413 return default
414 414 value = default
415 415 try:
416 416 return util.sizetoint(value)
417 417 except error.ParseError:
418 418 raise error.ConfigError(_("%s.%s is not a byte quantity ('%s')")
419 419 % (section, name, value))
420 420
421 421 def configlist(self, section, name, default=None, untrusted=False):
422 422 """parse a configuration element as a list of comma/space separated
423 423 strings
424 424
425 425 >>> u = ui(); s = 'foo'
426 426 >>> u.setconfig(s, 'list1', 'this,is "a small" ,test')
427 427 >>> u.configlist(s, 'list1')
428 428 ['this', 'is', 'a small', 'test']
429 429 """
430 430
431 431 def _parse_plain(parts, s, offset):
432 432 whitespace = False
433 433 while offset < len(s) and (s[offset].isspace() or s[offset] == ','):
434 434 whitespace = True
435 435 offset += 1
436 436 if offset >= len(s):
437 437 return None, parts, offset
438 438 if whitespace:
439 439 parts.append('')
440 440 if s[offset] == '"' and not parts[-1]:
441 441 return _parse_quote, parts, offset + 1
442 442 elif s[offset] == '"' and parts[-1][-1] == '\\':
443 443 parts[-1] = parts[-1][:-1] + s[offset]
444 444 return _parse_plain, parts, offset + 1
445 445 parts[-1] += s[offset]
446 446 return _parse_plain, parts, offset + 1
447 447
448 448 def _parse_quote(parts, s, offset):
449 449 if offset < len(s) and s[offset] == '"': # ""
450 450 parts.append('')
451 451 offset += 1
452 452 while offset < len(s) and (s[offset].isspace() or
453 453 s[offset] == ','):
454 454 offset += 1
455 455 return _parse_plain, parts, offset
456 456
457 457 while offset < len(s) and s[offset] != '"':
458 458 if (s[offset] == '\\' and offset + 1 < len(s)
459 459 and s[offset + 1] == '"'):
460 460 offset += 1
461 461 parts[-1] += '"'
462 462 else:
463 463 parts[-1] += s[offset]
464 464 offset += 1
465 465
466 466 if offset >= len(s):
467 467 real_parts = _configlist(parts[-1])
468 468 if not real_parts:
469 469 parts[-1] = '"'
470 470 else:
471 471 real_parts[0] = '"' + real_parts[0]
472 472 parts = parts[:-1]
473 473 parts.extend(real_parts)
474 474 return None, parts, offset
475 475
476 476 offset += 1
477 477 while offset < len(s) and s[offset] in [' ', ',']:
478 478 offset += 1
479 479
480 480 if offset < len(s):
481 481 if offset + 1 == len(s) and s[offset] == '"':
482 482 parts[-1] += '"'
483 483 offset += 1
484 484 else:
485 485 parts.append('')
486 486 else:
487 487 return None, parts, offset
488 488
489 489 return _parse_plain, parts, offset
490 490
491 491 def _configlist(s):
492 492 s = s.rstrip(' ,')
493 493 if not s:
494 494 return []
495 495 parser, parts, offset = _parse_plain, [''], 0
496 496 while parser:
497 497 parser, parts, offset = parser(parts, s, offset)
498 498 return parts
499 499
500 500 result = self.config(section, name, untrusted=untrusted)
501 501 if result is None:
502 502 result = default or []
503 503 if isinstance(result, basestring):
504 504 result = _configlist(result.lstrip(' ,\n'))
505 505 if result is None:
506 506 result = default or []
507 507 return result
508 508
509 509 def has_section(self, section, untrusted=False):
510 510 '''tell whether section exists in config.'''
511 511 return section in self._data(untrusted)
512 512
513 513 def configitems(self, section, untrusted=False, ignoresub=False):
514 514 items = self._data(untrusted).items(section)
515 515 if ignoresub:
516 516 newitems = {}
517 517 for k, v in items:
518 518 if ':' not in k:
519 519 newitems[k] = v
520 520 items = newitems.items()
521 521 if self.debugflag and not untrusted and self._reportuntrusted:
522 522 for k, v in self._ucfg.items(section):
523 523 if self._tcfg.get(section, k) != v:
524 524 self.debug("ignoring untrusted configuration option "
525 525 "%s.%s = %s\n" % (section, k, v))
526 526 return items
527 527
528 528 def walkconfig(self, untrusted=False):
529 529 cfg = self._data(untrusted)
530 530 for section in cfg.sections():
531 531 for name, value in self.configitems(section, untrusted):
532 532 yield section, name, value
533 533
534 534 def plain(self, feature=None):
535 535 '''is plain mode active?
536 536
537 537 Plain mode means that all configuration variables which affect
538 538 the behavior and output of Mercurial should be
539 539 ignored. Additionally, the output should be stable,
540 540 reproducible and suitable for use in scripts or applications.
541 541
542 542 The only way to trigger plain mode is by setting either the
543 543 `HGPLAIN' or `HGPLAINEXCEPT' environment variables.
544 544
545 545 The return value can either be
546 546 - False if HGPLAIN is not set, or feature is in HGPLAINEXCEPT
547 547 - True otherwise
548 548 '''
549 549 if 'HGPLAIN' not in os.environ and 'HGPLAINEXCEPT' not in os.environ:
550 550 return False
551 551 exceptions = os.environ.get('HGPLAINEXCEPT', '').strip().split(',')
552 552 if feature and exceptions:
553 553 return feature not in exceptions
554 554 return True
555 555
556 556 def username(self):
557 557 """Return default username to be used in commits.
558 558
559 559 Searched in this order: $HGUSER, [ui] section of hgrcs, $EMAIL
560 560 and stop searching if one of these is set.
561 561 If not found and ui.askusername is True, ask the user, else use
562 562 ($LOGNAME or $USER or $LNAME or $USERNAME) + "@full.hostname".
563 563 """
564 564 user = os.environ.get("HGUSER")
565 565 if user is None:
566 566 user = self.config("ui", ["username", "user"])
567 567 if user is not None:
568 568 user = os.path.expandvars(user)
569 569 if user is None:
570 570 user = os.environ.get("EMAIL")
571 571 if user is None and self.configbool("ui", "askusername"):
572 572 user = self.prompt(_("enter a commit username:"), default=None)
573 573 if user is None and not self.interactive():
574 574 try:
575 575 user = '%s@%s' % (util.getuser(), socket.getfqdn())
576 576 self.warn(_("no username found, using '%s' instead\n") % user)
577 577 except KeyError:
578 578 pass
579 579 if not user:
580 580 raise error.Abort(_('no username supplied'),
581 581 hint=_('use "hg config --edit" '
582 582 'to set your username'))
583 583 if "\n" in user:
584 584 raise error.Abort(_("username %s contains a newline\n")
585 585 % repr(user))
586 586 return user
587 587
588 588 def shortuser(self, user):
589 589 """Return a short representation of a user name or email address."""
590 590 if not self.verbose:
591 591 user = util.shortuser(user)
592 592 return user
593 593
594 594 def expandpath(self, loc, default=None):
595 595 """Return repository location relative to cwd or from [paths]"""
596 596 try:
597 597 p = self.paths.getpath(loc)
598 598 if p:
599 599 return p.rawloc
600 600 except error.RepoError:
601 601 pass
602 602
603 603 if default:
604 604 try:
605 605 p = self.paths.getpath(default)
606 606 if p:
607 607 return p.rawloc
608 608 except error.RepoError:
609 609 pass
610 610
611 611 return loc
612 612
613 613 @util.propertycache
614 614 def paths(self):
615 615 return paths(self)
616 616
617 617 def pushbuffer(self, error=False, subproc=False, labeled=False):
618 618 """install a buffer to capture standard output of the ui object
619 619
620 620 If error is True, the error output will be captured too.
621 621
622 622 If subproc is True, output from subprocesses (typically hooks) will be
623 623 captured too.
624 624
625 625 If labeled is True, any labels associated with buffered
626 626 output will be handled. By default, this has no effect
627 627 on the output returned, but extensions and GUI tools may
628 628 handle this argument and returned styled output. If output
629 629 is being buffered so it can be captured and parsed or
630 630 processed, labeled should not be set to True.
631 631 """
632 632 self._buffers.append([])
633 633 self._bufferstates.append((error, subproc, labeled))
634 634 self._bufferapplylabels = labeled
635 635
636 636 def popbuffer(self):
637 637 '''pop the last buffer and return the buffered output'''
638 638 self._bufferstates.pop()
639 639 if self._bufferstates:
640 640 self._bufferapplylabels = self._bufferstates[-1][2]
641 641 else:
642 642 self._bufferapplylabels = None
643 643
644 644 return "".join(self._buffers.pop())
645 645
646 646 def write(self, *args, **opts):
647 647 '''write args to output
648 648
649 649 By default, this method simply writes to the buffer or stdout,
650 650 but extensions or GUI tools may override this method,
651 651 write_err(), popbuffer(), and label() to style output from
652 652 various parts of hg.
653 653
654 654 An optional keyword argument, "label", can be passed in.
655 655 This should be a string containing label names separated by
656 656 space. Label names take the form of "topic.type". For example,
657 657 ui.debug() issues a label of "ui.debug".
658 658
659 659 When labeling output for a specific command, a label of
660 660 "cmdname.type" is recommended. For example, status issues
661 661 a label of "status.modified" for modified files.
662 662 '''
663 663 if self._buffers:
664 664 self._buffers[-1].extend(a for a in args)
665 665 else:
666 666 self._progclear()
667 667 for a in args:
668 668 self.fout.write(a)
669 669
670 670 def write_err(self, *args, **opts):
671 671 self._progclear()
672 672 try:
673 673 if self._bufferstates and self._bufferstates[-1][0]:
674 674 return self.write(*args, **opts)
675 675 if not getattr(self.fout, 'closed', False):
676 676 self.fout.flush()
677 677 for a in args:
678 678 self.ferr.write(a)
679 679 # stderr may be buffered under win32 when redirected to files,
680 680 # including stdout.
681 681 if not getattr(self.ferr, 'closed', False):
682 682 self.ferr.flush()
683 683 except IOError as inst:
684 684 if inst.errno not in (errno.EPIPE, errno.EIO, errno.EBADF):
685 685 raise
686 686
687 687 def flush(self):
688 688 try: self.fout.flush()
689 689 except (IOError, ValueError): pass
690 690 try: self.ferr.flush()
691 691 except (IOError, ValueError): pass
692 692
693 693 def _isatty(self, fh):
694 694 if self.configbool('ui', 'nontty', False):
695 695 return False
696 696 return util.isatty(fh)
697 697
698 698 def interactive(self):
699 699 '''is interactive input allowed?
700 700
701 701 An interactive session is a session where input can be reasonably read
702 702 from `sys.stdin'. If this function returns false, any attempt to read
703 703 from stdin should fail with an error, unless a sensible default has been
704 704 specified.
705 705
706 706 Interactiveness is triggered by the value of the `ui.interactive'
707 707 configuration variable or - if it is unset - when `sys.stdin' points
708 708 to a terminal device.
709 709
710 710 This function refers to input only; for output, see `ui.formatted()'.
711 711 '''
712 712 i = self.configbool("ui", "interactive", None)
713 713 if i is None:
714 714 # some environments replace stdin without implementing isatty
715 715 # usually those are non-interactive
716 716 return self._isatty(self.fin)
717 717
718 718 return i
719 719
720 720 def termwidth(self):
721 721 '''how wide is the terminal in columns?
722 722 '''
723 723 if 'COLUMNS' in os.environ:
724 724 try:
725 725 return int(os.environ['COLUMNS'])
726 726 except ValueError:
727 727 pass
728 728 return util.termwidth()
729 729
730 730 def formatted(self):
731 731 '''should formatted output be used?
732 732
733 733 It is often desirable to format the output to suite the output medium.
734 734 Examples of this are truncating long lines or colorizing messages.
735 735 However, this is not often not desirable when piping output into other
736 736 utilities, e.g. `grep'.
737 737
738 738 Formatted output is triggered by the value of the `ui.formatted'
739 739 configuration variable or - if it is unset - when `sys.stdout' points
740 740 to a terminal device. Please note that `ui.formatted' should be
741 741 considered an implementation detail; it is not intended for use outside
742 742 Mercurial or its extensions.
743 743
744 744 This function refers to output only; for input, see `ui.interactive()'.
745 745 This function always returns false when in plain mode, see `ui.plain()'.
746 746 '''
747 747 if self.plain():
748 748 return False
749 749
750 750 i = self.configbool("ui", "formatted", None)
751 751 if i is None:
752 752 # some environments replace stdout without implementing isatty
753 753 # usually those are non-interactive
754 754 return self._isatty(self.fout)
755 755
756 756 return i
757 757
758 758 def _readline(self, prompt=''):
759 759 if self._isatty(self.fin):
760 760 try:
761 761 # magically add command line editing support, where
762 762 # available
763 763 import readline
764 764 # force demandimport to really load the module
765 765 readline.read_history_file
766 766 # windows sometimes raises something other than ImportError
767 767 except Exception:
768 768 pass
769 769
770 770 # call write() so output goes through subclassed implementation
771 771 # e.g. color extension on Windows
772 772 self.write(prompt)
773 773
774 774 # instead of trying to emulate raw_input, swap (self.fin,
775 775 # self.fout) with (sys.stdin, sys.stdout)
776 776 oldin = sys.stdin
777 777 oldout = sys.stdout
778 778 sys.stdin = self.fin
779 779 sys.stdout = self.fout
780 780 # prompt ' ' must exist; otherwise readline may delete entire line
781 781 # - http://bugs.python.org/issue12833
782 782 line = raw_input(' ')
783 783 sys.stdin = oldin
784 784 sys.stdout = oldout
785 785
786 786 # When stdin is in binary mode on Windows, it can cause
787 787 # raw_input() to emit an extra trailing carriage return
788 788 if os.linesep == '\r\n' and line and line[-1] == '\r':
789 789 line = line[:-1]
790 790 return line
791 791
792 792 def prompt(self, msg, default="y"):
793 793 """Prompt user with msg, read response.
794 794 If ui is not interactive, the default is returned.
795 795 """
796 796 if not self.interactive():
797 797 self.write(msg, ' ', default, "\n")
798 798 return default
799 799 try:
800 800 r = self._readline(self.label(msg, 'ui.prompt'))
801 801 if not r:
802 802 r = default
803 803 if self.configbool('ui', 'promptecho'):
804 804 self.write(r, "\n")
805 805 return r
806 806 except EOFError:
807 807 raise error.ResponseExpected()
808 808
809 809 @staticmethod
810 810 def extractchoices(prompt):
811 811 """Extract prompt message and list of choices from specified prompt.
812 812
813 813 This returns tuple "(message, choices)", and "choices" is the
814 814 list of tuple "(response character, text without &)".
815 815 """
816 816 parts = prompt.split('$$')
817 817 msg = parts[0].rstrip(' ')
818 818 choices = [p.strip(' ') for p in parts[1:]]
819 819 return (msg,
820 820 [(s[s.index('&') + 1].lower(), s.replace('&', '', 1))
821 821 for s in choices])
822 822
823 823 def promptchoice(self, prompt, default=0):
824 824 """Prompt user with a message, read response, and ensure it matches
825 825 one of the provided choices. The prompt is formatted as follows:
826 826
827 827 "would you like fries with that (Yn)? $$ &Yes $$ &No"
828 828
829 829 The index of the choice is returned. Responses are case
830 830 insensitive. If ui is not interactive, the default is
831 831 returned.
832 832 """
833 833
834 834 msg, choices = self.extractchoices(prompt)
835 835 resps = [r for r, t in choices]
836 836 while True:
837 837 r = self.prompt(msg, resps[default])
838 838 if r.lower() in resps:
839 839 return resps.index(r.lower())
840 840 self.write(_("unrecognized response\n"))
841 841
842 842 def getpass(self, prompt=None, default=None):
843 843 if not self.interactive():
844 844 return default
845 845 try:
846 846 self.write_err(self.label(prompt or _('password: '), 'ui.prompt'))
847 847 # disable getpass() only if explicitly specified. it's still valid
848 848 # to interact with tty even if fin is not a tty.
849 849 if self.configbool('ui', 'nontty'):
850 850 return self.fin.readline().rstrip('\n')
851 851 else:
852 852 return getpass.getpass('')
853 853 except EOFError:
854 854 raise error.ResponseExpected()
855 855 def status(self, *msg, **opts):
856 856 '''write status message to output (if ui.quiet is False)
857 857
858 858 This adds an output label of "ui.status".
859 859 '''
860 860 if not self.quiet:
861 861 opts['label'] = opts.get('label', '') + ' ui.status'
862 862 self.write(*msg, **opts)
863 863 def warn(self, *msg, **opts):
864 864 '''write warning message to output (stderr)
865 865
866 866 This adds an output label of "ui.warning".
867 867 '''
868 868 opts['label'] = opts.get('label', '') + ' ui.warning'
869 869 self.write_err(*msg, **opts)
870 870 def note(self, *msg, **opts):
871 871 '''write note to output (if ui.verbose is True)
872 872
873 873 This adds an output label of "ui.note".
874 874 '''
875 875 if self.verbose:
876 876 opts['label'] = opts.get('label', '') + ' ui.note'
877 877 self.write(*msg, **opts)
878 878 def debug(self, *msg, **opts):
879 879 '''write debug message to output (if ui.debugflag is True)
880 880
881 881 This adds an output label of "ui.debug".
882 882 '''
883 883 if self.debugflag:
884 884 opts['label'] = opts.get('label', '') + ' ui.debug'
885 885 self.write(*msg, **opts)
886 886
887 887 def edit(self, text, user, extra=None, editform=None, pending=None):
888 888 extra_defaults = { 'prefix': 'editor' }
889 889 if extra is not None:
890 890 extra_defaults.update(extra)
891 891 extra = extra_defaults
892 892 (fd, name) = tempfile.mkstemp(prefix='hg-' + extra['prefix'] + '-',
893 893 suffix=".txt", text=True)
894 894 try:
895 895 f = os.fdopen(fd, "w")
896 896 f.write(text)
897 897 f.close()
898 898
899 899 environ = {'HGUSER': user}
900 900 if 'transplant_source' in extra:
901 901 environ.update({'HGREVISION': hex(extra['transplant_source'])})
902 902 for label in ('intermediate-source', 'source', 'rebase_source'):
903 903 if label in extra:
904 904 environ.update({'HGREVISION': extra[label]})
905 905 break
906 906 if editform:
907 907 environ.update({'HGEDITFORM': editform})
908 908 if pending:
909 909 environ.update({'HG_PENDING': pending})
910 910
911 911 editor = self.geteditor()
912 912
913 913 self.system("%s \"%s\"" % (editor, name),
914 914 environ=environ,
915 915 onerr=error.Abort, errprefix=_("edit failed"))
916 916
917 917 f = open(name)
918 918 t = f.read()
919 919 f.close()
920 920 finally:
921 921 os.unlink(name)
922 922
923 923 return t
924 924
925 925 def system(self, cmd, environ=None, cwd=None, onerr=None, errprefix=None):
926 926 '''execute shell command with appropriate output stream. command
927 927 output will be redirected if fout is not stdout.
928 928 '''
929 929 out = self.fout
930 930 if any(s[1] for s in self._bufferstates):
931 931 out = self
932 932 return util.system(cmd, environ=environ, cwd=cwd, onerr=onerr,
933 933 errprefix=errprefix, out=out)
934 934
935 935 def traceback(self, exc=None, force=False):
936 936 '''print exception traceback if traceback printing enabled or forced.
937 937 only to call in exception handler. returns true if traceback
938 938 printed.'''
939 939 if self.tracebackflag or force:
940 940 if exc is None:
941 941 exc = sys.exc_info()
942 942 cause = getattr(exc[1], 'cause', None)
943 943
944 944 if cause is not None:
945 945 causetb = traceback.format_tb(cause[2])
946 946 exctb = traceback.format_tb(exc[2])
947 947 exconly = traceback.format_exception_only(cause[0], cause[1])
948 948
949 949 # exclude frame where 'exc' was chained and rethrown from exctb
950 950 self.write_err('Traceback (most recent call last):\n',
951 951 ''.join(exctb[:-1]),
952 952 ''.join(causetb),
953 953 ''.join(exconly))
954 954 else:
955 955 output = traceback.format_exception(exc[0], exc[1], exc[2])
956 956 self.write_err(''.join(output))
957 957 return self.tracebackflag or force
958 958
959 959 def geteditor(self):
960 960 '''return editor to use'''
961 961 if sys.platform == 'plan9':
962 962 # vi is the MIPS instruction simulator on Plan 9. We
963 963 # instead default to E to plumb commit messages to
964 964 # avoid confusion.
965 965 editor = 'E'
966 966 else:
967 967 editor = 'vi'
968 968 return (os.environ.get("HGEDITOR") or
969 969 self.config("ui", "editor") or
970 970 os.environ.get("VISUAL") or
971 971 os.environ.get("EDITOR", editor))
972 972
973 973 @util.propertycache
974 974 def _progbar(self):
975 975 """setup the progbar singleton to the ui object"""
976 976 if (self.quiet or self.debugflag
977 977 or self.configbool('progress', 'disable', False)
978 978 or not progress.shouldprint(self)):
979 979 return None
980 980 return getprogbar(self)
981 981
982 982 def _progclear(self):
983 983 """clear progress bar output if any. use it before any output"""
984 984 if '_progbar' not in vars(self): # nothing loaded yet
985 985 return
986 986 if self._progbar is not None and self._progbar.printed:
987 987 self._progbar.clear()
988 988
989 989 def progress(self, topic, pos, item="", unit="", total=None):
990 990 '''show a progress message
991 991
992 992 With stock hg, this is simply a debug message that is hidden
993 993 by default, but with extensions or GUI tools it may be
994 994 visible. 'topic' is the current operation, 'item' is a
995 995 non-numeric marker of the current position (i.e. the currently
996 996 in-process file), 'pos' is the current numeric position (i.e.
997 997 revision, bytes, etc.), unit is a corresponding unit label,
998 998 and total is the highest expected pos.
999 999
1000 1000 Multiple nested topics may be active at a time.
1001 1001
1002 1002 All topics should be marked closed by setting pos to None at
1003 1003 termination.
1004 1004 '''
1005 1005 if self._progbar is not None:
1006 1006 self._progbar.progress(topic, pos, item=item, unit=unit,
1007 1007 total=total)
1008 1008 if pos is None or not self.configbool('progress', 'debug'):
1009 1009 return
1010 1010
1011 1011 if unit:
1012 1012 unit = ' ' + unit
1013 1013 if item:
1014 1014 item = ' ' + item
1015 1015
1016 1016 if total:
1017 1017 pct = 100.0 * pos / total
1018 1018 self.debug('%s:%s %s/%s%s (%4.2f%%)\n'
1019 1019 % (topic, item, pos, total, unit, pct))
1020 1020 else:
1021 1021 self.debug('%s:%s %s%s\n' % (topic, item, pos, unit))
1022 1022
1023 1023 def log(self, service, *msg, **opts):
1024 1024 '''hook for logging facility extensions
1025 1025
1026 1026 service should be a readily-identifiable subsystem, which will
1027 1027 allow filtering.
1028 1028
1029 1029 *msg should be a newline-terminated format string to log, and
1030 1030 then any values to %-format into that format string.
1031 1031
1032 1032 **opts currently has no defined meanings.
1033 1033 '''
1034 1034
1035 1035 def label(self, msg, label):
1036 1036 '''style msg based on supplied label
1037 1037
1038 1038 Like ui.write(), this just returns msg unchanged, but extensions
1039 1039 and GUI tools can override it to allow styling output without
1040 1040 writing it.
1041 1041
1042 1042 ui.write(s, 'label') is equivalent to
1043 1043 ui.write(ui.label(s, 'label')).
1044 1044 '''
1045 1045 return msg
1046 1046
1047 1047 def develwarn(self, msg):
1048 1048 """issue a developer warning message"""
1049 1049 msg = 'devel-warn: ' + msg
1050 1050 if self.tracebackflag:
1051 1051 util.debugstacktrace(msg, 2, self.ferr, self.fout)
1052 1052 else:
1053 1053 curframe = inspect.currentframe()
1054 1054 calframe = inspect.getouterframes(curframe, 2)
1055 1055 self.write_err('%s at: %s:%s (%s)\n' % ((msg,) + calframe[2][1:4]))
1056 1056
1057 1057 class paths(dict):
1058 1058 """Represents a collection of paths and their configs.
1059 1059
1060 1060 Data is initially derived from ui instances and the config files they have
1061 1061 loaded.
1062 1062 """
1063 1063 def __init__(self, ui):
1064 1064 dict.__init__(self)
1065 1065
1066 for name, loc in ui.configitems('paths'):
1066 for name, loc in ui.configitems('paths', ignoresub=True):
1067 1067 # No location is the same as not existing.
1068 1068 if not loc:
1069 1069 continue
1070 1070
1071 1071 # TODO ignore default-push once all consumers stop referencing it
1072 1072 # since it is handled specifically below.
1073 1073
1074 self[name] = path(ui, name, rawloc=loc)
1074 loc, sub = ui.configsuboptions('paths', name)
1075 self[name] = path(ui, name, rawloc=loc, suboptions=sub)
1075 1076
1076 1077 # Handle default-push, which is a one-off that defines the push URL for
1077 1078 # the "default" path.
1078 1079 defaultpush = ui.config('paths', 'default-push')
1079 1080 if defaultpush:
1080 1081 # "default-push" can be defined without "default" entry. This is a
1081 1082 # bit weird, but is allowed for backwards compatibility.
1082 1083 if 'default' not in self:
1083 1084 self['default'] = path(ui, 'default', rawloc=defaultpush)
1084 1085 self['default'].pushloc = defaultpush
1085 1086
1086 1087 def getpath(self, name, default=None):
1087 1088 """Return a ``path`` from a string, falling back to a default.
1088 1089
1089 1090 ``name`` can be a named path or locations. Locations are filesystem
1090 1091 paths or URIs.
1091 1092
1092 1093 Returns None if ``name`` is not a registered path, a URI, or a local
1093 1094 path to a repo.
1094 1095 """
1095 1096 # Only fall back to default if no path was requested.
1096 1097 if name is None:
1097 1098 if default:
1098 1099 try:
1099 1100 return self[default]
1100 1101 except KeyError:
1101 1102 return None
1102 1103 else:
1103 1104 return None
1104 1105
1105 1106 # Most likely empty string.
1106 1107 # This may need to raise in the future.
1107 1108 if not name:
1108 1109 return None
1109 1110
1110 1111 try:
1111 1112 return self[name]
1112 1113 except KeyError:
1113 1114 # Try to resolve as a local path or URI.
1114 1115 try:
1115 1116 # We don't pass sub-options in, so no need to pass ui instance.
1116 1117 return path(None, None, rawloc=name)
1117 1118 except ValueError:
1118 1119 raise error.RepoError(_('repository %s does not exist') %
1119 1120 name)
1120 1121
1121 1122 assert False
1122 1123
1124 _pathsuboptions = {}
1125
1126 def pathsuboption(option, attr):
1127 """Decorator used to declare a path sub-option.
1128
1129 Arguments are the sub-option name and the attribute it should set on
1130 ``path`` instances.
1131
1132 The decorated function will receive as arguments a ``ui`` instance,
1133 ``path`` instance, and the string value of this option from the config.
1134 The function should return the value that will be set on the ``path``
1135 instance.
1136
1137 This decorator can be used to perform additional verification of
1138 sub-options and to change the type of sub-options.
1139 """
1140 def register(func):
1141 _pathsuboptions[option] = (attr, func)
1142 return func
1143 return register
1144
1145 @pathsuboption('pushurl', 'pushloc')
1146 def pushurlpathoption(ui, path, value):
1147 u = util.url(value)
1148 # Actually require a URL.
1149 if not u.scheme:
1150 ui.warn(_('(paths.%s:pushurl not a URL; ignoring)\n') % path.name)
1151 return None
1152
1153 # Don't support the #foo syntax in the push URL to declare branch to
1154 # push.
1155 if u.fragment:
1156 ui.warn(_('("#fragment" in paths.%s:pushurl not supported; '
1157 'ignoring)\n') % path.name)
1158 u.fragment = None
1159
1160 return str(u)
1161
1123 1162 class path(object):
1124 1163 """Represents an individual path and its configuration."""
1125 1164
1126 def __init__(self, ui, name, rawloc=None, pushloc=None):
1165 def __init__(self, ui, name, rawloc=None, suboptions=None):
1127 1166 """Construct a path from its config options.
1128 1167
1129 1168 ``ui`` is the ``ui`` instance the path is coming from.
1130 1169 ``name`` is the symbolic name of the path.
1131 1170 ``rawloc`` is the raw location, as defined in the config.
1132 1171 ``pushloc`` is the raw locations pushes should be made to.
1133 1172
1134 1173 If ``name`` is not defined, we require that the location be a) a local
1135 1174 filesystem path with a .hg directory or b) a URL. If not,
1136 1175 ``ValueError`` is raised.
1137 1176 """
1138 1177 if not rawloc:
1139 1178 raise ValueError('rawloc must be defined')
1140 1179
1141 1180 # Locations may define branches via syntax <base>#<branch>.
1142 1181 u = util.url(rawloc)
1143 1182 branch = None
1144 1183 if u.fragment:
1145 1184 branch = u.fragment
1146 1185 u.fragment = None
1147 1186
1148 1187 self.url = u
1149 1188 self.branch = branch
1150 1189
1151 1190 self.name = name
1152 1191 self.rawloc = rawloc
1153 1192 self.loc = str(u)
1154 self.pushloc = pushloc
1155 1193
1156 1194 # When given a raw location but not a symbolic name, validate the
1157 1195 # location is valid.
1158 1196 if not name and not u.scheme and not self._isvalidlocalpath(self.loc):
1159 1197 raise ValueError('location is not a URL or path to a local '
1160 1198 'repo: %s' % rawloc)
1161 1199
1200 suboptions = suboptions or {}
1201
1202 # Now process the sub-options. If a sub-option is registered, its
1203 # attribute will always be present. The value will be None if there
1204 # was no valid sub-option.
1205 for suboption, (attr, func) in _pathsuboptions.iteritems():
1206 if suboption not in suboptions:
1207 setattr(self, attr, None)
1208 continue
1209
1210 value = func(ui, self, suboptions[suboption])
1211 setattr(self, attr, value)
1212
1162 1213 def _isvalidlocalpath(self, path):
1163 1214 """Returns True if the given path is a potentially valid repository.
1164 1215 This is its own function so that extensions can change the definition of
1165 1216 'valid' in this case (like when pulling from a git repo into a hg
1166 1217 one)."""
1167 1218 return os.path.isdir(os.path.join(path, '.hg'))
1168 1219
1220 @property
1221 def suboptions(self):
1222 """Return sub-options and their values for this path.
1223
1224 This is intended to be used for presentation purposes.
1225 """
1226 d = {}
1227 for subopt, (attr, _func) in _pathsuboptions.iteritems():
1228 value = getattr(self, attr)
1229 if value is not None:
1230 d[subopt] = value
1231 return d
1232
1169 1233 # we instantiate one globally shared progress bar to avoid
1170 1234 # competing progress bars when multiple UI objects get created
1171 1235 _progresssingleton = None
1172 1236
1173 1237 def getprogbar(ui):
1174 1238 global _progresssingleton
1175 1239 if _progresssingleton is None:
1176 1240 # passing 'ui' object to the singleton is fishy,
1177 1241 # this is how the extension used to work but feel free to rework it.
1178 1242 _progresssingleton = progress.progbar(ui)
1179 1243 return _progresssingleton
@@ -1,71 +1,94 b''
1 1 $ hg init a
2 2
3 3 $ echo a > a/a
4 4 $ hg --cwd a ci -Ama
5 5 adding a
6 6
7 7 $ hg clone a c
8 8 updating to branch default
9 9 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
10 10
11 11 $ hg clone a b
12 12 updating to branch default
13 13 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
14 14
15 15 $ echo b >> b/a
16 16 $ hg --cwd b ci -mb
17 17
18 18 Push should provide a hint when both 'default' and 'default-push' not set:
19 19 $ cd c
20 20 $ hg push --config paths.default=
21 21 abort: default repository not configured!
22 22 (see the "path" section in "hg help config")
23 23 [255]
24 24
25 25 $ cd ..
26 26
27 27 Push should push to 'default' when 'default-push' not set:
28 28
29 29 $ hg --cwd b push
30 30 pushing to $TESTTMP/a (glob)
31 31 searching for changes
32 32 adding changesets
33 33 adding manifests
34 34 adding file changes
35 35 added 1 changesets with 1 changes to 1 files
36 36
37 37 Push should push to 'default-push' when set:
38 38
39 39 $ echo '[paths]' >> b/.hg/hgrc
40 40 $ echo 'default-push = ../c' >> b/.hg/hgrc
41 41 $ hg --cwd b push
42 42 pushing to $TESTTMP/c (glob)
43 43 searching for changes
44 44 adding changesets
45 45 adding manifests
46 46 adding file changes
47 47 added 1 changesets with 1 changes to 1 files
48 48
49 49 Push should push to 'default-push' when 'default' is not set
50 50
51 51 $ hg -q clone a push-default-only
52 52 $ cd push-default-only
53 53 $ rm .hg/hgrc
54 54
55 55 $ touch foo
56 56 $ hg -q commit -A -m 'add foo'
57 57 $ hg --config paths.default-push=../a push
58 58 pushing to $TESTTMP/a (glob)
59 59 searching for changes
60 60 adding changesets
61 61 adding manifests
62 62 adding file changes
63 63 added 1 changesets with 1 changes to 1 files
64 64
65 65 $ cd ..
66 66
67 67 Pushing to a path that isn't defined should not fall back to default
68 68
69 69 $ hg --cwd b push doesnotexist
70 70 abort: repository doesnotexist does not exist!
71 71 [255]
72
73 :pushurl is used when defined
74
75 $ hg -q clone a pushurlsource
76 $ hg -q clone a pushurldest
77 $ cd pushurlsource
78 $ cat > .hg/hgrc << EOF
79 > [paths]
80 > default = https://example.com/not/relevant
81 > default:pushurl = file://`pwd`/../pushurldest
82 > EOF
83
84 $ touch pushurl
85 $ hg -q commit -A -m 'add pushurl'
86 $ hg push
87 pushing to file:/*/$TESTTMP/pushurlsource/../pushurldest (glob)
88 searching for changes
89 adding changesets
90 adding manifests
91 adding file changes
92 added 1 changesets with 1 changes to 1 files
93
94 $ cd ..
@@ -1,2415 +1,2430 b''
1 1 Short help:
2 2
3 3 $ hg
4 4 Mercurial Distributed SCM
5 5
6 6 basic commands:
7 7
8 8 add add the specified files on the next commit
9 9 annotate show changeset information by line for each file
10 10 clone make a copy of an existing repository
11 11 commit commit the specified files or all outstanding changes
12 12 diff diff repository (or selected files)
13 13 export dump the header and diffs for one or more changesets
14 14 forget forget the specified files on the next commit
15 15 init create a new repository in the given directory
16 16 log show revision history of entire repository or files
17 17 merge merge another revision into working directory
18 18 pull pull changes from the specified source
19 19 push push changes to the specified destination
20 20 remove remove the specified files on the next commit
21 21 serve start stand-alone webserver
22 22 status show changed files in the working directory
23 23 summary summarize working directory state
24 24 update update working directory (or switch revisions)
25 25
26 26 (use "hg help" for the full list of commands or "hg -v" for details)
27 27
28 28 $ hg -q
29 29 add add the specified files on the next commit
30 30 annotate show changeset information by line for each file
31 31 clone make a copy of an existing repository
32 32 commit commit the specified files or all outstanding changes
33 33 diff diff repository (or selected files)
34 34 export dump the header and diffs for one or more changesets
35 35 forget forget the specified files on the next commit
36 36 init create a new repository in the given directory
37 37 log show revision history of entire repository or files
38 38 merge merge another revision into working directory
39 39 pull pull changes from the specified source
40 40 push push changes to the specified destination
41 41 remove remove the specified files on the next commit
42 42 serve start stand-alone webserver
43 43 status show changed files in the working directory
44 44 summary summarize working directory state
45 45 update update working directory (or switch revisions)
46 46
47 47 $ hg help
48 48 Mercurial Distributed SCM
49 49
50 50 list of commands:
51 51
52 52 add add the specified files on the next commit
53 53 addremove add all new files, delete all missing files
54 54 annotate show changeset information by line for each file
55 55 archive create an unversioned archive of a repository revision
56 56 backout reverse effect of earlier changeset
57 57 bisect subdivision search of changesets
58 58 bookmarks create a new bookmark or list existing bookmarks
59 59 branch set or show the current branch name
60 60 branches list repository named branches
61 61 bundle create a changegroup file
62 62 cat output the current or given revision of files
63 63 clone make a copy of an existing repository
64 64 commit commit the specified files or all outstanding changes
65 65 config show combined config settings from all hgrc files
66 66 copy mark files as copied for the next commit
67 67 diff diff repository (or selected files)
68 68 export dump the header and diffs for one or more changesets
69 69 files list tracked files
70 70 forget forget the specified files on the next commit
71 71 graft copy changes from other branches onto the current branch
72 72 grep search for a pattern in specified files and revisions
73 73 heads show branch heads
74 74 help show help for a given topic or a help overview
75 75 identify identify the working directory or specified revision
76 76 import import an ordered set of patches
77 77 incoming show new changesets found in source
78 78 init create a new repository in the given directory
79 79 log show revision history of entire repository or files
80 80 manifest output the current or given revision of the project manifest
81 81 merge merge another revision into working directory
82 82 outgoing show changesets not found in the destination
83 83 paths show aliases for remote repositories
84 84 phase set or show the current phase name
85 85 pull pull changes from the specified source
86 86 push push changes to the specified destination
87 87 recover roll back an interrupted transaction
88 88 remove remove the specified files on the next commit
89 89 rename rename files; equivalent of copy + remove
90 90 resolve redo merges or set/view the merge status of files
91 91 revert restore files to their checkout state
92 92 root print the root (top) of the current working directory
93 93 serve start stand-alone webserver
94 94 status show changed files in the working directory
95 95 summary summarize working directory state
96 96 tag add one or more tags for the current or given revision
97 97 tags list repository tags
98 98 unbundle apply one or more changegroup files
99 99 update update working directory (or switch revisions)
100 100 verify verify the integrity of the repository
101 101 version output version and copyright information
102 102
103 103 additional help topics:
104 104
105 105 config Configuration Files
106 106 dates Date Formats
107 107 diffs Diff Formats
108 108 environment Environment Variables
109 109 extensions Using Additional Features
110 110 filesets Specifying File Sets
111 111 glossary Glossary
112 112 hgignore Syntax for Mercurial Ignore Files
113 113 hgweb Configuring hgweb
114 114 merge-tools Merge Tools
115 115 multirevs Specifying Multiple Revisions
116 116 patterns File Name Patterns
117 117 phases Working with Phases
118 118 revisions Specifying Single Revisions
119 119 revsets Specifying Revision Sets
120 120 scripting Using Mercurial from scripts and automation
121 121 subrepos Subrepositories
122 122 templating Template Usage
123 123 urls URL Paths
124 124
125 125 (use "hg help -v" to show built-in aliases and global options)
126 126
127 127 $ hg -q help
128 128 add add the specified files on the next commit
129 129 addremove add all new files, delete all missing files
130 130 annotate show changeset information by line for each file
131 131 archive create an unversioned archive of a repository revision
132 132 backout reverse effect of earlier changeset
133 133 bisect subdivision search of changesets
134 134 bookmarks create a new bookmark or list existing bookmarks
135 135 branch set or show the current branch name
136 136 branches list repository named branches
137 137 bundle create a changegroup file
138 138 cat output the current or given revision of files
139 139 clone make a copy of an existing repository
140 140 commit commit the specified files or all outstanding changes
141 141 config show combined config settings from all hgrc files
142 142 copy mark files as copied for the next commit
143 143 diff diff repository (or selected files)
144 144 export dump the header and diffs for one or more changesets
145 145 files list tracked files
146 146 forget forget the specified files on the next commit
147 147 graft copy changes from other branches onto the current branch
148 148 grep search for a pattern in specified files and revisions
149 149 heads show branch heads
150 150 help show help for a given topic or a help overview
151 151 identify identify the working directory or specified revision
152 152 import import an ordered set of patches
153 153 incoming show new changesets found in source
154 154 init create a new repository in the given directory
155 155 log show revision history of entire repository or files
156 156 manifest output the current or given revision of the project manifest
157 157 merge merge another revision into working directory
158 158 outgoing show changesets not found in the destination
159 159 paths show aliases for remote repositories
160 160 phase set or show the current phase name
161 161 pull pull changes from the specified source
162 162 push push changes to the specified destination
163 163 recover roll back an interrupted transaction
164 164 remove remove the specified files on the next commit
165 165 rename rename files; equivalent of copy + remove
166 166 resolve redo merges or set/view the merge status of files
167 167 revert restore files to their checkout state
168 168 root print the root (top) of the current working directory
169 169 serve start stand-alone webserver
170 170 status show changed files in the working directory
171 171 summary summarize working directory state
172 172 tag add one or more tags for the current or given revision
173 173 tags list repository tags
174 174 unbundle apply one or more changegroup files
175 175 update update working directory (or switch revisions)
176 176 verify verify the integrity of the repository
177 177 version output version and copyright information
178 178
179 179 additional help topics:
180 180
181 181 config Configuration Files
182 182 dates Date Formats
183 183 diffs Diff Formats
184 184 environment Environment Variables
185 185 extensions Using Additional Features
186 186 filesets Specifying File Sets
187 187 glossary Glossary
188 188 hgignore Syntax for Mercurial Ignore Files
189 189 hgweb Configuring hgweb
190 190 merge-tools Merge Tools
191 191 multirevs Specifying Multiple Revisions
192 192 patterns File Name Patterns
193 193 phases Working with Phases
194 194 revisions Specifying Single Revisions
195 195 revsets Specifying Revision Sets
196 196 scripting Using Mercurial from scripts and automation
197 197 subrepos Subrepositories
198 198 templating Template Usage
199 199 urls URL Paths
200 200
201 201 Test extension help:
202 202 $ hg help extensions --config extensions.rebase= --config extensions.children=
203 203 Using Additional Features
204 204 """""""""""""""""""""""""
205 205
206 206 Mercurial has the ability to add new features through the use of
207 207 extensions. Extensions may add new commands, add options to existing
208 208 commands, change the default behavior of commands, or implement hooks.
209 209
210 210 To enable the "foo" extension, either shipped with Mercurial or in the
211 211 Python search path, create an entry for it in your configuration file,
212 212 like this:
213 213
214 214 [extensions]
215 215 foo =
216 216
217 217 You may also specify the full path to an extension:
218 218
219 219 [extensions]
220 220 myfeature = ~/.hgext/myfeature.py
221 221
222 222 See "hg help config" for more information on configuration files.
223 223
224 224 Extensions are not loaded by default for a variety of reasons: they can
225 225 increase startup overhead; they may be meant for advanced usage only; they
226 226 may provide potentially dangerous abilities (such as letting you destroy
227 227 or modify history); they might not be ready for prime time; or they may
228 228 alter some usual behaviors of stock Mercurial. It is thus up to the user
229 229 to activate extensions as needed.
230 230
231 231 To explicitly disable an extension enabled in a configuration file of
232 232 broader scope, prepend its path with !:
233 233
234 234 [extensions]
235 235 # disabling extension bar residing in /path/to/extension/bar.py
236 236 bar = !/path/to/extension/bar.py
237 237 # ditto, but no path was supplied for extension baz
238 238 baz = !
239 239
240 240 enabled extensions:
241 241
242 242 children command to display child changesets (DEPRECATED)
243 243 rebase command to move sets of revisions to a different ancestor
244 244
245 245 disabled extensions:
246 246
247 247 acl hooks for controlling repository access
248 248 blackbox log repository events to a blackbox for debugging
249 249 bugzilla hooks for integrating with the Bugzilla bug tracker
250 250 censor erase file content at a given revision
251 251 churn command to display statistics about repository history
252 252 clonebundles advertise pre-generated bundles to seed clones
253 253 (experimental)
254 254 color colorize output from some commands
255 255 convert import revisions from foreign VCS repositories into
256 256 Mercurial
257 257 eol automatically manage newlines in repository files
258 258 extdiff command to allow external programs to compare revisions
259 259 factotum http authentication with factotum
260 260 gpg commands to sign and verify changesets
261 261 hgcia hooks for integrating with the CIA.vc notification service
262 262 hgk browse the repository in a graphical way
263 263 highlight syntax highlighting for hgweb (requires Pygments)
264 264 histedit interactive history editing
265 265 keyword expand keywords in tracked files
266 266 largefiles track large binary files
267 267 mq manage a stack of patches
268 268 notify hooks for sending email push notifications
269 269 pager browse command output with an external pager
270 270 patchbomb command to send changesets as (a series of) patch emails
271 271 purge command to delete untracked files from the working
272 272 directory
273 273 record commands to interactively select changes for
274 274 commit/qrefresh
275 275 relink recreates hardlinks between repository clones
276 276 schemes extend schemes with shortcuts to repository swarms
277 277 share share a common history between several working directories
278 278 shelve save and restore changes to the working directory
279 279 strip strip changesets and their descendants from history
280 280 transplant command to transplant changesets from another branch
281 281 win32mbcs allow the use of MBCS paths with problematic encodings
282 282 zeroconf discover and advertise repositories on the local network
283 283
284 284 Verify that extension keywords appear in help templates
285 285
286 286 $ hg help --config extensions.transplant= templating|grep transplant > /dev/null
287 287
288 288 Test short command list with verbose option
289 289
290 290 $ hg -v help shortlist
291 291 Mercurial Distributed SCM
292 292
293 293 basic commands:
294 294
295 295 add add the specified files on the next commit
296 296 annotate, blame
297 297 show changeset information by line for each file
298 298 clone make a copy of an existing repository
299 299 commit, ci commit the specified files or all outstanding changes
300 300 diff diff repository (or selected files)
301 301 export dump the header and diffs for one or more changesets
302 302 forget forget the specified files on the next commit
303 303 init create a new repository in the given directory
304 304 log, history show revision history of entire repository or files
305 305 merge merge another revision into working directory
306 306 pull pull changes from the specified source
307 307 push push changes to the specified destination
308 308 remove, rm remove the specified files on the next commit
309 309 serve start stand-alone webserver
310 310 status, st show changed files in the working directory
311 311 summary, sum summarize working directory state
312 312 update, up, checkout, co
313 313 update working directory (or switch revisions)
314 314
315 315 global options ([+] can be repeated):
316 316
317 317 -R --repository REPO repository root directory or name of overlay bundle
318 318 file
319 319 --cwd DIR change working directory
320 320 -y --noninteractive do not prompt, automatically pick the first choice for
321 321 all prompts
322 322 -q --quiet suppress output
323 323 -v --verbose enable additional output
324 324 --config CONFIG [+] set/override config option (use 'section.name=value')
325 325 --debug enable debugging output
326 326 --debugger start debugger
327 327 --encoding ENCODE set the charset encoding (default: ascii)
328 328 --encodingmode MODE set the charset encoding mode (default: strict)
329 329 --traceback always print a traceback on exception
330 330 --time time how long the command takes
331 331 --profile print command execution profile
332 332 --version output version information and exit
333 333 -h --help display help and exit
334 334 --hidden consider hidden changesets
335 335
336 336 (use "hg help" for the full list of commands)
337 337
338 338 $ hg add -h
339 339 hg add [OPTION]... [FILE]...
340 340
341 341 add the specified files on the next commit
342 342
343 343 Schedule files to be version controlled and added to the repository.
344 344
345 345 The files will be added to the repository at the next commit. To undo an
346 346 add before that, see "hg forget".
347 347
348 348 If no names are given, add all files to the repository.
349 349
350 350 Returns 0 if all files are successfully added.
351 351
352 352 options ([+] can be repeated):
353 353
354 354 -I --include PATTERN [+] include names matching the given patterns
355 355 -X --exclude PATTERN [+] exclude names matching the given patterns
356 356 -S --subrepos recurse into subrepositories
357 357 -n --dry-run do not perform actions, just print output
358 358
359 359 (some details hidden, use --verbose to show complete help)
360 360
361 361 Verbose help for add
362 362
363 363 $ hg add -hv
364 364 hg add [OPTION]... [FILE]...
365 365
366 366 add the specified files on the next commit
367 367
368 368 Schedule files to be version controlled and added to the repository.
369 369
370 370 The files will be added to the repository at the next commit. To undo an
371 371 add before that, see "hg forget".
372 372
373 373 If no names are given, add all files to the repository.
374 374
375 375 Examples:
376 376
377 377 - New (unknown) files are added automatically by "hg add":
378 378
379 379 $ ls
380 380 foo.c
381 381 $ hg status
382 382 ? foo.c
383 383 $ hg add
384 384 adding foo.c
385 385 $ hg status
386 386 A foo.c
387 387
388 388 - Specific files to be added can be specified:
389 389
390 390 $ ls
391 391 bar.c foo.c
392 392 $ hg status
393 393 ? bar.c
394 394 ? foo.c
395 395 $ hg add bar.c
396 396 $ hg status
397 397 A bar.c
398 398 ? foo.c
399 399
400 400 Returns 0 if all files are successfully added.
401 401
402 402 options ([+] can be repeated):
403 403
404 404 -I --include PATTERN [+] include names matching the given patterns
405 405 -X --exclude PATTERN [+] exclude names matching the given patterns
406 406 -S --subrepos recurse into subrepositories
407 407 -n --dry-run do not perform actions, just print output
408 408
409 409 global options ([+] can be repeated):
410 410
411 411 -R --repository REPO repository root directory or name of overlay bundle
412 412 file
413 413 --cwd DIR change working directory
414 414 -y --noninteractive do not prompt, automatically pick the first choice for
415 415 all prompts
416 416 -q --quiet suppress output
417 417 -v --verbose enable additional output
418 418 --config CONFIG [+] set/override config option (use 'section.name=value')
419 419 --debug enable debugging output
420 420 --debugger start debugger
421 421 --encoding ENCODE set the charset encoding (default: ascii)
422 422 --encodingmode MODE set the charset encoding mode (default: strict)
423 423 --traceback always print a traceback on exception
424 424 --time time how long the command takes
425 425 --profile print command execution profile
426 426 --version output version information and exit
427 427 -h --help display help and exit
428 428 --hidden consider hidden changesets
429 429
430 430 Test help option with version option
431 431
432 432 $ hg add -h --version
433 433 Mercurial Distributed SCM (version *) (glob)
434 434 (see https://mercurial-scm.org for more information)
435 435
436 436 Copyright (C) 2005-2015 Matt Mackall and others
437 437 This is free software; see the source for copying conditions. There is NO
438 438 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
439 439
440 440 $ hg add --skjdfks
441 441 hg add: option --skjdfks not recognized
442 442 hg add [OPTION]... [FILE]...
443 443
444 444 add the specified files on the next commit
445 445
446 446 options ([+] can be repeated):
447 447
448 448 -I --include PATTERN [+] include names matching the given patterns
449 449 -X --exclude PATTERN [+] exclude names matching the given patterns
450 450 -S --subrepos recurse into subrepositories
451 451 -n --dry-run do not perform actions, just print output
452 452
453 453 (use "hg add -h" to show more help)
454 454 [255]
455 455
456 456 Test ambiguous command help
457 457
458 458 $ hg help ad
459 459 list of commands:
460 460
461 461 add add the specified files on the next commit
462 462 addremove add all new files, delete all missing files
463 463
464 464 (use "hg help -v ad" to show built-in aliases and global options)
465 465
466 466 Test command without options
467 467
468 468 $ hg help verify
469 469 hg verify
470 470
471 471 verify the integrity of the repository
472 472
473 473 Verify the integrity of the current repository.
474 474
475 475 This will perform an extensive check of the repository's integrity,
476 476 validating the hashes and checksums of each entry in the changelog,
477 477 manifest, and tracked files, as well as the integrity of their crosslinks
478 478 and indices.
479 479
480 480 Please see https://mercurial-scm.org/wiki/RepositoryCorruption for more
481 481 information about recovery from corruption of the repository.
482 482
483 483 Returns 0 on success, 1 if errors are encountered.
484 484
485 485 (some details hidden, use --verbose to show complete help)
486 486
487 487 $ hg help diff
488 488 hg diff [OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...
489 489
490 490 diff repository (or selected files)
491 491
492 492 Show differences between revisions for the specified files.
493 493
494 494 Differences between files are shown using the unified diff format.
495 495
496 496 Note:
497 497 diff may generate unexpected results for merges, as it will default to
498 498 comparing against the working directory's first parent changeset if no
499 499 revisions are specified.
500 500
501 501 When two revision arguments are given, then changes are shown between
502 502 those revisions. If only one revision is specified then that revision is
503 503 compared to the working directory, and, when no revisions are specified,
504 504 the working directory files are compared to its parent.
505 505
506 506 Alternatively you can specify -c/--change with a revision to see the
507 507 changes in that changeset relative to its first parent.
508 508
509 509 Without the -a/--text option, diff will avoid generating diffs of files it
510 510 detects as binary. With -a, diff will generate a diff anyway, probably
511 511 with undesirable results.
512 512
513 513 Use the -g/--git option to generate diffs in the git extended diff format.
514 514 For more information, read "hg help diffs".
515 515
516 516 Returns 0 on success.
517 517
518 518 options ([+] can be repeated):
519 519
520 520 -r --rev REV [+] revision
521 521 -c --change REV change made by revision
522 522 -a --text treat all files as text
523 523 -g --git use git extended diff format
524 524 --nodates omit dates from diff headers
525 525 --noprefix omit a/ and b/ prefixes from filenames
526 526 -p --show-function show which function each change is in
527 527 --reverse produce a diff that undoes the changes
528 528 -w --ignore-all-space ignore white space when comparing lines
529 529 -b --ignore-space-change ignore changes in the amount of white space
530 530 -B --ignore-blank-lines ignore changes whose lines are all blank
531 531 -U --unified NUM number of lines of context to show
532 532 --stat output diffstat-style summary of changes
533 533 --root DIR produce diffs relative to subdirectory
534 534 -I --include PATTERN [+] include names matching the given patterns
535 535 -X --exclude PATTERN [+] exclude names matching the given patterns
536 536 -S --subrepos recurse into subrepositories
537 537
538 538 (some details hidden, use --verbose to show complete help)
539 539
540 540 $ hg help status
541 541 hg status [OPTION]... [FILE]...
542 542
543 543 aliases: st
544 544
545 545 show changed files in the working directory
546 546
547 547 Show status of files in the repository. If names are given, only files
548 548 that match are shown. Files that are clean or ignored or the source of a
549 549 copy/move operation, are not listed unless -c/--clean, -i/--ignored,
550 550 -C/--copies or -A/--all are given. Unless options described with "show
551 551 only ..." are given, the options -mardu are used.
552 552
553 553 Option -q/--quiet hides untracked (unknown and ignored) files unless
554 554 explicitly requested with -u/--unknown or -i/--ignored.
555 555
556 556 Note:
557 557 status may appear to disagree with diff if permissions have changed or
558 558 a merge has occurred. The standard diff format does not report
559 559 permission changes and diff only reports changes relative to one merge
560 560 parent.
561 561
562 562 If one revision is given, it is used as the base revision. If two
563 563 revisions are given, the differences between them are shown. The --change
564 564 option can also be used as a shortcut to list the changed files of a
565 565 revision from its first parent.
566 566
567 567 The codes used to show the status of files are:
568 568
569 569 M = modified
570 570 A = added
571 571 R = removed
572 572 C = clean
573 573 ! = missing (deleted by non-hg command, but still tracked)
574 574 ? = not tracked
575 575 I = ignored
576 576 = origin of the previous file (with --copies)
577 577
578 578 Returns 0 on success.
579 579
580 580 options ([+] can be repeated):
581 581
582 582 -A --all show status of all files
583 583 -m --modified show only modified files
584 584 -a --added show only added files
585 585 -r --removed show only removed files
586 586 -d --deleted show only deleted (but tracked) files
587 587 -c --clean show only files without changes
588 588 -u --unknown show only unknown (not tracked) files
589 589 -i --ignored show only ignored files
590 590 -n --no-status hide status prefix
591 591 -C --copies show source of copied files
592 592 -0 --print0 end filenames with NUL, for use with xargs
593 593 --rev REV [+] show difference from revision
594 594 --change REV list the changed files of a revision
595 595 -I --include PATTERN [+] include names matching the given patterns
596 596 -X --exclude PATTERN [+] exclude names matching the given patterns
597 597 -S --subrepos recurse into subrepositories
598 598
599 599 (some details hidden, use --verbose to show complete help)
600 600
601 601 $ hg -q help status
602 602 hg status [OPTION]... [FILE]...
603 603
604 604 show changed files in the working directory
605 605
606 606 $ hg help foo
607 607 abort: no such help topic: foo
608 608 (try "hg help --keyword foo")
609 609 [255]
610 610
611 611 $ hg skjdfks
612 612 hg: unknown command 'skjdfks'
613 613 Mercurial Distributed SCM
614 614
615 615 basic commands:
616 616
617 617 add add the specified files on the next commit
618 618 annotate show changeset information by line for each file
619 619 clone make a copy of an existing repository
620 620 commit commit the specified files or all outstanding changes
621 621 diff diff repository (or selected files)
622 622 export dump the header and diffs for one or more changesets
623 623 forget forget the specified files on the next commit
624 624 init create a new repository in the given directory
625 625 log show revision history of entire repository or files
626 626 merge merge another revision into working directory
627 627 pull pull changes from the specified source
628 628 push push changes to the specified destination
629 629 remove remove the specified files on the next commit
630 630 serve start stand-alone webserver
631 631 status show changed files in the working directory
632 632 summary summarize working directory state
633 633 update update working directory (or switch revisions)
634 634
635 635 (use "hg help" for the full list of commands or "hg -v" for details)
636 636 [255]
637 637
638 638
639 639 Make sure that we don't run afoul of the help system thinking that
640 640 this is a section and erroring out weirdly.
641 641
642 642 $ hg .log
643 643 hg: unknown command '.log'
644 644 (did you mean one of log?)
645 645 [255]
646 646
647 647 $ hg log.
648 648 hg: unknown command 'log.'
649 649 (did you mean one of log?)
650 650 [255]
651 651 $ hg pu.lh
652 652 hg: unknown command 'pu.lh'
653 653 (did you mean one of pull, push?)
654 654 [255]
655 655
656 656 $ cat > helpext.py <<EOF
657 657 > import os
658 658 > from mercurial import cmdutil, commands
659 659 >
660 660 > cmdtable = {}
661 661 > command = cmdutil.command(cmdtable)
662 662 >
663 663 > @command('nohelp',
664 664 > [('', 'longdesc', 3, 'x'*90),
665 665 > ('n', '', None, 'normal desc'),
666 666 > ('', 'newline', '', 'line1\nline2')],
667 667 > 'hg nohelp',
668 668 > norepo=True)
669 669 > @command('debugoptDEP', [('', 'dopt', None, 'option is (DEPRECATED)')])
670 670 > @command('debugoptEXP', [('', 'eopt', None, 'option is (EXPERIMENTAL)')])
671 671 > def nohelp(ui, *args, **kwargs):
672 672 > pass
673 673 >
674 674 > EOF
675 675 $ echo '[extensions]' >> $HGRCPATH
676 676 $ echo "helpext = `pwd`/helpext.py" >> $HGRCPATH
677 677
678 678 Test command with no help text
679 679
680 680 $ hg help nohelp
681 681 hg nohelp
682 682
683 683 (no help text available)
684 684
685 685 options:
686 686
687 687 --longdesc VALUE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
688 688 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (default: 3)
689 689 -n -- normal desc
690 690 --newline VALUE line1 line2
691 691
692 692 (some details hidden, use --verbose to show complete help)
693 693
694 694 $ hg help -k nohelp
695 695 Commands:
696 696
697 697 nohelp hg nohelp
698 698
699 699 Extension Commands:
700 700
701 701 nohelp (no help text available)
702 702
703 703 Test that default list of commands omits extension commands
704 704
705 705 $ hg help
706 706 Mercurial Distributed SCM
707 707
708 708 list of commands:
709 709
710 710 add add the specified files on the next commit
711 711 addremove add all new files, delete all missing files
712 712 annotate show changeset information by line for each file
713 713 archive create an unversioned archive of a repository revision
714 714 backout reverse effect of earlier changeset
715 715 bisect subdivision search of changesets
716 716 bookmarks create a new bookmark or list existing bookmarks
717 717 branch set or show the current branch name
718 718 branches list repository named branches
719 719 bundle create a changegroup file
720 720 cat output the current or given revision of files
721 721 clone make a copy of an existing repository
722 722 commit commit the specified files or all outstanding changes
723 723 config show combined config settings from all hgrc files
724 724 copy mark files as copied for the next commit
725 725 diff diff repository (or selected files)
726 726 export dump the header and diffs for one or more changesets
727 727 files list tracked files
728 728 forget forget the specified files on the next commit
729 729 graft copy changes from other branches onto the current branch
730 730 grep search for a pattern in specified files and revisions
731 731 heads show branch heads
732 732 help show help for a given topic or a help overview
733 733 identify identify the working directory or specified revision
734 734 import import an ordered set of patches
735 735 incoming show new changesets found in source
736 736 init create a new repository in the given directory
737 737 log show revision history of entire repository or files
738 738 manifest output the current or given revision of the project manifest
739 739 merge merge another revision into working directory
740 740 outgoing show changesets not found in the destination
741 741 paths show aliases for remote repositories
742 742 phase set or show the current phase name
743 743 pull pull changes from the specified source
744 744 push push changes to the specified destination
745 745 recover roll back an interrupted transaction
746 746 remove remove the specified files on the next commit
747 747 rename rename files; equivalent of copy + remove
748 748 resolve redo merges or set/view the merge status of files
749 749 revert restore files to their checkout state
750 750 root print the root (top) of the current working directory
751 751 serve start stand-alone webserver
752 752 status show changed files in the working directory
753 753 summary summarize working directory state
754 754 tag add one or more tags for the current or given revision
755 755 tags list repository tags
756 756 unbundle apply one or more changegroup files
757 757 update update working directory (or switch revisions)
758 758 verify verify the integrity of the repository
759 759 version output version and copyright information
760 760
761 761 enabled extensions:
762 762
763 763 helpext (no help text available)
764 764
765 765 additional help topics:
766 766
767 767 config Configuration Files
768 768 dates Date Formats
769 769 diffs Diff Formats
770 770 environment Environment Variables
771 771 extensions Using Additional Features
772 772 filesets Specifying File Sets
773 773 glossary Glossary
774 774 hgignore Syntax for Mercurial Ignore Files
775 775 hgweb Configuring hgweb
776 776 merge-tools Merge Tools
777 777 multirevs Specifying Multiple Revisions
778 778 patterns File Name Patterns
779 779 phases Working with Phases
780 780 revisions Specifying Single Revisions
781 781 revsets Specifying Revision Sets
782 782 scripting Using Mercurial from scripts and automation
783 783 subrepos Subrepositories
784 784 templating Template Usage
785 785 urls URL Paths
786 786
787 787 (use "hg help -v" to show built-in aliases and global options)
788 788
789 789
790 790 Test list of internal help commands
791 791
792 792 $ hg help debug
793 793 debug commands (internal and unsupported):
794 794
795 795 debugancestor
796 796 find the ancestor revision of two revisions in a given index
797 797 debugapplystreamclonebundle
798 798 apply a stream clone bundle file
799 799 debugbuilddag
800 800 builds a repo with a given DAG from scratch in the current
801 801 empty repo
802 802 debugbundle lists the contents of a bundle
803 803 debugcheckstate
804 804 validate the correctness of the current dirstate
805 805 debugcommands
806 806 list all available commands and options
807 807 debugcomplete
808 808 returns the completion list associated with the given command
809 809 debugcreatestreamclonebundle
810 810 create a stream clone bundle file
811 811 debugdag format the changelog or an index DAG as a concise textual
812 812 description
813 813 debugdata dump the contents of a data file revision
814 814 debugdate parse and display a date
815 815 debugdeltachain
816 816 dump information about delta chains in a revlog
817 817 debugdirstate
818 818 show the contents of the current dirstate
819 819 debugdiscovery
820 820 runs the changeset discovery protocol in isolation
821 821 debugextensions
822 822 show information about active extensions
823 823 debugfileset parse and apply a fileset specification
824 824 debugfsinfo show information detected about current filesystem
825 825 debuggetbundle
826 826 retrieves a bundle from a repo
827 827 debugignore display the combined ignore pattern
828 828 debugindex dump the contents of an index file
829 829 debugindexdot
830 830 dump an index DAG as a graphviz dot file
831 831 debuginstall test Mercurial installation
832 832 debugknown test whether node ids are known to a repo
833 833 debuglocks show or modify state of locks
834 834 debugmergestate
835 835 print merge state
836 836 debugnamecomplete
837 837 complete "names" - tags, open branch names, bookmark names
838 838 debugobsolete
839 839 create arbitrary obsolete marker
840 840 debugoptDEP (no help text available)
841 841 debugoptEXP (no help text available)
842 842 debugpathcomplete
843 843 complete part or all of a tracked path
844 844 debugpushkey access the pushkey key/value protocol
845 845 debugpvec (no help text available)
846 846 debugrebuilddirstate
847 847 rebuild the dirstate as it would look like for the given
848 848 revision
849 849 debugrebuildfncache
850 850 rebuild the fncache file
851 851 debugrename dump rename information
852 852 debugrevlog show data and statistics about a revlog
853 853 debugrevspec parse and apply a revision specification
854 854 debugsetparents
855 855 manually set the parents of the current working directory
856 856 debugsub (no help text available)
857 857 debugsuccessorssets
858 858 show set of successors for revision
859 859 debugwalk show how files match on given patterns
860 860 debugwireargs
861 861 (no help text available)
862 862
863 863 (use "hg help -v debug" to show built-in aliases and global options)
864 864
865 865
866 866 Test list of commands with command with no help text
867 867
868 868 $ hg help helpext
869 869 helpext extension - no help text available
870 870
871 871 list of commands:
872 872
873 873 nohelp (no help text available)
874 874
875 875 (use "hg help -v helpext" to show built-in aliases and global options)
876 876
877 877
878 878 test deprecated and experimental options are hidden in command help
879 879 $ hg help debugoptDEP
880 880 hg debugoptDEP
881 881
882 882 (no help text available)
883 883
884 884 options:
885 885
886 886 (some details hidden, use --verbose to show complete help)
887 887
888 888 $ hg help debugoptEXP
889 889 hg debugoptEXP
890 890
891 891 (no help text available)
892 892
893 893 options:
894 894
895 895 (some details hidden, use --verbose to show complete help)
896 896
897 897 test deprecated and experimental options is shown with -v
898 898 $ hg help -v debugoptDEP | grep dopt
899 899 --dopt option is (DEPRECATED)
900 900 $ hg help -v debugoptEXP | grep eopt
901 901 --eopt option is (EXPERIMENTAL)
902 902
903 903 #if gettext
904 904 test deprecated option is hidden with translation with untranslated description
905 905 (use many globy for not failing on changed transaction)
906 906 $ LANGUAGE=sv hg help debugoptDEP
907 907 hg debugoptDEP
908 908
909 909 (*) (glob)
910 910
911 911 options:
912 912
913 913 (some details hidden, use --verbose to show complete help)
914 914 #endif
915 915
916 916 Test commands that collide with topics (issue4240)
917 917
918 918 $ hg config -hq
919 919 hg config [-u] [NAME]...
920 920
921 921 show combined config settings from all hgrc files
922 922 $ hg showconfig -hq
923 923 hg config [-u] [NAME]...
924 924
925 925 show combined config settings from all hgrc files
926 926
927 927 Test a help topic
928 928
929 929 $ hg help revs
930 930 Specifying Single Revisions
931 931 """""""""""""""""""""""""""
932 932
933 933 Mercurial supports several ways to specify individual revisions.
934 934
935 935 A plain integer is treated as a revision number. Negative integers are
936 936 treated as sequential offsets from the tip, with -1 denoting the tip, -2
937 937 denoting the revision prior to the tip, and so forth.
938 938
939 939 A 40-digit hexadecimal string is treated as a unique revision identifier.
940 940
941 941 A hexadecimal string less than 40 characters long is treated as a unique
942 942 revision identifier and is referred to as a short-form identifier. A
943 943 short-form identifier is only valid if it is the prefix of exactly one
944 944 full-length identifier.
945 945
946 946 Any other string is treated as a bookmark, tag, or branch name. A bookmark
947 947 is a movable pointer to a revision. A tag is a permanent name associated
948 948 with a revision. A branch name denotes the tipmost open branch head of
949 949 that branch - or if they are all closed, the tipmost closed head of the
950 950 branch. Bookmark, tag, and branch names must not contain the ":"
951 951 character.
952 952
953 953 The reserved name "tip" always identifies the most recent revision.
954 954
955 955 The reserved name "null" indicates the null revision. This is the revision
956 956 of an empty repository, and the parent of revision 0.
957 957
958 958 The reserved name "." indicates the working directory parent. If no
959 959 working directory is checked out, it is equivalent to null. If an
960 960 uncommitted merge is in progress, "." is the revision of the first parent.
961 961
962 962 Test repeated config section name
963 963
964 964 $ hg help config.host
965 965 "http_proxy.host"
966 966 Host name and (optional) port of the proxy server, for example
967 967 "myproxy:8000".
968 968
969 969 "smtp.host"
970 970 Host name of mail server, e.g. "mail.example.com".
971 971
972 972 Unrelated trailing paragraphs shouldn't be included
973 973
974 974 $ hg help config.extramsg | grep '^$'
975 975
976 976
977 977 Test capitalized section name
978 978
979 979 $ hg help scripting.HGPLAIN > /dev/null
980 980
981 981 Help subsection:
982 982
983 983 $ hg help config.charsets |grep "Email example:" > /dev/null
984 984 [1]
985 985
986 986 Show nested definitions
987 987 ("profiling.type"[break]"ls"[break]"stat"[break])
988 988
989 989 $ hg help config.type | egrep '^$'|wc -l
990 990 \s*3 (re)
991 991
992 992 Last item in help config.*:
993 993
994 994 $ hg help config.`hg help config|grep '^ "'| \
995 995 > tail -1|sed 's![ "]*!!g'`| \
996 996 > grep "hg help -c config" > /dev/null
997 997 [1]
998 998
999 999 note to use help -c for general hg help config:
1000 1000
1001 1001 $ hg help config |grep "hg help -c config" > /dev/null
1002 1002
1003 1003 Test templating help
1004 1004
1005 1005 $ hg help templating | egrep '(desc|diffstat|firstline|nonempty) '
1006 1006 desc String. The text of the changeset description.
1007 1007 diffstat String. Statistics of changes with the following format:
1008 1008 firstline Any text. Returns the first line of text.
1009 1009 nonempty Any text. Returns '(none)' if the string is empty.
1010 1010
1011 1011 Test deprecated items
1012 1012
1013 1013 $ hg help -v templating | grep currentbookmark
1014 1014 currentbookmark
1015 1015 $ hg help templating | (grep currentbookmark || true)
1016 1016
1017 1017 Test help hooks
1018 1018
1019 1019 $ cat > helphook1.py <<EOF
1020 1020 > from mercurial import help
1021 1021 >
1022 1022 > def rewrite(ui, topic, doc):
1023 1023 > return doc + '\nhelphook1\n'
1024 1024 >
1025 1025 > def extsetup(ui):
1026 1026 > help.addtopichook('revsets', rewrite)
1027 1027 > EOF
1028 1028 $ cat > helphook2.py <<EOF
1029 1029 > from mercurial import help
1030 1030 >
1031 1031 > def rewrite(ui, topic, doc):
1032 1032 > return doc + '\nhelphook2\n'
1033 1033 >
1034 1034 > def extsetup(ui):
1035 1035 > help.addtopichook('revsets', rewrite)
1036 1036 > EOF
1037 1037 $ echo '[extensions]' >> $HGRCPATH
1038 1038 $ echo "helphook1 = `pwd`/helphook1.py" >> $HGRCPATH
1039 1039 $ echo "helphook2 = `pwd`/helphook2.py" >> $HGRCPATH
1040 1040 $ hg help revsets | grep helphook
1041 1041 helphook1
1042 1042 helphook2
1043 1043
1044 1044 Test -e / -c / -k combinations
1045 1045
1046 1046 $ hg help -c schemes
1047 1047 abort: no such help topic: schemes
1048 1048 (try "hg help --keyword schemes")
1049 1049 [255]
1050 1050 $ hg help -e schemes |head -1
1051 1051 schemes extension - extend schemes with shortcuts to repository swarms
1052 1052 $ hg help -c -k dates |egrep '^(Topics|Extensions|Commands):'
1053 1053 Commands:
1054 1054 $ hg help -e -k a |egrep '^(Topics|Extensions|Commands):'
1055 1055 Extensions:
1056 1056 $ hg help -e -c -k date |egrep '^(Topics|Extensions|Commands):'
1057 1057 Extensions:
1058 1058 Commands:
1059 1059 $ hg help -c commit > /dev/null
1060 1060 $ hg help -e -c commit > /dev/null
1061 1061 $ hg help -e commit > /dev/null
1062 1062 abort: no such help topic: commit
1063 1063 (try "hg help --keyword commit")
1064 1064 [255]
1065 1065
1066 1066 Test keyword search help
1067 1067
1068 1068 $ cat > prefixedname.py <<EOF
1069 1069 > '''matched against word "clone"
1070 1070 > '''
1071 1071 > EOF
1072 1072 $ echo '[extensions]' >> $HGRCPATH
1073 1073 $ echo "dot.dot.prefixedname = `pwd`/prefixedname.py" >> $HGRCPATH
1074 1074 $ hg help -k clone
1075 1075 Topics:
1076 1076
1077 1077 config Configuration Files
1078 1078 extensions Using Additional Features
1079 1079 glossary Glossary
1080 1080 phases Working with Phases
1081 1081 subrepos Subrepositories
1082 1082 urls URL Paths
1083 1083
1084 1084 Commands:
1085 1085
1086 1086 bookmarks create a new bookmark or list existing bookmarks
1087 1087 clone make a copy of an existing repository
1088 1088 debugapplystreamclonebundle apply a stream clone bundle file
1089 1089 debugcreatestreamclonebundle create a stream clone bundle file
1090 1090 paths show aliases for remote repositories
1091 1091 update update working directory (or switch revisions)
1092 1092
1093 1093 Extensions:
1094 1094
1095 1095 clonebundles advertise pre-generated bundles to seed clones (experimental)
1096 1096 prefixedname matched against word "clone"
1097 1097 relink recreates hardlinks between repository clones
1098 1098
1099 1099 Extension Commands:
1100 1100
1101 1101 qclone clone main and patch repository at same time
1102 1102
1103 1103 Test unfound topic
1104 1104
1105 1105 $ hg help nonexistingtopicthatwillneverexisteverever
1106 1106 abort: no such help topic: nonexistingtopicthatwillneverexisteverever
1107 1107 (try "hg help --keyword nonexistingtopicthatwillneverexisteverever")
1108 1108 [255]
1109 1109
1110 1110 Test unfound keyword
1111 1111
1112 1112 $ hg help --keyword nonexistingwordthatwillneverexisteverever
1113 1113 abort: no matches
1114 1114 (try "hg help" for a list of topics)
1115 1115 [255]
1116 1116
1117 1117 Test omit indicating for help
1118 1118
1119 1119 $ cat > addverboseitems.py <<EOF
1120 1120 > '''extension to test omit indicating.
1121 1121 >
1122 1122 > This paragraph is never omitted (for extension)
1123 1123 >
1124 1124 > .. container:: verbose
1125 1125 >
1126 1126 > This paragraph is omitted,
1127 1127 > if :hg:\`help\` is invoked without \`\`-v\`\` (for extension)
1128 1128 >
1129 1129 > This paragraph is never omitted, too (for extension)
1130 1130 > '''
1131 1131 >
1132 1132 > from mercurial import help, commands
1133 1133 > testtopic = """This paragraph is never omitted (for topic).
1134 1134 >
1135 1135 > .. container:: verbose
1136 1136 >
1137 1137 > This paragraph is omitted,
1138 1138 > if :hg:\`help\` is invoked without \`\`-v\`\` (for topic)
1139 1139 >
1140 1140 > This paragraph is never omitted, too (for topic)
1141 1141 > """
1142 1142 > def extsetup(ui):
1143 1143 > help.helptable.append((["topic-containing-verbose"],
1144 1144 > "This is the topic to test omit indicating.",
1145 1145 > lambda ui: testtopic))
1146 1146 > EOF
1147 1147 $ echo '[extensions]' >> $HGRCPATH
1148 1148 $ echo "addverboseitems = `pwd`/addverboseitems.py" >> $HGRCPATH
1149 1149 $ hg help addverboseitems
1150 1150 addverboseitems extension - extension to test omit indicating.
1151 1151
1152 1152 This paragraph is never omitted (for extension)
1153 1153
1154 1154 This paragraph is never omitted, too (for extension)
1155 1155
1156 1156 (some details hidden, use --verbose to show complete help)
1157 1157
1158 1158 no commands defined
1159 1159 $ hg help -v addverboseitems
1160 1160 addverboseitems extension - extension to test omit indicating.
1161 1161
1162 1162 This paragraph is never omitted (for extension)
1163 1163
1164 1164 This paragraph is omitted, if "hg help" is invoked without "-v" (for
1165 1165 extension)
1166 1166
1167 1167 This paragraph is never omitted, too (for extension)
1168 1168
1169 1169 no commands defined
1170 1170 $ hg help topic-containing-verbose
1171 1171 This is the topic to test omit indicating.
1172 1172 """"""""""""""""""""""""""""""""""""""""""
1173 1173
1174 1174 This paragraph is never omitted (for topic).
1175 1175
1176 1176 This paragraph is never omitted, too (for topic)
1177 1177
1178 1178 (some details hidden, use --verbose to show complete help)
1179 1179 $ hg help -v topic-containing-verbose
1180 1180 This is the topic to test omit indicating.
1181 1181 """"""""""""""""""""""""""""""""""""""""""
1182 1182
1183 1183 This paragraph is never omitted (for topic).
1184 1184
1185 1185 This paragraph is omitted, if "hg help" is invoked without "-v" (for
1186 1186 topic)
1187 1187
1188 1188 This paragraph is never omitted, too (for topic)
1189 1189
1190 1190 Test section lookup
1191 1191
1192 1192 $ hg help revset.merge
1193 1193 "merge()"
1194 1194 Changeset is a merge changeset.
1195 1195
1196 1196 $ hg help glossary.dag
1197 1197 DAG
1198 1198 The repository of changesets of a distributed version control system
1199 1199 (DVCS) can be described as a directed acyclic graph (DAG), consisting
1200 1200 of nodes and edges, where nodes correspond to changesets and edges
1201 1201 imply a parent -> child relation. This graph can be visualized by
1202 1202 graphical tools such as "hg log --graph". In Mercurial, the DAG is
1203 1203 limited by the requirement for children to have at most two parents.
1204 1204
1205 1205
1206 1206 $ hg help hgrc.paths
1207 1207 "paths"
1208 1208 -------
1209 1209
1210 Assigns symbolic names to repositories. The left side is the symbolic
1211 name, and the right gives the directory or URL that is the location of the
1212 repository. Default paths can be declared by setting the following
1213 entries.
1210 Assigns symbolic names and behavior to repositories.
1211
1212 Options are symbolic names defining the URL or directory that is the
1213 location of the repository. Example:
1214
1215 [paths]
1216 my_server = https://example.com/my_repo
1217 local_path = /home/me/repo
1218
1219 These symbolic names can be used from the command line. To pull from
1220 "my_server": "hg pull my_server". To push to "local_path": "hg push
1221 local_path".
1222
1223 Options containing colons (":") denote sub-options that can influence
1224 behavior for that specific path. Example:
1225
1226 [paths]
1227 my_server = https://example.com/my_path
1228 my_server:pushurl = ssh://example.com/my_path
1229
1230 The following sub-options can be defined:
1231
1232 "pushurl"
1233 The URL to use for push operations. If not defined, the location
1234 defined by the path's main entry is used.
1235
1236 The following special named paths exist:
1214 1237
1215 1238 "default"
1216 Directory or URL to use when pulling if no source is specified.
1217 (default: repository from which the current repository was cloned)
1239 The URL or directory to use when no source or remote is specified.
1240
1241 "hg clone" will automatically define this path to the location the
1242 repository was cloned from.
1218 1243
1219 1244 "default-push"
1220 Optional. Directory or URL to use when pushing if no destination is
1221 specified.
1222
1223 Custom paths can be defined by assigning the path to a name that later can
1224 be used from the command line. Example:
1225
1226 [paths]
1227 my_path = http://example.com/path
1228
1229 To push to the path defined in "my_path" run the command:
1230
1231 hg push my_path
1245 (deprecated) The URL or directory for the default "hg push" location.
1246 "default:pushurl" should be used instead.
1232 1247
1233 1248 $ hg help glossary.mcguffin
1234 1249 abort: help section not found
1235 1250 [255]
1236 1251
1237 1252 $ hg help glossary.mc.guffin
1238 1253 abort: help section not found
1239 1254 [255]
1240 1255
1241 1256 $ hg help template.files
1242 1257 files List of strings. All files modified, added, or removed by
1243 1258 this changeset.
1244 1259
1245 1260 Test dynamic list of merge tools only shows up once
1246 1261 $ hg help merge-tools
1247 1262 Merge Tools
1248 1263 """""""""""
1249 1264
1250 1265 To merge files Mercurial uses merge tools.
1251 1266
1252 1267 A merge tool combines two different versions of a file into a merged file.
1253 1268 Merge tools are given the two files and the greatest common ancestor of
1254 1269 the two file versions, so they can determine the changes made on both
1255 1270 branches.
1256 1271
1257 1272 Merge tools are used both for "hg resolve", "hg merge", "hg update", "hg
1258 1273 backout" and in several extensions.
1259 1274
1260 1275 Usually, the merge tool tries to automatically reconcile the files by
1261 1276 combining all non-overlapping changes that occurred separately in the two
1262 1277 different evolutions of the same initial base file. Furthermore, some
1263 1278 interactive merge programs make it easier to manually resolve conflicting
1264 1279 merges, either in a graphical way, or by inserting some conflict markers.
1265 1280 Mercurial does not include any interactive merge programs but relies on
1266 1281 external tools for that.
1267 1282
1268 1283 Available merge tools
1269 1284 =====================
1270 1285
1271 1286 External merge tools and their properties are configured in the merge-
1272 1287 tools configuration section - see hgrc(5) - but they can often just be
1273 1288 named by their executable.
1274 1289
1275 1290 A merge tool is generally usable if its executable can be found on the
1276 1291 system and if it can handle the merge. The executable is found if it is an
1277 1292 absolute or relative executable path or the name of an application in the
1278 1293 executable search path. The tool is assumed to be able to handle the merge
1279 1294 if it can handle symlinks if the file is a symlink, if it can handle
1280 1295 binary files if the file is binary, and if a GUI is available if the tool
1281 1296 requires a GUI.
1282 1297
1283 1298 There are some internal merge tools which can be used. The internal merge
1284 1299 tools are:
1285 1300
1286 1301 ":dump"
1287 1302 Creates three versions of the files to merge, containing the contents of
1288 1303 local, other and base. These files can then be used to perform a merge
1289 1304 manually. If the file to be merged is named "a.txt", these files will
1290 1305 accordingly be named "a.txt.local", "a.txt.other" and "a.txt.base" and
1291 1306 they will be placed in the same directory as "a.txt".
1292 1307
1293 1308 ":fail"
1294 1309 Rather than attempting to merge files that were modified on both
1295 1310 branches, it marks them as unresolved. The resolve command must be used
1296 1311 to resolve these conflicts.
1297 1312
1298 1313 ":local"
1299 1314 Uses the local version of files as the merged version.
1300 1315
1301 1316 ":merge"
1302 1317 Uses the internal non-interactive simple merge algorithm for merging
1303 1318 files. It will fail if there are any conflicts and leave markers in the
1304 1319 partially merged file. Markers will have two sections, one for each side
1305 1320 of merge.
1306 1321
1307 1322 ":merge-local"
1308 1323 Like :merge, but resolve all conflicts non-interactively in favor of the
1309 1324 local changes.
1310 1325
1311 1326 ":merge-other"
1312 1327 Like :merge, but resolve all conflicts non-interactively in favor of the
1313 1328 other changes.
1314 1329
1315 1330 ":merge3"
1316 1331 Uses the internal non-interactive simple merge algorithm for merging
1317 1332 files. It will fail if there are any conflicts and leave markers in the
1318 1333 partially merged file. Marker will have three sections, one from each
1319 1334 side of the merge and one for the base content.
1320 1335
1321 1336 ":other"
1322 1337 Uses the other version of files as the merged version.
1323 1338
1324 1339 ":prompt"
1325 1340 Asks the user which of the local or the other version to keep as the
1326 1341 merged version.
1327 1342
1328 1343 ":tagmerge"
1329 1344 Uses the internal tag merge algorithm (experimental).
1330 1345
1331 1346 ":union"
1332 1347 Uses the internal non-interactive simple merge algorithm for merging
1333 1348 files. It will use both left and right sides for conflict regions. No
1334 1349 markers are inserted.
1335 1350
1336 1351 Internal tools are always available and do not require a GUI but will by
1337 1352 default not handle symlinks or binary files.
1338 1353
1339 1354 Choosing a merge tool
1340 1355 =====================
1341 1356
1342 1357 Mercurial uses these rules when deciding which merge tool to use:
1343 1358
1344 1359 1. If a tool has been specified with the --tool option to merge or
1345 1360 resolve, it is used. If it is the name of a tool in the merge-tools
1346 1361 configuration, its configuration is used. Otherwise the specified tool
1347 1362 must be executable by the shell.
1348 1363 2. If the "HGMERGE" environment variable is present, its value is used and
1349 1364 must be executable by the shell.
1350 1365 3. If the filename of the file to be merged matches any of the patterns in
1351 1366 the merge-patterns configuration section, the first usable merge tool
1352 1367 corresponding to a matching pattern is used. Here, binary capabilities
1353 1368 of the merge tool are not considered.
1354 1369 4. If ui.merge is set it will be considered next. If the value is not the
1355 1370 name of a configured tool, the specified value is used and must be
1356 1371 executable by the shell. Otherwise the named tool is used if it is
1357 1372 usable.
1358 1373 5. If any usable merge tools are present in the merge-tools configuration
1359 1374 section, the one with the highest priority is used.
1360 1375 6. If a program named "hgmerge" can be found on the system, it is used -
1361 1376 but it will by default not be used for symlinks and binary files.
1362 1377 7. If the file to be merged is not binary and is not a symlink, then
1363 1378 internal ":merge" is used.
1364 1379 8. The merge of the file fails and must be resolved before commit.
1365 1380
1366 1381 Note:
1367 1382 After selecting a merge program, Mercurial will by default attempt to
1368 1383 merge the files using a simple merge algorithm first. Only if it
1369 1384 doesn't succeed because of conflicting changes Mercurial will actually
1370 1385 execute the merge program. Whether to use the simple merge algorithm
1371 1386 first can be controlled by the premerge setting of the merge tool.
1372 1387 Premerge is enabled by default unless the file is binary or a symlink.
1373 1388
1374 1389 See the merge-tools and ui sections of hgrc(5) for details on the
1375 1390 configuration of merge tools.
1376 1391
1377 1392 Test usage of section marks in help documents
1378 1393
1379 1394 $ cd "$TESTDIR"/../doc
1380 1395 $ python check-seclevel.py
1381 1396 $ cd $TESTTMP
1382 1397
1383 1398 #if serve
1384 1399
1385 1400 Test the help pages in hgweb.
1386 1401
1387 1402 Dish up an empty repo; serve it cold.
1388 1403
1389 1404 $ hg init "$TESTTMP/test"
1390 1405 $ hg serve -R "$TESTTMP/test" -n test -p $HGPORT -d --pid-file=hg.pid
1391 1406 $ cat hg.pid >> $DAEMON_PIDS
1392 1407
1393 1408 $ get-with-headers.py 127.0.0.1:$HGPORT "help"
1394 1409 200 Script output follows
1395 1410
1396 1411 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
1397 1412 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
1398 1413 <head>
1399 1414 <link rel="icon" href="/static/hgicon.png" type="image/png" />
1400 1415 <meta name="robots" content="index, nofollow" />
1401 1416 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
1402 1417 <script type="text/javascript" src="/static/mercurial.js"></script>
1403 1418
1404 1419 <title>Help: Index</title>
1405 1420 </head>
1406 1421 <body>
1407 1422
1408 1423 <div class="container">
1409 1424 <div class="menu">
1410 1425 <div class="logo">
1411 1426 <a href="https://mercurial-scm.org/">
1412 1427 <img src="/static/hglogo.png" alt="mercurial" /></a>
1413 1428 </div>
1414 1429 <ul>
1415 1430 <li><a href="/shortlog">log</a></li>
1416 1431 <li><a href="/graph">graph</a></li>
1417 1432 <li><a href="/tags">tags</a></li>
1418 1433 <li><a href="/bookmarks">bookmarks</a></li>
1419 1434 <li><a href="/branches">branches</a></li>
1420 1435 </ul>
1421 1436 <ul>
1422 1437 <li class="active">help</li>
1423 1438 </ul>
1424 1439 </div>
1425 1440
1426 1441 <div class="main">
1427 1442 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
1428 1443 <form class="search" action="/log">
1429 1444
1430 1445 <p><input name="rev" id="search1" type="text" size="30" /></p>
1431 1446 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
1432 1447 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
1433 1448 </form>
1434 1449 <table class="bigtable">
1435 1450 <tr><td colspan="2"><h2><a name="main" href="#topics">Topics</a></h2></td></tr>
1436 1451
1437 1452 <tr><td>
1438 1453 <a href="/help/config">
1439 1454 config
1440 1455 </a>
1441 1456 </td><td>
1442 1457 Configuration Files
1443 1458 </td></tr>
1444 1459 <tr><td>
1445 1460 <a href="/help/dates">
1446 1461 dates
1447 1462 </a>
1448 1463 </td><td>
1449 1464 Date Formats
1450 1465 </td></tr>
1451 1466 <tr><td>
1452 1467 <a href="/help/diffs">
1453 1468 diffs
1454 1469 </a>
1455 1470 </td><td>
1456 1471 Diff Formats
1457 1472 </td></tr>
1458 1473 <tr><td>
1459 1474 <a href="/help/environment">
1460 1475 environment
1461 1476 </a>
1462 1477 </td><td>
1463 1478 Environment Variables
1464 1479 </td></tr>
1465 1480 <tr><td>
1466 1481 <a href="/help/extensions">
1467 1482 extensions
1468 1483 </a>
1469 1484 </td><td>
1470 1485 Using Additional Features
1471 1486 </td></tr>
1472 1487 <tr><td>
1473 1488 <a href="/help/filesets">
1474 1489 filesets
1475 1490 </a>
1476 1491 </td><td>
1477 1492 Specifying File Sets
1478 1493 </td></tr>
1479 1494 <tr><td>
1480 1495 <a href="/help/glossary">
1481 1496 glossary
1482 1497 </a>
1483 1498 </td><td>
1484 1499 Glossary
1485 1500 </td></tr>
1486 1501 <tr><td>
1487 1502 <a href="/help/hgignore">
1488 1503 hgignore
1489 1504 </a>
1490 1505 </td><td>
1491 1506 Syntax for Mercurial Ignore Files
1492 1507 </td></tr>
1493 1508 <tr><td>
1494 1509 <a href="/help/hgweb">
1495 1510 hgweb
1496 1511 </a>
1497 1512 </td><td>
1498 1513 Configuring hgweb
1499 1514 </td></tr>
1500 1515 <tr><td>
1501 1516 <a href="/help/merge-tools">
1502 1517 merge-tools
1503 1518 </a>
1504 1519 </td><td>
1505 1520 Merge Tools
1506 1521 </td></tr>
1507 1522 <tr><td>
1508 1523 <a href="/help/multirevs">
1509 1524 multirevs
1510 1525 </a>
1511 1526 </td><td>
1512 1527 Specifying Multiple Revisions
1513 1528 </td></tr>
1514 1529 <tr><td>
1515 1530 <a href="/help/patterns">
1516 1531 patterns
1517 1532 </a>
1518 1533 </td><td>
1519 1534 File Name Patterns
1520 1535 </td></tr>
1521 1536 <tr><td>
1522 1537 <a href="/help/phases">
1523 1538 phases
1524 1539 </a>
1525 1540 </td><td>
1526 1541 Working with Phases
1527 1542 </td></tr>
1528 1543 <tr><td>
1529 1544 <a href="/help/revisions">
1530 1545 revisions
1531 1546 </a>
1532 1547 </td><td>
1533 1548 Specifying Single Revisions
1534 1549 </td></tr>
1535 1550 <tr><td>
1536 1551 <a href="/help/revsets">
1537 1552 revsets
1538 1553 </a>
1539 1554 </td><td>
1540 1555 Specifying Revision Sets
1541 1556 </td></tr>
1542 1557 <tr><td>
1543 1558 <a href="/help/scripting">
1544 1559 scripting
1545 1560 </a>
1546 1561 </td><td>
1547 1562 Using Mercurial from scripts and automation
1548 1563 </td></tr>
1549 1564 <tr><td>
1550 1565 <a href="/help/subrepos">
1551 1566 subrepos
1552 1567 </a>
1553 1568 </td><td>
1554 1569 Subrepositories
1555 1570 </td></tr>
1556 1571 <tr><td>
1557 1572 <a href="/help/templating">
1558 1573 templating
1559 1574 </a>
1560 1575 </td><td>
1561 1576 Template Usage
1562 1577 </td></tr>
1563 1578 <tr><td>
1564 1579 <a href="/help/urls">
1565 1580 urls
1566 1581 </a>
1567 1582 </td><td>
1568 1583 URL Paths
1569 1584 </td></tr>
1570 1585 <tr><td>
1571 1586 <a href="/help/topic-containing-verbose">
1572 1587 topic-containing-verbose
1573 1588 </a>
1574 1589 </td><td>
1575 1590 This is the topic to test omit indicating.
1576 1591 </td></tr>
1577 1592
1578 1593 <tr><td colspan="2"><h2><a name="main" href="#main">Main Commands</a></h2></td></tr>
1579 1594
1580 1595 <tr><td>
1581 1596 <a href="/help/add">
1582 1597 add
1583 1598 </a>
1584 1599 </td><td>
1585 1600 add the specified files on the next commit
1586 1601 </td></tr>
1587 1602 <tr><td>
1588 1603 <a href="/help/annotate">
1589 1604 annotate
1590 1605 </a>
1591 1606 </td><td>
1592 1607 show changeset information by line for each file
1593 1608 </td></tr>
1594 1609 <tr><td>
1595 1610 <a href="/help/clone">
1596 1611 clone
1597 1612 </a>
1598 1613 </td><td>
1599 1614 make a copy of an existing repository
1600 1615 </td></tr>
1601 1616 <tr><td>
1602 1617 <a href="/help/commit">
1603 1618 commit
1604 1619 </a>
1605 1620 </td><td>
1606 1621 commit the specified files or all outstanding changes
1607 1622 </td></tr>
1608 1623 <tr><td>
1609 1624 <a href="/help/diff">
1610 1625 diff
1611 1626 </a>
1612 1627 </td><td>
1613 1628 diff repository (or selected files)
1614 1629 </td></tr>
1615 1630 <tr><td>
1616 1631 <a href="/help/export">
1617 1632 export
1618 1633 </a>
1619 1634 </td><td>
1620 1635 dump the header and diffs for one or more changesets
1621 1636 </td></tr>
1622 1637 <tr><td>
1623 1638 <a href="/help/forget">
1624 1639 forget
1625 1640 </a>
1626 1641 </td><td>
1627 1642 forget the specified files on the next commit
1628 1643 </td></tr>
1629 1644 <tr><td>
1630 1645 <a href="/help/init">
1631 1646 init
1632 1647 </a>
1633 1648 </td><td>
1634 1649 create a new repository in the given directory
1635 1650 </td></tr>
1636 1651 <tr><td>
1637 1652 <a href="/help/log">
1638 1653 log
1639 1654 </a>
1640 1655 </td><td>
1641 1656 show revision history of entire repository or files
1642 1657 </td></tr>
1643 1658 <tr><td>
1644 1659 <a href="/help/merge">
1645 1660 merge
1646 1661 </a>
1647 1662 </td><td>
1648 1663 merge another revision into working directory
1649 1664 </td></tr>
1650 1665 <tr><td>
1651 1666 <a href="/help/pull">
1652 1667 pull
1653 1668 </a>
1654 1669 </td><td>
1655 1670 pull changes from the specified source
1656 1671 </td></tr>
1657 1672 <tr><td>
1658 1673 <a href="/help/push">
1659 1674 push
1660 1675 </a>
1661 1676 </td><td>
1662 1677 push changes to the specified destination
1663 1678 </td></tr>
1664 1679 <tr><td>
1665 1680 <a href="/help/remove">
1666 1681 remove
1667 1682 </a>
1668 1683 </td><td>
1669 1684 remove the specified files on the next commit
1670 1685 </td></tr>
1671 1686 <tr><td>
1672 1687 <a href="/help/serve">
1673 1688 serve
1674 1689 </a>
1675 1690 </td><td>
1676 1691 start stand-alone webserver
1677 1692 </td></tr>
1678 1693 <tr><td>
1679 1694 <a href="/help/status">
1680 1695 status
1681 1696 </a>
1682 1697 </td><td>
1683 1698 show changed files in the working directory
1684 1699 </td></tr>
1685 1700 <tr><td>
1686 1701 <a href="/help/summary">
1687 1702 summary
1688 1703 </a>
1689 1704 </td><td>
1690 1705 summarize working directory state
1691 1706 </td></tr>
1692 1707 <tr><td>
1693 1708 <a href="/help/update">
1694 1709 update
1695 1710 </a>
1696 1711 </td><td>
1697 1712 update working directory (or switch revisions)
1698 1713 </td></tr>
1699 1714
1700 1715 <tr><td colspan="2"><h2><a name="other" href="#other">Other Commands</a></h2></td></tr>
1701 1716
1702 1717 <tr><td>
1703 1718 <a href="/help/addremove">
1704 1719 addremove
1705 1720 </a>
1706 1721 </td><td>
1707 1722 add all new files, delete all missing files
1708 1723 </td></tr>
1709 1724 <tr><td>
1710 1725 <a href="/help/archive">
1711 1726 archive
1712 1727 </a>
1713 1728 </td><td>
1714 1729 create an unversioned archive of a repository revision
1715 1730 </td></tr>
1716 1731 <tr><td>
1717 1732 <a href="/help/backout">
1718 1733 backout
1719 1734 </a>
1720 1735 </td><td>
1721 1736 reverse effect of earlier changeset
1722 1737 </td></tr>
1723 1738 <tr><td>
1724 1739 <a href="/help/bisect">
1725 1740 bisect
1726 1741 </a>
1727 1742 </td><td>
1728 1743 subdivision search of changesets
1729 1744 </td></tr>
1730 1745 <tr><td>
1731 1746 <a href="/help/bookmarks">
1732 1747 bookmarks
1733 1748 </a>
1734 1749 </td><td>
1735 1750 create a new bookmark or list existing bookmarks
1736 1751 </td></tr>
1737 1752 <tr><td>
1738 1753 <a href="/help/branch">
1739 1754 branch
1740 1755 </a>
1741 1756 </td><td>
1742 1757 set or show the current branch name
1743 1758 </td></tr>
1744 1759 <tr><td>
1745 1760 <a href="/help/branches">
1746 1761 branches
1747 1762 </a>
1748 1763 </td><td>
1749 1764 list repository named branches
1750 1765 </td></tr>
1751 1766 <tr><td>
1752 1767 <a href="/help/bundle">
1753 1768 bundle
1754 1769 </a>
1755 1770 </td><td>
1756 1771 create a changegroup file
1757 1772 </td></tr>
1758 1773 <tr><td>
1759 1774 <a href="/help/cat">
1760 1775 cat
1761 1776 </a>
1762 1777 </td><td>
1763 1778 output the current or given revision of files
1764 1779 </td></tr>
1765 1780 <tr><td>
1766 1781 <a href="/help/config">
1767 1782 config
1768 1783 </a>
1769 1784 </td><td>
1770 1785 show combined config settings from all hgrc files
1771 1786 </td></tr>
1772 1787 <tr><td>
1773 1788 <a href="/help/copy">
1774 1789 copy
1775 1790 </a>
1776 1791 </td><td>
1777 1792 mark files as copied for the next commit
1778 1793 </td></tr>
1779 1794 <tr><td>
1780 1795 <a href="/help/files">
1781 1796 files
1782 1797 </a>
1783 1798 </td><td>
1784 1799 list tracked files
1785 1800 </td></tr>
1786 1801 <tr><td>
1787 1802 <a href="/help/graft">
1788 1803 graft
1789 1804 </a>
1790 1805 </td><td>
1791 1806 copy changes from other branches onto the current branch
1792 1807 </td></tr>
1793 1808 <tr><td>
1794 1809 <a href="/help/grep">
1795 1810 grep
1796 1811 </a>
1797 1812 </td><td>
1798 1813 search for a pattern in specified files and revisions
1799 1814 </td></tr>
1800 1815 <tr><td>
1801 1816 <a href="/help/heads">
1802 1817 heads
1803 1818 </a>
1804 1819 </td><td>
1805 1820 show branch heads
1806 1821 </td></tr>
1807 1822 <tr><td>
1808 1823 <a href="/help/help">
1809 1824 help
1810 1825 </a>
1811 1826 </td><td>
1812 1827 show help for a given topic or a help overview
1813 1828 </td></tr>
1814 1829 <tr><td>
1815 1830 <a href="/help/identify">
1816 1831 identify
1817 1832 </a>
1818 1833 </td><td>
1819 1834 identify the working directory or specified revision
1820 1835 </td></tr>
1821 1836 <tr><td>
1822 1837 <a href="/help/import">
1823 1838 import
1824 1839 </a>
1825 1840 </td><td>
1826 1841 import an ordered set of patches
1827 1842 </td></tr>
1828 1843 <tr><td>
1829 1844 <a href="/help/incoming">
1830 1845 incoming
1831 1846 </a>
1832 1847 </td><td>
1833 1848 show new changesets found in source
1834 1849 </td></tr>
1835 1850 <tr><td>
1836 1851 <a href="/help/manifest">
1837 1852 manifest
1838 1853 </a>
1839 1854 </td><td>
1840 1855 output the current or given revision of the project manifest
1841 1856 </td></tr>
1842 1857 <tr><td>
1843 1858 <a href="/help/nohelp">
1844 1859 nohelp
1845 1860 </a>
1846 1861 </td><td>
1847 1862 (no help text available)
1848 1863 </td></tr>
1849 1864 <tr><td>
1850 1865 <a href="/help/outgoing">
1851 1866 outgoing
1852 1867 </a>
1853 1868 </td><td>
1854 1869 show changesets not found in the destination
1855 1870 </td></tr>
1856 1871 <tr><td>
1857 1872 <a href="/help/paths">
1858 1873 paths
1859 1874 </a>
1860 1875 </td><td>
1861 1876 show aliases for remote repositories
1862 1877 </td></tr>
1863 1878 <tr><td>
1864 1879 <a href="/help/phase">
1865 1880 phase
1866 1881 </a>
1867 1882 </td><td>
1868 1883 set or show the current phase name
1869 1884 </td></tr>
1870 1885 <tr><td>
1871 1886 <a href="/help/recover">
1872 1887 recover
1873 1888 </a>
1874 1889 </td><td>
1875 1890 roll back an interrupted transaction
1876 1891 </td></tr>
1877 1892 <tr><td>
1878 1893 <a href="/help/rename">
1879 1894 rename
1880 1895 </a>
1881 1896 </td><td>
1882 1897 rename files; equivalent of copy + remove
1883 1898 </td></tr>
1884 1899 <tr><td>
1885 1900 <a href="/help/resolve">
1886 1901 resolve
1887 1902 </a>
1888 1903 </td><td>
1889 1904 redo merges or set/view the merge status of files
1890 1905 </td></tr>
1891 1906 <tr><td>
1892 1907 <a href="/help/revert">
1893 1908 revert
1894 1909 </a>
1895 1910 </td><td>
1896 1911 restore files to their checkout state
1897 1912 </td></tr>
1898 1913 <tr><td>
1899 1914 <a href="/help/root">
1900 1915 root
1901 1916 </a>
1902 1917 </td><td>
1903 1918 print the root (top) of the current working directory
1904 1919 </td></tr>
1905 1920 <tr><td>
1906 1921 <a href="/help/tag">
1907 1922 tag
1908 1923 </a>
1909 1924 </td><td>
1910 1925 add one or more tags for the current or given revision
1911 1926 </td></tr>
1912 1927 <tr><td>
1913 1928 <a href="/help/tags">
1914 1929 tags
1915 1930 </a>
1916 1931 </td><td>
1917 1932 list repository tags
1918 1933 </td></tr>
1919 1934 <tr><td>
1920 1935 <a href="/help/unbundle">
1921 1936 unbundle
1922 1937 </a>
1923 1938 </td><td>
1924 1939 apply one or more changegroup files
1925 1940 </td></tr>
1926 1941 <tr><td>
1927 1942 <a href="/help/verify">
1928 1943 verify
1929 1944 </a>
1930 1945 </td><td>
1931 1946 verify the integrity of the repository
1932 1947 </td></tr>
1933 1948 <tr><td>
1934 1949 <a href="/help/version">
1935 1950 version
1936 1951 </a>
1937 1952 </td><td>
1938 1953 output version and copyright information
1939 1954 </td></tr>
1940 1955 </table>
1941 1956 </div>
1942 1957 </div>
1943 1958
1944 1959 <script type="text/javascript">process_dates()</script>
1945 1960
1946 1961
1947 1962 </body>
1948 1963 </html>
1949 1964
1950 1965
1951 1966 $ get-with-headers.py 127.0.0.1:$HGPORT "help/add"
1952 1967 200 Script output follows
1953 1968
1954 1969 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
1955 1970 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
1956 1971 <head>
1957 1972 <link rel="icon" href="/static/hgicon.png" type="image/png" />
1958 1973 <meta name="robots" content="index, nofollow" />
1959 1974 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
1960 1975 <script type="text/javascript" src="/static/mercurial.js"></script>
1961 1976
1962 1977 <title>Help: add</title>
1963 1978 </head>
1964 1979 <body>
1965 1980
1966 1981 <div class="container">
1967 1982 <div class="menu">
1968 1983 <div class="logo">
1969 1984 <a href="https://mercurial-scm.org/">
1970 1985 <img src="/static/hglogo.png" alt="mercurial" /></a>
1971 1986 </div>
1972 1987 <ul>
1973 1988 <li><a href="/shortlog">log</a></li>
1974 1989 <li><a href="/graph">graph</a></li>
1975 1990 <li><a href="/tags">tags</a></li>
1976 1991 <li><a href="/bookmarks">bookmarks</a></li>
1977 1992 <li><a href="/branches">branches</a></li>
1978 1993 </ul>
1979 1994 <ul>
1980 1995 <li class="active"><a href="/help">help</a></li>
1981 1996 </ul>
1982 1997 </div>
1983 1998
1984 1999 <div class="main">
1985 2000 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
1986 2001 <h3>Help: add</h3>
1987 2002
1988 2003 <form class="search" action="/log">
1989 2004
1990 2005 <p><input name="rev" id="search1" type="text" size="30" /></p>
1991 2006 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
1992 2007 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
1993 2008 </form>
1994 2009 <div id="doc">
1995 2010 <p>
1996 2011 hg add [OPTION]... [FILE]...
1997 2012 </p>
1998 2013 <p>
1999 2014 add the specified files on the next commit
2000 2015 </p>
2001 2016 <p>
2002 2017 Schedule files to be version controlled and added to the
2003 2018 repository.
2004 2019 </p>
2005 2020 <p>
2006 2021 The files will be added to the repository at the next commit. To
2007 2022 undo an add before that, see &quot;hg forget&quot;.
2008 2023 </p>
2009 2024 <p>
2010 2025 If no names are given, add all files to the repository.
2011 2026 </p>
2012 2027 <p>
2013 2028 Examples:
2014 2029 </p>
2015 2030 <ul>
2016 2031 <li> New (unknown) files are added automatically by &quot;hg add&quot;:
2017 2032 <pre>
2018 2033 \$ ls (re)
2019 2034 foo.c
2020 2035 \$ hg status (re)
2021 2036 ? foo.c
2022 2037 \$ hg add (re)
2023 2038 adding foo.c
2024 2039 \$ hg status (re)
2025 2040 A foo.c
2026 2041 </pre>
2027 2042 <li> Specific files to be added can be specified:
2028 2043 <pre>
2029 2044 \$ ls (re)
2030 2045 bar.c foo.c
2031 2046 \$ hg status (re)
2032 2047 ? bar.c
2033 2048 ? foo.c
2034 2049 \$ hg add bar.c (re)
2035 2050 \$ hg status (re)
2036 2051 A bar.c
2037 2052 ? foo.c
2038 2053 </pre>
2039 2054 </ul>
2040 2055 <p>
2041 2056 Returns 0 if all files are successfully added.
2042 2057 </p>
2043 2058 <p>
2044 2059 options ([+] can be repeated):
2045 2060 </p>
2046 2061 <table>
2047 2062 <tr><td>-I</td>
2048 2063 <td>--include PATTERN [+]</td>
2049 2064 <td>include names matching the given patterns</td></tr>
2050 2065 <tr><td>-X</td>
2051 2066 <td>--exclude PATTERN [+]</td>
2052 2067 <td>exclude names matching the given patterns</td></tr>
2053 2068 <tr><td>-S</td>
2054 2069 <td>--subrepos</td>
2055 2070 <td>recurse into subrepositories</td></tr>
2056 2071 <tr><td>-n</td>
2057 2072 <td>--dry-run</td>
2058 2073 <td>do not perform actions, just print output</td></tr>
2059 2074 </table>
2060 2075 <p>
2061 2076 global options ([+] can be repeated):
2062 2077 </p>
2063 2078 <table>
2064 2079 <tr><td>-R</td>
2065 2080 <td>--repository REPO</td>
2066 2081 <td>repository root directory or name of overlay bundle file</td></tr>
2067 2082 <tr><td></td>
2068 2083 <td>--cwd DIR</td>
2069 2084 <td>change working directory</td></tr>
2070 2085 <tr><td>-y</td>
2071 2086 <td>--noninteractive</td>
2072 2087 <td>do not prompt, automatically pick the first choice for all prompts</td></tr>
2073 2088 <tr><td>-q</td>
2074 2089 <td>--quiet</td>
2075 2090 <td>suppress output</td></tr>
2076 2091 <tr><td>-v</td>
2077 2092 <td>--verbose</td>
2078 2093 <td>enable additional output</td></tr>
2079 2094 <tr><td></td>
2080 2095 <td>--config CONFIG [+]</td>
2081 2096 <td>set/override config option (use 'section.name=value')</td></tr>
2082 2097 <tr><td></td>
2083 2098 <td>--debug</td>
2084 2099 <td>enable debugging output</td></tr>
2085 2100 <tr><td></td>
2086 2101 <td>--debugger</td>
2087 2102 <td>start debugger</td></tr>
2088 2103 <tr><td></td>
2089 2104 <td>--encoding ENCODE</td>
2090 2105 <td>set the charset encoding (default: ascii)</td></tr>
2091 2106 <tr><td></td>
2092 2107 <td>--encodingmode MODE</td>
2093 2108 <td>set the charset encoding mode (default: strict)</td></tr>
2094 2109 <tr><td></td>
2095 2110 <td>--traceback</td>
2096 2111 <td>always print a traceback on exception</td></tr>
2097 2112 <tr><td></td>
2098 2113 <td>--time</td>
2099 2114 <td>time how long the command takes</td></tr>
2100 2115 <tr><td></td>
2101 2116 <td>--profile</td>
2102 2117 <td>print command execution profile</td></tr>
2103 2118 <tr><td></td>
2104 2119 <td>--version</td>
2105 2120 <td>output version information and exit</td></tr>
2106 2121 <tr><td>-h</td>
2107 2122 <td>--help</td>
2108 2123 <td>display help and exit</td></tr>
2109 2124 <tr><td></td>
2110 2125 <td>--hidden</td>
2111 2126 <td>consider hidden changesets</td></tr>
2112 2127 </table>
2113 2128
2114 2129 </div>
2115 2130 </div>
2116 2131 </div>
2117 2132
2118 2133 <script type="text/javascript">process_dates()</script>
2119 2134
2120 2135
2121 2136 </body>
2122 2137 </html>
2123 2138
2124 2139
2125 2140 $ get-with-headers.py 127.0.0.1:$HGPORT "help/remove"
2126 2141 200 Script output follows
2127 2142
2128 2143 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
2129 2144 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
2130 2145 <head>
2131 2146 <link rel="icon" href="/static/hgicon.png" type="image/png" />
2132 2147 <meta name="robots" content="index, nofollow" />
2133 2148 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
2134 2149 <script type="text/javascript" src="/static/mercurial.js"></script>
2135 2150
2136 2151 <title>Help: remove</title>
2137 2152 </head>
2138 2153 <body>
2139 2154
2140 2155 <div class="container">
2141 2156 <div class="menu">
2142 2157 <div class="logo">
2143 2158 <a href="https://mercurial-scm.org/">
2144 2159 <img src="/static/hglogo.png" alt="mercurial" /></a>
2145 2160 </div>
2146 2161 <ul>
2147 2162 <li><a href="/shortlog">log</a></li>
2148 2163 <li><a href="/graph">graph</a></li>
2149 2164 <li><a href="/tags">tags</a></li>
2150 2165 <li><a href="/bookmarks">bookmarks</a></li>
2151 2166 <li><a href="/branches">branches</a></li>
2152 2167 </ul>
2153 2168 <ul>
2154 2169 <li class="active"><a href="/help">help</a></li>
2155 2170 </ul>
2156 2171 </div>
2157 2172
2158 2173 <div class="main">
2159 2174 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
2160 2175 <h3>Help: remove</h3>
2161 2176
2162 2177 <form class="search" action="/log">
2163 2178
2164 2179 <p><input name="rev" id="search1" type="text" size="30" /></p>
2165 2180 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
2166 2181 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
2167 2182 </form>
2168 2183 <div id="doc">
2169 2184 <p>
2170 2185 hg remove [OPTION]... FILE...
2171 2186 </p>
2172 2187 <p>
2173 2188 aliases: rm
2174 2189 </p>
2175 2190 <p>
2176 2191 remove the specified files on the next commit
2177 2192 </p>
2178 2193 <p>
2179 2194 Schedule the indicated files for removal from the current branch.
2180 2195 </p>
2181 2196 <p>
2182 2197 This command schedules the files to be removed at the next commit.
2183 2198 To undo a remove before that, see &quot;hg revert&quot;. To undo added
2184 2199 files, see &quot;hg forget&quot;.
2185 2200 </p>
2186 2201 <p>
2187 2202 -A/--after can be used to remove only files that have already
2188 2203 been deleted, -f/--force can be used to force deletion, and -Af
2189 2204 can be used to remove files from the next revision without
2190 2205 deleting them from the working directory.
2191 2206 </p>
2192 2207 <p>
2193 2208 The following table details the behavior of remove for different
2194 2209 file states (columns) and option combinations (rows). The file
2195 2210 states are Added [A], Clean [C], Modified [M] and Missing [!]
2196 2211 (as reported by &quot;hg status&quot;). The actions are Warn, Remove
2197 2212 (from branch) and Delete (from disk):
2198 2213 </p>
2199 2214 <table>
2200 2215 <tr><td>opt/state</td>
2201 2216 <td>A</td>
2202 2217 <td>C</td>
2203 2218 <td>M</td>
2204 2219 <td>!</td></tr>
2205 2220 <tr><td>none</td>
2206 2221 <td>W</td>
2207 2222 <td>RD</td>
2208 2223 <td>W</td>
2209 2224 <td>R</td></tr>
2210 2225 <tr><td>-f</td>
2211 2226 <td>R</td>
2212 2227 <td>RD</td>
2213 2228 <td>RD</td>
2214 2229 <td>R</td></tr>
2215 2230 <tr><td>-A</td>
2216 2231 <td>W</td>
2217 2232 <td>W</td>
2218 2233 <td>W</td>
2219 2234 <td>R</td></tr>
2220 2235 <tr><td>-Af</td>
2221 2236 <td>R</td>
2222 2237 <td>R</td>
2223 2238 <td>R</td>
2224 2239 <td>R</td></tr>
2225 2240 </table>
2226 2241 <p>
2227 2242 Note that remove never deletes files in Added [A] state from the
2228 2243 working directory, not even if option --force is specified.
2229 2244 </p>
2230 2245 <p>
2231 2246 Returns 0 on success, 1 if any warnings encountered.
2232 2247 </p>
2233 2248 <p>
2234 2249 options ([+] can be repeated):
2235 2250 </p>
2236 2251 <table>
2237 2252 <tr><td>-A</td>
2238 2253 <td>--after</td>
2239 2254 <td>record delete for missing files</td></tr>
2240 2255 <tr><td>-f</td>
2241 2256 <td>--force</td>
2242 2257 <td>remove (and delete) file even if added or modified</td></tr>
2243 2258 <tr><td>-S</td>
2244 2259 <td>--subrepos</td>
2245 2260 <td>recurse into subrepositories</td></tr>
2246 2261 <tr><td>-I</td>
2247 2262 <td>--include PATTERN [+]</td>
2248 2263 <td>include names matching the given patterns</td></tr>
2249 2264 <tr><td>-X</td>
2250 2265 <td>--exclude PATTERN [+]</td>
2251 2266 <td>exclude names matching the given patterns</td></tr>
2252 2267 </table>
2253 2268 <p>
2254 2269 global options ([+] can be repeated):
2255 2270 </p>
2256 2271 <table>
2257 2272 <tr><td>-R</td>
2258 2273 <td>--repository REPO</td>
2259 2274 <td>repository root directory or name of overlay bundle file</td></tr>
2260 2275 <tr><td></td>
2261 2276 <td>--cwd DIR</td>
2262 2277 <td>change working directory</td></tr>
2263 2278 <tr><td>-y</td>
2264 2279 <td>--noninteractive</td>
2265 2280 <td>do not prompt, automatically pick the first choice for all prompts</td></tr>
2266 2281 <tr><td>-q</td>
2267 2282 <td>--quiet</td>
2268 2283 <td>suppress output</td></tr>
2269 2284 <tr><td>-v</td>
2270 2285 <td>--verbose</td>
2271 2286 <td>enable additional output</td></tr>
2272 2287 <tr><td></td>
2273 2288 <td>--config CONFIG [+]</td>
2274 2289 <td>set/override config option (use 'section.name=value')</td></tr>
2275 2290 <tr><td></td>
2276 2291 <td>--debug</td>
2277 2292 <td>enable debugging output</td></tr>
2278 2293 <tr><td></td>
2279 2294 <td>--debugger</td>
2280 2295 <td>start debugger</td></tr>
2281 2296 <tr><td></td>
2282 2297 <td>--encoding ENCODE</td>
2283 2298 <td>set the charset encoding (default: ascii)</td></tr>
2284 2299 <tr><td></td>
2285 2300 <td>--encodingmode MODE</td>
2286 2301 <td>set the charset encoding mode (default: strict)</td></tr>
2287 2302 <tr><td></td>
2288 2303 <td>--traceback</td>
2289 2304 <td>always print a traceback on exception</td></tr>
2290 2305 <tr><td></td>
2291 2306 <td>--time</td>
2292 2307 <td>time how long the command takes</td></tr>
2293 2308 <tr><td></td>
2294 2309 <td>--profile</td>
2295 2310 <td>print command execution profile</td></tr>
2296 2311 <tr><td></td>
2297 2312 <td>--version</td>
2298 2313 <td>output version information and exit</td></tr>
2299 2314 <tr><td>-h</td>
2300 2315 <td>--help</td>
2301 2316 <td>display help and exit</td></tr>
2302 2317 <tr><td></td>
2303 2318 <td>--hidden</td>
2304 2319 <td>consider hidden changesets</td></tr>
2305 2320 </table>
2306 2321
2307 2322 </div>
2308 2323 </div>
2309 2324 </div>
2310 2325
2311 2326 <script type="text/javascript">process_dates()</script>
2312 2327
2313 2328
2314 2329 </body>
2315 2330 </html>
2316 2331
2317 2332
2318 2333 $ get-with-headers.py 127.0.0.1:$HGPORT "help/revisions"
2319 2334 200 Script output follows
2320 2335
2321 2336 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
2322 2337 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
2323 2338 <head>
2324 2339 <link rel="icon" href="/static/hgicon.png" type="image/png" />
2325 2340 <meta name="robots" content="index, nofollow" />
2326 2341 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
2327 2342 <script type="text/javascript" src="/static/mercurial.js"></script>
2328 2343
2329 2344 <title>Help: revisions</title>
2330 2345 </head>
2331 2346 <body>
2332 2347
2333 2348 <div class="container">
2334 2349 <div class="menu">
2335 2350 <div class="logo">
2336 2351 <a href="https://mercurial-scm.org/">
2337 2352 <img src="/static/hglogo.png" alt="mercurial" /></a>
2338 2353 </div>
2339 2354 <ul>
2340 2355 <li><a href="/shortlog">log</a></li>
2341 2356 <li><a href="/graph">graph</a></li>
2342 2357 <li><a href="/tags">tags</a></li>
2343 2358 <li><a href="/bookmarks">bookmarks</a></li>
2344 2359 <li><a href="/branches">branches</a></li>
2345 2360 </ul>
2346 2361 <ul>
2347 2362 <li class="active"><a href="/help">help</a></li>
2348 2363 </ul>
2349 2364 </div>
2350 2365
2351 2366 <div class="main">
2352 2367 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
2353 2368 <h3>Help: revisions</h3>
2354 2369
2355 2370 <form class="search" action="/log">
2356 2371
2357 2372 <p><input name="rev" id="search1" type="text" size="30" /></p>
2358 2373 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
2359 2374 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
2360 2375 </form>
2361 2376 <div id="doc">
2362 2377 <h1>Specifying Single Revisions</h1>
2363 2378 <p>
2364 2379 Mercurial supports several ways to specify individual revisions.
2365 2380 </p>
2366 2381 <p>
2367 2382 A plain integer is treated as a revision number. Negative integers are
2368 2383 treated as sequential offsets from the tip, with -1 denoting the tip,
2369 2384 -2 denoting the revision prior to the tip, and so forth.
2370 2385 </p>
2371 2386 <p>
2372 2387 A 40-digit hexadecimal string is treated as a unique revision
2373 2388 identifier.
2374 2389 </p>
2375 2390 <p>
2376 2391 A hexadecimal string less than 40 characters long is treated as a
2377 2392 unique revision identifier and is referred to as a short-form
2378 2393 identifier. A short-form identifier is only valid if it is the prefix
2379 2394 of exactly one full-length identifier.
2380 2395 </p>
2381 2396 <p>
2382 2397 Any other string is treated as a bookmark, tag, or branch name. A
2383 2398 bookmark is a movable pointer to a revision. A tag is a permanent name
2384 2399 associated with a revision. A branch name denotes the tipmost open branch head
2385 2400 of that branch - or if they are all closed, the tipmost closed head of the
2386 2401 branch. Bookmark, tag, and branch names must not contain the &quot;:&quot; character.
2387 2402 </p>
2388 2403 <p>
2389 2404 The reserved name &quot;tip&quot; always identifies the most recent revision.
2390 2405 </p>
2391 2406 <p>
2392 2407 The reserved name &quot;null&quot; indicates the null revision. This is the
2393 2408 revision of an empty repository, and the parent of revision 0.
2394 2409 </p>
2395 2410 <p>
2396 2411 The reserved name &quot;.&quot; indicates the working directory parent. If no
2397 2412 working directory is checked out, it is equivalent to null. If an
2398 2413 uncommitted merge is in progress, &quot;.&quot; is the revision of the first
2399 2414 parent.
2400 2415 </p>
2401 2416
2402 2417 </div>
2403 2418 </div>
2404 2419 </div>
2405 2420
2406 2421 <script type="text/javascript">process_dates()</script>
2407 2422
2408 2423
2409 2424 </body>
2410 2425 </html>
2411 2426
2412 2427
2413 2428 $ killdaemons.py
2414 2429
2415 2430 #endif
@@ -1,65 +1,118 b''
1 1 $ hg init a
2 2 $ hg clone a b
3 3 updating to branch default
4 4 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
5 5 $ cd a
6 6 $ echo '[paths]' >> .hg/hgrc
7 7 $ echo 'dupe = ../b' >> .hg/hgrc
8 8 $ echo 'expand = $SOMETHING/bar' >> .hg/hgrc
9 9 $ hg in dupe
10 10 comparing with $TESTTMP/b (glob)
11 11 no changes found
12 12 [1]
13 13 $ cd ..
14 14 $ hg -R a in dupe
15 15 comparing with $TESTTMP/b (glob)
16 16 no changes found
17 17 [1]
18 18 $ cd a
19 19 $ hg paths
20 20 dupe = $TESTTMP/b (glob)
21 21 expand = $TESTTMP/a/$SOMETHING/bar (glob)
22 22 $ SOMETHING=foo hg paths
23 23 dupe = $TESTTMP/b (glob)
24 24 expand = $TESTTMP/a/foo/bar (glob)
25 25 #if msys
26 26 $ SOMETHING=//foo hg paths
27 27 dupe = $TESTTMP/b (glob)
28 28 expand = /foo/bar
29 29 #else
30 30 $ SOMETHING=/foo hg paths
31 31 dupe = $TESTTMP/b (glob)
32 32 expand = /foo/bar
33 33 #endif
34 34 $ hg paths -q
35 35 dupe
36 36 expand
37 37 $ hg paths dupe
38 38 $TESTTMP/b (glob)
39 39 $ hg paths -q dupe
40 40 $ hg paths unknown
41 41 not found!
42 42 [1]
43 43 $ hg paths -q unknown
44 44 [1]
45 45 $ cd ..
46 46
47 sub-options for an undeclared path are ignored
48
49 $ hg init suboptions
50 $ cd suboptions
51
52 $ cat > .hg/hgrc << EOF
53 > [paths]
54 > path0 = https://example.com/path0
55 > path1:pushurl = https://example.com/path1
56 > EOF
57 $ hg paths
58 path0 = https://example.com/path0
59
60 unknown sub-options aren't displayed
61
62 $ cat > .hg/hgrc << EOF
63 > [paths]
64 > path0 = https://example.com/path0
65 > path0:foo = https://example.com/path1
66 > EOF
67
68 $ hg paths
69 path0 = https://example.com/path0
70
71 :pushurl must be a URL
72
73 $ cat > .hg/hgrc << EOF
74 > [paths]
75 > default = /path/to/nothing
76 > default:pushurl = /not/a/url
77 > EOF
78
79 $ hg paths
80 (paths.default:pushurl not a URL; ignoring)
81 default = /path/to/nothing
82
83 #fragment is not allowed in :pushurl
84
85 $ cat > .hg/hgrc << EOF
86 > [paths]
87 > default = https://example.com/repo
88 > invalid = https://example.com/repo
89 > invalid:pushurl = https://example.com/repo#branch
90 > EOF
91
92 $ hg paths
93 ("#fragment" in paths.invalid:pushurl not supported; ignoring)
94 default = https://example.com/repo
95 invalid = https://example.com/repo
96 invalid:pushurl = https://example.com/repo
97
98 $ cd ..
99
47 100 'file:' disables [paths] entries for clone destination
48 101
49 102 $ cat >> $HGRCPATH <<EOF
50 103 > [paths]
51 104 > gpath1 = http://hg.example.com
52 105 > EOF
53 106
54 107 $ hg clone a gpath1
55 108 abort: cannot create new http repository
56 109 [255]
57 110
58 111 $ hg clone a file:gpath1
59 112 updating to branch default
60 113 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
61 114 $ cd gpath1
62 115 $ hg -q id
63 116 000000000000
64 117
65 118 $ cd ..
General Comments 0
You need to be logged in to leave comments. Login now