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