##// END OF EJS Templates
debugcommands: move 'debugextensions' to the new module
Gregory Szorc -
r30518:a8b17859 default
parent child Browse files
Show More
@@ -1,6923 +1,6877 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import difflib
10 import difflib
11 import errno
11 import errno
12 import operator
13 import os
12 import os
14 import re
13 import re
15 import shlex
14 import shlex
16 import socket
15 import socket
17 import string
16 import string
18 import sys
17 import sys
19 import tempfile
18 import tempfile
20 import time
19 import time
21
20
22 from .i18n import _
21 from .i18n import _
23 from .node import (
22 from .node import (
24 bin,
23 bin,
25 hex,
24 hex,
26 nullhex,
25 nullhex,
27 nullid,
26 nullid,
28 nullrev,
27 nullrev,
29 short,
28 short,
30 )
29 )
31 from . import (
30 from . import (
32 archival,
31 archival,
33 bookmarks,
32 bookmarks,
34 bundle2,
33 bundle2,
35 changegroup,
34 changegroup,
36 cmdutil,
35 cmdutil,
37 copies,
36 copies,
38 destutil,
37 destutil,
39 dirstateguard,
38 dirstateguard,
40 discovery,
39 discovery,
41 encoding,
40 encoding,
42 error,
41 error,
43 exchange,
42 exchange,
44 extensions,
43 extensions,
45 fileset,
44 fileset,
46 formatter,
45 formatter,
47 graphmod,
46 graphmod,
48 hbisect,
47 hbisect,
49 help,
48 help,
50 hg,
49 hg,
51 lock as lockmod,
50 lock as lockmod,
52 merge as mergemod,
51 merge as mergemod,
53 minirst,
52 minirst,
54 obsolete,
53 obsolete,
55 patch,
54 patch,
56 phases,
55 phases,
57 policy,
56 policy,
58 pvec,
57 pvec,
59 pycompat,
58 pycompat,
60 repair,
59 repair,
61 revlog,
60 revlog,
62 revset,
61 revset,
63 scmutil,
62 scmutil,
64 server,
63 server,
65 sshserver,
64 sshserver,
66 sslutil,
65 sslutil,
67 streamclone,
66 streamclone,
68 templatekw,
67 templatekw,
69 templater,
68 templater,
70 ui as uimod,
69 ui as uimod,
71 util,
70 util,
72 )
71 )
73
72
74 release = lockmod.release
73 release = lockmod.release
75
74
76 table = {}
75 table = {}
77
76
78 command = cmdutil.command(table)
77 command = cmdutil.command(table)
79
78
80 # label constants
79 # label constants
81 # until 3.5, bookmarks.current was the advertised name, not
80 # until 3.5, bookmarks.current was the advertised name, not
82 # bookmarks.active, so we must use both to avoid breaking old
81 # bookmarks.active, so we must use both to avoid breaking old
83 # custom styles
82 # custom styles
84 activebookmarklabel = 'bookmarks.active bookmarks.current'
83 activebookmarklabel = 'bookmarks.active bookmarks.current'
85
84
86 # common command options
85 # common command options
87
86
88 globalopts = [
87 globalopts = [
89 ('R', 'repository', '',
88 ('R', 'repository', '',
90 _('repository root directory or name of overlay bundle file'),
89 _('repository root directory or name of overlay bundle file'),
91 _('REPO')),
90 _('REPO')),
92 ('', 'cwd', '',
91 ('', 'cwd', '',
93 _('change working directory'), _('DIR')),
92 _('change working directory'), _('DIR')),
94 ('y', 'noninteractive', None,
93 ('y', 'noninteractive', None,
95 _('do not prompt, automatically pick the first choice for all prompts')),
94 _('do not prompt, automatically pick the first choice for all prompts')),
96 ('q', 'quiet', None, _('suppress output')),
95 ('q', 'quiet', None, _('suppress output')),
97 ('v', 'verbose', None, _('enable additional output')),
96 ('v', 'verbose', None, _('enable additional output')),
98 ('', 'config', [],
97 ('', 'config', [],
99 _('set/override config option (use \'section.name=value\')'),
98 _('set/override config option (use \'section.name=value\')'),
100 _('CONFIG')),
99 _('CONFIG')),
101 ('', 'debug', None, _('enable debugging output')),
100 ('', 'debug', None, _('enable debugging output')),
102 ('', 'debugger', None, _('start debugger')),
101 ('', 'debugger', None, _('start debugger')),
103 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
102 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
104 _('ENCODE')),
103 _('ENCODE')),
105 ('', 'encodingmode', encoding.encodingmode,
104 ('', 'encodingmode', encoding.encodingmode,
106 _('set the charset encoding mode'), _('MODE')),
105 _('set the charset encoding mode'), _('MODE')),
107 ('', 'traceback', None, _('always print a traceback on exception')),
106 ('', 'traceback', None, _('always print a traceback on exception')),
108 ('', 'time', None, _('time how long the command takes')),
107 ('', 'time', None, _('time how long the command takes')),
109 ('', 'profile', None, _('print command execution profile')),
108 ('', 'profile', None, _('print command execution profile')),
110 ('', 'version', None, _('output version information and exit')),
109 ('', 'version', None, _('output version information and exit')),
111 ('h', 'help', None, _('display help and exit')),
110 ('h', 'help', None, _('display help and exit')),
112 ('', 'hidden', False, _('consider hidden changesets')),
111 ('', 'hidden', False, _('consider hidden changesets')),
113 ]
112 ]
114
113
115 dryrunopts = [('n', 'dry-run', None,
114 dryrunopts = [('n', 'dry-run', None,
116 _('do not perform actions, just print output'))]
115 _('do not perform actions, just print output'))]
117
116
118 remoteopts = [
117 remoteopts = [
119 ('e', 'ssh', '',
118 ('e', 'ssh', '',
120 _('specify ssh command to use'), _('CMD')),
119 _('specify ssh command to use'), _('CMD')),
121 ('', 'remotecmd', '',
120 ('', 'remotecmd', '',
122 _('specify hg command to run on the remote side'), _('CMD')),
121 _('specify hg command to run on the remote side'), _('CMD')),
123 ('', 'insecure', None,
122 ('', 'insecure', None,
124 _('do not verify server certificate (ignoring web.cacerts config)')),
123 _('do not verify server certificate (ignoring web.cacerts config)')),
125 ]
124 ]
126
125
127 walkopts = [
126 walkopts = [
128 ('I', 'include', [],
127 ('I', 'include', [],
129 _('include names matching the given patterns'), _('PATTERN')),
128 _('include names matching the given patterns'), _('PATTERN')),
130 ('X', 'exclude', [],
129 ('X', 'exclude', [],
131 _('exclude names matching the given patterns'), _('PATTERN')),
130 _('exclude names matching the given patterns'), _('PATTERN')),
132 ]
131 ]
133
132
134 commitopts = [
133 commitopts = [
135 ('m', 'message', '',
134 ('m', 'message', '',
136 _('use text as commit message'), _('TEXT')),
135 _('use text as commit message'), _('TEXT')),
137 ('l', 'logfile', '',
136 ('l', 'logfile', '',
138 _('read commit message from file'), _('FILE')),
137 _('read commit message from file'), _('FILE')),
139 ]
138 ]
140
139
141 commitopts2 = [
140 commitopts2 = [
142 ('d', 'date', '',
141 ('d', 'date', '',
143 _('record the specified date as commit date'), _('DATE')),
142 _('record the specified date as commit date'), _('DATE')),
144 ('u', 'user', '',
143 ('u', 'user', '',
145 _('record the specified user as committer'), _('USER')),
144 _('record the specified user as committer'), _('USER')),
146 ]
145 ]
147
146
148 # hidden for now
147 # hidden for now
149 formatteropts = [
148 formatteropts = [
150 ('T', 'template', '',
149 ('T', 'template', '',
151 _('display with template (EXPERIMENTAL)'), _('TEMPLATE')),
150 _('display with template (EXPERIMENTAL)'), _('TEMPLATE')),
152 ]
151 ]
153
152
154 templateopts = [
153 templateopts = [
155 ('', 'style', '',
154 ('', 'style', '',
156 _('display using template map file (DEPRECATED)'), _('STYLE')),
155 _('display using template map file (DEPRECATED)'), _('STYLE')),
157 ('T', 'template', '',
156 ('T', 'template', '',
158 _('display with template'), _('TEMPLATE')),
157 _('display with template'), _('TEMPLATE')),
159 ]
158 ]
160
159
161 logopts = [
160 logopts = [
162 ('p', 'patch', None, _('show patch')),
161 ('p', 'patch', None, _('show patch')),
163 ('g', 'git', None, _('use git extended diff format')),
162 ('g', 'git', None, _('use git extended diff format')),
164 ('l', 'limit', '',
163 ('l', 'limit', '',
165 _('limit number of changes displayed'), _('NUM')),
164 _('limit number of changes displayed'), _('NUM')),
166 ('M', 'no-merges', None, _('do not show merges')),
165 ('M', 'no-merges', None, _('do not show merges')),
167 ('', 'stat', None, _('output diffstat-style summary of changes')),
166 ('', 'stat', None, _('output diffstat-style summary of changes')),
168 ('G', 'graph', None, _("show the revision DAG")),
167 ('G', 'graph', None, _("show the revision DAG")),
169 ] + templateopts
168 ] + templateopts
170
169
171 diffopts = [
170 diffopts = [
172 ('a', 'text', None, _('treat all files as text')),
171 ('a', 'text', None, _('treat all files as text')),
173 ('g', 'git', None, _('use git extended diff format')),
172 ('g', 'git', None, _('use git extended diff format')),
174 ('', 'nodates', None, _('omit dates from diff headers'))
173 ('', 'nodates', None, _('omit dates from diff headers'))
175 ]
174 ]
176
175
177 diffwsopts = [
176 diffwsopts = [
178 ('w', 'ignore-all-space', None,
177 ('w', 'ignore-all-space', None,
179 _('ignore white space when comparing lines')),
178 _('ignore white space when comparing lines')),
180 ('b', 'ignore-space-change', None,
179 ('b', 'ignore-space-change', None,
181 _('ignore changes in the amount of white space')),
180 _('ignore changes in the amount of white space')),
182 ('B', 'ignore-blank-lines', None,
181 ('B', 'ignore-blank-lines', None,
183 _('ignore changes whose lines are all blank')),
182 _('ignore changes whose lines are all blank')),
184 ]
183 ]
185
184
186 diffopts2 = [
185 diffopts2 = [
187 ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
186 ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
188 ('p', 'show-function', None, _('show which function each change is in')),
187 ('p', 'show-function', None, _('show which function each change is in')),
189 ('', 'reverse', None, _('produce a diff that undoes the changes')),
188 ('', 'reverse', None, _('produce a diff that undoes the changes')),
190 ] + diffwsopts + [
189 ] + diffwsopts + [
191 ('U', 'unified', '',
190 ('U', 'unified', '',
192 _('number of lines of context to show'), _('NUM')),
191 _('number of lines of context to show'), _('NUM')),
193 ('', 'stat', None, _('output diffstat-style summary of changes')),
192 ('', 'stat', None, _('output diffstat-style summary of changes')),
194 ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
193 ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
195 ]
194 ]
196
195
197 mergetoolopts = [
196 mergetoolopts = [
198 ('t', 'tool', '', _('specify merge tool')),
197 ('t', 'tool', '', _('specify merge tool')),
199 ]
198 ]
200
199
201 similarityopts = [
200 similarityopts = [
202 ('s', 'similarity', '',
201 ('s', 'similarity', '',
203 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
202 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
204 ]
203 ]
205
204
206 subrepoopts = [
205 subrepoopts = [
207 ('S', 'subrepos', None,
206 ('S', 'subrepos', None,
208 _('recurse into subrepositories'))
207 _('recurse into subrepositories'))
209 ]
208 ]
210
209
211 debugrevlogopts = [
210 debugrevlogopts = [
212 ('c', 'changelog', False, _('open changelog')),
211 ('c', 'changelog', False, _('open changelog')),
213 ('m', 'manifest', False, _('open manifest')),
212 ('m', 'manifest', False, _('open manifest')),
214 ('', 'dir', '', _('open directory manifest')),
213 ('', 'dir', '', _('open directory manifest')),
215 ]
214 ]
216
215
217 # Commands start here, listed alphabetically
216 # Commands start here, listed alphabetically
218
217
219 @command('^add',
218 @command('^add',
220 walkopts + subrepoopts + dryrunopts,
219 walkopts + subrepoopts + dryrunopts,
221 _('[OPTION]... [FILE]...'),
220 _('[OPTION]... [FILE]...'),
222 inferrepo=True)
221 inferrepo=True)
223 def add(ui, repo, *pats, **opts):
222 def add(ui, repo, *pats, **opts):
224 """add the specified files on the next commit
223 """add the specified files on the next commit
225
224
226 Schedule files to be version controlled and added to the
225 Schedule files to be version controlled and added to the
227 repository.
226 repository.
228
227
229 The files will be added to the repository at the next commit. To
228 The files will be added to the repository at the next commit. To
230 undo an add before that, see :hg:`forget`.
229 undo an add before that, see :hg:`forget`.
231
230
232 If no names are given, add all files to the repository (except
231 If no names are given, add all files to the repository (except
233 files matching ``.hgignore``).
232 files matching ``.hgignore``).
234
233
235 .. container:: verbose
234 .. container:: verbose
236
235
237 Examples:
236 Examples:
238
237
239 - New (unknown) files are added
238 - New (unknown) files are added
240 automatically by :hg:`add`::
239 automatically by :hg:`add`::
241
240
242 $ ls
241 $ ls
243 foo.c
242 foo.c
244 $ hg status
243 $ hg status
245 ? foo.c
244 ? foo.c
246 $ hg add
245 $ hg add
247 adding foo.c
246 adding foo.c
248 $ hg status
247 $ hg status
249 A foo.c
248 A foo.c
250
249
251 - Specific files to be added can be specified::
250 - Specific files to be added can be specified::
252
251
253 $ ls
252 $ ls
254 bar.c foo.c
253 bar.c foo.c
255 $ hg status
254 $ hg status
256 ? bar.c
255 ? bar.c
257 ? foo.c
256 ? foo.c
258 $ hg add bar.c
257 $ hg add bar.c
259 $ hg status
258 $ hg status
260 A bar.c
259 A bar.c
261 ? foo.c
260 ? foo.c
262
261
263 Returns 0 if all files are successfully added.
262 Returns 0 if all files are successfully added.
264 """
263 """
265
264
266 m = scmutil.match(repo[None], pats, opts)
265 m = scmutil.match(repo[None], pats, opts)
267 rejected = cmdutil.add(ui, repo, m, "", False, **opts)
266 rejected = cmdutil.add(ui, repo, m, "", False, **opts)
268 return rejected and 1 or 0
267 return rejected and 1 or 0
269
268
270 @command('addremove',
269 @command('addremove',
271 similarityopts + subrepoopts + walkopts + dryrunopts,
270 similarityopts + subrepoopts + walkopts + dryrunopts,
272 _('[OPTION]... [FILE]...'),
271 _('[OPTION]... [FILE]...'),
273 inferrepo=True)
272 inferrepo=True)
274 def addremove(ui, repo, *pats, **opts):
273 def addremove(ui, repo, *pats, **opts):
275 """add all new files, delete all missing files
274 """add all new files, delete all missing files
276
275
277 Add all new files and remove all missing files from the
276 Add all new files and remove all missing files from the
278 repository.
277 repository.
279
278
280 Unless names are given, new files are ignored if they match any of
279 Unless names are given, new files are ignored if they match any of
281 the patterns in ``.hgignore``. As with add, these changes take
280 the patterns in ``.hgignore``. As with add, these changes take
282 effect at the next commit.
281 effect at the next commit.
283
282
284 Use the -s/--similarity option to detect renamed files. This
283 Use the -s/--similarity option to detect renamed files. This
285 option takes a percentage between 0 (disabled) and 100 (files must
284 option takes a percentage between 0 (disabled) and 100 (files must
286 be identical) as its parameter. With a parameter greater than 0,
285 be identical) as its parameter. With a parameter greater than 0,
287 this compares every removed file with every added file and records
286 this compares every removed file with every added file and records
288 those similar enough as renames. Detecting renamed files this way
287 those similar enough as renames. Detecting renamed files this way
289 can be expensive. After using this option, :hg:`status -C` can be
288 can be expensive. After using this option, :hg:`status -C` can be
290 used to check which files were identified as moved or renamed. If
289 used to check which files were identified as moved or renamed. If
291 not specified, -s/--similarity defaults to 100 and only renames of
290 not specified, -s/--similarity defaults to 100 and only renames of
292 identical files are detected.
291 identical files are detected.
293
292
294 .. container:: verbose
293 .. container:: verbose
295
294
296 Examples:
295 Examples:
297
296
298 - A number of files (bar.c and foo.c) are new,
297 - A number of files (bar.c and foo.c) are new,
299 while foobar.c has been removed (without using :hg:`remove`)
298 while foobar.c has been removed (without using :hg:`remove`)
300 from the repository::
299 from the repository::
301
300
302 $ ls
301 $ ls
303 bar.c foo.c
302 bar.c foo.c
304 $ hg status
303 $ hg status
305 ! foobar.c
304 ! foobar.c
306 ? bar.c
305 ? bar.c
307 ? foo.c
306 ? foo.c
308 $ hg addremove
307 $ hg addremove
309 adding bar.c
308 adding bar.c
310 adding foo.c
309 adding foo.c
311 removing foobar.c
310 removing foobar.c
312 $ hg status
311 $ hg status
313 A bar.c
312 A bar.c
314 A foo.c
313 A foo.c
315 R foobar.c
314 R foobar.c
316
315
317 - A file foobar.c was moved to foo.c without using :hg:`rename`.
316 - A file foobar.c was moved to foo.c without using :hg:`rename`.
318 Afterwards, it was edited slightly::
317 Afterwards, it was edited slightly::
319
318
320 $ ls
319 $ ls
321 foo.c
320 foo.c
322 $ hg status
321 $ hg status
323 ! foobar.c
322 ! foobar.c
324 ? foo.c
323 ? foo.c
325 $ hg addremove --similarity 90
324 $ hg addremove --similarity 90
326 removing foobar.c
325 removing foobar.c
327 adding foo.c
326 adding foo.c
328 recording removal of foobar.c as rename to foo.c (94% similar)
327 recording removal of foobar.c as rename to foo.c (94% similar)
329 $ hg status -C
328 $ hg status -C
330 A foo.c
329 A foo.c
331 foobar.c
330 foobar.c
332 R foobar.c
331 R foobar.c
333
332
334 Returns 0 if all files are successfully added.
333 Returns 0 if all files are successfully added.
335 """
334 """
336 try:
335 try:
337 sim = float(opts.get('similarity') or 100)
336 sim = float(opts.get('similarity') or 100)
338 except ValueError:
337 except ValueError:
339 raise error.Abort(_('similarity must be a number'))
338 raise error.Abort(_('similarity must be a number'))
340 if sim < 0 or sim > 100:
339 if sim < 0 or sim > 100:
341 raise error.Abort(_('similarity must be between 0 and 100'))
340 raise error.Abort(_('similarity must be between 0 and 100'))
342 matcher = scmutil.match(repo[None], pats, opts)
341 matcher = scmutil.match(repo[None], pats, opts)
343 return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
342 return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
344
343
345 @command('^annotate|blame',
344 @command('^annotate|blame',
346 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
345 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
347 ('', 'follow', None,
346 ('', 'follow', None,
348 _('follow copies/renames and list the filename (DEPRECATED)')),
347 _('follow copies/renames and list the filename (DEPRECATED)')),
349 ('', 'no-follow', None, _("don't follow copies and renames")),
348 ('', 'no-follow', None, _("don't follow copies and renames")),
350 ('a', 'text', None, _('treat all files as text')),
349 ('a', 'text', None, _('treat all files as text')),
351 ('u', 'user', None, _('list the author (long with -v)')),
350 ('u', 'user', None, _('list the author (long with -v)')),
352 ('f', 'file', None, _('list the filename')),
351 ('f', 'file', None, _('list the filename')),
353 ('d', 'date', None, _('list the date (short with -q)')),
352 ('d', 'date', None, _('list the date (short with -q)')),
354 ('n', 'number', None, _('list the revision number (default)')),
353 ('n', 'number', None, _('list the revision number (default)')),
355 ('c', 'changeset', None, _('list the changeset')),
354 ('c', 'changeset', None, _('list the changeset')),
356 ('l', 'line-number', None, _('show line number at the first appearance'))
355 ('l', 'line-number', None, _('show line number at the first appearance'))
357 ] + diffwsopts + walkopts + formatteropts,
356 ] + diffwsopts + walkopts + formatteropts,
358 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
357 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
359 inferrepo=True)
358 inferrepo=True)
360 def annotate(ui, repo, *pats, **opts):
359 def annotate(ui, repo, *pats, **opts):
361 """show changeset information by line for each file
360 """show changeset information by line for each file
362
361
363 List changes in files, showing the revision id responsible for
362 List changes in files, showing the revision id responsible for
364 each line.
363 each line.
365
364
366 This command is useful for discovering when a change was made and
365 This command is useful for discovering when a change was made and
367 by whom.
366 by whom.
368
367
369 If you include --file, --user, or --date, the revision number is
368 If you include --file, --user, or --date, the revision number is
370 suppressed unless you also include --number.
369 suppressed unless you also include --number.
371
370
372 Without the -a/--text option, annotate will avoid processing files
371 Without the -a/--text option, annotate will avoid processing files
373 it detects as binary. With -a, annotate will annotate the file
372 it detects as binary. With -a, annotate will annotate the file
374 anyway, although the results will probably be neither useful
373 anyway, although the results will probably be neither useful
375 nor desirable.
374 nor desirable.
376
375
377 Returns 0 on success.
376 Returns 0 on success.
378 """
377 """
379 if not pats:
378 if not pats:
380 raise error.Abort(_('at least one filename or pattern is required'))
379 raise error.Abort(_('at least one filename or pattern is required'))
381
380
382 if opts.get('follow'):
381 if opts.get('follow'):
383 # --follow is deprecated and now just an alias for -f/--file
382 # --follow is deprecated and now just an alias for -f/--file
384 # to mimic the behavior of Mercurial before version 1.5
383 # to mimic the behavior of Mercurial before version 1.5
385 opts['file'] = True
384 opts['file'] = True
386
385
387 ctx = scmutil.revsingle(repo, opts.get('rev'))
386 ctx = scmutil.revsingle(repo, opts.get('rev'))
388
387
389 fm = ui.formatter('annotate', opts)
388 fm = ui.formatter('annotate', opts)
390 if ui.quiet:
389 if ui.quiet:
391 datefunc = util.shortdate
390 datefunc = util.shortdate
392 else:
391 else:
393 datefunc = util.datestr
392 datefunc = util.datestr
394 if ctx.rev() is None:
393 if ctx.rev() is None:
395 def hexfn(node):
394 def hexfn(node):
396 if node is None:
395 if node is None:
397 return None
396 return None
398 else:
397 else:
399 return fm.hexfunc(node)
398 return fm.hexfunc(node)
400 if opts.get('changeset'):
399 if opts.get('changeset'):
401 # omit "+" suffix which is appended to node hex
400 # omit "+" suffix which is appended to node hex
402 def formatrev(rev):
401 def formatrev(rev):
403 if rev is None:
402 if rev is None:
404 return '%d' % ctx.p1().rev()
403 return '%d' % ctx.p1().rev()
405 else:
404 else:
406 return '%d' % rev
405 return '%d' % rev
407 else:
406 else:
408 def formatrev(rev):
407 def formatrev(rev):
409 if rev is None:
408 if rev is None:
410 return '%d+' % ctx.p1().rev()
409 return '%d+' % ctx.p1().rev()
411 else:
410 else:
412 return '%d ' % rev
411 return '%d ' % rev
413 def formathex(hex):
412 def formathex(hex):
414 if hex is None:
413 if hex is None:
415 return '%s+' % fm.hexfunc(ctx.p1().node())
414 return '%s+' % fm.hexfunc(ctx.p1().node())
416 else:
415 else:
417 return '%s ' % hex
416 return '%s ' % hex
418 else:
417 else:
419 hexfn = fm.hexfunc
418 hexfn = fm.hexfunc
420 formatrev = formathex = str
419 formatrev = formathex = str
421
420
422 opmap = [('user', ' ', lambda x: x[0].user(), ui.shortuser),
421 opmap = [('user', ' ', lambda x: x[0].user(), ui.shortuser),
423 ('number', ' ', lambda x: x[0].rev(), formatrev),
422 ('number', ' ', lambda x: x[0].rev(), formatrev),
424 ('changeset', ' ', lambda x: hexfn(x[0].node()), formathex),
423 ('changeset', ' ', lambda x: hexfn(x[0].node()), formathex),
425 ('date', ' ', lambda x: x[0].date(), util.cachefunc(datefunc)),
424 ('date', ' ', lambda x: x[0].date(), util.cachefunc(datefunc)),
426 ('file', ' ', lambda x: x[0].path(), str),
425 ('file', ' ', lambda x: x[0].path(), str),
427 ('line_number', ':', lambda x: x[1], str),
426 ('line_number', ':', lambda x: x[1], str),
428 ]
427 ]
429 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
428 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
430
429
431 if (not opts.get('user') and not opts.get('changeset')
430 if (not opts.get('user') and not opts.get('changeset')
432 and not opts.get('date') and not opts.get('file')):
431 and not opts.get('date') and not opts.get('file')):
433 opts['number'] = True
432 opts['number'] = True
434
433
435 linenumber = opts.get('line_number') is not None
434 linenumber = opts.get('line_number') is not None
436 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
435 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
437 raise error.Abort(_('at least one of -n/-c is required for -l'))
436 raise error.Abort(_('at least one of -n/-c is required for -l'))
438
437
439 if fm.isplain():
438 if fm.isplain():
440 def makefunc(get, fmt):
439 def makefunc(get, fmt):
441 return lambda x: fmt(get(x))
440 return lambda x: fmt(get(x))
442 else:
441 else:
443 def makefunc(get, fmt):
442 def makefunc(get, fmt):
444 return get
443 return get
445 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
444 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
446 if opts.get(op)]
445 if opts.get(op)]
447 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
446 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
448 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
447 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
449 if opts.get(op))
448 if opts.get(op))
450
449
451 def bad(x, y):
450 def bad(x, y):
452 raise error.Abort("%s: %s" % (x, y))
451 raise error.Abort("%s: %s" % (x, y))
453
452
454 m = scmutil.match(ctx, pats, opts, badfn=bad)
453 m = scmutil.match(ctx, pats, opts, badfn=bad)
455
454
456 follow = not opts.get('no_follow')
455 follow = not opts.get('no_follow')
457 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
456 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
458 whitespace=True)
457 whitespace=True)
459 for abs in ctx.walk(m):
458 for abs in ctx.walk(m):
460 fctx = ctx[abs]
459 fctx = ctx[abs]
461 if not opts.get('text') and util.binary(fctx.data()):
460 if not opts.get('text') and util.binary(fctx.data()):
462 fm.plain(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
461 fm.plain(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
463 continue
462 continue
464
463
465 lines = fctx.annotate(follow=follow, linenumber=linenumber,
464 lines = fctx.annotate(follow=follow, linenumber=linenumber,
466 diffopts=diffopts)
465 diffopts=diffopts)
467 if not lines:
466 if not lines:
468 continue
467 continue
469 formats = []
468 formats = []
470 pieces = []
469 pieces = []
471
470
472 for f, sep in funcmap:
471 for f, sep in funcmap:
473 l = [f(n) for n, dummy in lines]
472 l = [f(n) for n, dummy in lines]
474 if fm.isplain():
473 if fm.isplain():
475 sizes = [encoding.colwidth(x) for x in l]
474 sizes = [encoding.colwidth(x) for x in l]
476 ml = max(sizes)
475 ml = max(sizes)
477 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
476 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
478 else:
477 else:
479 formats.append(['%s' for x in l])
478 formats.append(['%s' for x in l])
480 pieces.append(l)
479 pieces.append(l)
481
480
482 for f, p, l in zip(zip(*formats), zip(*pieces), lines):
481 for f, p, l in zip(zip(*formats), zip(*pieces), lines):
483 fm.startitem()
482 fm.startitem()
484 fm.write(fields, "".join(f), *p)
483 fm.write(fields, "".join(f), *p)
485 fm.write('line', ": %s", l[1])
484 fm.write('line', ": %s", l[1])
486
485
487 if not lines[-1][1].endswith('\n'):
486 if not lines[-1][1].endswith('\n'):
488 fm.plain('\n')
487 fm.plain('\n')
489
488
490 fm.end()
489 fm.end()
491
490
492 @command('archive',
491 @command('archive',
493 [('', 'no-decode', None, _('do not pass files through decoders')),
492 [('', 'no-decode', None, _('do not pass files through decoders')),
494 ('p', 'prefix', '', _('directory prefix for files in archive'),
493 ('p', 'prefix', '', _('directory prefix for files in archive'),
495 _('PREFIX')),
494 _('PREFIX')),
496 ('r', 'rev', '', _('revision to distribute'), _('REV')),
495 ('r', 'rev', '', _('revision to distribute'), _('REV')),
497 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
496 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
498 ] + subrepoopts + walkopts,
497 ] + subrepoopts + walkopts,
499 _('[OPTION]... DEST'))
498 _('[OPTION]... DEST'))
500 def archive(ui, repo, dest, **opts):
499 def archive(ui, repo, dest, **opts):
501 '''create an unversioned archive of a repository revision
500 '''create an unversioned archive of a repository revision
502
501
503 By default, the revision used is the parent of the working
502 By default, the revision used is the parent of the working
504 directory; use -r/--rev to specify a different revision.
503 directory; use -r/--rev to specify a different revision.
505
504
506 The archive type is automatically detected based on file
505 The archive type is automatically detected based on file
507 extension (to override, use -t/--type).
506 extension (to override, use -t/--type).
508
507
509 .. container:: verbose
508 .. container:: verbose
510
509
511 Examples:
510 Examples:
512
511
513 - create a zip file containing the 1.0 release::
512 - create a zip file containing the 1.0 release::
514
513
515 hg archive -r 1.0 project-1.0.zip
514 hg archive -r 1.0 project-1.0.zip
516
515
517 - create a tarball excluding .hg files::
516 - create a tarball excluding .hg files::
518
517
519 hg archive project.tar.gz -X ".hg*"
518 hg archive project.tar.gz -X ".hg*"
520
519
521 Valid types are:
520 Valid types are:
522
521
523 :``files``: a directory full of files (default)
522 :``files``: a directory full of files (default)
524 :``tar``: tar archive, uncompressed
523 :``tar``: tar archive, uncompressed
525 :``tbz2``: tar archive, compressed using bzip2
524 :``tbz2``: tar archive, compressed using bzip2
526 :``tgz``: tar archive, compressed using gzip
525 :``tgz``: tar archive, compressed using gzip
527 :``uzip``: zip archive, uncompressed
526 :``uzip``: zip archive, uncompressed
528 :``zip``: zip archive, compressed using deflate
527 :``zip``: zip archive, compressed using deflate
529
528
530 The exact name of the destination archive or directory is given
529 The exact name of the destination archive or directory is given
531 using a format string; see :hg:`help export` for details.
530 using a format string; see :hg:`help export` for details.
532
531
533 Each member added to an archive file has a directory prefix
532 Each member added to an archive file has a directory prefix
534 prepended. Use -p/--prefix to specify a format string for the
533 prepended. Use -p/--prefix to specify a format string for the
535 prefix. The default is the basename of the archive, with suffixes
534 prefix. The default is the basename of the archive, with suffixes
536 removed.
535 removed.
537
536
538 Returns 0 on success.
537 Returns 0 on success.
539 '''
538 '''
540
539
541 ctx = scmutil.revsingle(repo, opts.get('rev'))
540 ctx = scmutil.revsingle(repo, opts.get('rev'))
542 if not ctx:
541 if not ctx:
543 raise error.Abort(_('no working directory: please specify a revision'))
542 raise error.Abort(_('no working directory: please specify a revision'))
544 node = ctx.node()
543 node = ctx.node()
545 dest = cmdutil.makefilename(repo, dest, node)
544 dest = cmdutil.makefilename(repo, dest, node)
546 if os.path.realpath(dest) == repo.root:
545 if os.path.realpath(dest) == repo.root:
547 raise error.Abort(_('repository root cannot be destination'))
546 raise error.Abort(_('repository root cannot be destination'))
548
547
549 kind = opts.get('type') or archival.guesskind(dest) or 'files'
548 kind = opts.get('type') or archival.guesskind(dest) or 'files'
550 prefix = opts.get('prefix')
549 prefix = opts.get('prefix')
551
550
552 if dest == '-':
551 if dest == '-':
553 if kind == 'files':
552 if kind == 'files':
554 raise error.Abort(_('cannot archive plain files to stdout'))
553 raise error.Abort(_('cannot archive plain files to stdout'))
555 dest = cmdutil.makefileobj(repo, dest)
554 dest = cmdutil.makefileobj(repo, dest)
556 if not prefix:
555 if not prefix:
557 prefix = os.path.basename(repo.root) + '-%h'
556 prefix = os.path.basename(repo.root) + '-%h'
558
557
559 prefix = cmdutil.makefilename(repo, prefix, node)
558 prefix = cmdutil.makefilename(repo, prefix, node)
560 matchfn = scmutil.match(ctx, [], opts)
559 matchfn = scmutil.match(ctx, [], opts)
561 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
560 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
562 matchfn, prefix, subrepos=opts.get('subrepos'))
561 matchfn, prefix, subrepos=opts.get('subrepos'))
563
562
564 @command('backout',
563 @command('backout',
565 [('', 'merge', None, _('merge with old dirstate parent after backout')),
564 [('', 'merge', None, _('merge with old dirstate parent after backout')),
566 ('', 'commit', None,
565 ('', 'commit', None,
567 _('commit if no conflicts were encountered (DEPRECATED)')),
566 _('commit if no conflicts were encountered (DEPRECATED)')),
568 ('', 'no-commit', None, _('do not commit')),
567 ('', 'no-commit', None, _('do not commit')),
569 ('', 'parent', '',
568 ('', 'parent', '',
570 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
569 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
571 ('r', 'rev', '', _('revision to backout'), _('REV')),
570 ('r', 'rev', '', _('revision to backout'), _('REV')),
572 ('e', 'edit', False, _('invoke editor on commit messages')),
571 ('e', 'edit', False, _('invoke editor on commit messages')),
573 ] + mergetoolopts + walkopts + commitopts + commitopts2,
572 ] + mergetoolopts + walkopts + commitopts + commitopts2,
574 _('[OPTION]... [-r] REV'))
573 _('[OPTION]... [-r] REV'))
575 def backout(ui, repo, node=None, rev=None, **opts):
574 def backout(ui, repo, node=None, rev=None, **opts):
576 '''reverse effect of earlier changeset
575 '''reverse effect of earlier changeset
577
576
578 Prepare a new changeset with the effect of REV undone in the
577 Prepare a new changeset with the effect of REV undone in the
579 current working directory. If no conflicts were encountered,
578 current working directory. If no conflicts were encountered,
580 it will be committed immediately.
579 it will be committed immediately.
581
580
582 If REV is the parent of the working directory, then this new changeset
581 If REV is the parent of the working directory, then this new changeset
583 is committed automatically (unless --no-commit is specified).
582 is committed automatically (unless --no-commit is specified).
584
583
585 .. note::
584 .. note::
586
585
587 :hg:`backout` cannot be used to fix either an unwanted or
586 :hg:`backout` cannot be used to fix either an unwanted or
588 incorrect merge.
587 incorrect merge.
589
588
590 .. container:: verbose
589 .. container:: verbose
591
590
592 Examples:
591 Examples:
593
592
594 - Reverse the effect of the parent of the working directory.
593 - Reverse the effect of the parent of the working directory.
595 This backout will be committed immediately::
594 This backout will be committed immediately::
596
595
597 hg backout -r .
596 hg backout -r .
598
597
599 - Reverse the effect of previous bad revision 23::
598 - Reverse the effect of previous bad revision 23::
600
599
601 hg backout -r 23
600 hg backout -r 23
602
601
603 - Reverse the effect of previous bad revision 23 and
602 - Reverse the effect of previous bad revision 23 and
604 leave changes uncommitted::
603 leave changes uncommitted::
605
604
606 hg backout -r 23 --no-commit
605 hg backout -r 23 --no-commit
607 hg commit -m "Backout revision 23"
606 hg commit -m "Backout revision 23"
608
607
609 By default, the pending changeset will have one parent,
608 By default, the pending changeset will have one parent,
610 maintaining a linear history. With --merge, the pending
609 maintaining a linear history. With --merge, the pending
611 changeset will instead have two parents: the old parent of the
610 changeset will instead have two parents: the old parent of the
612 working directory and a new child of REV that simply undoes REV.
611 working directory and a new child of REV that simply undoes REV.
613
612
614 Before version 1.7, the behavior without --merge was equivalent
613 Before version 1.7, the behavior without --merge was equivalent
615 to specifying --merge followed by :hg:`update --clean .` to
614 to specifying --merge followed by :hg:`update --clean .` to
616 cancel the merge and leave the child of REV as a head to be
615 cancel the merge and leave the child of REV as a head to be
617 merged separately.
616 merged separately.
618
617
619 See :hg:`help dates` for a list of formats valid for -d/--date.
618 See :hg:`help dates` for a list of formats valid for -d/--date.
620
619
621 See :hg:`help revert` for a way to restore files to the state
620 See :hg:`help revert` for a way to restore files to the state
622 of another revision.
621 of another revision.
623
622
624 Returns 0 on success, 1 if nothing to backout or there are unresolved
623 Returns 0 on success, 1 if nothing to backout or there are unresolved
625 files.
624 files.
626 '''
625 '''
627 wlock = lock = None
626 wlock = lock = None
628 try:
627 try:
629 wlock = repo.wlock()
628 wlock = repo.wlock()
630 lock = repo.lock()
629 lock = repo.lock()
631 return _dobackout(ui, repo, node, rev, **opts)
630 return _dobackout(ui, repo, node, rev, **opts)
632 finally:
631 finally:
633 release(lock, wlock)
632 release(lock, wlock)
634
633
635 def _dobackout(ui, repo, node=None, rev=None, **opts):
634 def _dobackout(ui, repo, node=None, rev=None, **opts):
636 if opts.get('commit') and opts.get('no_commit'):
635 if opts.get('commit') and opts.get('no_commit'):
637 raise error.Abort(_("cannot use --commit with --no-commit"))
636 raise error.Abort(_("cannot use --commit with --no-commit"))
638 if opts.get('merge') and opts.get('no_commit'):
637 if opts.get('merge') and opts.get('no_commit'):
639 raise error.Abort(_("cannot use --merge with --no-commit"))
638 raise error.Abort(_("cannot use --merge with --no-commit"))
640
639
641 if rev and node:
640 if rev and node:
642 raise error.Abort(_("please specify just one revision"))
641 raise error.Abort(_("please specify just one revision"))
643
642
644 if not rev:
643 if not rev:
645 rev = node
644 rev = node
646
645
647 if not rev:
646 if not rev:
648 raise error.Abort(_("please specify a revision to backout"))
647 raise error.Abort(_("please specify a revision to backout"))
649
648
650 date = opts.get('date')
649 date = opts.get('date')
651 if date:
650 if date:
652 opts['date'] = util.parsedate(date)
651 opts['date'] = util.parsedate(date)
653
652
654 cmdutil.checkunfinished(repo)
653 cmdutil.checkunfinished(repo)
655 cmdutil.bailifchanged(repo)
654 cmdutil.bailifchanged(repo)
656 node = scmutil.revsingle(repo, rev).node()
655 node = scmutil.revsingle(repo, rev).node()
657
656
658 op1, op2 = repo.dirstate.parents()
657 op1, op2 = repo.dirstate.parents()
659 if not repo.changelog.isancestor(node, op1):
658 if not repo.changelog.isancestor(node, op1):
660 raise error.Abort(_('cannot backout change that is not an ancestor'))
659 raise error.Abort(_('cannot backout change that is not an ancestor'))
661
660
662 p1, p2 = repo.changelog.parents(node)
661 p1, p2 = repo.changelog.parents(node)
663 if p1 == nullid:
662 if p1 == nullid:
664 raise error.Abort(_('cannot backout a change with no parents'))
663 raise error.Abort(_('cannot backout a change with no parents'))
665 if p2 != nullid:
664 if p2 != nullid:
666 if not opts.get('parent'):
665 if not opts.get('parent'):
667 raise error.Abort(_('cannot backout a merge changeset'))
666 raise error.Abort(_('cannot backout a merge changeset'))
668 p = repo.lookup(opts['parent'])
667 p = repo.lookup(opts['parent'])
669 if p not in (p1, p2):
668 if p not in (p1, p2):
670 raise error.Abort(_('%s is not a parent of %s') %
669 raise error.Abort(_('%s is not a parent of %s') %
671 (short(p), short(node)))
670 (short(p), short(node)))
672 parent = p
671 parent = p
673 else:
672 else:
674 if opts.get('parent'):
673 if opts.get('parent'):
675 raise error.Abort(_('cannot use --parent on non-merge changeset'))
674 raise error.Abort(_('cannot use --parent on non-merge changeset'))
676 parent = p1
675 parent = p1
677
676
678 # the backout should appear on the same branch
677 # the backout should appear on the same branch
679 branch = repo.dirstate.branch()
678 branch = repo.dirstate.branch()
680 bheads = repo.branchheads(branch)
679 bheads = repo.branchheads(branch)
681 rctx = scmutil.revsingle(repo, hex(parent))
680 rctx = scmutil.revsingle(repo, hex(parent))
682 if not opts.get('merge') and op1 != node:
681 if not opts.get('merge') and op1 != node:
683 dsguard = dirstateguard.dirstateguard(repo, 'backout')
682 dsguard = dirstateguard.dirstateguard(repo, 'backout')
684 try:
683 try:
685 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
684 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
686 'backout')
685 'backout')
687 stats = mergemod.update(repo, parent, True, True, node, False)
686 stats = mergemod.update(repo, parent, True, True, node, False)
688 repo.setparents(op1, op2)
687 repo.setparents(op1, op2)
689 dsguard.close()
688 dsguard.close()
690 hg._showstats(repo, stats)
689 hg._showstats(repo, stats)
691 if stats[3]:
690 if stats[3]:
692 repo.ui.status(_("use 'hg resolve' to retry unresolved "
691 repo.ui.status(_("use 'hg resolve' to retry unresolved "
693 "file merges\n"))
692 "file merges\n"))
694 return 1
693 return 1
695 finally:
694 finally:
696 ui.setconfig('ui', 'forcemerge', '', '')
695 ui.setconfig('ui', 'forcemerge', '', '')
697 lockmod.release(dsguard)
696 lockmod.release(dsguard)
698 else:
697 else:
699 hg.clean(repo, node, show_stats=False)
698 hg.clean(repo, node, show_stats=False)
700 repo.dirstate.setbranch(branch)
699 repo.dirstate.setbranch(branch)
701 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
700 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
702
701
703 if opts.get('no_commit'):
702 if opts.get('no_commit'):
704 msg = _("changeset %s backed out, "
703 msg = _("changeset %s backed out, "
705 "don't forget to commit.\n")
704 "don't forget to commit.\n")
706 ui.status(msg % short(node))
705 ui.status(msg % short(node))
707 return 0
706 return 0
708
707
709 def commitfunc(ui, repo, message, match, opts):
708 def commitfunc(ui, repo, message, match, opts):
710 editform = 'backout'
709 editform = 'backout'
711 e = cmdutil.getcommiteditor(editform=editform, **opts)
710 e = cmdutil.getcommiteditor(editform=editform, **opts)
712 if not message:
711 if not message:
713 # we don't translate commit messages
712 # we don't translate commit messages
714 message = "Backed out changeset %s" % short(node)
713 message = "Backed out changeset %s" % short(node)
715 e = cmdutil.getcommiteditor(edit=True, editform=editform)
714 e = cmdutil.getcommiteditor(edit=True, editform=editform)
716 return repo.commit(message, opts.get('user'), opts.get('date'),
715 return repo.commit(message, opts.get('user'), opts.get('date'),
717 match, editor=e)
716 match, editor=e)
718 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
717 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
719 if not newnode:
718 if not newnode:
720 ui.status(_("nothing changed\n"))
719 ui.status(_("nothing changed\n"))
721 return 1
720 return 1
722 cmdutil.commitstatus(repo, newnode, branch, bheads)
721 cmdutil.commitstatus(repo, newnode, branch, bheads)
723
722
724 def nice(node):
723 def nice(node):
725 return '%d:%s' % (repo.changelog.rev(node), short(node))
724 return '%d:%s' % (repo.changelog.rev(node), short(node))
726 ui.status(_('changeset %s backs out changeset %s\n') %
725 ui.status(_('changeset %s backs out changeset %s\n') %
727 (nice(repo.changelog.tip()), nice(node)))
726 (nice(repo.changelog.tip()), nice(node)))
728 if opts.get('merge') and op1 != node:
727 if opts.get('merge') and op1 != node:
729 hg.clean(repo, op1, show_stats=False)
728 hg.clean(repo, op1, show_stats=False)
730 ui.status(_('merging with changeset %s\n')
729 ui.status(_('merging with changeset %s\n')
731 % nice(repo.changelog.tip()))
730 % nice(repo.changelog.tip()))
732 try:
731 try:
733 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
732 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
734 'backout')
733 'backout')
735 return hg.merge(repo, hex(repo.changelog.tip()))
734 return hg.merge(repo, hex(repo.changelog.tip()))
736 finally:
735 finally:
737 ui.setconfig('ui', 'forcemerge', '', '')
736 ui.setconfig('ui', 'forcemerge', '', '')
738 return 0
737 return 0
739
738
740 @command('bisect',
739 @command('bisect',
741 [('r', 'reset', False, _('reset bisect state')),
740 [('r', 'reset', False, _('reset bisect state')),
742 ('g', 'good', False, _('mark changeset good')),
741 ('g', 'good', False, _('mark changeset good')),
743 ('b', 'bad', False, _('mark changeset bad')),
742 ('b', 'bad', False, _('mark changeset bad')),
744 ('s', 'skip', False, _('skip testing changeset')),
743 ('s', 'skip', False, _('skip testing changeset')),
745 ('e', 'extend', False, _('extend the bisect range')),
744 ('e', 'extend', False, _('extend the bisect range')),
746 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
745 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
747 ('U', 'noupdate', False, _('do not update to target'))],
746 ('U', 'noupdate', False, _('do not update to target'))],
748 _("[-gbsr] [-U] [-c CMD] [REV]"))
747 _("[-gbsr] [-U] [-c CMD] [REV]"))
749 def bisect(ui, repo, rev=None, extra=None, command=None,
748 def bisect(ui, repo, rev=None, extra=None, command=None,
750 reset=None, good=None, bad=None, skip=None, extend=None,
749 reset=None, good=None, bad=None, skip=None, extend=None,
751 noupdate=None):
750 noupdate=None):
752 """subdivision search of changesets
751 """subdivision search of changesets
753
752
754 This command helps to find changesets which introduce problems. To
753 This command helps to find changesets which introduce problems. To
755 use, mark the earliest changeset you know exhibits the problem as
754 use, mark the earliest changeset you know exhibits the problem as
756 bad, then mark the latest changeset which is free from the problem
755 bad, then mark the latest changeset which is free from the problem
757 as good. Bisect will update your working directory to a revision
756 as good. Bisect will update your working directory to a revision
758 for testing (unless the -U/--noupdate option is specified). Once
757 for testing (unless the -U/--noupdate option is specified). Once
759 you have performed tests, mark the working directory as good or
758 you have performed tests, mark the working directory as good or
760 bad, and bisect will either update to another candidate changeset
759 bad, and bisect will either update to another candidate changeset
761 or announce that it has found the bad revision.
760 or announce that it has found the bad revision.
762
761
763 As a shortcut, you can also use the revision argument to mark a
762 As a shortcut, you can also use the revision argument to mark a
764 revision as good or bad without checking it out first.
763 revision as good or bad without checking it out first.
765
764
766 If you supply a command, it will be used for automatic bisection.
765 If you supply a command, it will be used for automatic bisection.
767 The environment variable HG_NODE will contain the ID of the
766 The environment variable HG_NODE will contain the ID of the
768 changeset being tested. The exit status of the command will be
767 changeset being tested. The exit status of the command will be
769 used to mark revisions as good or bad: status 0 means good, 125
768 used to mark revisions as good or bad: status 0 means good, 125
770 means to skip the revision, 127 (command not found) will abort the
769 means to skip the revision, 127 (command not found) will abort the
771 bisection, and any other non-zero exit status means the revision
770 bisection, and any other non-zero exit status means the revision
772 is bad.
771 is bad.
773
772
774 .. container:: verbose
773 .. container:: verbose
775
774
776 Some examples:
775 Some examples:
777
776
778 - start a bisection with known bad revision 34, and good revision 12::
777 - start a bisection with known bad revision 34, and good revision 12::
779
778
780 hg bisect --bad 34
779 hg bisect --bad 34
781 hg bisect --good 12
780 hg bisect --good 12
782
781
783 - advance the current bisection by marking current revision as good or
782 - advance the current bisection by marking current revision as good or
784 bad::
783 bad::
785
784
786 hg bisect --good
785 hg bisect --good
787 hg bisect --bad
786 hg bisect --bad
788
787
789 - mark the current revision, or a known revision, to be skipped (e.g. if
788 - mark the current revision, or a known revision, to be skipped (e.g. if
790 that revision is not usable because of another issue)::
789 that revision is not usable because of another issue)::
791
790
792 hg bisect --skip
791 hg bisect --skip
793 hg bisect --skip 23
792 hg bisect --skip 23
794
793
795 - skip all revisions that do not touch directories ``foo`` or ``bar``::
794 - skip all revisions that do not touch directories ``foo`` or ``bar``::
796
795
797 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
796 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
798
797
799 - forget the current bisection::
798 - forget the current bisection::
800
799
801 hg bisect --reset
800 hg bisect --reset
802
801
803 - use 'make && make tests' to automatically find the first broken
802 - use 'make && make tests' to automatically find the first broken
804 revision::
803 revision::
805
804
806 hg bisect --reset
805 hg bisect --reset
807 hg bisect --bad 34
806 hg bisect --bad 34
808 hg bisect --good 12
807 hg bisect --good 12
809 hg bisect --command "make && make tests"
808 hg bisect --command "make && make tests"
810
809
811 - see all changesets whose states are already known in the current
810 - see all changesets whose states are already known in the current
812 bisection::
811 bisection::
813
812
814 hg log -r "bisect(pruned)"
813 hg log -r "bisect(pruned)"
815
814
816 - see the changeset currently being bisected (especially useful
815 - see the changeset currently being bisected (especially useful
817 if running with -U/--noupdate)::
816 if running with -U/--noupdate)::
818
817
819 hg log -r "bisect(current)"
818 hg log -r "bisect(current)"
820
819
821 - see all changesets that took part in the current bisection::
820 - see all changesets that took part in the current bisection::
822
821
823 hg log -r "bisect(range)"
822 hg log -r "bisect(range)"
824
823
825 - you can even get a nice graph::
824 - you can even get a nice graph::
826
825
827 hg log --graph -r "bisect(range)"
826 hg log --graph -r "bisect(range)"
828
827
829 See :hg:`help revsets` for more about the `bisect()` keyword.
828 See :hg:`help revsets` for more about the `bisect()` keyword.
830
829
831 Returns 0 on success.
830 Returns 0 on success.
832 """
831 """
833 # backward compatibility
832 # backward compatibility
834 if rev in "good bad reset init".split():
833 if rev in "good bad reset init".split():
835 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
834 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
836 cmd, rev, extra = rev, extra, None
835 cmd, rev, extra = rev, extra, None
837 if cmd == "good":
836 if cmd == "good":
838 good = True
837 good = True
839 elif cmd == "bad":
838 elif cmd == "bad":
840 bad = True
839 bad = True
841 else:
840 else:
842 reset = True
841 reset = True
843 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
842 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
844 raise error.Abort(_('incompatible arguments'))
843 raise error.Abort(_('incompatible arguments'))
845
844
846 cmdutil.checkunfinished(repo)
845 cmdutil.checkunfinished(repo)
847
846
848 if reset:
847 if reset:
849 hbisect.resetstate(repo)
848 hbisect.resetstate(repo)
850 return
849 return
851
850
852 state = hbisect.load_state(repo)
851 state = hbisect.load_state(repo)
853
852
854 # update state
853 # update state
855 if good or bad or skip:
854 if good or bad or skip:
856 if rev:
855 if rev:
857 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
856 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
858 else:
857 else:
859 nodes = [repo.lookup('.')]
858 nodes = [repo.lookup('.')]
860 if good:
859 if good:
861 state['good'] += nodes
860 state['good'] += nodes
862 elif bad:
861 elif bad:
863 state['bad'] += nodes
862 state['bad'] += nodes
864 elif skip:
863 elif skip:
865 state['skip'] += nodes
864 state['skip'] += nodes
866 hbisect.save_state(repo, state)
865 hbisect.save_state(repo, state)
867 if not (state['good'] and state['bad']):
866 if not (state['good'] and state['bad']):
868 return
867 return
869
868
870 def mayupdate(repo, node, show_stats=True):
869 def mayupdate(repo, node, show_stats=True):
871 """common used update sequence"""
870 """common used update sequence"""
872 if noupdate:
871 if noupdate:
873 return
872 return
874 cmdutil.bailifchanged(repo)
873 cmdutil.bailifchanged(repo)
875 return hg.clean(repo, node, show_stats=show_stats)
874 return hg.clean(repo, node, show_stats=show_stats)
876
875
877 displayer = cmdutil.show_changeset(ui, repo, {})
876 displayer = cmdutil.show_changeset(ui, repo, {})
878
877
879 if command:
878 if command:
880 changesets = 1
879 changesets = 1
881 if noupdate:
880 if noupdate:
882 try:
881 try:
883 node = state['current'][0]
882 node = state['current'][0]
884 except LookupError:
883 except LookupError:
885 raise error.Abort(_('current bisect revision is unknown - '
884 raise error.Abort(_('current bisect revision is unknown - '
886 'start a new bisect to fix'))
885 'start a new bisect to fix'))
887 else:
886 else:
888 node, p2 = repo.dirstate.parents()
887 node, p2 = repo.dirstate.parents()
889 if p2 != nullid:
888 if p2 != nullid:
890 raise error.Abort(_('current bisect revision is a merge'))
889 raise error.Abort(_('current bisect revision is a merge'))
891 if rev:
890 if rev:
892 node = repo[scmutil.revsingle(repo, rev, node)].node()
891 node = repo[scmutil.revsingle(repo, rev, node)].node()
893 try:
892 try:
894 while changesets:
893 while changesets:
895 # update state
894 # update state
896 state['current'] = [node]
895 state['current'] = [node]
897 hbisect.save_state(repo, state)
896 hbisect.save_state(repo, state)
898 status = ui.system(command, environ={'HG_NODE': hex(node)})
897 status = ui.system(command, environ={'HG_NODE': hex(node)})
899 if status == 125:
898 if status == 125:
900 transition = "skip"
899 transition = "skip"
901 elif status == 0:
900 elif status == 0:
902 transition = "good"
901 transition = "good"
903 # status < 0 means process was killed
902 # status < 0 means process was killed
904 elif status == 127:
903 elif status == 127:
905 raise error.Abort(_("failed to execute %s") % command)
904 raise error.Abort(_("failed to execute %s") % command)
906 elif status < 0:
905 elif status < 0:
907 raise error.Abort(_("%s killed") % command)
906 raise error.Abort(_("%s killed") % command)
908 else:
907 else:
909 transition = "bad"
908 transition = "bad"
910 state[transition].append(node)
909 state[transition].append(node)
911 ctx = repo[node]
910 ctx = repo[node]
912 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
911 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
913 hbisect.checkstate(state)
912 hbisect.checkstate(state)
914 # bisect
913 # bisect
915 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
914 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
916 # update to next check
915 # update to next check
917 node = nodes[0]
916 node = nodes[0]
918 mayupdate(repo, node, show_stats=False)
917 mayupdate(repo, node, show_stats=False)
919 finally:
918 finally:
920 state['current'] = [node]
919 state['current'] = [node]
921 hbisect.save_state(repo, state)
920 hbisect.save_state(repo, state)
922 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
921 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
923 return
922 return
924
923
925 hbisect.checkstate(state)
924 hbisect.checkstate(state)
926
925
927 # actually bisect
926 # actually bisect
928 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
927 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
929 if extend:
928 if extend:
930 if not changesets:
929 if not changesets:
931 extendnode = hbisect.extendrange(repo, state, nodes, good)
930 extendnode = hbisect.extendrange(repo, state, nodes, good)
932 if extendnode is not None:
931 if extendnode is not None:
933 ui.write(_("Extending search to changeset %d:%s\n")
932 ui.write(_("Extending search to changeset %d:%s\n")
934 % (extendnode.rev(), extendnode))
933 % (extendnode.rev(), extendnode))
935 state['current'] = [extendnode.node()]
934 state['current'] = [extendnode.node()]
936 hbisect.save_state(repo, state)
935 hbisect.save_state(repo, state)
937 return mayupdate(repo, extendnode.node())
936 return mayupdate(repo, extendnode.node())
938 raise error.Abort(_("nothing to extend"))
937 raise error.Abort(_("nothing to extend"))
939
938
940 if changesets == 0:
939 if changesets == 0:
941 hbisect.printresult(ui, repo, state, displayer, nodes, good)
940 hbisect.printresult(ui, repo, state, displayer, nodes, good)
942 else:
941 else:
943 assert len(nodes) == 1 # only a single node can be tested next
942 assert len(nodes) == 1 # only a single node can be tested next
944 node = nodes[0]
943 node = nodes[0]
945 # compute the approximate number of remaining tests
944 # compute the approximate number of remaining tests
946 tests, size = 0, 2
945 tests, size = 0, 2
947 while size <= changesets:
946 while size <= changesets:
948 tests, size = tests + 1, size * 2
947 tests, size = tests + 1, size * 2
949 rev = repo.changelog.rev(node)
948 rev = repo.changelog.rev(node)
950 ui.write(_("Testing changeset %d:%s "
949 ui.write(_("Testing changeset %d:%s "
951 "(%d changesets remaining, ~%d tests)\n")
950 "(%d changesets remaining, ~%d tests)\n")
952 % (rev, short(node), changesets, tests))
951 % (rev, short(node), changesets, tests))
953 state['current'] = [node]
952 state['current'] = [node]
954 hbisect.save_state(repo, state)
953 hbisect.save_state(repo, state)
955 return mayupdate(repo, node)
954 return mayupdate(repo, node)
956
955
957 @command('bookmarks|bookmark',
956 @command('bookmarks|bookmark',
958 [('f', 'force', False, _('force')),
957 [('f', 'force', False, _('force')),
959 ('r', 'rev', '', _('revision for bookmark action'), _('REV')),
958 ('r', 'rev', '', _('revision for bookmark action'), _('REV')),
960 ('d', 'delete', False, _('delete a given bookmark')),
959 ('d', 'delete', False, _('delete a given bookmark')),
961 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
960 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
962 ('i', 'inactive', False, _('mark a bookmark inactive')),
961 ('i', 'inactive', False, _('mark a bookmark inactive')),
963 ] + formatteropts,
962 ] + formatteropts,
964 _('hg bookmarks [OPTIONS]... [NAME]...'))
963 _('hg bookmarks [OPTIONS]... [NAME]...'))
965 def bookmark(ui, repo, *names, **opts):
964 def bookmark(ui, repo, *names, **opts):
966 '''create a new bookmark or list existing bookmarks
965 '''create a new bookmark or list existing bookmarks
967
966
968 Bookmarks are labels on changesets to help track lines of development.
967 Bookmarks are labels on changesets to help track lines of development.
969 Bookmarks are unversioned and can be moved, renamed and deleted.
968 Bookmarks are unversioned and can be moved, renamed and deleted.
970 Deleting or moving a bookmark has no effect on the associated changesets.
969 Deleting or moving a bookmark has no effect on the associated changesets.
971
970
972 Creating or updating to a bookmark causes it to be marked as 'active'.
971 Creating or updating to a bookmark causes it to be marked as 'active'.
973 The active bookmark is indicated with a '*'.
972 The active bookmark is indicated with a '*'.
974 When a commit is made, the active bookmark will advance to the new commit.
973 When a commit is made, the active bookmark will advance to the new commit.
975 A plain :hg:`update` will also advance an active bookmark, if possible.
974 A plain :hg:`update` will also advance an active bookmark, if possible.
976 Updating away from a bookmark will cause it to be deactivated.
975 Updating away from a bookmark will cause it to be deactivated.
977
976
978 Bookmarks can be pushed and pulled between repositories (see
977 Bookmarks can be pushed and pulled between repositories (see
979 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
978 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
980 diverged, a new 'divergent bookmark' of the form 'name@path' will
979 diverged, a new 'divergent bookmark' of the form 'name@path' will
981 be created. Using :hg:`merge` will resolve the divergence.
980 be created. Using :hg:`merge` will resolve the divergence.
982
981
983 A bookmark named '@' has the special property that :hg:`clone` will
982 A bookmark named '@' has the special property that :hg:`clone` will
984 check it out by default if it exists.
983 check it out by default if it exists.
985
984
986 .. container:: verbose
985 .. container:: verbose
987
986
988 Examples:
987 Examples:
989
988
990 - create an active bookmark for a new line of development::
989 - create an active bookmark for a new line of development::
991
990
992 hg book new-feature
991 hg book new-feature
993
992
994 - create an inactive bookmark as a place marker::
993 - create an inactive bookmark as a place marker::
995
994
996 hg book -i reviewed
995 hg book -i reviewed
997
996
998 - create an inactive bookmark on another changeset::
997 - create an inactive bookmark on another changeset::
999
998
1000 hg book -r .^ tested
999 hg book -r .^ tested
1001
1000
1002 - rename bookmark turkey to dinner::
1001 - rename bookmark turkey to dinner::
1003
1002
1004 hg book -m turkey dinner
1003 hg book -m turkey dinner
1005
1004
1006 - move the '@' bookmark from another branch::
1005 - move the '@' bookmark from another branch::
1007
1006
1008 hg book -f @
1007 hg book -f @
1009 '''
1008 '''
1010 force = opts.get('force')
1009 force = opts.get('force')
1011 rev = opts.get('rev')
1010 rev = opts.get('rev')
1012 delete = opts.get('delete')
1011 delete = opts.get('delete')
1013 rename = opts.get('rename')
1012 rename = opts.get('rename')
1014 inactive = opts.get('inactive')
1013 inactive = opts.get('inactive')
1015
1014
1016 def checkformat(mark):
1015 def checkformat(mark):
1017 mark = mark.strip()
1016 mark = mark.strip()
1018 if not mark:
1017 if not mark:
1019 raise error.Abort(_("bookmark names cannot consist entirely of "
1018 raise error.Abort(_("bookmark names cannot consist entirely of "
1020 "whitespace"))
1019 "whitespace"))
1021 scmutil.checknewlabel(repo, mark, 'bookmark')
1020 scmutil.checknewlabel(repo, mark, 'bookmark')
1022 return mark
1021 return mark
1023
1022
1024 def checkconflict(repo, mark, cur, force=False, target=None):
1023 def checkconflict(repo, mark, cur, force=False, target=None):
1025 if mark in marks and not force:
1024 if mark in marks and not force:
1026 if target:
1025 if target:
1027 if marks[mark] == target and target == cur:
1026 if marks[mark] == target and target == cur:
1028 # re-activating a bookmark
1027 # re-activating a bookmark
1029 return
1028 return
1030 anc = repo.changelog.ancestors([repo[target].rev()])
1029 anc = repo.changelog.ancestors([repo[target].rev()])
1031 bmctx = repo[marks[mark]]
1030 bmctx = repo[marks[mark]]
1032 divs = [repo[b].node() for b in marks
1031 divs = [repo[b].node() for b in marks
1033 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
1032 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
1034
1033
1035 # allow resolving a single divergent bookmark even if moving
1034 # allow resolving a single divergent bookmark even if moving
1036 # the bookmark across branches when a revision is specified
1035 # the bookmark across branches when a revision is specified
1037 # that contains a divergent bookmark
1036 # that contains a divergent bookmark
1038 if bmctx.rev() not in anc and target in divs:
1037 if bmctx.rev() not in anc and target in divs:
1039 bookmarks.deletedivergent(repo, [target], mark)
1038 bookmarks.deletedivergent(repo, [target], mark)
1040 return
1039 return
1041
1040
1042 deletefrom = [b for b in divs
1041 deletefrom = [b for b in divs
1043 if repo[b].rev() in anc or b == target]
1042 if repo[b].rev() in anc or b == target]
1044 bookmarks.deletedivergent(repo, deletefrom, mark)
1043 bookmarks.deletedivergent(repo, deletefrom, mark)
1045 if bookmarks.validdest(repo, bmctx, repo[target]):
1044 if bookmarks.validdest(repo, bmctx, repo[target]):
1046 ui.status(_("moving bookmark '%s' forward from %s\n") %
1045 ui.status(_("moving bookmark '%s' forward from %s\n") %
1047 (mark, short(bmctx.node())))
1046 (mark, short(bmctx.node())))
1048 return
1047 return
1049 raise error.Abort(_("bookmark '%s' already exists "
1048 raise error.Abort(_("bookmark '%s' already exists "
1050 "(use -f to force)") % mark)
1049 "(use -f to force)") % mark)
1051 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
1050 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
1052 and not force):
1051 and not force):
1053 raise error.Abort(
1052 raise error.Abort(
1054 _("a bookmark cannot have the name of an existing branch"))
1053 _("a bookmark cannot have the name of an existing branch"))
1055
1054
1056 if delete and rename:
1055 if delete and rename:
1057 raise error.Abort(_("--delete and --rename are incompatible"))
1056 raise error.Abort(_("--delete and --rename are incompatible"))
1058 if delete and rev:
1057 if delete and rev:
1059 raise error.Abort(_("--rev is incompatible with --delete"))
1058 raise error.Abort(_("--rev is incompatible with --delete"))
1060 if rename and rev:
1059 if rename and rev:
1061 raise error.Abort(_("--rev is incompatible with --rename"))
1060 raise error.Abort(_("--rev is incompatible with --rename"))
1062 if not names and (delete or rev):
1061 if not names and (delete or rev):
1063 raise error.Abort(_("bookmark name required"))
1062 raise error.Abort(_("bookmark name required"))
1064
1063
1065 if delete or rename or names or inactive:
1064 if delete or rename or names or inactive:
1066 wlock = lock = tr = None
1065 wlock = lock = tr = None
1067 try:
1066 try:
1068 wlock = repo.wlock()
1067 wlock = repo.wlock()
1069 lock = repo.lock()
1068 lock = repo.lock()
1070 cur = repo.changectx('.').node()
1069 cur = repo.changectx('.').node()
1071 marks = repo._bookmarks
1070 marks = repo._bookmarks
1072 if delete:
1071 if delete:
1073 tr = repo.transaction('bookmark')
1072 tr = repo.transaction('bookmark')
1074 for mark in names:
1073 for mark in names:
1075 if mark not in marks:
1074 if mark not in marks:
1076 raise error.Abort(_("bookmark '%s' does not exist") %
1075 raise error.Abort(_("bookmark '%s' does not exist") %
1077 mark)
1076 mark)
1078 if mark == repo._activebookmark:
1077 if mark == repo._activebookmark:
1079 bookmarks.deactivate(repo)
1078 bookmarks.deactivate(repo)
1080 del marks[mark]
1079 del marks[mark]
1081
1080
1082 elif rename:
1081 elif rename:
1083 tr = repo.transaction('bookmark')
1082 tr = repo.transaction('bookmark')
1084 if not names:
1083 if not names:
1085 raise error.Abort(_("new bookmark name required"))
1084 raise error.Abort(_("new bookmark name required"))
1086 elif len(names) > 1:
1085 elif len(names) > 1:
1087 raise error.Abort(_("only one new bookmark name allowed"))
1086 raise error.Abort(_("only one new bookmark name allowed"))
1088 mark = checkformat(names[0])
1087 mark = checkformat(names[0])
1089 if rename not in marks:
1088 if rename not in marks:
1090 raise error.Abort(_("bookmark '%s' does not exist")
1089 raise error.Abort(_("bookmark '%s' does not exist")
1091 % rename)
1090 % rename)
1092 checkconflict(repo, mark, cur, force)
1091 checkconflict(repo, mark, cur, force)
1093 marks[mark] = marks[rename]
1092 marks[mark] = marks[rename]
1094 if repo._activebookmark == rename and not inactive:
1093 if repo._activebookmark == rename and not inactive:
1095 bookmarks.activate(repo, mark)
1094 bookmarks.activate(repo, mark)
1096 del marks[rename]
1095 del marks[rename]
1097 elif names:
1096 elif names:
1098 tr = repo.transaction('bookmark')
1097 tr = repo.transaction('bookmark')
1099 newact = None
1098 newact = None
1100 for mark in names:
1099 for mark in names:
1101 mark = checkformat(mark)
1100 mark = checkformat(mark)
1102 if newact is None:
1101 if newact is None:
1103 newact = mark
1102 newact = mark
1104 if inactive and mark == repo._activebookmark:
1103 if inactive and mark == repo._activebookmark:
1105 bookmarks.deactivate(repo)
1104 bookmarks.deactivate(repo)
1106 return
1105 return
1107 tgt = cur
1106 tgt = cur
1108 if rev:
1107 if rev:
1109 tgt = scmutil.revsingle(repo, rev).node()
1108 tgt = scmutil.revsingle(repo, rev).node()
1110 checkconflict(repo, mark, cur, force, tgt)
1109 checkconflict(repo, mark, cur, force, tgt)
1111 marks[mark] = tgt
1110 marks[mark] = tgt
1112 if not inactive and cur == marks[newact] and not rev:
1111 if not inactive and cur == marks[newact] and not rev:
1113 bookmarks.activate(repo, newact)
1112 bookmarks.activate(repo, newact)
1114 elif cur != tgt and newact == repo._activebookmark:
1113 elif cur != tgt and newact == repo._activebookmark:
1115 bookmarks.deactivate(repo)
1114 bookmarks.deactivate(repo)
1116 elif inactive:
1115 elif inactive:
1117 if len(marks) == 0:
1116 if len(marks) == 0:
1118 ui.status(_("no bookmarks set\n"))
1117 ui.status(_("no bookmarks set\n"))
1119 elif not repo._activebookmark:
1118 elif not repo._activebookmark:
1120 ui.status(_("no active bookmark\n"))
1119 ui.status(_("no active bookmark\n"))
1121 else:
1120 else:
1122 bookmarks.deactivate(repo)
1121 bookmarks.deactivate(repo)
1123 if tr is not None:
1122 if tr is not None:
1124 marks.recordchange(tr)
1123 marks.recordchange(tr)
1125 tr.close()
1124 tr.close()
1126 finally:
1125 finally:
1127 lockmod.release(tr, lock, wlock)
1126 lockmod.release(tr, lock, wlock)
1128 else: # show bookmarks
1127 else: # show bookmarks
1129 fm = ui.formatter('bookmarks', opts)
1128 fm = ui.formatter('bookmarks', opts)
1130 hexfn = fm.hexfunc
1129 hexfn = fm.hexfunc
1131 marks = repo._bookmarks
1130 marks = repo._bookmarks
1132 if len(marks) == 0 and fm.isplain():
1131 if len(marks) == 0 and fm.isplain():
1133 ui.status(_("no bookmarks set\n"))
1132 ui.status(_("no bookmarks set\n"))
1134 for bmark, n in sorted(marks.iteritems()):
1133 for bmark, n in sorted(marks.iteritems()):
1135 active = repo._activebookmark
1134 active = repo._activebookmark
1136 if bmark == active:
1135 if bmark == active:
1137 prefix, label = '*', activebookmarklabel
1136 prefix, label = '*', activebookmarklabel
1138 else:
1137 else:
1139 prefix, label = ' ', ''
1138 prefix, label = ' ', ''
1140
1139
1141 fm.startitem()
1140 fm.startitem()
1142 if not ui.quiet:
1141 if not ui.quiet:
1143 fm.plain(' %s ' % prefix, label=label)
1142 fm.plain(' %s ' % prefix, label=label)
1144 fm.write('bookmark', '%s', bmark, label=label)
1143 fm.write('bookmark', '%s', bmark, label=label)
1145 pad = " " * (25 - encoding.colwidth(bmark))
1144 pad = " " * (25 - encoding.colwidth(bmark))
1146 fm.condwrite(not ui.quiet, 'rev node', pad + ' %d:%s',
1145 fm.condwrite(not ui.quiet, 'rev node', pad + ' %d:%s',
1147 repo.changelog.rev(n), hexfn(n), label=label)
1146 repo.changelog.rev(n), hexfn(n), label=label)
1148 fm.data(active=(bmark == active))
1147 fm.data(active=(bmark == active))
1149 fm.plain('\n')
1148 fm.plain('\n')
1150 fm.end()
1149 fm.end()
1151
1150
1152 @command('branch',
1151 @command('branch',
1153 [('f', 'force', None,
1152 [('f', 'force', None,
1154 _('set branch name even if it shadows an existing branch')),
1153 _('set branch name even if it shadows an existing branch')),
1155 ('C', 'clean', None, _('reset branch name to parent branch name'))],
1154 ('C', 'clean', None, _('reset branch name to parent branch name'))],
1156 _('[-fC] [NAME]'))
1155 _('[-fC] [NAME]'))
1157 def branch(ui, repo, label=None, **opts):
1156 def branch(ui, repo, label=None, **opts):
1158 """set or show the current branch name
1157 """set or show the current branch name
1159
1158
1160 .. note::
1159 .. note::
1161
1160
1162 Branch names are permanent and global. Use :hg:`bookmark` to create a
1161 Branch names are permanent and global. Use :hg:`bookmark` to create a
1163 light-weight bookmark instead. See :hg:`help glossary` for more
1162 light-weight bookmark instead. See :hg:`help glossary` for more
1164 information about named branches and bookmarks.
1163 information about named branches and bookmarks.
1165
1164
1166 With no argument, show the current branch name. With one argument,
1165 With no argument, show the current branch name. With one argument,
1167 set the working directory branch name (the branch will not exist
1166 set the working directory branch name (the branch will not exist
1168 in the repository until the next commit). Standard practice
1167 in the repository until the next commit). Standard practice
1169 recommends that primary development take place on the 'default'
1168 recommends that primary development take place on the 'default'
1170 branch.
1169 branch.
1171
1170
1172 Unless -f/--force is specified, branch will not let you set a
1171 Unless -f/--force is specified, branch will not let you set a
1173 branch name that already exists.
1172 branch name that already exists.
1174
1173
1175 Use -C/--clean to reset the working directory branch to that of
1174 Use -C/--clean to reset the working directory branch to that of
1176 the parent of the working directory, negating a previous branch
1175 the parent of the working directory, negating a previous branch
1177 change.
1176 change.
1178
1177
1179 Use the command :hg:`update` to switch to an existing branch. Use
1178 Use the command :hg:`update` to switch to an existing branch. Use
1180 :hg:`commit --close-branch` to mark this branch head as closed.
1179 :hg:`commit --close-branch` to mark this branch head as closed.
1181 When all heads of a branch are closed, the branch will be
1180 When all heads of a branch are closed, the branch will be
1182 considered closed.
1181 considered closed.
1183
1182
1184 Returns 0 on success.
1183 Returns 0 on success.
1185 """
1184 """
1186 if label:
1185 if label:
1187 label = label.strip()
1186 label = label.strip()
1188
1187
1189 if not opts.get('clean') and not label:
1188 if not opts.get('clean') and not label:
1190 ui.write("%s\n" % repo.dirstate.branch())
1189 ui.write("%s\n" % repo.dirstate.branch())
1191 return
1190 return
1192
1191
1193 with repo.wlock():
1192 with repo.wlock():
1194 if opts.get('clean'):
1193 if opts.get('clean'):
1195 label = repo[None].p1().branch()
1194 label = repo[None].p1().branch()
1196 repo.dirstate.setbranch(label)
1195 repo.dirstate.setbranch(label)
1197 ui.status(_('reset working directory to branch %s\n') % label)
1196 ui.status(_('reset working directory to branch %s\n') % label)
1198 elif label:
1197 elif label:
1199 if not opts.get('force') and label in repo.branchmap():
1198 if not opts.get('force') and label in repo.branchmap():
1200 if label not in [p.branch() for p in repo[None].parents()]:
1199 if label not in [p.branch() for p in repo[None].parents()]:
1201 raise error.Abort(_('a branch of the same name already'
1200 raise error.Abort(_('a branch of the same name already'
1202 ' exists'),
1201 ' exists'),
1203 # i18n: "it" refers to an existing branch
1202 # i18n: "it" refers to an existing branch
1204 hint=_("use 'hg update' to switch to it"))
1203 hint=_("use 'hg update' to switch to it"))
1205 scmutil.checknewlabel(repo, label, 'branch')
1204 scmutil.checknewlabel(repo, label, 'branch')
1206 repo.dirstate.setbranch(label)
1205 repo.dirstate.setbranch(label)
1207 ui.status(_('marked working directory as branch %s\n') % label)
1206 ui.status(_('marked working directory as branch %s\n') % label)
1208
1207
1209 # find any open named branches aside from default
1208 # find any open named branches aside from default
1210 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1209 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1211 if n != "default" and not c]
1210 if n != "default" and not c]
1212 if not others:
1211 if not others:
1213 ui.status(_('(branches are permanent and global, '
1212 ui.status(_('(branches are permanent and global, '
1214 'did you want a bookmark?)\n'))
1213 'did you want a bookmark?)\n'))
1215
1214
1216 @command('branches',
1215 @command('branches',
1217 [('a', 'active', False,
1216 [('a', 'active', False,
1218 _('show only branches that have unmerged heads (DEPRECATED)')),
1217 _('show only branches that have unmerged heads (DEPRECATED)')),
1219 ('c', 'closed', False, _('show normal and closed branches')),
1218 ('c', 'closed', False, _('show normal and closed branches')),
1220 ] + formatteropts,
1219 ] + formatteropts,
1221 _('[-c]'))
1220 _('[-c]'))
1222 def branches(ui, repo, active=False, closed=False, **opts):
1221 def branches(ui, repo, active=False, closed=False, **opts):
1223 """list repository named branches
1222 """list repository named branches
1224
1223
1225 List the repository's named branches, indicating which ones are
1224 List the repository's named branches, indicating which ones are
1226 inactive. If -c/--closed is specified, also list branches which have
1225 inactive. If -c/--closed is specified, also list branches which have
1227 been marked closed (see :hg:`commit --close-branch`).
1226 been marked closed (see :hg:`commit --close-branch`).
1228
1227
1229 Use the command :hg:`update` to switch to an existing branch.
1228 Use the command :hg:`update` to switch to an existing branch.
1230
1229
1231 Returns 0.
1230 Returns 0.
1232 """
1231 """
1233
1232
1234 fm = ui.formatter('branches', opts)
1233 fm = ui.formatter('branches', opts)
1235 hexfunc = fm.hexfunc
1234 hexfunc = fm.hexfunc
1236
1235
1237 allheads = set(repo.heads())
1236 allheads = set(repo.heads())
1238 branches = []
1237 branches = []
1239 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1238 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1240 isactive = not isclosed and bool(set(heads) & allheads)
1239 isactive = not isclosed and bool(set(heads) & allheads)
1241 branches.append((tag, repo[tip], isactive, not isclosed))
1240 branches.append((tag, repo[tip], isactive, not isclosed))
1242 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1241 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1243 reverse=True)
1242 reverse=True)
1244
1243
1245 for tag, ctx, isactive, isopen in branches:
1244 for tag, ctx, isactive, isopen in branches:
1246 if active and not isactive:
1245 if active and not isactive:
1247 continue
1246 continue
1248 if isactive:
1247 if isactive:
1249 label = 'branches.active'
1248 label = 'branches.active'
1250 notice = ''
1249 notice = ''
1251 elif not isopen:
1250 elif not isopen:
1252 if not closed:
1251 if not closed:
1253 continue
1252 continue
1254 label = 'branches.closed'
1253 label = 'branches.closed'
1255 notice = _(' (closed)')
1254 notice = _(' (closed)')
1256 else:
1255 else:
1257 label = 'branches.inactive'
1256 label = 'branches.inactive'
1258 notice = _(' (inactive)')
1257 notice = _(' (inactive)')
1259 current = (tag == repo.dirstate.branch())
1258 current = (tag == repo.dirstate.branch())
1260 if current:
1259 if current:
1261 label = 'branches.current'
1260 label = 'branches.current'
1262
1261
1263 fm.startitem()
1262 fm.startitem()
1264 fm.write('branch', '%s', tag, label=label)
1263 fm.write('branch', '%s', tag, label=label)
1265 rev = ctx.rev()
1264 rev = ctx.rev()
1266 padsize = max(31 - len(str(rev)) - encoding.colwidth(tag), 0)
1265 padsize = max(31 - len(str(rev)) - encoding.colwidth(tag), 0)
1267 fmt = ' ' * padsize + ' %d:%s'
1266 fmt = ' ' * padsize + ' %d:%s'
1268 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1267 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1269 label='log.changeset changeset.%s' % ctx.phasestr())
1268 label='log.changeset changeset.%s' % ctx.phasestr())
1270 fm.data(active=isactive, closed=not isopen, current=current)
1269 fm.data(active=isactive, closed=not isopen, current=current)
1271 if not ui.quiet:
1270 if not ui.quiet:
1272 fm.plain(notice)
1271 fm.plain(notice)
1273 fm.plain('\n')
1272 fm.plain('\n')
1274 fm.end()
1273 fm.end()
1275
1274
1276 @command('bundle',
1275 @command('bundle',
1277 [('f', 'force', None, _('run even when the destination is unrelated')),
1276 [('f', 'force', None, _('run even when the destination is unrelated')),
1278 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1277 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1279 _('REV')),
1278 _('REV')),
1280 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1279 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1281 _('BRANCH')),
1280 _('BRANCH')),
1282 ('', 'base', [],
1281 ('', 'base', [],
1283 _('a base changeset assumed to be available at the destination'),
1282 _('a base changeset assumed to be available at the destination'),
1284 _('REV')),
1283 _('REV')),
1285 ('a', 'all', None, _('bundle all changesets in the repository')),
1284 ('a', 'all', None, _('bundle all changesets in the repository')),
1286 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1285 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1287 ] + remoteopts,
1286 ] + remoteopts,
1288 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1287 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1289 def bundle(ui, repo, fname, dest=None, **opts):
1288 def bundle(ui, repo, fname, dest=None, **opts):
1290 """create a changegroup file
1289 """create a changegroup file
1291
1290
1292 Generate a changegroup file collecting changesets to be added
1291 Generate a changegroup file collecting changesets to be added
1293 to a repository.
1292 to a repository.
1294
1293
1295 To create a bundle containing all changesets, use -a/--all
1294 To create a bundle containing all changesets, use -a/--all
1296 (or --base null). Otherwise, hg assumes the destination will have
1295 (or --base null). Otherwise, hg assumes the destination will have
1297 all the nodes you specify with --base parameters. Otherwise, hg
1296 all the nodes you specify with --base parameters. Otherwise, hg
1298 will assume the repository has all the nodes in destination, or
1297 will assume the repository has all the nodes in destination, or
1299 default-push/default if no destination is specified.
1298 default-push/default if no destination is specified.
1300
1299
1301 You can change bundle format with the -t/--type option. You can
1300 You can change bundle format with the -t/--type option. You can
1302 specify a compression, a bundle version or both using a dash
1301 specify a compression, a bundle version or both using a dash
1303 (comp-version). The available compression methods are: none, bzip2,
1302 (comp-version). The available compression methods are: none, bzip2,
1304 and gzip (by default, bundles are compressed using bzip2). The
1303 and gzip (by default, bundles are compressed using bzip2). The
1305 available formats are: v1, v2 (default to most suitable).
1304 available formats are: v1, v2 (default to most suitable).
1306
1305
1307 The bundle file can then be transferred using conventional means
1306 The bundle file can then be transferred using conventional means
1308 and applied to another repository with the unbundle or pull
1307 and applied to another repository with the unbundle or pull
1309 command. This is useful when direct push and pull are not
1308 command. This is useful when direct push and pull are not
1310 available or when exporting an entire repository is undesirable.
1309 available or when exporting an entire repository is undesirable.
1311
1310
1312 Applying bundles preserves all changeset contents including
1311 Applying bundles preserves all changeset contents including
1313 permissions, copy/rename information, and revision history.
1312 permissions, copy/rename information, and revision history.
1314
1313
1315 Returns 0 on success, 1 if no changes found.
1314 Returns 0 on success, 1 if no changes found.
1316 """
1315 """
1317 revs = None
1316 revs = None
1318 if 'rev' in opts:
1317 if 'rev' in opts:
1319 revstrings = opts['rev']
1318 revstrings = opts['rev']
1320 revs = scmutil.revrange(repo, revstrings)
1319 revs = scmutil.revrange(repo, revstrings)
1321 if revstrings and not revs:
1320 if revstrings and not revs:
1322 raise error.Abort(_('no commits to bundle'))
1321 raise error.Abort(_('no commits to bundle'))
1323
1322
1324 bundletype = opts.get('type', 'bzip2').lower()
1323 bundletype = opts.get('type', 'bzip2').lower()
1325 try:
1324 try:
1326 bcompression, cgversion, params = exchange.parsebundlespec(
1325 bcompression, cgversion, params = exchange.parsebundlespec(
1327 repo, bundletype, strict=False)
1326 repo, bundletype, strict=False)
1328 except error.UnsupportedBundleSpecification as e:
1327 except error.UnsupportedBundleSpecification as e:
1329 raise error.Abort(str(e),
1328 raise error.Abort(str(e),
1330 hint=_("see 'hg help bundle' for supported "
1329 hint=_("see 'hg help bundle' for supported "
1331 "values for --type"))
1330 "values for --type"))
1332
1331
1333 # Packed bundles are a pseudo bundle format for now.
1332 # Packed bundles are a pseudo bundle format for now.
1334 if cgversion == 's1':
1333 if cgversion == 's1':
1335 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1334 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1336 hint=_("use 'hg debugcreatestreamclonebundle'"))
1335 hint=_("use 'hg debugcreatestreamclonebundle'"))
1337
1336
1338 if opts.get('all'):
1337 if opts.get('all'):
1339 if dest:
1338 if dest:
1340 raise error.Abort(_("--all is incompatible with specifying "
1339 raise error.Abort(_("--all is incompatible with specifying "
1341 "a destination"))
1340 "a destination"))
1342 if opts.get('base'):
1341 if opts.get('base'):
1343 ui.warn(_("ignoring --base because --all was specified\n"))
1342 ui.warn(_("ignoring --base because --all was specified\n"))
1344 base = ['null']
1343 base = ['null']
1345 else:
1344 else:
1346 base = scmutil.revrange(repo, opts.get('base'))
1345 base = scmutil.revrange(repo, opts.get('base'))
1347 # TODO: get desired bundlecaps from command line.
1346 # TODO: get desired bundlecaps from command line.
1348 bundlecaps = None
1347 bundlecaps = None
1349 if cgversion not in changegroup.supportedoutgoingversions(repo):
1348 if cgversion not in changegroup.supportedoutgoingversions(repo):
1350 raise error.Abort(_("repository does not support bundle version %s") %
1349 raise error.Abort(_("repository does not support bundle version %s") %
1351 cgversion)
1350 cgversion)
1352
1351
1353 if base:
1352 if base:
1354 if dest:
1353 if dest:
1355 raise error.Abort(_("--base is incompatible with specifying "
1354 raise error.Abort(_("--base is incompatible with specifying "
1356 "a destination"))
1355 "a destination"))
1357 common = [repo.lookup(rev) for rev in base]
1356 common = [repo.lookup(rev) for rev in base]
1358 heads = revs and map(repo.lookup, revs) or None
1357 heads = revs and map(repo.lookup, revs) or None
1359 outgoing = discovery.outgoing(repo, common, heads)
1358 outgoing = discovery.outgoing(repo, common, heads)
1360 cg = changegroup.getchangegroup(repo, 'bundle', outgoing,
1359 cg = changegroup.getchangegroup(repo, 'bundle', outgoing,
1361 bundlecaps=bundlecaps,
1360 bundlecaps=bundlecaps,
1362 version=cgversion)
1361 version=cgversion)
1363 outgoing = None
1362 outgoing = None
1364 else:
1363 else:
1365 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1364 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1366 dest, branches = hg.parseurl(dest, opts.get('branch'))
1365 dest, branches = hg.parseurl(dest, opts.get('branch'))
1367 other = hg.peer(repo, opts, dest)
1366 other = hg.peer(repo, opts, dest)
1368 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1367 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1369 heads = revs and map(repo.lookup, revs) or revs
1368 heads = revs and map(repo.lookup, revs) or revs
1370 outgoing = discovery.findcommonoutgoing(repo, other,
1369 outgoing = discovery.findcommonoutgoing(repo, other,
1371 onlyheads=heads,
1370 onlyheads=heads,
1372 force=opts.get('force'),
1371 force=opts.get('force'),
1373 portable=True)
1372 portable=True)
1374 cg = changegroup.getlocalchangegroup(repo, 'bundle', outgoing,
1373 cg = changegroup.getlocalchangegroup(repo, 'bundle', outgoing,
1375 bundlecaps, version=cgversion)
1374 bundlecaps, version=cgversion)
1376 if not cg:
1375 if not cg:
1377 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1376 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1378 return 1
1377 return 1
1379
1378
1380 if cgversion == '01': #bundle1
1379 if cgversion == '01': #bundle1
1381 if bcompression is None:
1380 if bcompression is None:
1382 bcompression = 'UN'
1381 bcompression = 'UN'
1383 bversion = 'HG10' + bcompression
1382 bversion = 'HG10' + bcompression
1384 bcompression = None
1383 bcompression = None
1385 else:
1384 else:
1386 assert cgversion == '02'
1385 assert cgversion == '02'
1387 bversion = 'HG20'
1386 bversion = 'HG20'
1388
1387
1389 bundle2.writebundle(ui, cg, fname, bversion, compression=bcompression)
1388 bundle2.writebundle(ui, cg, fname, bversion, compression=bcompression)
1390
1389
1391 @command('cat',
1390 @command('cat',
1392 [('o', 'output', '',
1391 [('o', 'output', '',
1393 _('print output to file with formatted name'), _('FORMAT')),
1392 _('print output to file with formatted name'), _('FORMAT')),
1394 ('r', 'rev', '', _('print the given revision'), _('REV')),
1393 ('r', 'rev', '', _('print the given revision'), _('REV')),
1395 ('', 'decode', None, _('apply any matching decode filter')),
1394 ('', 'decode', None, _('apply any matching decode filter')),
1396 ] + walkopts,
1395 ] + walkopts,
1397 _('[OPTION]... FILE...'),
1396 _('[OPTION]... FILE...'),
1398 inferrepo=True)
1397 inferrepo=True)
1399 def cat(ui, repo, file1, *pats, **opts):
1398 def cat(ui, repo, file1, *pats, **opts):
1400 """output the current or given revision of files
1399 """output the current or given revision of files
1401
1400
1402 Print the specified files as they were at the given revision. If
1401 Print the specified files as they were at the given revision. If
1403 no revision is given, the parent of the working directory is used.
1402 no revision is given, the parent of the working directory is used.
1404
1403
1405 Output may be to a file, in which case the name of the file is
1404 Output may be to a file, in which case the name of the file is
1406 given using a format string. The formatting rules as follows:
1405 given using a format string. The formatting rules as follows:
1407
1406
1408 :``%%``: literal "%" character
1407 :``%%``: literal "%" character
1409 :``%s``: basename of file being printed
1408 :``%s``: basename of file being printed
1410 :``%d``: dirname of file being printed, or '.' if in repository root
1409 :``%d``: dirname of file being printed, or '.' if in repository root
1411 :``%p``: root-relative path name of file being printed
1410 :``%p``: root-relative path name of file being printed
1412 :``%H``: changeset hash (40 hexadecimal digits)
1411 :``%H``: changeset hash (40 hexadecimal digits)
1413 :``%R``: changeset revision number
1412 :``%R``: changeset revision number
1414 :``%h``: short-form changeset hash (12 hexadecimal digits)
1413 :``%h``: short-form changeset hash (12 hexadecimal digits)
1415 :``%r``: zero-padded changeset revision number
1414 :``%r``: zero-padded changeset revision number
1416 :``%b``: basename of the exporting repository
1415 :``%b``: basename of the exporting repository
1417
1416
1418 Returns 0 on success.
1417 Returns 0 on success.
1419 """
1418 """
1420 ctx = scmutil.revsingle(repo, opts.get('rev'))
1419 ctx = scmutil.revsingle(repo, opts.get('rev'))
1421 m = scmutil.match(ctx, (file1,) + pats, opts)
1420 m = scmutil.match(ctx, (file1,) + pats, opts)
1422
1421
1423 return cmdutil.cat(ui, repo, ctx, m, '', **opts)
1422 return cmdutil.cat(ui, repo, ctx, m, '', **opts)
1424
1423
1425 @command('^clone',
1424 @command('^clone',
1426 [('U', 'noupdate', None, _('the clone will include an empty working '
1425 [('U', 'noupdate', None, _('the clone will include an empty working '
1427 'directory (only a repository)')),
1426 'directory (only a repository)')),
1428 ('u', 'updaterev', '', _('revision, tag, or branch to check out'),
1427 ('u', 'updaterev', '', _('revision, tag, or branch to check out'),
1429 _('REV')),
1428 _('REV')),
1430 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1429 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1431 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1430 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1432 ('', 'pull', None, _('use pull protocol to copy metadata')),
1431 ('', 'pull', None, _('use pull protocol to copy metadata')),
1433 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1432 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1434 ] + remoteopts,
1433 ] + remoteopts,
1435 _('[OPTION]... SOURCE [DEST]'),
1434 _('[OPTION]... SOURCE [DEST]'),
1436 norepo=True)
1435 norepo=True)
1437 def clone(ui, source, dest=None, **opts):
1436 def clone(ui, source, dest=None, **opts):
1438 """make a copy of an existing repository
1437 """make a copy of an existing repository
1439
1438
1440 Create a copy of an existing repository in a new directory.
1439 Create a copy of an existing repository in a new directory.
1441
1440
1442 If no destination directory name is specified, it defaults to the
1441 If no destination directory name is specified, it defaults to the
1443 basename of the source.
1442 basename of the source.
1444
1443
1445 The location of the source is added to the new repository's
1444 The location of the source is added to the new repository's
1446 ``.hg/hgrc`` file, as the default to be used for future pulls.
1445 ``.hg/hgrc`` file, as the default to be used for future pulls.
1447
1446
1448 Only local paths and ``ssh://`` URLs are supported as
1447 Only local paths and ``ssh://`` URLs are supported as
1449 destinations. For ``ssh://`` destinations, no working directory or
1448 destinations. For ``ssh://`` destinations, no working directory or
1450 ``.hg/hgrc`` will be created on the remote side.
1449 ``.hg/hgrc`` will be created on the remote side.
1451
1450
1452 If the source repository has a bookmark called '@' set, that
1451 If the source repository has a bookmark called '@' set, that
1453 revision will be checked out in the new repository by default.
1452 revision will be checked out in the new repository by default.
1454
1453
1455 To check out a particular version, use -u/--update, or
1454 To check out a particular version, use -u/--update, or
1456 -U/--noupdate to create a clone with no working directory.
1455 -U/--noupdate to create a clone with no working directory.
1457
1456
1458 To pull only a subset of changesets, specify one or more revisions
1457 To pull only a subset of changesets, specify one or more revisions
1459 identifiers with -r/--rev or branches with -b/--branch. The
1458 identifiers with -r/--rev or branches with -b/--branch. The
1460 resulting clone will contain only the specified changesets and
1459 resulting clone will contain only the specified changesets and
1461 their ancestors. These options (or 'clone src#rev dest') imply
1460 their ancestors. These options (or 'clone src#rev dest') imply
1462 --pull, even for local source repositories.
1461 --pull, even for local source repositories.
1463
1462
1464 .. note::
1463 .. note::
1465
1464
1466 Specifying a tag will include the tagged changeset but not the
1465 Specifying a tag will include the tagged changeset but not the
1467 changeset containing the tag.
1466 changeset containing the tag.
1468
1467
1469 .. container:: verbose
1468 .. container:: verbose
1470
1469
1471 For efficiency, hardlinks are used for cloning whenever the
1470 For efficiency, hardlinks are used for cloning whenever the
1472 source and destination are on the same filesystem (note this
1471 source and destination are on the same filesystem (note this
1473 applies only to the repository data, not to the working
1472 applies only to the repository data, not to the working
1474 directory). Some filesystems, such as AFS, implement hardlinking
1473 directory). Some filesystems, such as AFS, implement hardlinking
1475 incorrectly, but do not report errors. In these cases, use the
1474 incorrectly, but do not report errors. In these cases, use the
1476 --pull option to avoid hardlinking.
1475 --pull option to avoid hardlinking.
1477
1476
1478 In some cases, you can clone repositories and the working
1477 In some cases, you can clone repositories and the working
1479 directory using full hardlinks with ::
1478 directory using full hardlinks with ::
1480
1479
1481 $ cp -al REPO REPOCLONE
1480 $ cp -al REPO REPOCLONE
1482
1481
1483 This is the fastest way to clone, but it is not always safe. The
1482 This is the fastest way to clone, but it is not always safe. The
1484 operation is not atomic (making sure REPO is not modified during
1483 operation is not atomic (making sure REPO is not modified during
1485 the operation is up to you) and you have to make sure your
1484 the operation is up to you) and you have to make sure your
1486 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1485 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1487 so). Also, this is not compatible with certain extensions that
1486 so). Also, this is not compatible with certain extensions that
1488 place their metadata under the .hg directory, such as mq.
1487 place their metadata under the .hg directory, such as mq.
1489
1488
1490 Mercurial will update the working directory to the first applicable
1489 Mercurial will update the working directory to the first applicable
1491 revision from this list:
1490 revision from this list:
1492
1491
1493 a) null if -U or the source repository has no changesets
1492 a) null if -U or the source repository has no changesets
1494 b) if -u . and the source repository is local, the first parent of
1493 b) if -u . and the source repository is local, the first parent of
1495 the source repository's working directory
1494 the source repository's working directory
1496 c) the changeset specified with -u (if a branch name, this means the
1495 c) the changeset specified with -u (if a branch name, this means the
1497 latest head of that branch)
1496 latest head of that branch)
1498 d) the changeset specified with -r
1497 d) the changeset specified with -r
1499 e) the tipmost head specified with -b
1498 e) the tipmost head specified with -b
1500 f) the tipmost head specified with the url#branch source syntax
1499 f) the tipmost head specified with the url#branch source syntax
1501 g) the revision marked with the '@' bookmark, if present
1500 g) the revision marked with the '@' bookmark, if present
1502 h) the tipmost head of the default branch
1501 h) the tipmost head of the default branch
1503 i) tip
1502 i) tip
1504
1503
1505 When cloning from servers that support it, Mercurial may fetch
1504 When cloning from servers that support it, Mercurial may fetch
1506 pre-generated data from a server-advertised URL. When this is done,
1505 pre-generated data from a server-advertised URL. When this is done,
1507 hooks operating on incoming changesets and changegroups may fire twice,
1506 hooks operating on incoming changesets and changegroups may fire twice,
1508 once for the bundle fetched from the URL and another for any additional
1507 once for the bundle fetched from the URL and another for any additional
1509 data not fetched from this URL. In addition, if an error occurs, the
1508 data not fetched from this URL. In addition, if an error occurs, the
1510 repository may be rolled back to a partial clone. This behavior may
1509 repository may be rolled back to a partial clone. This behavior may
1511 change in future releases. See :hg:`help -e clonebundles` for more.
1510 change in future releases. See :hg:`help -e clonebundles` for more.
1512
1511
1513 Examples:
1512 Examples:
1514
1513
1515 - clone a remote repository to a new directory named hg/::
1514 - clone a remote repository to a new directory named hg/::
1516
1515
1517 hg clone https://www.mercurial-scm.org/repo/hg/
1516 hg clone https://www.mercurial-scm.org/repo/hg/
1518
1517
1519 - create a lightweight local clone::
1518 - create a lightweight local clone::
1520
1519
1521 hg clone project/ project-feature/
1520 hg clone project/ project-feature/
1522
1521
1523 - clone from an absolute path on an ssh server (note double-slash)::
1522 - clone from an absolute path on an ssh server (note double-slash)::
1524
1523
1525 hg clone ssh://user@server//home/projects/alpha/
1524 hg clone ssh://user@server//home/projects/alpha/
1526
1525
1527 - do a high-speed clone over a LAN while checking out a
1526 - do a high-speed clone over a LAN while checking out a
1528 specified version::
1527 specified version::
1529
1528
1530 hg clone --uncompressed http://server/repo -u 1.5
1529 hg clone --uncompressed http://server/repo -u 1.5
1531
1530
1532 - create a repository without changesets after a particular revision::
1531 - create a repository without changesets after a particular revision::
1533
1532
1534 hg clone -r 04e544 experimental/ good/
1533 hg clone -r 04e544 experimental/ good/
1535
1534
1536 - clone (and track) a particular named branch::
1535 - clone (and track) a particular named branch::
1537
1536
1538 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1537 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1539
1538
1540 See :hg:`help urls` for details on specifying URLs.
1539 See :hg:`help urls` for details on specifying URLs.
1541
1540
1542 Returns 0 on success.
1541 Returns 0 on success.
1543 """
1542 """
1544 if opts.get('noupdate') and opts.get('updaterev'):
1543 if opts.get('noupdate') and opts.get('updaterev'):
1545 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1544 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1546
1545
1547 r = hg.clone(ui, opts, source, dest,
1546 r = hg.clone(ui, opts, source, dest,
1548 pull=opts.get('pull'),
1547 pull=opts.get('pull'),
1549 stream=opts.get('uncompressed'),
1548 stream=opts.get('uncompressed'),
1550 rev=opts.get('rev'),
1549 rev=opts.get('rev'),
1551 update=opts.get('updaterev') or not opts.get('noupdate'),
1550 update=opts.get('updaterev') or not opts.get('noupdate'),
1552 branch=opts.get('branch'),
1551 branch=opts.get('branch'),
1553 shareopts=opts.get('shareopts'))
1552 shareopts=opts.get('shareopts'))
1554
1553
1555 return r is None
1554 return r is None
1556
1555
1557 @command('^commit|ci',
1556 @command('^commit|ci',
1558 [('A', 'addremove', None,
1557 [('A', 'addremove', None,
1559 _('mark new/missing files as added/removed before committing')),
1558 _('mark new/missing files as added/removed before committing')),
1560 ('', 'close-branch', None,
1559 ('', 'close-branch', None,
1561 _('mark a branch head as closed')),
1560 _('mark a branch head as closed')),
1562 ('', 'amend', None, _('amend the parent of the working directory')),
1561 ('', 'amend', None, _('amend the parent of the working directory')),
1563 ('s', 'secret', None, _('use the secret phase for committing')),
1562 ('s', 'secret', None, _('use the secret phase for committing')),
1564 ('e', 'edit', None, _('invoke editor on commit messages')),
1563 ('e', 'edit', None, _('invoke editor on commit messages')),
1565 ('i', 'interactive', None, _('use interactive mode')),
1564 ('i', 'interactive', None, _('use interactive mode')),
1566 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1565 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1567 _('[OPTION]... [FILE]...'),
1566 _('[OPTION]... [FILE]...'),
1568 inferrepo=True)
1567 inferrepo=True)
1569 def commit(ui, repo, *pats, **opts):
1568 def commit(ui, repo, *pats, **opts):
1570 """commit the specified files or all outstanding changes
1569 """commit the specified files or all outstanding changes
1571
1570
1572 Commit changes to the given files into the repository. Unlike a
1571 Commit changes to the given files into the repository. Unlike a
1573 centralized SCM, this operation is a local operation. See
1572 centralized SCM, this operation is a local operation. See
1574 :hg:`push` for a way to actively distribute your changes.
1573 :hg:`push` for a way to actively distribute your changes.
1575
1574
1576 If a list of files is omitted, all changes reported by :hg:`status`
1575 If a list of files is omitted, all changes reported by :hg:`status`
1577 will be committed.
1576 will be committed.
1578
1577
1579 If you are committing the result of a merge, do not provide any
1578 If you are committing the result of a merge, do not provide any
1580 filenames or -I/-X filters.
1579 filenames or -I/-X filters.
1581
1580
1582 If no commit message is specified, Mercurial starts your
1581 If no commit message is specified, Mercurial starts your
1583 configured editor where you can enter a message. In case your
1582 configured editor where you can enter a message. In case your
1584 commit fails, you will find a backup of your message in
1583 commit fails, you will find a backup of your message in
1585 ``.hg/last-message.txt``.
1584 ``.hg/last-message.txt``.
1586
1585
1587 The --close-branch flag can be used to mark the current branch
1586 The --close-branch flag can be used to mark the current branch
1588 head closed. When all heads of a branch are closed, the branch
1587 head closed. When all heads of a branch are closed, the branch
1589 will be considered closed and no longer listed.
1588 will be considered closed and no longer listed.
1590
1589
1591 The --amend flag can be used to amend the parent of the
1590 The --amend flag can be used to amend the parent of the
1592 working directory with a new commit that contains the changes
1591 working directory with a new commit that contains the changes
1593 in the parent in addition to those currently reported by :hg:`status`,
1592 in the parent in addition to those currently reported by :hg:`status`,
1594 if there are any. The old commit is stored in a backup bundle in
1593 if there are any. The old commit is stored in a backup bundle in
1595 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1594 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1596 on how to restore it).
1595 on how to restore it).
1597
1596
1598 Message, user and date are taken from the amended commit unless
1597 Message, user and date are taken from the amended commit unless
1599 specified. When a message isn't specified on the command line,
1598 specified. When a message isn't specified on the command line,
1600 the editor will open with the message of the amended commit.
1599 the editor will open with the message of the amended commit.
1601
1600
1602 It is not possible to amend public changesets (see :hg:`help phases`)
1601 It is not possible to amend public changesets (see :hg:`help phases`)
1603 or changesets that have children.
1602 or changesets that have children.
1604
1603
1605 See :hg:`help dates` for a list of formats valid for -d/--date.
1604 See :hg:`help dates` for a list of formats valid for -d/--date.
1606
1605
1607 Returns 0 on success, 1 if nothing changed.
1606 Returns 0 on success, 1 if nothing changed.
1608
1607
1609 .. container:: verbose
1608 .. container:: verbose
1610
1609
1611 Examples:
1610 Examples:
1612
1611
1613 - commit all files ending in .py::
1612 - commit all files ending in .py::
1614
1613
1615 hg commit --include "set:**.py"
1614 hg commit --include "set:**.py"
1616
1615
1617 - commit all non-binary files::
1616 - commit all non-binary files::
1618
1617
1619 hg commit --exclude "set:binary()"
1618 hg commit --exclude "set:binary()"
1620
1619
1621 - amend the current commit and set the date to now::
1620 - amend the current commit and set the date to now::
1622
1621
1623 hg commit --amend --date now
1622 hg commit --amend --date now
1624 """
1623 """
1625 wlock = lock = None
1624 wlock = lock = None
1626 try:
1625 try:
1627 wlock = repo.wlock()
1626 wlock = repo.wlock()
1628 lock = repo.lock()
1627 lock = repo.lock()
1629 return _docommit(ui, repo, *pats, **opts)
1628 return _docommit(ui, repo, *pats, **opts)
1630 finally:
1629 finally:
1631 release(lock, wlock)
1630 release(lock, wlock)
1632
1631
1633 def _docommit(ui, repo, *pats, **opts):
1632 def _docommit(ui, repo, *pats, **opts):
1634 if opts.get('interactive'):
1633 if opts.get('interactive'):
1635 opts.pop('interactive')
1634 opts.pop('interactive')
1636 ret = cmdutil.dorecord(ui, repo, commit, None, False,
1635 ret = cmdutil.dorecord(ui, repo, commit, None, False,
1637 cmdutil.recordfilter, *pats, **opts)
1636 cmdutil.recordfilter, *pats, **opts)
1638 # ret can be 0 (no changes to record) or the value returned by
1637 # ret can be 0 (no changes to record) or the value returned by
1639 # commit(), 1 if nothing changed or None on success.
1638 # commit(), 1 if nothing changed or None on success.
1640 return 1 if ret == 0 else ret
1639 return 1 if ret == 0 else ret
1641
1640
1642 if opts.get('subrepos'):
1641 if opts.get('subrepos'):
1643 if opts.get('amend'):
1642 if opts.get('amend'):
1644 raise error.Abort(_('cannot amend with --subrepos'))
1643 raise error.Abort(_('cannot amend with --subrepos'))
1645 # Let --subrepos on the command line override config setting.
1644 # Let --subrepos on the command line override config setting.
1646 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1645 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1647
1646
1648 cmdutil.checkunfinished(repo, commit=True)
1647 cmdutil.checkunfinished(repo, commit=True)
1649
1648
1650 branch = repo[None].branch()
1649 branch = repo[None].branch()
1651 bheads = repo.branchheads(branch)
1650 bheads = repo.branchheads(branch)
1652
1651
1653 extra = {}
1652 extra = {}
1654 if opts.get('close_branch'):
1653 if opts.get('close_branch'):
1655 extra['close'] = 1
1654 extra['close'] = 1
1656
1655
1657 if not bheads:
1656 if not bheads:
1658 raise error.Abort(_('can only close branch heads'))
1657 raise error.Abort(_('can only close branch heads'))
1659 elif opts.get('amend'):
1658 elif opts.get('amend'):
1660 if repo[None].parents()[0].p1().branch() != branch and \
1659 if repo[None].parents()[0].p1().branch() != branch and \
1661 repo[None].parents()[0].p2().branch() != branch:
1660 repo[None].parents()[0].p2().branch() != branch:
1662 raise error.Abort(_('can only close branch heads'))
1661 raise error.Abort(_('can only close branch heads'))
1663
1662
1664 if opts.get('amend'):
1663 if opts.get('amend'):
1665 if ui.configbool('ui', 'commitsubrepos'):
1664 if ui.configbool('ui', 'commitsubrepos'):
1666 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1665 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1667
1666
1668 old = repo['.']
1667 old = repo['.']
1669 if not old.mutable():
1668 if not old.mutable():
1670 raise error.Abort(_('cannot amend public changesets'))
1669 raise error.Abort(_('cannot amend public changesets'))
1671 if len(repo[None].parents()) > 1:
1670 if len(repo[None].parents()) > 1:
1672 raise error.Abort(_('cannot amend while merging'))
1671 raise error.Abort(_('cannot amend while merging'))
1673 allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
1672 allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
1674 if not allowunstable and old.children():
1673 if not allowunstable and old.children():
1675 raise error.Abort(_('cannot amend changeset with children'))
1674 raise error.Abort(_('cannot amend changeset with children'))
1676
1675
1677 # Currently histedit gets confused if an amend happens while histedit
1676 # Currently histedit gets confused if an amend happens while histedit
1678 # is in progress. Since we have a checkunfinished command, we are
1677 # is in progress. Since we have a checkunfinished command, we are
1679 # temporarily honoring it.
1678 # temporarily honoring it.
1680 #
1679 #
1681 # Note: eventually this guard will be removed. Please do not expect
1680 # Note: eventually this guard will be removed. Please do not expect
1682 # this behavior to remain.
1681 # this behavior to remain.
1683 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1682 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1684 cmdutil.checkunfinished(repo)
1683 cmdutil.checkunfinished(repo)
1685
1684
1686 # commitfunc is used only for temporary amend commit by cmdutil.amend
1685 # commitfunc is used only for temporary amend commit by cmdutil.amend
1687 def commitfunc(ui, repo, message, match, opts):
1686 def commitfunc(ui, repo, message, match, opts):
1688 return repo.commit(message,
1687 return repo.commit(message,
1689 opts.get('user') or old.user(),
1688 opts.get('user') or old.user(),
1690 opts.get('date') or old.date(),
1689 opts.get('date') or old.date(),
1691 match,
1690 match,
1692 extra=extra)
1691 extra=extra)
1693
1692
1694 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1693 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1695 if node == old.node():
1694 if node == old.node():
1696 ui.status(_("nothing changed\n"))
1695 ui.status(_("nothing changed\n"))
1697 return 1
1696 return 1
1698 else:
1697 else:
1699 def commitfunc(ui, repo, message, match, opts):
1698 def commitfunc(ui, repo, message, match, opts):
1700 backup = ui.backupconfig('phases', 'new-commit')
1699 backup = ui.backupconfig('phases', 'new-commit')
1701 baseui = repo.baseui
1700 baseui = repo.baseui
1702 basebackup = baseui.backupconfig('phases', 'new-commit')
1701 basebackup = baseui.backupconfig('phases', 'new-commit')
1703 try:
1702 try:
1704 if opts.get('secret'):
1703 if opts.get('secret'):
1705 ui.setconfig('phases', 'new-commit', 'secret', 'commit')
1704 ui.setconfig('phases', 'new-commit', 'secret', 'commit')
1706 # Propagate to subrepos
1705 # Propagate to subrepos
1707 baseui.setconfig('phases', 'new-commit', 'secret', 'commit')
1706 baseui.setconfig('phases', 'new-commit', 'secret', 'commit')
1708
1707
1709 editform = cmdutil.mergeeditform(repo[None], 'commit.normal')
1708 editform = cmdutil.mergeeditform(repo[None], 'commit.normal')
1710 editor = cmdutil.getcommiteditor(editform=editform, **opts)
1709 editor = cmdutil.getcommiteditor(editform=editform, **opts)
1711 return repo.commit(message, opts.get('user'), opts.get('date'),
1710 return repo.commit(message, opts.get('user'), opts.get('date'),
1712 match,
1711 match,
1713 editor=editor,
1712 editor=editor,
1714 extra=extra)
1713 extra=extra)
1715 finally:
1714 finally:
1716 ui.restoreconfig(backup)
1715 ui.restoreconfig(backup)
1717 repo.baseui.restoreconfig(basebackup)
1716 repo.baseui.restoreconfig(basebackup)
1718
1717
1719
1718
1720 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1719 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1721
1720
1722 if not node:
1721 if not node:
1723 stat = cmdutil.postcommitstatus(repo, pats, opts)
1722 stat = cmdutil.postcommitstatus(repo, pats, opts)
1724 if stat[3]:
1723 if stat[3]:
1725 ui.status(_("nothing changed (%d missing files, see "
1724 ui.status(_("nothing changed (%d missing files, see "
1726 "'hg status')\n") % len(stat[3]))
1725 "'hg status')\n") % len(stat[3]))
1727 else:
1726 else:
1728 ui.status(_("nothing changed\n"))
1727 ui.status(_("nothing changed\n"))
1729 return 1
1728 return 1
1730
1729
1731 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1730 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1732
1731
1733 @command('config|showconfig|debugconfig',
1732 @command('config|showconfig|debugconfig',
1734 [('u', 'untrusted', None, _('show untrusted configuration options')),
1733 [('u', 'untrusted', None, _('show untrusted configuration options')),
1735 ('e', 'edit', None, _('edit user config')),
1734 ('e', 'edit', None, _('edit user config')),
1736 ('l', 'local', None, _('edit repository config')),
1735 ('l', 'local', None, _('edit repository config')),
1737 ('g', 'global', None, _('edit global config'))] + formatteropts,
1736 ('g', 'global', None, _('edit global config'))] + formatteropts,
1738 _('[-u] [NAME]...'),
1737 _('[-u] [NAME]...'),
1739 optionalrepo=True)
1738 optionalrepo=True)
1740 def config(ui, repo, *values, **opts):
1739 def config(ui, repo, *values, **opts):
1741 """show combined config settings from all hgrc files
1740 """show combined config settings from all hgrc files
1742
1741
1743 With no arguments, print names and values of all config items.
1742 With no arguments, print names and values of all config items.
1744
1743
1745 With one argument of the form section.name, print just the value
1744 With one argument of the form section.name, print just the value
1746 of that config item.
1745 of that config item.
1747
1746
1748 With multiple arguments, print names and values of all config
1747 With multiple arguments, print names and values of all config
1749 items with matching section names.
1748 items with matching section names.
1750
1749
1751 With --edit, start an editor on the user-level config file. With
1750 With --edit, start an editor on the user-level config file. With
1752 --global, edit the system-wide config file. With --local, edit the
1751 --global, edit the system-wide config file. With --local, edit the
1753 repository-level config file.
1752 repository-level config file.
1754
1753
1755 With --debug, the source (filename and line number) is printed
1754 With --debug, the source (filename and line number) is printed
1756 for each config item.
1755 for each config item.
1757
1756
1758 See :hg:`help config` for more information about config files.
1757 See :hg:`help config` for more information about config files.
1759
1758
1760 Returns 0 on success, 1 if NAME does not exist.
1759 Returns 0 on success, 1 if NAME does not exist.
1761
1760
1762 """
1761 """
1763
1762
1764 if opts.get('edit') or opts.get('local') or opts.get('global'):
1763 if opts.get('edit') or opts.get('local') or opts.get('global'):
1765 if opts.get('local') and opts.get('global'):
1764 if opts.get('local') and opts.get('global'):
1766 raise error.Abort(_("can't use --local and --global together"))
1765 raise error.Abort(_("can't use --local and --global together"))
1767
1766
1768 if opts.get('local'):
1767 if opts.get('local'):
1769 if not repo:
1768 if not repo:
1770 raise error.Abort(_("can't use --local outside a repository"))
1769 raise error.Abort(_("can't use --local outside a repository"))
1771 paths = [repo.join('hgrc')]
1770 paths = [repo.join('hgrc')]
1772 elif opts.get('global'):
1771 elif opts.get('global'):
1773 paths = scmutil.systemrcpath()
1772 paths = scmutil.systemrcpath()
1774 else:
1773 else:
1775 paths = scmutil.userrcpath()
1774 paths = scmutil.userrcpath()
1776
1775
1777 for f in paths:
1776 for f in paths:
1778 if os.path.exists(f):
1777 if os.path.exists(f):
1779 break
1778 break
1780 else:
1779 else:
1781 if opts.get('global'):
1780 if opts.get('global'):
1782 samplehgrc = uimod.samplehgrcs['global']
1781 samplehgrc = uimod.samplehgrcs['global']
1783 elif opts.get('local'):
1782 elif opts.get('local'):
1784 samplehgrc = uimod.samplehgrcs['local']
1783 samplehgrc = uimod.samplehgrcs['local']
1785 else:
1784 else:
1786 samplehgrc = uimod.samplehgrcs['user']
1785 samplehgrc = uimod.samplehgrcs['user']
1787
1786
1788 f = paths[0]
1787 f = paths[0]
1789 fp = open(f, "w")
1788 fp = open(f, "w")
1790 fp.write(samplehgrc)
1789 fp.write(samplehgrc)
1791 fp.close()
1790 fp.close()
1792
1791
1793 editor = ui.geteditor()
1792 editor = ui.geteditor()
1794 ui.system("%s \"%s\"" % (editor, f),
1793 ui.system("%s \"%s\"" % (editor, f),
1795 onerr=error.Abort, errprefix=_("edit failed"))
1794 onerr=error.Abort, errprefix=_("edit failed"))
1796 return
1795 return
1797
1796
1798 fm = ui.formatter('config', opts)
1797 fm = ui.formatter('config', opts)
1799 for f in scmutil.rcpath():
1798 for f in scmutil.rcpath():
1800 ui.debug('read config from: %s\n' % f)
1799 ui.debug('read config from: %s\n' % f)
1801 untrusted = bool(opts.get('untrusted'))
1800 untrusted = bool(opts.get('untrusted'))
1802 if values:
1801 if values:
1803 sections = [v for v in values if '.' not in v]
1802 sections = [v for v in values if '.' not in v]
1804 items = [v for v in values if '.' in v]
1803 items = [v for v in values if '.' in v]
1805 if len(items) > 1 or items and sections:
1804 if len(items) > 1 or items and sections:
1806 raise error.Abort(_('only one config item permitted'))
1805 raise error.Abort(_('only one config item permitted'))
1807 matched = False
1806 matched = False
1808 for section, name, value in ui.walkconfig(untrusted=untrusted):
1807 for section, name, value in ui.walkconfig(untrusted=untrusted):
1809 value = str(value)
1808 value = str(value)
1810 if fm.isplain():
1809 if fm.isplain():
1811 value = value.replace('\n', '\\n')
1810 value = value.replace('\n', '\\n')
1812 entryname = section + '.' + name
1811 entryname = section + '.' + name
1813 if values:
1812 if values:
1814 for v in values:
1813 for v in values:
1815 if v == section:
1814 if v == section:
1816 fm.startitem()
1815 fm.startitem()
1817 fm.condwrite(ui.debugflag, 'source', '%s: ',
1816 fm.condwrite(ui.debugflag, 'source', '%s: ',
1818 ui.configsource(section, name, untrusted))
1817 ui.configsource(section, name, untrusted))
1819 fm.write('name value', '%s=%s\n', entryname, value)
1818 fm.write('name value', '%s=%s\n', entryname, value)
1820 matched = True
1819 matched = True
1821 elif v == entryname:
1820 elif v == entryname:
1822 fm.startitem()
1821 fm.startitem()
1823 fm.condwrite(ui.debugflag, 'source', '%s: ',
1822 fm.condwrite(ui.debugflag, 'source', '%s: ',
1824 ui.configsource(section, name, untrusted))
1823 ui.configsource(section, name, untrusted))
1825 fm.write('value', '%s\n', value)
1824 fm.write('value', '%s\n', value)
1826 fm.data(name=entryname)
1825 fm.data(name=entryname)
1827 matched = True
1826 matched = True
1828 else:
1827 else:
1829 fm.startitem()
1828 fm.startitem()
1830 fm.condwrite(ui.debugflag, 'source', '%s: ',
1829 fm.condwrite(ui.debugflag, 'source', '%s: ',
1831 ui.configsource(section, name, untrusted))
1830 ui.configsource(section, name, untrusted))
1832 fm.write('name value', '%s=%s\n', entryname, value)
1831 fm.write('name value', '%s=%s\n', entryname, value)
1833 matched = True
1832 matched = True
1834 fm.end()
1833 fm.end()
1835 if matched:
1834 if matched:
1836 return 0
1835 return 0
1837 return 1
1836 return 1
1838
1837
1839 @command('copy|cp',
1838 @command('copy|cp',
1840 [('A', 'after', None, _('record a copy that has already occurred')),
1839 [('A', 'after', None, _('record a copy that has already occurred')),
1841 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1840 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1842 ] + walkopts + dryrunopts,
1841 ] + walkopts + dryrunopts,
1843 _('[OPTION]... [SOURCE]... DEST'))
1842 _('[OPTION]... [SOURCE]... DEST'))
1844 def copy(ui, repo, *pats, **opts):
1843 def copy(ui, repo, *pats, **opts):
1845 """mark files as copied for the next commit
1844 """mark files as copied for the next commit
1846
1845
1847 Mark dest as having copies of source files. If dest is a
1846 Mark dest as having copies of source files. If dest is a
1848 directory, copies are put in that directory. If dest is a file,
1847 directory, copies are put in that directory. If dest is a file,
1849 the source must be a single file.
1848 the source must be a single file.
1850
1849
1851 By default, this command copies the contents of files as they
1850 By default, this command copies the contents of files as they
1852 exist in the working directory. If invoked with -A/--after, the
1851 exist in the working directory. If invoked with -A/--after, the
1853 operation is recorded, but no copying is performed.
1852 operation is recorded, but no copying is performed.
1854
1853
1855 This command takes effect with the next commit. To undo a copy
1854 This command takes effect with the next commit. To undo a copy
1856 before that, see :hg:`revert`.
1855 before that, see :hg:`revert`.
1857
1856
1858 Returns 0 on success, 1 if errors are encountered.
1857 Returns 0 on success, 1 if errors are encountered.
1859 """
1858 """
1860 with repo.wlock(False):
1859 with repo.wlock(False):
1861 return cmdutil.copy(ui, repo, pats, opts)
1860 return cmdutil.copy(ui, repo, pats, opts)
1862
1861
1863 @command('debugextensions', formatteropts, [], norepo=True)
1864 def debugextensions(ui, **opts):
1865 '''show information about active extensions'''
1866 exts = extensions.extensions(ui)
1867 hgver = util.version()
1868 fm = ui.formatter('debugextensions', opts)
1869 for extname, extmod in sorted(exts, key=operator.itemgetter(0)):
1870 isinternal = extensions.ismoduleinternal(extmod)
1871 extsource = extmod.__file__
1872 if isinternal:
1873 exttestedwith = [] # never expose magic string to users
1874 else:
1875 exttestedwith = getattr(extmod, 'testedwith', '').split()
1876 extbuglink = getattr(extmod, 'buglink', None)
1877
1878 fm.startitem()
1879
1880 if ui.quiet or ui.verbose:
1881 fm.write('name', '%s\n', extname)
1882 else:
1883 fm.write('name', '%s', extname)
1884 if isinternal or hgver in exttestedwith:
1885 fm.plain('\n')
1886 elif not exttestedwith:
1887 fm.plain(_(' (untested!)\n'))
1888 else:
1889 lasttestedversion = exttestedwith[-1]
1890 fm.plain(' (%s!)\n' % lasttestedversion)
1891
1892 fm.condwrite(ui.verbose and extsource, 'source',
1893 _(' location: %s\n'), extsource or "")
1894
1895 if ui.verbose:
1896 fm.plain(_(' bundled: %s\n') % ['no', 'yes'][isinternal])
1897 fm.data(bundled=isinternal)
1898
1899 fm.condwrite(ui.verbose and exttestedwith, 'testedwith',
1900 _(' tested with: %s\n'),
1901 fm.formatlist(exttestedwith, name='ver'))
1902
1903 fm.condwrite(ui.verbose and extbuglink, 'buglink',
1904 _(' bug reporting: %s\n'), extbuglink or "")
1905
1906 fm.end()
1907
1908 @command('debugfileset',
1862 @command('debugfileset',
1909 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
1863 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
1910 _('[-r REV] FILESPEC'))
1864 _('[-r REV] FILESPEC'))
1911 def debugfileset(ui, repo, expr, **opts):
1865 def debugfileset(ui, repo, expr, **opts):
1912 '''parse and apply a fileset specification'''
1866 '''parse and apply a fileset specification'''
1913 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
1867 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
1914 if ui.verbose:
1868 if ui.verbose:
1915 tree = fileset.parse(expr)
1869 tree = fileset.parse(expr)
1916 ui.note(fileset.prettyformat(tree), "\n")
1870 ui.note(fileset.prettyformat(tree), "\n")
1917
1871
1918 for f in ctx.getfileset(expr):
1872 for f in ctx.getfileset(expr):
1919 ui.write("%s\n" % f)
1873 ui.write("%s\n" % f)
1920
1874
1921 @command('debugfsinfo', [], _('[PATH]'), norepo=True)
1875 @command('debugfsinfo', [], _('[PATH]'), norepo=True)
1922 def debugfsinfo(ui, path="."):
1876 def debugfsinfo(ui, path="."):
1923 """show information detected about current filesystem"""
1877 """show information detected about current filesystem"""
1924 util.writefile('.debugfsinfo', '')
1878 util.writefile('.debugfsinfo', '')
1925 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
1879 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
1926 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
1880 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
1927 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
1881 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
1928 ui.write(('case-sensitive: %s\n') % (util.fscasesensitive('.debugfsinfo')
1882 ui.write(('case-sensitive: %s\n') % (util.fscasesensitive('.debugfsinfo')
1929 and 'yes' or 'no'))
1883 and 'yes' or 'no'))
1930 os.unlink('.debugfsinfo')
1884 os.unlink('.debugfsinfo')
1931
1885
1932 @command('debuggetbundle',
1886 @command('debuggetbundle',
1933 [('H', 'head', [], _('id of head node'), _('ID')),
1887 [('H', 'head', [], _('id of head node'), _('ID')),
1934 ('C', 'common', [], _('id of common node'), _('ID')),
1888 ('C', 'common', [], _('id of common node'), _('ID')),
1935 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1889 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1936 _('REPO FILE [-H|-C ID]...'),
1890 _('REPO FILE [-H|-C ID]...'),
1937 norepo=True)
1891 norepo=True)
1938 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1892 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1939 """retrieves a bundle from a repo
1893 """retrieves a bundle from a repo
1940
1894
1941 Every ID must be a full-length hex node id string. Saves the bundle to the
1895 Every ID must be a full-length hex node id string. Saves the bundle to the
1942 given file.
1896 given file.
1943 """
1897 """
1944 repo = hg.peer(ui, opts, repopath)
1898 repo = hg.peer(ui, opts, repopath)
1945 if not repo.capable('getbundle'):
1899 if not repo.capable('getbundle'):
1946 raise error.Abort("getbundle() not supported by target repository")
1900 raise error.Abort("getbundle() not supported by target repository")
1947 args = {}
1901 args = {}
1948 if common:
1902 if common:
1949 args['common'] = [bin(s) for s in common]
1903 args['common'] = [bin(s) for s in common]
1950 if head:
1904 if head:
1951 args['heads'] = [bin(s) for s in head]
1905 args['heads'] = [bin(s) for s in head]
1952 # TODO: get desired bundlecaps from command line.
1906 # TODO: get desired bundlecaps from command line.
1953 args['bundlecaps'] = None
1907 args['bundlecaps'] = None
1954 bundle = repo.getbundle('debug', **args)
1908 bundle = repo.getbundle('debug', **args)
1955
1909
1956 bundletype = opts.get('type', 'bzip2').lower()
1910 bundletype = opts.get('type', 'bzip2').lower()
1957 btypes = {'none': 'HG10UN',
1911 btypes = {'none': 'HG10UN',
1958 'bzip2': 'HG10BZ',
1912 'bzip2': 'HG10BZ',
1959 'gzip': 'HG10GZ',
1913 'gzip': 'HG10GZ',
1960 'bundle2': 'HG20'}
1914 'bundle2': 'HG20'}
1961 bundletype = btypes.get(bundletype)
1915 bundletype = btypes.get(bundletype)
1962 if bundletype not in bundle2.bundletypes:
1916 if bundletype not in bundle2.bundletypes:
1963 raise error.Abort(_('unknown bundle type specified with --type'))
1917 raise error.Abort(_('unknown bundle type specified with --type'))
1964 bundle2.writebundle(ui, bundle, bundlepath, bundletype)
1918 bundle2.writebundle(ui, bundle, bundlepath, bundletype)
1965
1919
1966 @command('debugignore', [], '[FILE]')
1920 @command('debugignore', [], '[FILE]')
1967 def debugignore(ui, repo, *files, **opts):
1921 def debugignore(ui, repo, *files, **opts):
1968 """display the combined ignore pattern and information about ignored files
1922 """display the combined ignore pattern and information about ignored files
1969
1923
1970 With no argument display the combined ignore pattern.
1924 With no argument display the combined ignore pattern.
1971
1925
1972 Given space separated file names, shows if the given file is ignored and
1926 Given space separated file names, shows if the given file is ignored and
1973 if so, show the ignore rule (file and line number) that matched it.
1927 if so, show the ignore rule (file and line number) that matched it.
1974 """
1928 """
1975 ignore = repo.dirstate._ignore
1929 ignore = repo.dirstate._ignore
1976 if not files:
1930 if not files:
1977 # Show all the patterns
1931 # Show all the patterns
1978 includepat = getattr(ignore, 'includepat', None)
1932 includepat = getattr(ignore, 'includepat', None)
1979 if includepat is not None:
1933 if includepat is not None:
1980 ui.write("%s\n" % includepat)
1934 ui.write("%s\n" % includepat)
1981 else:
1935 else:
1982 raise error.Abort(_("no ignore patterns found"))
1936 raise error.Abort(_("no ignore patterns found"))
1983 else:
1937 else:
1984 for f in files:
1938 for f in files:
1985 nf = util.normpath(f)
1939 nf = util.normpath(f)
1986 ignored = None
1940 ignored = None
1987 ignoredata = None
1941 ignoredata = None
1988 if nf != '.':
1942 if nf != '.':
1989 if ignore(nf):
1943 if ignore(nf):
1990 ignored = nf
1944 ignored = nf
1991 ignoredata = repo.dirstate._ignorefileandline(nf)
1945 ignoredata = repo.dirstate._ignorefileandline(nf)
1992 else:
1946 else:
1993 for p in util.finddirs(nf):
1947 for p in util.finddirs(nf):
1994 if ignore(p):
1948 if ignore(p):
1995 ignored = p
1949 ignored = p
1996 ignoredata = repo.dirstate._ignorefileandline(p)
1950 ignoredata = repo.dirstate._ignorefileandline(p)
1997 break
1951 break
1998 if ignored:
1952 if ignored:
1999 if ignored == nf:
1953 if ignored == nf:
2000 ui.write(_("%s is ignored\n") % f)
1954 ui.write(_("%s is ignored\n") % f)
2001 else:
1955 else:
2002 ui.write(_("%s is ignored because of "
1956 ui.write(_("%s is ignored because of "
2003 "containing folder %s\n")
1957 "containing folder %s\n")
2004 % (f, ignored))
1958 % (f, ignored))
2005 ignorefile, lineno, line = ignoredata
1959 ignorefile, lineno, line = ignoredata
2006 ui.write(_("(ignore rule in %s, line %d: '%s')\n")
1960 ui.write(_("(ignore rule in %s, line %d: '%s')\n")
2007 % (ignorefile, lineno, line))
1961 % (ignorefile, lineno, line))
2008 else:
1962 else:
2009 ui.write(_("%s is not ignored\n") % f)
1963 ui.write(_("%s is not ignored\n") % f)
2010
1964
2011 @command('debugindex', debugrevlogopts +
1965 @command('debugindex', debugrevlogopts +
2012 [('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1966 [('f', 'format', 0, _('revlog format'), _('FORMAT'))],
2013 _('[-f FORMAT] -c|-m|FILE'),
1967 _('[-f FORMAT] -c|-m|FILE'),
2014 optionalrepo=True)
1968 optionalrepo=True)
2015 def debugindex(ui, repo, file_=None, **opts):
1969 def debugindex(ui, repo, file_=None, **opts):
2016 """dump the contents of an index file"""
1970 """dump the contents of an index file"""
2017 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1971 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
2018 format = opts.get('format', 0)
1972 format = opts.get('format', 0)
2019 if format not in (0, 1):
1973 if format not in (0, 1):
2020 raise error.Abort(_("unknown format %d") % format)
1974 raise error.Abort(_("unknown format %d") % format)
2021
1975
2022 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1976 generaldelta = r.version & revlog.REVLOGGENERALDELTA
2023 if generaldelta:
1977 if generaldelta:
2024 basehdr = ' delta'
1978 basehdr = ' delta'
2025 else:
1979 else:
2026 basehdr = ' base'
1980 basehdr = ' base'
2027
1981
2028 if ui.debugflag:
1982 if ui.debugflag:
2029 shortfn = hex
1983 shortfn = hex
2030 else:
1984 else:
2031 shortfn = short
1985 shortfn = short
2032
1986
2033 # There might not be anything in r, so have a sane default
1987 # There might not be anything in r, so have a sane default
2034 idlen = 12
1988 idlen = 12
2035 for i in r:
1989 for i in r:
2036 idlen = len(shortfn(r.node(i)))
1990 idlen = len(shortfn(r.node(i)))
2037 break
1991 break
2038
1992
2039 if format == 0:
1993 if format == 0:
2040 ui.write((" rev offset length " + basehdr + " linkrev"
1994 ui.write((" rev offset length " + basehdr + " linkrev"
2041 " %s %s p2\n") % ("nodeid".ljust(idlen), "p1".ljust(idlen)))
1995 " %s %s p2\n") % ("nodeid".ljust(idlen), "p1".ljust(idlen)))
2042 elif format == 1:
1996 elif format == 1:
2043 ui.write((" rev flag offset length"
1997 ui.write((" rev flag offset length"
2044 " size " + basehdr + " link p1 p2"
1998 " size " + basehdr + " link p1 p2"
2045 " %s\n") % "nodeid".rjust(idlen))
1999 " %s\n") % "nodeid".rjust(idlen))
2046
2000
2047 for i in r:
2001 for i in r:
2048 node = r.node(i)
2002 node = r.node(i)
2049 if generaldelta:
2003 if generaldelta:
2050 base = r.deltaparent(i)
2004 base = r.deltaparent(i)
2051 else:
2005 else:
2052 base = r.chainbase(i)
2006 base = r.chainbase(i)
2053 if format == 0:
2007 if format == 0:
2054 try:
2008 try:
2055 pp = r.parents(node)
2009 pp = r.parents(node)
2056 except Exception:
2010 except Exception:
2057 pp = [nullid, nullid]
2011 pp = [nullid, nullid]
2058 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
2012 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
2059 i, r.start(i), r.length(i), base, r.linkrev(i),
2013 i, r.start(i), r.length(i), base, r.linkrev(i),
2060 shortfn(node), shortfn(pp[0]), shortfn(pp[1])))
2014 shortfn(node), shortfn(pp[0]), shortfn(pp[1])))
2061 elif format == 1:
2015 elif format == 1:
2062 pr = r.parentrevs(i)
2016 pr = r.parentrevs(i)
2063 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
2017 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
2064 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
2018 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
2065 base, r.linkrev(i), pr[0], pr[1], shortfn(node)))
2019 base, r.linkrev(i), pr[0], pr[1], shortfn(node)))
2066
2020
2067 @command('debugindexdot', debugrevlogopts,
2021 @command('debugindexdot', debugrevlogopts,
2068 _('-c|-m|FILE'), optionalrepo=True)
2022 _('-c|-m|FILE'), optionalrepo=True)
2069 def debugindexdot(ui, repo, file_=None, **opts):
2023 def debugindexdot(ui, repo, file_=None, **opts):
2070 """dump an index DAG as a graphviz dot file"""
2024 """dump an index DAG as a graphviz dot file"""
2071 r = cmdutil.openrevlog(repo, 'debugindexdot', file_, opts)
2025 r = cmdutil.openrevlog(repo, 'debugindexdot', file_, opts)
2072 ui.write(("digraph G {\n"))
2026 ui.write(("digraph G {\n"))
2073 for i in r:
2027 for i in r:
2074 node = r.node(i)
2028 node = r.node(i)
2075 pp = r.parents(node)
2029 pp = r.parents(node)
2076 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
2030 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
2077 if pp[1] != nullid:
2031 if pp[1] != nullid:
2078 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
2032 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
2079 ui.write("}\n")
2033 ui.write("}\n")
2080
2034
2081 @command('debugdeltachain',
2035 @command('debugdeltachain',
2082 debugrevlogopts + formatteropts,
2036 debugrevlogopts + formatteropts,
2083 _('-c|-m|FILE'),
2037 _('-c|-m|FILE'),
2084 optionalrepo=True)
2038 optionalrepo=True)
2085 def debugdeltachain(ui, repo, file_=None, **opts):
2039 def debugdeltachain(ui, repo, file_=None, **opts):
2086 """dump information about delta chains in a revlog
2040 """dump information about delta chains in a revlog
2087
2041
2088 Output can be templatized. Available template keywords are:
2042 Output can be templatized. Available template keywords are:
2089
2043
2090 :``rev``: revision number
2044 :``rev``: revision number
2091 :``chainid``: delta chain identifier (numbered by unique base)
2045 :``chainid``: delta chain identifier (numbered by unique base)
2092 :``chainlen``: delta chain length to this revision
2046 :``chainlen``: delta chain length to this revision
2093 :``prevrev``: previous revision in delta chain
2047 :``prevrev``: previous revision in delta chain
2094 :``deltatype``: role of delta / how it was computed
2048 :``deltatype``: role of delta / how it was computed
2095 :``compsize``: compressed size of revision
2049 :``compsize``: compressed size of revision
2096 :``uncompsize``: uncompressed size of revision
2050 :``uncompsize``: uncompressed size of revision
2097 :``chainsize``: total size of compressed revisions in chain
2051 :``chainsize``: total size of compressed revisions in chain
2098 :``chainratio``: total chain size divided by uncompressed revision size
2052 :``chainratio``: total chain size divided by uncompressed revision size
2099 (new delta chains typically start at ratio 2.00)
2053 (new delta chains typically start at ratio 2.00)
2100 :``lindist``: linear distance from base revision in delta chain to end
2054 :``lindist``: linear distance from base revision in delta chain to end
2101 of this revision
2055 of this revision
2102 :``extradist``: total size of revisions not part of this delta chain from
2056 :``extradist``: total size of revisions not part of this delta chain from
2103 base of delta chain to end of this revision; a measurement
2057 base of delta chain to end of this revision; a measurement
2104 of how much extra data we need to read/seek across to read
2058 of how much extra data we need to read/seek across to read
2105 the delta chain for this revision
2059 the delta chain for this revision
2106 :``extraratio``: extradist divided by chainsize; another representation of
2060 :``extraratio``: extradist divided by chainsize; another representation of
2107 how much unrelated data is needed to load this delta chain
2061 how much unrelated data is needed to load this delta chain
2108 """
2062 """
2109 r = cmdutil.openrevlog(repo, 'debugdeltachain', file_, opts)
2063 r = cmdutil.openrevlog(repo, 'debugdeltachain', file_, opts)
2110 index = r.index
2064 index = r.index
2111 generaldelta = r.version & revlog.REVLOGGENERALDELTA
2065 generaldelta = r.version & revlog.REVLOGGENERALDELTA
2112
2066
2113 def revinfo(rev):
2067 def revinfo(rev):
2114 e = index[rev]
2068 e = index[rev]
2115 compsize = e[1]
2069 compsize = e[1]
2116 uncompsize = e[2]
2070 uncompsize = e[2]
2117 chainsize = 0
2071 chainsize = 0
2118
2072
2119 if generaldelta:
2073 if generaldelta:
2120 if e[3] == e[5]:
2074 if e[3] == e[5]:
2121 deltatype = 'p1'
2075 deltatype = 'p1'
2122 elif e[3] == e[6]:
2076 elif e[3] == e[6]:
2123 deltatype = 'p2'
2077 deltatype = 'p2'
2124 elif e[3] == rev - 1:
2078 elif e[3] == rev - 1:
2125 deltatype = 'prev'
2079 deltatype = 'prev'
2126 elif e[3] == rev:
2080 elif e[3] == rev:
2127 deltatype = 'base'
2081 deltatype = 'base'
2128 else:
2082 else:
2129 deltatype = 'other'
2083 deltatype = 'other'
2130 else:
2084 else:
2131 if e[3] == rev:
2085 if e[3] == rev:
2132 deltatype = 'base'
2086 deltatype = 'base'
2133 else:
2087 else:
2134 deltatype = 'prev'
2088 deltatype = 'prev'
2135
2089
2136 chain = r._deltachain(rev)[0]
2090 chain = r._deltachain(rev)[0]
2137 for iterrev in chain:
2091 for iterrev in chain:
2138 e = index[iterrev]
2092 e = index[iterrev]
2139 chainsize += e[1]
2093 chainsize += e[1]
2140
2094
2141 return compsize, uncompsize, deltatype, chain, chainsize
2095 return compsize, uncompsize, deltatype, chain, chainsize
2142
2096
2143 fm = ui.formatter('debugdeltachain', opts)
2097 fm = ui.formatter('debugdeltachain', opts)
2144
2098
2145 fm.plain(' rev chain# chainlen prev delta '
2099 fm.plain(' rev chain# chainlen prev delta '
2146 'size rawsize chainsize ratio lindist extradist '
2100 'size rawsize chainsize ratio lindist extradist '
2147 'extraratio\n')
2101 'extraratio\n')
2148
2102
2149 chainbases = {}
2103 chainbases = {}
2150 for rev in r:
2104 for rev in r:
2151 comp, uncomp, deltatype, chain, chainsize = revinfo(rev)
2105 comp, uncomp, deltatype, chain, chainsize = revinfo(rev)
2152 chainbase = chain[0]
2106 chainbase = chain[0]
2153 chainid = chainbases.setdefault(chainbase, len(chainbases) + 1)
2107 chainid = chainbases.setdefault(chainbase, len(chainbases) + 1)
2154 basestart = r.start(chainbase)
2108 basestart = r.start(chainbase)
2155 revstart = r.start(rev)
2109 revstart = r.start(rev)
2156 lineardist = revstart + comp - basestart
2110 lineardist = revstart + comp - basestart
2157 extradist = lineardist - chainsize
2111 extradist = lineardist - chainsize
2158 try:
2112 try:
2159 prevrev = chain[-2]
2113 prevrev = chain[-2]
2160 except IndexError:
2114 except IndexError:
2161 prevrev = -1
2115 prevrev = -1
2162
2116
2163 chainratio = float(chainsize) / float(uncomp)
2117 chainratio = float(chainsize) / float(uncomp)
2164 extraratio = float(extradist) / float(chainsize)
2118 extraratio = float(extradist) / float(chainsize)
2165
2119
2166 fm.startitem()
2120 fm.startitem()
2167 fm.write('rev chainid chainlen prevrev deltatype compsize '
2121 fm.write('rev chainid chainlen prevrev deltatype compsize '
2168 'uncompsize chainsize chainratio lindist extradist '
2122 'uncompsize chainsize chainratio lindist extradist '
2169 'extraratio',
2123 'extraratio',
2170 '%7d %7d %8d %8d %7s %10d %10d %10d %9.5f %9d %9d %10.5f\n',
2124 '%7d %7d %8d %8d %7s %10d %10d %10d %9.5f %9d %9d %10.5f\n',
2171 rev, chainid, len(chain), prevrev, deltatype, comp,
2125 rev, chainid, len(chain), prevrev, deltatype, comp,
2172 uncomp, chainsize, chainratio, lineardist, extradist,
2126 uncomp, chainsize, chainratio, lineardist, extradist,
2173 extraratio,
2127 extraratio,
2174 rev=rev, chainid=chainid, chainlen=len(chain),
2128 rev=rev, chainid=chainid, chainlen=len(chain),
2175 prevrev=prevrev, deltatype=deltatype, compsize=comp,
2129 prevrev=prevrev, deltatype=deltatype, compsize=comp,
2176 uncompsize=uncomp, chainsize=chainsize,
2130 uncompsize=uncomp, chainsize=chainsize,
2177 chainratio=chainratio, lindist=lineardist,
2131 chainratio=chainratio, lindist=lineardist,
2178 extradist=extradist, extraratio=extraratio)
2132 extradist=extradist, extraratio=extraratio)
2179
2133
2180 fm.end()
2134 fm.end()
2181
2135
2182 @command('debuginstall', [] + formatteropts, '', norepo=True)
2136 @command('debuginstall', [] + formatteropts, '', norepo=True)
2183 def debuginstall(ui, **opts):
2137 def debuginstall(ui, **opts):
2184 '''test Mercurial installation
2138 '''test Mercurial installation
2185
2139
2186 Returns 0 on success.
2140 Returns 0 on success.
2187 '''
2141 '''
2188
2142
2189 def writetemp(contents):
2143 def writetemp(contents):
2190 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2144 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2191 f = os.fdopen(fd, "wb")
2145 f = os.fdopen(fd, "wb")
2192 f.write(contents)
2146 f.write(contents)
2193 f.close()
2147 f.close()
2194 return name
2148 return name
2195
2149
2196 problems = 0
2150 problems = 0
2197
2151
2198 fm = ui.formatter('debuginstall', opts)
2152 fm = ui.formatter('debuginstall', opts)
2199 fm.startitem()
2153 fm.startitem()
2200
2154
2201 # encoding
2155 # encoding
2202 fm.write('encoding', _("checking encoding (%s)...\n"), encoding.encoding)
2156 fm.write('encoding', _("checking encoding (%s)...\n"), encoding.encoding)
2203 err = None
2157 err = None
2204 try:
2158 try:
2205 encoding.fromlocal("test")
2159 encoding.fromlocal("test")
2206 except error.Abort as inst:
2160 except error.Abort as inst:
2207 err = inst
2161 err = inst
2208 problems += 1
2162 problems += 1
2209 fm.condwrite(err, 'encodingerror', _(" %s\n"
2163 fm.condwrite(err, 'encodingerror', _(" %s\n"
2210 " (check that your locale is properly set)\n"), err)
2164 " (check that your locale is properly set)\n"), err)
2211
2165
2212 # Python
2166 # Python
2213 fm.write('pythonexe', _("checking Python executable (%s)\n"),
2167 fm.write('pythonexe', _("checking Python executable (%s)\n"),
2214 sys.executable)
2168 sys.executable)
2215 fm.write('pythonver', _("checking Python version (%s)\n"),
2169 fm.write('pythonver', _("checking Python version (%s)\n"),
2216 ("%s.%s.%s" % sys.version_info[:3]))
2170 ("%s.%s.%s" % sys.version_info[:3]))
2217 fm.write('pythonlib', _("checking Python lib (%s)...\n"),
2171 fm.write('pythonlib', _("checking Python lib (%s)...\n"),
2218 os.path.dirname(os.__file__))
2172 os.path.dirname(os.__file__))
2219
2173
2220 security = set(sslutil.supportedprotocols)
2174 security = set(sslutil.supportedprotocols)
2221 if sslutil.hassni:
2175 if sslutil.hassni:
2222 security.add('sni')
2176 security.add('sni')
2223
2177
2224 fm.write('pythonsecurity', _("checking Python security support (%s)\n"),
2178 fm.write('pythonsecurity', _("checking Python security support (%s)\n"),
2225 fm.formatlist(sorted(security), name='protocol',
2179 fm.formatlist(sorted(security), name='protocol',
2226 fmt='%s', sep=','))
2180 fmt='%s', sep=','))
2227
2181
2228 # These are warnings, not errors. So don't increment problem count. This
2182 # These are warnings, not errors. So don't increment problem count. This
2229 # may change in the future.
2183 # may change in the future.
2230 if 'tls1.2' not in security:
2184 if 'tls1.2' not in security:
2231 fm.plain(_(' TLS 1.2 not supported by Python install; '
2185 fm.plain(_(' TLS 1.2 not supported by Python install; '
2232 'network connections lack modern security\n'))
2186 'network connections lack modern security\n'))
2233 if 'sni' not in security:
2187 if 'sni' not in security:
2234 fm.plain(_(' SNI not supported by Python install; may have '
2188 fm.plain(_(' SNI not supported by Python install; may have '
2235 'connectivity issues with some servers\n'))
2189 'connectivity issues with some servers\n'))
2236
2190
2237 # TODO print CA cert info
2191 # TODO print CA cert info
2238
2192
2239 # hg version
2193 # hg version
2240 hgver = util.version()
2194 hgver = util.version()
2241 fm.write('hgver', _("checking Mercurial version (%s)\n"),
2195 fm.write('hgver', _("checking Mercurial version (%s)\n"),
2242 hgver.split('+')[0])
2196 hgver.split('+')[0])
2243 fm.write('hgverextra', _("checking Mercurial custom build (%s)\n"),
2197 fm.write('hgverextra', _("checking Mercurial custom build (%s)\n"),
2244 '+'.join(hgver.split('+')[1:]))
2198 '+'.join(hgver.split('+')[1:]))
2245
2199
2246 # compiled modules
2200 # compiled modules
2247 fm.write('hgmodulepolicy', _("checking module policy (%s)\n"),
2201 fm.write('hgmodulepolicy', _("checking module policy (%s)\n"),
2248 policy.policy)
2202 policy.policy)
2249 fm.write('hgmodules', _("checking installed modules (%s)...\n"),
2203 fm.write('hgmodules', _("checking installed modules (%s)...\n"),
2250 os.path.dirname(__file__))
2204 os.path.dirname(__file__))
2251
2205
2252 err = None
2206 err = None
2253 try:
2207 try:
2254 from . import (
2208 from . import (
2255 base85,
2209 base85,
2256 bdiff,
2210 bdiff,
2257 mpatch,
2211 mpatch,
2258 osutil,
2212 osutil,
2259 )
2213 )
2260 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2214 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2261 except Exception as inst:
2215 except Exception as inst:
2262 err = inst
2216 err = inst
2263 problems += 1
2217 problems += 1
2264 fm.condwrite(err, 'extensionserror', " %s\n", err)
2218 fm.condwrite(err, 'extensionserror', " %s\n", err)
2265
2219
2266 compengines = util.compengines._engines.values()
2220 compengines = util.compengines._engines.values()
2267 fm.write('compengines', _('checking registered compression engines (%s)\n'),
2221 fm.write('compengines', _('checking registered compression engines (%s)\n'),
2268 fm.formatlist(sorted(e.name() for e in compengines),
2222 fm.formatlist(sorted(e.name() for e in compengines),
2269 name='compengine', fmt='%s', sep=', '))
2223 name='compengine', fmt='%s', sep=', '))
2270 fm.write('compenginesavail', _('checking available compression engines '
2224 fm.write('compenginesavail', _('checking available compression engines '
2271 '(%s)\n'),
2225 '(%s)\n'),
2272 fm.formatlist(sorted(e.name() for e in compengines
2226 fm.formatlist(sorted(e.name() for e in compengines
2273 if e.available()),
2227 if e.available()),
2274 name='compengine', fmt='%s', sep=', '))
2228 name='compengine', fmt='%s', sep=', '))
2275
2229
2276 # templates
2230 # templates
2277 p = templater.templatepaths()
2231 p = templater.templatepaths()
2278 fm.write('templatedirs', 'checking templates (%s)...\n', ' '.join(p))
2232 fm.write('templatedirs', 'checking templates (%s)...\n', ' '.join(p))
2279 fm.condwrite(not p, '', _(" no template directories found\n"))
2233 fm.condwrite(not p, '', _(" no template directories found\n"))
2280 if p:
2234 if p:
2281 m = templater.templatepath("map-cmdline.default")
2235 m = templater.templatepath("map-cmdline.default")
2282 if m:
2236 if m:
2283 # template found, check if it is working
2237 # template found, check if it is working
2284 err = None
2238 err = None
2285 try:
2239 try:
2286 templater.templater.frommapfile(m)
2240 templater.templater.frommapfile(m)
2287 except Exception as inst:
2241 except Exception as inst:
2288 err = inst
2242 err = inst
2289 p = None
2243 p = None
2290 fm.condwrite(err, 'defaulttemplateerror', " %s\n", err)
2244 fm.condwrite(err, 'defaulttemplateerror', " %s\n", err)
2291 else:
2245 else:
2292 p = None
2246 p = None
2293 fm.condwrite(p, 'defaulttemplate',
2247 fm.condwrite(p, 'defaulttemplate',
2294 _("checking default template (%s)\n"), m)
2248 _("checking default template (%s)\n"), m)
2295 fm.condwrite(not m, 'defaulttemplatenotfound',
2249 fm.condwrite(not m, 'defaulttemplatenotfound',
2296 _(" template '%s' not found\n"), "default")
2250 _(" template '%s' not found\n"), "default")
2297 if not p:
2251 if not p:
2298 problems += 1
2252 problems += 1
2299 fm.condwrite(not p, '',
2253 fm.condwrite(not p, '',
2300 _(" (templates seem to have been installed incorrectly)\n"))
2254 _(" (templates seem to have been installed incorrectly)\n"))
2301
2255
2302 # editor
2256 # editor
2303 editor = ui.geteditor()
2257 editor = ui.geteditor()
2304 editor = util.expandpath(editor)
2258 editor = util.expandpath(editor)
2305 fm.write('editor', _("checking commit editor... (%s)\n"), editor)
2259 fm.write('editor', _("checking commit editor... (%s)\n"), editor)
2306 cmdpath = util.findexe(shlex.split(editor)[0])
2260 cmdpath = util.findexe(shlex.split(editor)[0])
2307 fm.condwrite(not cmdpath and editor == 'vi', 'vinotfound',
2261 fm.condwrite(not cmdpath and editor == 'vi', 'vinotfound',
2308 _(" No commit editor set and can't find %s in PATH\n"
2262 _(" No commit editor set and can't find %s in PATH\n"
2309 " (specify a commit editor in your configuration"
2263 " (specify a commit editor in your configuration"
2310 " file)\n"), not cmdpath and editor == 'vi' and editor)
2264 " file)\n"), not cmdpath and editor == 'vi' and editor)
2311 fm.condwrite(not cmdpath and editor != 'vi', 'editornotfound',
2265 fm.condwrite(not cmdpath and editor != 'vi', 'editornotfound',
2312 _(" Can't find editor '%s' in PATH\n"
2266 _(" Can't find editor '%s' in PATH\n"
2313 " (specify a commit editor in your configuration"
2267 " (specify a commit editor in your configuration"
2314 " file)\n"), not cmdpath and editor)
2268 " file)\n"), not cmdpath and editor)
2315 if not cmdpath and editor != 'vi':
2269 if not cmdpath and editor != 'vi':
2316 problems += 1
2270 problems += 1
2317
2271
2318 # check username
2272 # check username
2319 username = None
2273 username = None
2320 err = None
2274 err = None
2321 try:
2275 try:
2322 username = ui.username()
2276 username = ui.username()
2323 except error.Abort as e:
2277 except error.Abort as e:
2324 err = e
2278 err = e
2325 problems += 1
2279 problems += 1
2326
2280
2327 fm.condwrite(username, 'username', _("checking username (%s)\n"), username)
2281 fm.condwrite(username, 'username', _("checking username (%s)\n"), username)
2328 fm.condwrite(err, 'usernameerror', _("checking username...\n %s\n"
2282 fm.condwrite(err, 'usernameerror', _("checking username...\n %s\n"
2329 " (specify a username in your configuration file)\n"), err)
2283 " (specify a username in your configuration file)\n"), err)
2330
2284
2331 fm.condwrite(not problems, '',
2285 fm.condwrite(not problems, '',
2332 _("no problems detected\n"))
2286 _("no problems detected\n"))
2333 if not problems:
2287 if not problems:
2334 fm.data(problems=problems)
2288 fm.data(problems=problems)
2335 fm.condwrite(problems, 'problems',
2289 fm.condwrite(problems, 'problems',
2336 _("%d problems detected,"
2290 _("%d problems detected,"
2337 " please check your install!\n"), problems)
2291 " please check your install!\n"), problems)
2338 fm.end()
2292 fm.end()
2339
2293
2340 return problems
2294 return problems
2341
2295
2342 @command('debugknown', [], _('REPO ID...'), norepo=True)
2296 @command('debugknown', [], _('REPO ID...'), norepo=True)
2343 def debugknown(ui, repopath, *ids, **opts):
2297 def debugknown(ui, repopath, *ids, **opts):
2344 """test whether node ids are known to a repo
2298 """test whether node ids are known to a repo
2345
2299
2346 Every ID must be a full-length hex node id string. Returns a list of 0s
2300 Every ID must be a full-length hex node id string. Returns a list of 0s
2347 and 1s indicating unknown/known.
2301 and 1s indicating unknown/known.
2348 """
2302 """
2349 repo = hg.peer(ui, opts, repopath)
2303 repo = hg.peer(ui, opts, repopath)
2350 if not repo.capable('known'):
2304 if not repo.capable('known'):
2351 raise error.Abort("known() not supported by target repository")
2305 raise error.Abort("known() not supported by target repository")
2352 flags = repo.known([bin(s) for s in ids])
2306 flags = repo.known([bin(s) for s in ids])
2353 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2307 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2354
2308
2355 @command('debuglabelcomplete', [], _('LABEL...'))
2309 @command('debuglabelcomplete', [], _('LABEL...'))
2356 def debuglabelcomplete(ui, repo, *args):
2310 def debuglabelcomplete(ui, repo, *args):
2357 '''backwards compatibility with old bash completion scripts (DEPRECATED)'''
2311 '''backwards compatibility with old bash completion scripts (DEPRECATED)'''
2358 debugnamecomplete(ui, repo, *args)
2312 debugnamecomplete(ui, repo, *args)
2359
2313
2360 @command('debugmergestate', [], '')
2314 @command('debugmergestate', [], '')
2361 def debugmergestate(ui, repo, *args):
2315 def debugmergestate(ui, repo, *args):
2362 """print merge state
2316 """print merge state
2363
2317
2364 Use --verbose to print out information about whether v1 or v2 merge state
2318 Use --verbose to print out information about whether v1 or v2 merge state
2365 was chosen."""
2319 was chosen."""
2366 def _hashornull(h):
2320 def _hashornull(h):
2367 if h == nullhex:
2321 if h == nullhex:
2368 return 'null'
2322 return 'null'
2369 else:
2323 else:
2370 return h
2324 return h
2371
2325
2372 def printrecords(version):
2326 def printrecords(version):
2373 ui.write(('* version %s records\n') % version)
2327 ui.write(('* version %s records\n') % version)
2374 if version == 1:
2328 if version == 1:
2375 records = v1records
2329 records = v1records
2376 else:
2330 else:
2377 records = v2records
2331 records = v2records
2378
2332
2379 for rtype, record in records:
2333 for rtype, record in records:
2380 # pretty print some record types
2334 # pretty print some record types
2381 if rtype == 'L':
2335 if rtype == 'L':
2382 ui.write(('local: %s\n') % record)
2336 ui.write(('local: %s\n') % record)
2383 elif rtype == 'O':
2337 elif rtype == 'O':
2384 ui.write(('other: %s\n') % record)
2338 ui.write(('other: %s\n') % record)
2385 elif rtype == 'm':
2339 elif rtype == 'm':
2386 driver, mdstate = record.split('\0', 1)
2340 driver, mdstate = record.split('\0', 1)
2387 ui.write(('merge driver: %s (state "%s")\n')
2341 ui.write(('merge driver: %s (state "%s")\n')
2388 % (driver, mdstate))
2342 % (driver, mdstate))
2389 elif rtype in 'FDC':
2343 elif rtype in 'FDC':
2390 r = record.split('\0')
2344 r = record.split('\0')
2391 f, state, hash, lfile, afile, anode, ofile = r[0:7]
2345 f, state, hash, lfile, afile, anode, ofile = r[0:7]
2392 if version == 1:
2346 if version == 1:
2393 onode = 'not stored in v1 format'
2347 onode = 'not stored in v1 format'
2394 flags = r[7]
2348 flags = r[7]
2395 else:
2349 else:
2396 onode, flags = r[7:9]
2350 onode, flags = r[7:9]
2397 ui.write(('file: %s (record type "%s", state "%s", hash %s)\n')
2351 ui.write(('file: %s (record type "%s", state "%s", hash %s)\n')
2398 % (f, rtype, state, _hashornull(hash)))
2352 % (f, rtype, state, _hashornull(hash)))
2399 ui.write((' local path: %s (flags "%s")\n') % (lfile, flags))
2353 ui.write((' local path: %s (flags "%s")\n') % (lfile, flags))
2400 ui.write((' ancestor path: %s (node %s)\n')
2354 ui.write((' ancestor path: %s (node %s)\n')
2401 % (afile, _hashornull(anode)))
2355 % (afile, _hashornull(anode)))
2402 ui.write((' other path: %s (node %s)\n')
2356 ui.write((' other path: %s (node %s)\n')
2403 % (ofile, _hashornull(onode)))
2357 % (ofile, _hashornull(onode)))
2404 elif rtype == 'f':
2358 elif rtype == 'f':
2405 filename, rawextras = record.split('\0', 1)
2359 filename, rawextras = record.split('\0', 1)
2406 extras = rawextras.split('\0')
2360 extras = rawextras.split('\0')
2407 i = 0
2361 i = 0
2408 extrastrings = []
2362 extrastrings = []
2409 while i < len(extras):
2363 while i < len(extras):
2410 extrastrings.append('%s = %s' % (extras[i], extras[i + 1]))
2364 extrastrings.append('%s = %s' % (extras[i], extras[i + 1]))
2411 i += 2
2365 i += 2
2412
2366
2413 ui.write(('file extras: %s (%s)\n')
2367 ui.write(('file extras: %s (%s)\n')
2414 % (filename, ', '.join(extrastrings)))
2368 % (filename, ', '.join(extrastrings)))
2415 elif rtype == 'l':
2369 elif rtype == 'l':
2416 labels = record.split('\0', 2)
2370 labels = record.split('\0', 2)
2417 labels = [l for l in labels if len(l) > 0]
2371 labels = [l for l in labels if len(l) > 0]
2418 ui.write(('labels:\n'))
2372 ui.write(('labels:\n'))
2419 ui.write((' local: %s\n' % labels[0]))
2373 ui.write((' local: %s\n' % labels[0]))
2420 ui.write((' other: %s\n' % labels[1]))
2374 ui.write((' other: %s\n' % labels[1]))
2421 if len(labels) > 2:
2375 if len(labels) > 2:
2422 ui.write((' base: %s\n' % labels[2]))
2376 ui.write((' base: %s\n' % labels[2]))
2423 else:
2377 else:
2424 ui.write(('unrecognized entry: %s\t%s\n')
2378 ui.write(('unrecognized entry: %s\t%s\n')
2425 % (rtype, record.replace('\0', '\t')))
2379 % (rtype, record.replace('\0', '\t')))
2426
2380
2427 # Avoid mergestate.read() since it may raise an exception for unsupported
2381 # Avoid mergestate.read() since it may raise an exception for unsupported
2428 # merge state records. We shouldn't be doing this, but this is OK since this
2382 # merge state records. We shouldn't be doing this, but this is OK since this
2429 # command is pretty low-level.
2383 # command is pretty low-level.
2430 ms = mergemod.mergestate(repo)
2384 ms = mergemod.mergestate(repo)
2431
2385
2432 # sort so that reasonable information is on top
2386 # sort so that reasonable information is on top
2433 v1records = ms._readrecordsv1()
2387 v1records = ms._readrecordsv1()
2434 v2records = ms._readrecordsv2()
2388 v2records = ms._readrecordsv2()
2435 order = 'LOml'
2389 order = 'LOml'
2436 def key(r):
2390 def key(r):
2437 idx = order.find(r[0])
2391 idx = order.find(r[0])
2438 if idx == -1:
2392 if idx == -1:
2439 return (1, r[1])
2393 return (1, r[1])
2440 else:
2394 else:
2441 return (0, idx)
2395 return (0, idx)
2442 v1records.sort(key=key)
2396 v1records.sort(key=key)
2443 v2records.sort(key=key)
2397 v2records.sort(key=key)
2444
2398
2445 if not v1records and not v2records:
2399 if not v1records and not v2records:
2446 ui.write(('no merge state found\n'))
2400 ui.write(('no merge state found\n'))
2447 elif not v2records:
2401 elif not v2records:
2448 ui.note(('no version 2 merge state\n'))
2402 ui.note(('no version 2 merge state\n'))
2449 printrecords(1)
2403 printrecords(1)
2450 elif ms._v1v2match(v1records, v2records):
2404 elif ms._v1v2match(v1records, v2records):
2451 ui.note(('v1 and v2 states match: using v2\n'))
2405 ui.note(('v1 and v2 states match: using v2\n'))
2452 printrecords(2)
2406 printrecords(2)
2453 else:
2407 else:
2454 ui.note(('v1 and v2 states mismatch: using v1\n'))
2408 ui.note(('v1 and v2 states mismatch: using v1\n'))
2455 printrecords(1)
2409 printrecords(1)
2456 if ui.verbose:
2410 if ui.verbose:
2457 printrecords(2)
2411 printrecords(2)
2458
2412
2459 @command('debugnamecomplete', [], _('NAME...'))
2413 @command('debugnamecomplete', [], _('NAME...'))
2460 def debugnamecomplete(ui, repo, *args):
2414 def debugnamecomplete(ui, repo, *args):
2461 '''complete "names" - tags, open branch names, bookmark names'''
2415 '''complete "names" - tags, open branch names, bookmark names'''
2462
2416
2463 names = set()
2417 names = set()
2464 # since we previously only listed open branches, we will handle that
2418 # since we previously only listed open branches, we will handle that
2465 # specially (after this for loop)
2419 # specially (after this for loop)
2466 for name, ns in repo.names.iteritems():
2420 for name, ns in repo.names.iteritems():
2467 if name != 'branches':
2421 if name != 'branches':
2468 names.update(ns.listnames(repo))
2422 names.update(ns.listnames(repo))
2469 names.update(tag for (tag, heads, tip, closed)
2423 names.update(tag for (tag, heads, tip, closed)
2470 in repo.branchmap().iterbranches() if not closed)
2424 in repo.branchmap().iterbranches() if not closed)
2471 completions = set()
2425 completions = set()
2472 if not args:
2426 if not args:
2473 args = ['']
2427 args = ['']
2474 for a in args:
2428 for a in args:
2475 completions.update(n for n in names if n.startswith(a))
2429 completions.update(n for n in names if n.startswith(a))
2476 ui.write('\n'.join(sorted(completions)))
2430 ui.write('\n'.join(sorted(completions)))
2477 ui.write('\n')
2431 ui.write('\n')
2478
2432
2479 @command('debuglocks',
2433 @command('debuglocks',
2480 [('L', 'force-lock', None, _('free the store lock (DANGEROUS)')),
2434 [('L', 'force-lock', None, _('free the store lock (DANGEROUS)')),
2481 ('W', 'force-wlock', None,
2435 ('W', 'force-wlock', None,
2482 _('free the working state lock (DANGEROUS)'))],
2436 _('free the working state lock (DANGEROUS)'))],
2483 _('[OPTION]...'))
2437 _('[OPTION]...'))
2484 def debuglocks(ui, repo, **opts):
2438 def debuglocks(ui, repo, **opts):
2485 """show or modify state of locks
2439 """show or modify state of locks
2486
2440
2487 By default, this command will show which locks are held. This
2441 By default, this command will show which locks are held. This
2488 includes the user and process holding the lock, the amount of time
2442 includes the user and process holding the lock, the amount of time
2489 the lock has been held, and the machine name where the process is
2443 the lock has been held, and the machine name where the process is
2490 running if it's not local.
2444 running if it's not local.
2491
2445
2492 Locks protect the integrity of Mercurial's data, so should be
2446 Locks protect the integrity of Mercurial's data, so should be
2493 treated with care. System crashes or other interruptions may cause
2447 treated with care. System crashes or other interruptions may cause
2494 locks to not be properly released, though Mercurial will usually
2448 locks to not be properly released, though Mercurial will usually
2495 detect and remove such stale locks automatically.
2449 detect and remove such stale locks automatically.
2496
2450
2497 However, detecting stale locks may not always be possible (for
2451 However, detecting stale locks may not always be possible (for
2498 instance, on a shared filesystem). Removing locks may also be
2452 instance, on a shared filesystem). Removing locks may also be
2499 blocked by filesystem permissions.
2453 blocked by filesystem permissions.
2500
2454
2501 Returns 0 if no locks are held.
2455 Returns 0 if no locks are held.
2502
2456
2503 """
2457 """
2504
2458
2505 if opts.get('force_lock'):
2459 if opts.get('force_lock'):
2506 repo.svfs.unlink('lock')
2460 repo.svfs.unlink('lock')
2507 if opts.get('force_wlock'):
2461 if opts.get('force_wlock'):
2508 repo.vfs.unlink('wlock')
2462 repo.vfs.unlink('wlock')
2509 if opts.get('force_lock') or opts.get('force_lock'):
2463 if opts.get('force_lock') or opts.get('force_lock'):
2510 return 0
2464 return 0
2511
2465
2512 now = time.time()
2466 now = time.time()
2513 held = 0
2467 held = 0
2514
2468
2515 def report(vfs, name, method):
2469 def report(vfs, name, method):
2516 # this causes stale locks to get reaped for more accurate reporting
2470 # this causes stale locks to get reaped for more accurate reporting
2517 try:
2471 try:
2518 l = method(False)
2472 l = method(False)
2519 except error.LockHeld:
2473 except error.LockHeld:
2520 l = None
2474 l = None
2521
2475
2522 if l:
2476 if l:
2523 l.release()
2477 l.release()
2524 else:
2478 else:
2525 try:
2479 try:
2526 stat = vfs.lstat(name)
2480 stat = vfs.lstat(name)
2527 age = now - stat.st_mtime
2481 age = now - stat.st_mtime
2528 user = util.username(stat.st_uid)
2482 user = util.username(stat.st_uid)
2529 locker = vfs.readlock(name)
2483 locker = vfs.readlock(name)
2530 if ":" in locker:
2484 if ":" in locker:
2531 host, pid = locker.split(':')
2485 host, pid = locker.split(':')
2532 if host == socket.gethostname():
2486 if host == socket.gethostname():
2533 locker = 'user %s, process %s' % (user, pid)
2487 locker = 'user %s, process %s' % (user, pid)
2534 else:
2488 else:
2535 locker = 'user %s, process %s, host %s' \
2489 locker = 'user %s, process %s, host %s' \
2536 % (user, pid, host)
2490 % (user, pid, host)
2537 ui.write(("%-6s %s (%ds)\n") % (name + ":", locker, age))
2491 ui.write(("%-6s %s (%ds)\n") % (name + ":", locker, age))
2538 return 1
2492 return 1
2539 except OSError as e:
2493 except OSError as e:
2540 if e.errno != errno.ENOENT:
2494 if e.errno != errno.ENOENT:
2541 raise
2495 raise
2542
2496
2543 ui.write(("%-6s free\n") % (name + ":"))
2497 ui.write(("%-6s free\n") % (name + ":"))
2544 return 0
2498 return 0
2545
2499
2546 held += report(repo.svfs, "lock", repo.lock)
2500 held += report(repo.svfs, "lock", repo.lock)
2547 held += report(repo.vfs, "wlock", repo.wlock)
2501 held += report(repo.vfs, "wlock", repo.wlock)
2548
2502
2549 return held
2503 return held
2550
2504
2551 @command('debugobsolete',
2505 @command('debugobsolete',
2552 [('', 'flags', 0, _('markers flag')),
2506 [('', 'flags', 0, _('markers flag')),
2553 ('', 'record-parents', False,
2507 ('', 'record-parents', False,
2554 _('record parent information for the precursor')),
2508 _('record parent information for the precursor')),
2555 ('r', 'rev', [], _('display markers relevant to REV')),
2509 ('r', 'rev', [], _('display markers relevant to REV')),
2556 ('', 'index', False, _('display index of the marker')),
2510 ('', 'index', False, _('display index of the marker')),
2557 ('', 'delete', [], _('delete markers specified by indices')),
2511 ('', 'delete', [], _('delete markers specified by indices')),
2558 ] + commitopts2 + formatteropts,
2512 ] + commitopts2 + formatteropts,
2559 _('[OBSOLETED [REPLACEMENT ...]]'))
2513 _('[OBSOLETED [REPLACEMENT ...]]'))
2560 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2514 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2561 """create arbitrary obsolete marker
2515 """create arbitrary obsolete marker
2562
2516
2563 With no arguments, displays the list of obsolescence markers."""
2517 With no arguments, displays the list of obsolescence markers."""
2564
2518
2565 def parsenodeid(s):
2519 def parsenodeid(s):
2566 try:
2520 try:
2567 # We do not use revsingle/revrange functions here to accept
2521 # We do not use revsingle/revrange functions here to accept
2568 # arbitrary node identifiers, possibly not present in the
2522 # arbitrary node identifiers, possibly not present in the
2569 # local repository.
2523 # local repository.
2570 n = bin(s)
2524 n = bin(s)
2571 if len(n) != len(nullid):
2525 if len(n) != len(nullid):
2572 raise TypeError()
2526 raise TypeError()
2573 return n
2527 return n
2574 except TypeError:
2528 except TypeError:
2575 raise error.Abort('changeset references must be full hexadecimal '
2529 raise error.Abort('changeset references must be full hexadecimal '
2576 'node identifiers')
2530 'node identifiers')
2577
2531
2578 if opts.get('delete'):
2532 if opts.get('delete'):
2579 indices = []
2533 indices = []
2580 for v in opts.get('delete'):
2534 for v in opts.get('delete'):
2581 try:
2535 try:
2582 indices.append(int(v))
2536 indices.append(int(v))
2583 except ValueError:
2537 except ValueError:
2584 raise error.Abort(_('invalid index value: %r') % v,
2538 raise error.Abort(_('invalid index value: %r') % v,
2585 hint=_('use integers for indices'))
2539 hint=_('use integers for indices'))
2586
2540
2587 if repo.currenttransaction():
2541 if repo.currenttransaction():
2588 raise error.Abort(_('cannot delete obsmarkers in the middle '
2542 raise error.Abort(_('cannot delete obsmarkers in the middle '
2589 'of transaction.'))
2543 'of transaction.'))
2590
2544
2591 with repo.lock():
2545 with repo.lock():
2592 n = repair.deleteobsmarkers(repo.obsstore, indices)
2546 n = repair.deleteobsmarkers(repo.obsstore, indices)
2593 ui.write(_('deleted %i obsolescence markers\n') % n)
2547 ui.write(_('deleted %i obsolescence markers\n') % n)
2594
2548
2595 return
2549 return
2596
2550
2597 if precursor is not None:
2551 if precursor is not None:
2598 if opts['rev']:
2552 if opts['rev']:
2599 raise error.Abort('cannot select revision when creating marker')
2553 raise error.Abort('cannot select revision when creating marker')
2600 metadata = {}
2554 metadata = {}
2601 metadata['user'] = opts['user'] or ui.username()
2555 metadata['user'] = opts['user'] or ui.username()
2602 succs = tuple(parsenodeid(succ) for succ in successors)
2556 succs = tuple(parsenodeid(succ) for succ in successors)
2603 l = repo.lock()
2557 l = repo.lock()
2604 try:
2558 try:
2605 tr = repo.transaction('debugobsolete')
2559 tr = repo.transaction('debugobsolete')
2606 try:
2560 try:
2607 date = opts.get('date')
2561 date = opts.get('date')
2608 if date:
2562 if date:
2609 date = util.parsedate(date)
2563 date = util.parsedate(date)
2610 else:
2564 else:
2611 date = None
2565 date = None
2612 prec = parsenodeid(precursor)
2566 prec = parsenodeid(precursor)
2613 parents = None
2567 parents = None
2614 if opts['record_parents']:
2568 if opts['record_parents']:
2615 if prec not in repo.unfiltered():
2569 if prec not in repo.unfiltered():
2616 raise error.Abort('cannot used --record-parents on '
2570 raise error.Abort('cannot used --record-parents on '
2617 'unknown changesets')
2571 'unknown changesets')
2618 parents = repo.unfiltered()[prec].parents()
2572 parents = repo.unfiltered()[prec].parents()
2619 parents = tuple(p.node() for p in parents)
2573 parents = tuple(p.node() for p in parents)
2620 repo.obsstore.create(tr, prec, succs, opts['flags'],
2574 repo.obsstore.create(tr, prec, succs, opts['flags'],
2621 parents=parents, date=date,
2575 parents=parents, date=date,
2622 metadata=metadata)
2576 metadata=metadata)
2623 tr.close()
2577 tr.close()
2624 except ValueError as exc:
2578 except ValueError as exc:
2625 raise error.Abort(_('bad obsmarker input: %s') % exc)
2579 raise error.Abort(_('bad obsmarker input: %s') % exc)
2626 finally:
2580 finally:
2627 tr.release()
2581 tr.release()
2628 finally:
2582 finally:
2629 l.release()
2583 l.release()
2630 else:
2584 else:
2631 if opts['rev']:
2585 if opts['rev']:
2632 revs = scmutil.revrange(repo, opts['rev'])
2586 revs = scmutil.revrange(repo, opts['rev'])
2633 nodes = [repo[r].node() for r in revs]
2587 nodes = [repo[r].node() for r in revs]
2634 markers = list(obsolete.getmarkers(repo, nodes=nodes))
2588 markers = list(obsolete.getmarkers(repo, nodes=nodes))
2635 markers.sort(key=lambda x: x._data)
2589 markers.sort(key=lambda x: x._data)
2636 else:
2590 else:
2637 markers = obsolete.getmarkers(repo)
2591 markers = obsolete.getmarkers(repo)
2638
2592
2639 markerstoiter = markers
2593 markerstoiter = markers
2640 isrelevant = lambda m: True
2594 isrelevant = lambda m: True
2641 if opts.get('rev') and opts.get('index'):
2595 if opts.get('rev') and opts.get('index'):
2642 markerstoiter = obsolete.getmarkers(repo)
2596 markerstoiter = obsolete.getmarkers(repo)
2643 markerset = set(markers)
2597 markerset = set(markers)
2644 isrelevant = lambda m: m in markerset
2598 isrelevant = lambda m: m in markerset
2645
2599
2646 fm = ui.formatter('debugobsolete', opts)
2600 fm = ui.formatter('debugobsolete', opts)
2647 for i, m in enumerate(markerstoiter):
2601 for i, m in enumerate(markerstoiter):
2648 if not isrelevant(m):
2602 if not isrelevant(m):
2649 # marker can be irrelevant when we're iterating over a set
2603 # marker can be irrelevant when we're iterating over a set
2650 # of markers (markerstoiter) which is bigger than the set
2604 # of markers (markerstoiter) which is bigger than the set
2651 # of markers we want to display (markers)
2605 # of markers we want to display (markers)
2652 # this can happen if both --index and --rev options are
2606 # this can happen if both --index and --rev options are
2653 # provided and thus we need to iterate over all of the markers
2607 # provided and thus we need to iterate over all of the markers
2654 # to get the correct indices, but only display the ones that
2608 # to get the correct indices, but only display the ones that
2655 # are relevant to --rev value
2609 # are relevant to --rev value
2656 continue
2610 continue
2657 fm.startitem()
2611 fm.startitem()
2658 ind = i if opts.get('index') else None
2612 ind = i if opts.get('index') else None
2659 cmdutil.showmarker(fm, m, index=ind)
2613 cmdutil.showmarker(fm, m, index=ind)
2660 fm.end()
2614 fm.end()
2661
2615
2662 @command('debugpathcomplete',
2616 @command('debugpathcomplete',
2663 [('f', 'full', None, _('complete an entire path')),
2617 [('f', 'full', None, _('complete an entire path')),
2664 ('n', 'normal', None, _('show only normal files')),
2618 ('n', 'normal', None, _('show only normal files')),
2665 ('a', 'added', None, _('show only added files')),
2619 ('a', 'added', None, _('show only added files')),
2666 ('r', 'removed', None, _('show only removed files'))],
2620 ('r', 'removed', None, _('show only removed files'))],
2667 _('FILESPEC...'))
2621 _('FILESPEC...'))
2668 def debugpathcomplete(ui, repo, *specs, **opts):
2622 def debugpathcomplete(ui, repo, *specs, **opts):
2669 '''complete part or all of a tracked path
2623 '''complete part or all of a tracked path
2670
2624
2671 This command supports shells that offer path name completion. It
2625 This command supports shells that offer path name completion. It
2672 currently completes only files already known to the dirstate.
2626 currently completes only files already known to the dirstate.
2673
2627
2674 Completion extends only to the next path segment unless
2628 Completion extends only to the next path segment unless
2675 --full is specified, in which case entire paths are used.'''
2629 --full is specified, in which case entire paths are used.'''
2676
2630
2677 def complete(path, acceptable):
2631 def complete(path, acceptable):
2678 dirstate = repo.dirstate
2632 dirstate = repo.dirstate
2679 spec = os.path.normpath(os.path.join(os.getcwd(), path))
2633 spec = os.path.normpath(os.path.join(os.getcwd(), path))
2680 rootdir = repo.root + os.sep
2634 rootdir = repo.root + os.sep
2681 if spec != repo.root and not spec.startswith(rootdir):
2635 if spec != repo.root and not spec.startswith(rootdir):
2682 return [], []
2636 return [], []
2683 if os.path.isdir(spec):
2637 if os.path.isdir(spec):
2684 spec += '/'
2638 spec += '/'
2685 spec = spec[len(rootdir):]
2639 spec = spec[len(rootdir):]
2686 fixpaths = pycompat.ossep != '/'
2640 fixpaths = pycompat.ossep != '/'
2687 if fixpaths:
2641 if fixpaths:
2688 spec = spec.replace(os.sep, '/')
2642 spec = spec.replace(os.sep, '/')
2689 speclen = len(spec)
2643 speclen = len(spec)
2690 fullpaths = opts['full']
2644 fullpaths = opts['full']
2691 files, dirs = set(), set()
2645 files, dirs = set(), set()
2692 adddir, addfile = dirs.add, files.add
2646 adddir, addfile = dirs.add, files.add
2693 for f, st in dirstate.iteritems():
2647 for f, st in dirstate.iteritems():
2694 if f.startswith(spec) and st[0] in acceptable:
2648 if f.startswith(spec) and st[0] in acceptable:
2695 if fixpaths:
2649 if fixpaths:
2696 f = f.replace('/', os.sep)
2650 f = f.replace('/', os.sep)
2697 if fullpaths:
2651 if fullpaths:
2698 addfile(f)
2652 addfile(f)
2699 continue
2653 continue
2700 s = f.find(os.sep, speclen)
2654 s = f.find(os.sep, speclen)
2701 if s >= 0:
2655 if s >= 0:
2702 adddir(f[:s])
2656 adddir(f[:s])
2703 else:
2657 else:
2704 addfile(f)
2658 addfile(f)
2705 return files, dirs
2659 return files, dirs
2706
2660
2707 acceptable = ''
2661 acceptable = ''
2708 if opts['normal']:
2662 if opts['normal']:
2709 acceptable += 'nm'
2663 acceptable += 'nm'
2710 if opts['added']:
2664 if opts['added']:
2711 acceptable += 'a'
2665 acceptable += 'a'
2712 if opts['removed']:
2666 if opts['removed']:
2713 acceptable += 'r'
2667 acceptable += 'r'
2714 cwd = repo.getcwd()
2668 cwd = repo.getcwd()
2715 if not specs:
2669 if not specs:
2716 specs = ['.']
2670 specs = ['.']
2717
2671
2718 files, dirs = set(), set()
2672 files, dirs = set(), set()
2719 for spec in specs:
2673 for spec in specs:
2720 f, d = complete(spec, acceptable or 'nmar')
2674 f, d = complete(spec, acceptable or 'nmar')
2721 files.update(f)
2675 files.update(f)
2722 dirs.update(d)
2676 dirs.update(d)
2723 files.update(dirs)
2677 files.update(dirs)
2724 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2678 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2725 ui.write('\n')
2679 ui.write('\n')
2726
2680
2727 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
2681 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
2728 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2682 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2729 '''access the pushkey key/value protocol
2683 '''access the pushkey key/value protocol
2730
2684
2731 With two args, list the keys in the given namespace.
2685 With two args, list the keys in the given namespace.
2732
2686
2733 With five args, set a key to new if it currently is set to old.
2687 With five args, set a key to new if it currently is set to old.
2734 Reports success or failure.
2688 Reports success or failure.
2735 '''
2689 '''
2736
2690
2737 target = hg.peer(ui, {}, repopath)
2691 target = hg.peer(ui, {}, repopath)
2738 if keyinfo:
2692 if keyinfo:
2739 key, old, new = keyinfo
2693 key, old, new = keyinfo
2740 r = target.pushkey(namespace, key, old, new)
2694 r = target.pushkey(namespace, key, old, new)
2741 ui.status(str(r) + '\n')
2695 ui.status(str(r) + '\n')
2742 return not r
2696 return not r
2743 else:
2697 else:
2744 for k, v in sorted(target.listkeys(namespace).iteritems()):
2698 for k, v in sorted(target.listkeys(namespace).iteritems()):
2745 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2699 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2746 v.encode('string-escape')))
2700 v.encode('string-escape')))
2747
2701
2748 @command('debugpvec', [], _('A B'))
2702 @command('debugpvec', [], _('A B'))
2749 def debugpvec(ui, repo, a, b=None):
2703 def debugpvec(ui, repo, a, b=None):
2750 ca = scmutil.revsingle(repo, a)
2704 ca = scmutil.revsingle(repo, a)
2751 cb = scmutil.revsingle(repo, b)
2705 cb = scmutil.revsingle(repo, b)
2752 pa = pvec.ctxpvec(ca)
2706 pa = pvec.ctxpvec(ca)
2753 pb = pvec.ctxpvec(cb)
2707 pb = pvec.ctxpvec(cb)
2754 if pa == pb:
2708 if pa == pb:
2755 rel = "="
2709 rel = "="
2756 elif pa > pb:
2710 elif pa > pb:
2757 rel = ">"
2711 rel = ">"
2758 elif pa < pb:
2712 elif pa < pb:
2759 rel = "<"
2713 rel = "<"
2760 elif pa | pb:
2714 elif pa | pb:
2761 rel = "|"
2715 rel = "|"
2762 ui.write(_("a: %s\n") % pa)
2716 ui.write(_("a: %s\n") % pa)
2763 ui.write(_("b: %s\n") % pb)
2717 ui.write(_("b: %s\n") % pb)
2764 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2718 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2765 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2719 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2766 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2720 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2767 pa.distance(pb), rel))
2721 pa.distance(pb), rel))
2768
2722
2769 @command('debugrebuilddirstate|debugrebuildstate',
2723 @command('debugrebuilddirstate|debugrebuildstate',
2770 [('r', 'rev', '', _('revision to rebuild to'), _('REV')),
2724 [('r', 'rev', '', _('revision to rebuild to'), _('REV')),
2771 ('', 'minimal', None, _('only rebuild files that are inconsistent with '
2725 ('', 'minimal', None, _('only rebuild files that are inconsistent with '
2772 'the working copy parent')),
2726 'the working copy parent')),
2773 ],
2727 ],
2774 _('[-r REV]'))
2728 _('[-r REV]'))
2775 def debugrebuilddirstate(ui, repo, rev, **opts):
2729 def debugrebuilddirstate(ui, repo, rev, **opts):
2776 """rebuild the dirstate as it would look like for the given revision
2730 """rebuild the dirstate as it would look like for the given revision
2777
2731
2778 If no revision is specified the first current parent will be used.
2732 If no revision is specified the first current parent will be used.
2779
2733
2780 The dirstate will be set to the files of the given revision.
2734 The dirstate will be set to the files of the given revision.
2781 The actual working directory content or existing dirstate
2735 The actual working directory content or existing dirstate
2782 information such as adds or removes is not considered.
2736 information such as adds or removes is not considered.
2783
2737
2784 ``minimal`` will only rebuild the dirstate status for files that claim to be
2738 ``minimal`` will only rebuild the dirstate status for files that claim to be
2785 tracked but are not in the parent manifest, or that exist in the parent
2739 tracked but are not in the parent manifest, or that exist in the parent
2786 manifest but are not in the dirstate. It will not change adds, removes, or
2740 manifest but are not in the dirstate. It will not change adds, removes, or
2787 modified files that are in the working copy parent.
2741 modified files that are in the working copy parent.
2788
2742
2789 One use of this command is to make the next :hg:`status` invocation
2743 One use of this command is to make the next :hg:`status` invocation
2790 check the actual file content.
2744 check the actual file content.
2791 """
2745 """
2792 ctx = scmutil.revsingle(repo, rev)
2746 ctx = scmutil.revsingle(repo, rev)
2793 with repo.wlock():
2747 with repo.wlock():
2794 dirstate = repo.dirstate
2748 dirstate = repo.dirstate
2795 changedfiles = None
2749 changedfiles = None
2796 # See command doc for what minimal does.
2750 # See command doc for what minimal does.
2797 if opts.get('minimal'):
2751 if opts.get('minimal'):
2798 manifestfiles = set(ctx.manifest().keys())
2752 manifestfiles = set(ctx.manifest().keys())
2799 dirstatefiles = set(dirstate)
2753 dirstatefiles = set(dirstate)
2800 manifestonly = manifestfiles - dirstatefiles
2754 manifestonly = manifestfiles - dirstatefiles
2801 dsonly = dirstatefiles - manifestfiles
2755 dsonly = dirstatefiles - manifestfiles
2802 dsnotadded = set(f for f in dsonly if dirstate[f] != 'a')
2756 dsnotadded = set(f for f in dsonly if dirstate[f] != 'a')
2803 changedfiles = manifestonly | dsnotadded
2757 changedfiles = manifestonly | dsnotadded
2804
2758
2805 dirstate.rebuild(ctx.node(), ctx.manifest(), changedfiles)
2759 dirstate.rebuild(ctx.node(), ctx.manifest(), changedfiles)
2806
2760
2807 @command('debugrebuildfncache', [], '')
2761 @command('debugrebuildfncache', [], '')
2808 def debugrebuildfncache(ui, repo):
2762 def debugrebuildfncache(ui, repo):
2809 """rebuild the fncache file"""
2763 """rebuild the fncache file"""
2810 repair.rebuildfncache(ui, repo)
2764 repair.rebuildfncache(ui, repo)
2811
2765
2812 @command('debugrename',
2766 @command('debugrename',
2813 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2767 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2814 _('[-r REV] FILE'))
2768 _('[-r REV] FILE'))
2815 def debugrename(ui, repo, file1, *pats, **opts):
2769 def debugrename(ui, repo, file1, *pats, **opts):
2816 """dump rename information"""
2770 """dump rename information"""
2817
2771
2818 ctx = scmutil.revsingle(repo, opts.get('rev'))
2772 ctx = scmutil.revsingle(repo, opts.get('rev'))
2819 m = scmutil.match(ctx, (file1,) + pats, opts)
2773 m = scmutil.match(ctx, (file1,) + pats, opts)
2820 for abs in ctx.walk(m):
2774 for abs in ctx.walk(m):
2821 fctx = ctx[abs]
2775 fctx = ctx[abs]
2822 o = fctx.filelog().renamed(fctx.filenode())
2776 o = fctx.filelog().renamed(fctx.filenode())
2823 rel = m.rel(abs)
2777 rel = m.rel(abs)
2824 if o:
2778 if o:
2825 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2779 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2826 else:
2780 else:
2827 ui.write(_("%s not renamed\n") % rel)
2781 ui.write(_("%s not renamed\n") % rel)
2828
2782
2829 @command('debugrevlog', debugrevlogopts +
2783 @command('debugrevlog', debugrevlogopts +
2830 [('d', 'dump', False, _('dump index data'))],
2784 [('d', 'dump', False, _('dump index data'))],
2831 _('-c|-m|FILE'),
2785 _('-c|-m|FILE'),
2832 optionalrepo=True)
2786 optionalrepo=True)
2833 def debugrevlog(ui, repo, file_=None, **opts):
2787 def debugrevlog(ui, repo, file_=None, **opts):
2834 """show data and statistics about a revlog"""
2788 """show data and statistics about a revlog"""
2835 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2789 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2836
2790
2837 if opts.get("dump"):
2791 if opts.get("dump"):
2838 numrevs = len(r)
2792 numrevs = len(r)
2839 ui.write(("# rev p1rev p2rev start end deltastart base p1 p2"
2793 ui.write(("# rev p1rev p2rev start end deltastart base p1 p2"
2840 " rawsize totalsize compression heads chainlen\n"))
2794 " rawsize totalsize compression heads chainlen\n"))
2841 ts = 0
2795 ts = 0
2842 heads = set()
2796 heads = set()
2843
2797
2844 for rev in xrange(numrevs):
2798 for rev in xrange(numrevs):
2845 dbase = r.deltaparent(rev)
2799 dbase = r.deltaparent(rev)
2846 if dbase == -1:
2800 if dbase == -1:
2847 dbase = rev
2801 dbase = rev
2848 cbase = r.chainbase(rev)
2802 cbase = r.chainbase(rev)
2849 clen = r.chainlen(rev)
2803 clen = r.chainlen(rev)
2850 p1, p2 = r.parentrevs(rev)
2804 p1, p2 = r.parentrevs(rev)
2851 rs = r.rawsize(rev)
2805 rs = r.rawsize(rev)
2852 ts = ts + rs
2806 ts = ts + rs
2853 heads -= set(r.parentrevs(rev))
2807 heads -= set(r.parentrevs(rev))
2854 heads.add(rev)
2808 heads.add(rev)
2855 try:
2809 try:
2856 compression = ts / r.end(rev)
2810 compression = ts / r.end(rev)
2857 except ZeroDivisionError:
2811 except ZeroDivisionError:
2858 compression = 0
2812 compression = 0
2859 ui.write("%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d "
2813 ui.write("%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d "
2860 "%11d %5d %8d\n" %
2814 "%11d %5d %8d\n" %
2861 (rev, p1, p2, r.start(rev), r.end(rev),
2815 (rev, p1, p2, r.start(rev), r.end(rev),
2862 r.start(dbase), r.start(cbase),
2816 r.start(dbase), r.start(cbase),
2863 r.start(p1), r.start(p2),
2817 r.start(p1), r.start(p2),
2864 rs, ts, compression, len(heads), clen))
2818 rs, ts, compression, len(heads), clen))
2865 return 0
2819 return 0
2866
2820
2867 v = r.version
2821 v = r.version
2868 format = v & 0xFFFF
2822 format = v & 0xFFFF
2869 flags = []
2823 flags = []
2870 gdelta = False
2824 gdelta = False
2871 if v & revlog.REVLOGNGINLINEDATA:
2825 if v & revlog.REVLOGNGINLINEDATA:
2872 flags.append('inline')
2826 flags.append('inline')
2873 if v & revlog.REVLOGGENERALDELTA:
2827 if v & revlog.REVLOGGENERALDELTA:
2874 gdelta = True
2828 gdelta = True
2875 flags.append('generaldelta')
2829 flags.append('generaldelta')
2876 if not flags:
2830 if not flags:
2877 flags = ['(none)']
2831 flags = ['(none)']
2878
2832
2879 nummerges = 0
2833 nummerges = 0
2880 numfull = 0
2834 numfull = 0
2881 numprev = 0
2835 numprev = 0
2882 nump1 = 0
2836 nump1 = 0
2883 nump2 = 0
2837 nump2 = 0
2884 numother = 0
2838 numother = 0
2885 nump1prev = 0
2839 nump1prev = 0
2886 nump2prev = 0
2840 nump2prev = 0
2887 chainlengths = []
2841 chainlengths = []
2888
2842
2889 datasize = [None, 0, 0]
2843 datasize = [None, 0, 0]
2890 fullsize = [None, 0, 0]
2844 fullsize = [None, 0, 0]
2891 deltasize = [None, 0, 0]
2845 deltasize = [None, 0, 0]
2892 chunktypecounts = {}
2846 chunktypecounts = {}
2893 chunktypesizes = {}
2847 chunktypesizes = {}
2894
2848
2895 def addsize(size, l):
2849 def addsize(size, l):
2896 if l[0] is None or size < l[0]:
2850 if l[0] is None or size < l[0]:
2897 l[0] = size
2851 l[0] = size
2898 if size > l[1]:
2852 if size > l[1]:
2899 l[1] = size
2853 l[1] = size
2900 l[2] += size
2854 l[2] += size
2901
2855
2902 numrevs = len(r)
2856 numrevs = len(r)
2903 for rev in xrange(numrevs):
2857 for rev in xrange(numrevs):
2904 p1, p2 = r.parentrevs(rev)
2858 p1, p2 = r.parentrevs(rev)
2905 delta = r.deltaparent(rev)
2859 delta = r.deltaparent(rev)
2906 if format > 0:
2860 if format > 0:
2907 addsize(r.rawsize(rev), datasize)
2861 addsize(r.rawsize(rev), datasize)
2908 if p2 != nullrev:
2862 if p2 != nullrev:
2909 nummerges += 1
2863 nummerges += 1
2910 size = r.length(rev)
2864 size = r.length(rev)
2911 if delta == nullrev:
2865 if delta == nullrev:
2912 chainlengths.append(0)
2866 chainlengths.append(0)
2913 numfull += 1
2867 numfull += 1
2914 addsize(size, fullsize)
2868 addsize(size, fullsize)
2915 else:
2869 else:
2916 chainlengths.append(chainlengths[delta] + 1)
2870 chainlengths.append(chainlengths[delta] + 1)
2917 addsize(size, deltasize)
2871 addsize(size, deltasize)
2918 if delta == rev - 1:
2872 if delta == rev - 1:
2919 numprev += 1
2873 numprev += 1
2920 if delta == p1:
2874 if delta == p1:
2921 nump1prev += 1
2875 nump1prev += 1
2922 elif delta == p2:
2876 elif delta == p2:
2923 nump2prev += 1
2877 nump2prev += 1
2924 elif delta == p1:
2878 elif delta == p1:
2925 nump1 += 1
2879 nump1 += 1
2926 elif delta == p2:
2880 elif delta == p2:
2927 nump2 += 1
2881 nump2 += 1
2928 elif delta != nullrev:
2882 elif delta != nullrev:
2929 numother += 1
2883 numother += 1
2930
2884
2931 # Obtain data on the raw chunks in the revlog.
2885 # Obtain data on the raw chunks in the revlog.
2932 chunk = r._chunkraw(rev, rev)[1]
2886 chunk = r._chunkraw(rev, rev)[1]
2933 if chunk:
2887 if chunk:
2934 chunktype = chunk[0]
2888 chunktype = chunk[0]
2935 else:
2889 else:
2936 chunktype = 'empty'
2890 chunktype = 'empty'
2937
2891
2938 if chunktype not in chunktypecounts:
2892 if chunktype not in chunktypecounts:
2939 chunktypecounts[chunktype] = 0
2893 chunktypecounts[chunktype] = 0
2940 chunktypesizes[chunktype] = 0
2894 chunktypesizes[chunktype] = 0
2941
2895
2942 chunktypecounts[chunktype] += 1
2896 chunktypecounts[chunktype] += 1
2943 chunktypesizes[chunktype] += size
2897 chunktypesizes[chunktype] += size
2944
2898
2945 # Adjust size min value for empty cases
2899 # Adjust size min value for empty cases
2946 for size in (datasize, fullsize, deltasize):
2900 for size in (datasize, fullsize, deltasize):
2947 if size[0] is None:
2901 if size[0] is None:
2948 size[0] = 0
2902 size[0] = 0
2949
2903
2950 numdeltas = numrevs - numfull
2904 numdeltas = numrevs - numfull
2951 numoprev = numprev - nump1prev - nump2prev
2905 numoprev = numprev - nump1prev - nump2prev
2952 totalrawsize = datasize[2]
2906 totalrawsize = datasize[2]
2953 datasize[2] /= numrevs
2907 datasize[2] /= numrevs
2954 fulltotal = fullsize[2]
2908 fulltotal = fullsize[2]
2955 fullsize[2] /= numfull
2909 fullsize[2] /= numfull
2956 deltatotal = deltasize[2]
2910 deltatotal = deltasize[2]
2957 if numrevs - numfull > 0:
2911 if numrevs - numfull > 0:
2958 deltasize[2] /= numrevs - numfull
2912 deltasize[2] /= numrevs - numfull
2959 totalsize = fulltotal + deltatotal
2913 totalsize = fulltotal + deltatotal
2960 avgchainlen = sum(chainlengths) / numrevs
2914 avgchainlen = sum(chainlengths) / numrevs
2961 maxchainlen = max(chainlengths)
2915 maxchainlen = max(chainlengths)
2962 compratio = 1
2916 compratio = 1
2963 if totalsize:
2917 if totalsize:
2964 compratio = totalrawsize / totalsize
2918 compratio = totalrawsize / totalsize
2965
2919
2966 basedfmtstr = '%%%dd\n'
2920 basedfmtstr = '%%%dd\n'
2967 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2921 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2968
2922
2969 def dfmtstr(max):
2923 def dfmtstr(max):
2970 return basedfmtstr % len(str(max))
2924 return basedfmtstr % len(str(max))
2971 def pcfmtstr(max, padding=0):
2925 def pcfmtstr(max, padding=0):
2972 return basepcfmtstr % (len(str(max)), ' ' * padding)
2926 return basepcfmtstr % (len(str(max)), ' ' * padding)
2973
2927
2974 def pcfmt(value, total):
2928 def pcfmt(value, total):
2975 if total:
2929 if total:
2976 return (value, 100 * float(value) / total)
2930 return (value, 100 * float(value) / total)
2977 else:
2931 else:
2978 return value, 100.0
2932 return value, 100.0
2979
2933
2980 ui.write(('format : %d\n') % format)
2934 ui.write(('format : %d\n') % format)
2981 ui.write(('flags : %s\n') % ', '.join(flags))
2935 ui.write(('flags : %s\n') % ', '.join(flags))
2982
2936
2983 ui.write('\n')
2937 ui.write('\n')
2984 fmt = pcfmtstr(totalsize)
2938 fmt = pcfmtstr(totalsize)
2985 fmt2 = dfmtstr(totalsize)
2939 fmt2 = dfmtstr(totalsize)
2986 ui.write(('revisions : ') + fmt2 % numrevs)
2940 ui.write(('revisions : ') + fmt2 % numrevs)
2987 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2941 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2988 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2942 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2989 ui.write(('revisions : ') + fmt2 % numrevs)
2943 ui.write(('revisions : ') + fmt2 % numrevs)
2990 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2944 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2991 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2945 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2992 ui.write(('revision size : ') + fmt2 % totalsize)
2946 ui.write(('revision size : ') + fmt2 % totalsize)
2993 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2947 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2994 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2948 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2995
2949
2996 def fmtchunktype(chunktype):
2950 def fmtchunktype(chunktype):
2997 if chunktype == 'empty':
2951 if chunktype == 'empty':
2998 return ' %s : ' % chunktype
2952 return ' %s : ' % chunktype
2999 elif chunktype in string.ascii_letters:
2953 elif chunktype in string.ascii_letters:
3000 return ' 0x%s (%s) : ' % (hex(chunktype), chunktype)
2954 return ' 0x%s (%s) : ' % (hex(chunktype), chunktype)
3001 else:
2955 else:
3002 return ' 0x%s : ' % hex(chunktype)
2956 return ' 0x%s : ' % hex(chunktype)
3003
2957
3004 ui.write('\n')
2958 ui.write('\n')
3005 ui.write(('chunks : ') + fmt2 % numrevs)
2959 ui.write(('chunks : ') + fmt2 % numrevs)
3006 for chunktype in sorted(chunktypecounts):
2960 for chunktype in sorted(chunktypecounts):
3007 ui.write(fmtchunktype(chunktype))
2961 ui.write(fmtchunktype(chunktype))
3008 ui.write(fmt % pcfmt(chunktypecounts[chunktype], numrevs))
2962 ui.write(fmt % pcfmt(chunktypecounts[chunktype], numrevs))
3009 ui.write(('chunks size : ') + fmt2 % totalsize)
2963 ui.write(('chunks size : ') + fmt2 % totalsize)
3010 for chunktype in sorted(chunktypecounts):
2964 for chunktype in sorted(chunktypecounts):
3011 ui.write(fmtchunktype(chunktype))
2965 ui.write(fmtchunktype(chunktype))
3012 ui.write(fmt % pcfmt(chunktypesizes[chunktype], totalsize))
2966 ui.write(fmt % pcfmt(chunktypesizes[chunktype], totalsize))
3013
2967
3014 ui.write('\n')
2968 ui.write('\n')
3015 fmt = dfmtstr(max(avgchainlen, compratio))
2969 fmt = dfmtstr(max(avgchainlen, compratio))
3016 ui.write(('avg chain length : ') + fmt % avgchainlen)
2970 ui.write(('avg chain length : ') + fmt % avgchainlen)
3017 ui.write(('max chain length : ') + fmt % maxchainlen)
2971 ui.write(('max chain length : ') + fmt % maxchainlen)
3018 ui.write(('compression ratio : ') + fmt % compratio)
2972 ui.write(('compression ratio : ') + fmt % compratio)
3019
2973
3020 if format > 0:
2974 if format > 0:
3021 ui.write('\n')
2975 ui.write('\n')
3022 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
2976 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
3023 % tuple(datasize))
2977 % tuple(datasize))
3024 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
2978 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
3025 % tuple(fullsize))
2979 % tuple(fullsize))
3026 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
2980 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
3027 % tuple(deltasize))
2981 % tuple(deltasize))
3028
2982
3029 if numdeltas > 0:
2983 if numdeltas > 0:
3030 ui.write('\n')
2984 ui.write('\n')
3031 fmt = pcfmtstr(numdeltas)
2985 fmt = pcfmtstr(numdeltas)
3032 fmt2 = pcfmtstr(numdeltas, 4)
2986 fmt2 = pcfmtstr(numdeltas, 4)
3033 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
2987 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
3034 if numprev > 0:
2988 if numprev > 0:
3035 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
2989 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
3036 numprev))
2990 numprev))
3037 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
2991 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
3038 numprev))
2992 numprev))
3039 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
2993 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
3040 numprev))
2994 numprev))
3041 if gdelta:
2995 if gdelta:
3042 ui.write(('deltas against p1 : ')
2996 ui.write(('deltas against p1 : ')
3043 + fmt % pcfmt(nump1, numdeltas))
2997 + fmt % pcfmt(nump1, numdeltas))
3044 ui.write(('deltas against p2 : ')
2998 ui.write(('deltas against p2 : ')
3045 + fmt % pcfmt(nump2, numdeltas))
2999 + fmt % pcfmt(nump2, numdeltas))
3046 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
3000 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
3047 numdeltas))
3001 numdeltas))
3048
3002
3049 @command('debugrevspec',
3003 @command('debugrevspec',
3050 [('', 'optimize', None,
3004 [('', 'optimize', None,
3051 _('print parsed tree after optimizing (DEPRECATED)')),
3005 _('print parsed tree after optimizing (DEPRECATED)')),
3052 ('p', 'show-stage', [],
3006 ('p', 'show-stage', [],
3053 _('print parsed tree at the given stage'), _('NAME')),
3007 _('print parsed tree at the given stage'), _('NAME')),
3054 ('', 'no-optimized', False, _('evaluate tree without optimization')),
3008 ('', 'no-optimized', False, _('evaluate tree without optimization')),
3055 ('', 'verify-optimized', False, _('verify optimized result')),
3009 ('', 'verify-optimized', False, _('verify optimized result')),
3056 ],
3010 ],
3057 ('REVSPEC'))
3011 ('REVSPEC'))
3058 def debugrevspec(ui, repo, expr, **opts):
3012 def debugrevspec(ui, repo, expr, **opts):
3059 """parse and apply a revision specification
3013 """parse and apply a revision specification
3060
3014
3061 Use -p/--show-stage option to print the parsed tree at the given stages.
3015 Use -p/--show-stage option to print the parsed tree at the given stages.
3062 Use -p all to print tree at every stage.
3016 Use -p all to print tree at every stage.
3063
3017
3064 Use --verify-optimized to compare the optimized result with the unoptimized
3018 Use --verify-optimized to compare the optimized result with the unoptimized
3065 one. Returns 1 if the optimized result differs.
3019 one. Returns 1 if the optimized result differs.
3066 """
3020 """
3067 stages = [
3021 stages = [
3068 ('parsed', lambda tree: tree),
3022 ('parsed', lambda tree: tree),
3069 ('expanded', lambda tree: revset.expandaliases(ui, tree)),
3023 ('expanded', lambda tree: revset.expandaliases(ui, tree)),
3070 ('concatenated', revset.foldconcat),
3024 ('concatenated', revset.foldconcat),
3071 ('analyzed', revset.analyze),
3025 ('analyzed', revset.analyze),
3072 ('optimized', revset.optimize),
3026 ('optimized', revset.optimize),
3073 ]
3027 ]
3074 if opts['no_optimized']:
3028 if opts['no_optimized']:
3075 stages = stages[:-1]
3029 stages = stages[:-1]
3076 if opts['verify_optimized'] and opts['no_optimized']:
3030 if opts['verify_optimized'] and opts['no_optimized']:
3077 raise error.Abort(_('cannot use --verify-optimized with '
3031 raise error.Abort(_('cannot use --verify-optimized with '
3078 '--no-optimized'))
3032 '--no-optimized'))
3079 stagenames = set(n for n, f in stages)
3033 stagenames = set(n for n, f in stages)
3080
3034
3081 showalways = set()
3035 showalways = set()
3082 showchanged = set()
3036 showchanged = set()
3083 if ui.verbose and not opts['show_stage']:
3037 if ui.verbose and not opts['show_stage']:
3084 # show parsed tree by --verbose (deprecated)
3038 # show parsed tree by --verbose (deprecated)
3085 showalways.add('parsed')
3039 showalways.add('parsed')
3086 showchanged.update(['expanded', 'concatenated'])
3040 showchanged.update(['expanded', 'concatenated'])
3087 if opts['optimize']:
3041 if opts['optimize']:
3088 showalways.add('optimized')
3042 showalways.add('optimized')
3089 if opts['show_stage'] and opts['optimize']:
3043 if opts['show_stage'] and opts['optimize']:
3090 raise error.Abort(_('cannot use --optimize with --show-stage'))
3044 raise error.Abort(_('cannot use --optimize with --show-stage'))
3091 if opts['show_stage'] == ['all']:
3045 if opts['show_stage'] == ['all']:
3092 showalways.update(stagenames)
3046 showalways.update(stagenames)
3093 else:
3047 else:
3094 for n in opts['show_stage']:
3048 for n in opts['show_stage']:
3095 if n not in stagenames:
3049 if n not in stagenames:
3096 raise error.Abort(_('invalid stage name: %s') % n)
3050 raise error.Abort(_('invalid stage name: %s') % n)
3097 showalways.update(opts['show_stage'])
3051 showalways.update(opts['show_stage'])
3098
3052
3099 treebystage = {}
3053 treebystage = {}
3100 printedtree = None
3054 printedtree = None
3101 tree = revset.parse(expr, lookup=repo.__contains__)
3055 tree = revset.parse(expr, lookup=repo.__contains__)
3102 for n, f in stages:
3056 for n, f in stages:
3103 treebystage[n] = tree = f(tree)
3057 treebystage[n] = tree = f(tree)
3104 if n in showalways or (n in showchanged and tree != printedtree):
3058 if n in showalways or (n in showchanged and tree != printedtree):
3105 if opts['show_stage'] or n != 'parsed':
3059 if opts['show_stage'] or n != 'parsed':
3106 ui.write(("* %s:\n") % n)
3060 ui.write(("* %s:\n") % n)
3107 ui.write(revset.prettyformat(tree), "\n")
3061 ui.write(revset.prettyformat(tree), "\n")
3108 printedtree = tree
3062 printedtree = tree
3109
3063
3110 if opts['verify_optimized']:
3064 if opts['verify_optimized']:
3111 arevs = revset.makematcher(treebystage['analyzed'])(repo)
3065 arevs = revset.makematcher(treebystage['analyzed'])(repo)
3112 brevs = revset.makematcher(treebystage['optimized'])(repo)
3066 brevs = revset.makematcher(treebystage['optimized'])(repo)
3113 if ui.verbose:
3067 if ui.verbose:
3114 ui.note(("* analyzed set:\n"), revset.prettyformatset(arevs), "\n")
3068 ui.note(("* analyzed set:\n"), revset.prettyformatset(arevs), "\n")
3115 ui.note(("* optimized set:\n"), revset.prettyformatset(brevs), "\n")
3069 ui.note(("* optimized set:\n"), revset.prettyformatset(brevs), "\n")
3116 arevs = list(arevs)
3070 arevs = list(arevs)
3117 brevs = list(brevs)
3071 brevs = list(brevs)
3118 if arevs == brevs:
3072 if arevs == brevs:
3119 return 0
3073 return 0
3120 ui.write(('--- analyzed\n'), label='diff.file_a')
3074 ui.write(('--- analyzed\n'), label='diff.file_a')
3121 ui.write(('+++ optimized\n'), label='diff.file_b')
3075 ui.write(('+++ optimized\n'), label='diff.file_b')
3122 sm = difflib.SequenceMatcher(None, arevs, brevs)
3076 sm = difflib.SequenceMatcher(None, arevs, brevs)
3123 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3077 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3124 if tag in ('delete', 'replace'):
3078 if tag in ('delete', 'replace'):
3125 for c in arevs[alo:ahi]:
3079 for c in arevs[alo:ahi]:
3126 ui.write('-%s\n' % c, label='diff.deleted')
3080 ui.write('-%s\n' % c, label='diff.deleted')
3127 if tag in ('insert', 'replace'):
3081 if tag in ('insert', 'replace'):
3128 for c in brevs[blo:bhi]:
3082 for c in brevs[blo:bhi]:
3129 ui.write('+%s\n' % c, label='diff.inserted')
3083 ui.write('+%s\n' % c, label='diff.inserted')
3130 if tag == 'equal':
3084 if tag == 'equal':
3131 for c in arevs[alo:ahi]:
3085 for c in arevs[alo:ahi]:
3132 ui.write(' %s\n' % c)
3086 ui.write(' %s\n' % c)
3133 return 1
3087 return 1
3134
3088
3135 func = revset.makematcher(tree)
3089 func = revset.makematcher(tree)
3136 revs = func(repo)
3090 revs = func(repo)
3137 if ui.verbose:
3091 if ui.verbose:
3138 ui.note(("* set:\n"), revset.prettyformatset(revs), "\n")
3092 ui.note(("* set:\n"), revset.prettyformatset(revs), "\n")
3139 for c in revs:
3093 for c in revs:
3140 ui.write("%s\n" % c)
3094 ui.write("%s\n" % c)
3141
3095
3142 @command('debugsetparents', [], _('REV1 [REV2]'))
3096 @command('debugsetparents', [], _('REV1 [REV2]'))
3143 def debugsetparents(ui, repo, rev1, rev2=None):
3097 def debugsetparents(ui, repo, rev1, rev2=None):
3144 """manually set the parents of the current working directory
3098 """manually set the parents of the current working directory
3145
3099
3146 This is useful for writing repository conversion tools, but should
3100 This is useful for writing repository conversion tools, but should
3147 be used with care. For example, neither the working directory nor the
3101 be used with care. For example, neither the working directory nor the
3148 dirstate is updated, so file status may be incorrect after running this
3102 dirstate is updated, so file status may be incorrect after running this
3149 command.
3103 command.
3150
3104
3151 Returns 0 on success.
3105 Returns 0 on success.
3152 """
3106 """
3153
3107
3154 r1 = scmutil.revsingle(repo, rev1).node()
3108 r1 = scmutil.revsingle(repo, rev1).node()
3155 r2 = scmutil.revsingle(repo, rev2, 'null').node()
3109 r2 = scmutil.revsingle(repo, rev2, 'null').node()
3156
3110
3157 with repo.wlock():
3111 with repo.wlock():
3158 repo.setparents(r1, r2)
3112 repo.setparents(r1, r2)
3159
3113
3160 @command('debugdirstate|debugstate',
3114 @command('debugdirstate|debugstate',
3161 [('', 'nodates', None, _('do not display the saved mtime')),
3115 [('', 'nodates', None, _('do not display the saved mtime')),
3162 ('', 'datesort', None, _('sort by saved mtime'))],
3116 ('', 'datesort', None, _('sort by saved mtime'))],
3163 _('[OPTION]...'))
3117 _('[OPTION]...'))
3164 def debugstate(ui, repo, **opts):
3118 def debugstate(ui, repo, **opts):
3165 """show the contents of the current dirstate"""
3119 """show the contents of the current dirstate"""
3166
3120
3167 nodates = opts.get('nodates')
3121 nodates = opts.get('nodates')
3168 datesort = opts.get('datesort')
3122 datesort = opts.get('datesort')
3169
3123
3170 timestr = ""
3124 timestr = ""
3171 if datesort:
3125 if datesort:
3172 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
3126 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
3173 else:
3127 else:
3174 keyfunc = None # sort by filename
3128 keyfunc = None # sort by filename
3175 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
3129 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
3176 if ent[3] == -1:
3130 if ent[3] == -1:
3177 timestr = 'unset '
3131 timestr = 'unset '
3178 elif nodates:
3132 elif nodates:
3179 timestr = 'set '
3133 timestr = 'set '
3180 else:
3134 else:
3181 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
3135 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
3182 time.localtime(ent[3]))
3136 time.localtime(ent[3]))
3183 if ent[1] & 0o20000:
3137 if ent[1] & 0o20000:
3184 mode = 'lnk'
3138 mode = 'lnk'
3185 else:
3139 else:
3186 mode = '%3o' % (ent[1] & 0o777 & ~util.umask)
3140 mode = '%3o' % (ent[1] & 0o777 & ~util.umask)
3187 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
3141 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
3188 for f in repo.dirstate.copies():
3142 for f in repo.dirstate.copies():
3189 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
3143 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
3190
3144
3191 @command('debugsub',
3145 @command('debugsub',
3192 [('r', 'rev', '',
3146 [('r', 'rev', '',
3193 _('revision to check'), _('REV'))],
3147 _('revision to check'), _('REV'))],
3194 _('[-r REV] [REV]'))
3148 _('[-r REV] [REV]'))
3195 def debugsub(ui, repo, rev=None):
3149 def debugsub(ui, repo, rev=None):
3196 ctx = scmutil.revsingle(repo, rev, None)
3150 ctx = scmutil.revsingle(repo, rev, None)
3197 for k, v in sorted(ctx.substate.items()):
3151 for k, v in sorted(ctx.substate.items()):
3198 ui.write(('path %s\n') % k)
3152 ui.write(('path %s\n') % k)
3199 ui.write((' source %s\n') % v[0])
3153 ui.write((' source %s\n') % v[0])
3200 ui.write((' revision %s\n') % v[1])
3154 ui.write((' revision %s\n') % v[1])
3201
3155
3202 @command('debugsuccessorssets',
3156 @command('debugsuccessorssets',
3203 [],
3157 [],
3204 _('[REV]'))
3158 _('[REV]'))
3205 def debugsuccessorssets(ui, repo, *revs):
3159 def debugsuccessorssets(ui, repo, *revs):
3206 """show set of successors for revision
3160 """show set of successors for revision
3207
3161
3208 A successors set of changeset A is a consistent group of revisions that
3162 A successors set of changeset A is a consistent group of revisions that
3209 succeed A. It contains non-obsolete changesets only.
3163 succeed A. It contains non-obsolete changesets only.
3210
3164
3211 In most cases a changeset A has a single successors set containing a single
3165 In most cases a changeset A has a single successors set containing a single
3212 successor (changeset A replaced by A').
3166 successor (changeset A replaced by A').
3213
3167
3214 A changeset that is made obsolete with no successors are called "pruned".
3168 A changeset that is made obsolete with no successors are called "pruned".
3215 Such changesets have no successors sets at all.
3169 Such changesets have no successors sets at all.
3216
3170
3217 A changeset that has been "split" will have a successors set containing
3171 A changeset that has been "split" will have a successors set containing
3218 more than one successor.
3172 more than one successor.
3219
3173
3220 A changeset that has been rewritten in multiple different ways is called
3174 A changeset that has been rewritten in multiple different ways is called
3221 "divergent". Such changesets have multiple successor sets (each of which
3175 "divergent". Such changesets have multiple successor sets (each of which
3222 may also be split, i.e. have multiple successors).
3176 may also be split, i.e. have multiple successors).
3223
3177
3224 Results are displayed as follows::
3178 Results are displayed as follows::
3225
3179
3226 <rev1>
3180 <rev1>
3227 <successors-1A>
3181 <successors-1A>
3228 <rev2>
3182 <rev2>
3229 <successors-2A>
3183 <successors-2A>
3230 <successors-2B1> <successors-2B2> <successors-2B3>
3184 <successors-2B1> <successors-2B2> <successors-2B3>
3231
3185
3232 Here rev2 has two possible (i.e. divergent) successors sets. The first
3186 Here rev2 has two possible (i.e. divergent) successors sets. The first
3233 holds one element, whereas the second holds three (i.e. the changeset has
3187 holds one element, whereas the second holds three (i.e. the changeset has
3234 been split).
3188 been split).
3235 """
3189 """
3236 # passed to successorssets caching computation from one call to another
3190 # passed to successorssets caching computation from one call to another
3237 cache = {}
3191 cache = {}
3238 ctx2str = str
3192 ctx2str = str
3239 node2str = short
3193 node2str = short
3240 if ui.debug():
3194 if ui.debug():
3241 def ctx2str(ctx):
3195 def ctx2str(ctx):
3242 return ctx.hex()
3196 return ctx.hex()
3243 node2str = hex
3197 node2str = hex
3244 for rev in scmutil.revrange(repo, revs):
3198 for rev in scmutil.revrange(repo, revs):
3245 ctx = repo[rev]
3199 ctx = repo[rev]
3246 ui.write('%s\n'% ctx2str(ctx))
3200 ui.write('%s\n'% ctx2str(ctx))
3247 for succsset in obsolete.successorssets(repo, ctx.node(), cache):
3201 for succsset in obsolete.successorssets(repo, ctx.node(), cache):
3248 if succsset:
3202 if succsset:
3249 ui.write(' ')
3203 ui.write(' ')
3250 ui.write(node2str(succsset[0]))
3204 ui.write(node2str(succsset[0]))
3251 for node in succsset[1:]:
3205 for node in succsset[1:]:
3252 ui.write(' ')
3206 ui.write(' ')
3253 ui.write(node2str(node))
3207 ui.write(node2str(node))
3254 ui.write('\n')
3208 ui.write('\n')
3255
3209
3256 @command('debugtemplate',
3210 @command('debugtemplate',
3257 [('r', 'rev', [], _('apply template on changesets'), _('REV')),
3211 [('r', 'rev', [], _('apply template on changesets'), _('REV')),
3258 ('D', 'define', [], _('define template keyword'), _('KEY=VALUE'))],
3212 ('D', 'define', [], _('define template keyword'), _('KEY=VALUE'))],
3259 _('[-r REV]... [-D KEY=VALUE]... TEMPLATE'),
3213 _('[-r REV]... [-D KEY=VALUE]... TEMPLATE'),
3260 optionalrepo=True)
3214 optionalrepo=True)
3261 def debugtemplate(ui, repo, tmpl, **opts):
3215 def debugtemplate(ui, repo, tmpl, **opts):
3262 """parse and apply a template
3216 """parse and apply a template
3263
3217
3264 If -r/--rev is given, the template is processed as a log template and
3218 If -r/--rev is given, the template is processed as a log template and
3265 applied to the given changesets. Otherwise, it is processed as a generic
3219 applied to the given changesets. Otherwise, it is processed as a generic
3266 template.
3220 template.
3267
3221
3268 Use --verbose to print the parsed tree.
3222 Use --verbose to print the parsed tree.
3269 """
3223 """
3270 revs = None
3224 revs = None
3271 if opts['rev']:
3225 if opts['rev']:
3272 if repo is None:
3226 if repo is None:
3273 raise error.RepoError(_('there is no Mercurial repository here '
3227 raise error.RepoError(_('there is no Mercurial repository here '
3274 '(.hg not found)'))
3228 '(.hg not found)'))
3275 revs = scmutil.revrange(repo, opts['rev'])
3229 revs = scmutil.revrange(repo, opts['rev'])
3276
3230
3277 props = {}
3231 props = {}
3278 for d in opts['define']:
3232 for d in opts['define']:
3279 try:
3233 try:
3280 k, v = (e.strip() for e in d.split('=', 1))
3234 k, v = (e.strip() for e in d.split('=', 1))
3281 if not k:
3235 if not k:
3282 raise ValueError
3236 raise ValueError
3283 props[k] = v
3237 props[k] = v
3284 except ValueError:
3238 except ValueError:
3285 raise error.Abort(_('malformed keyword definition: %s') % d)
3239 raise error.Abort(_('malformed keyword definition: %s') % d)
3286
3240
3287 if ui.verbose:
3241 if ui.verbose:
3288 aliases = ui.configitems('templatealias')
3242 aliases = ui.configitems('templatealias')
3289 tree = templater.parse(tmpl)
3243 tree = templater.parse(tmpl)
3290 ui.note(templater.prettyformat(tree), '\n')
3244 ui.note(templater.prettyformat(tree), '\n')
3291 newtree = templater.expandaliases(tree, aliases)
3245 newtree = templater.expandaliases(tree, aliases)
3292 if newtree != tree:
3246 if newtree != tree:
3293 ui.note(("* expanded:\n"), templater.prettyformat(newtree), '\n')
3247 ui.note(("* expanded:\n"), templater.prettyformat(newtree), '\n')
3294
3248
3295 mapfile = None
3249 mapfile = None
3296 if revs is None:
3250 if revs is None:
3297 k = 'debugtemplate'
3251 k = 'debugtemplate'
3298 t = formatter.maketemplater(ui, k, tmpl)
3252 t = formatter.maketemplater(ui, k, tmpl)
3299 ui.write(templater.stringify(t(k, **props)))
3253 ui.write(templater.stringify(t(k, **props)))
3300 else:
3254 else:
3301 displayer = cmdutil.changeset_templater(ui, repo, None, opts, tmpl,
3255 displayer = cmdutil.changeset_templater(ui, repo, None, opts, tmpl,
3302 mapfile, buffered=False)
3256 mapfile, buffered=False)
3303 for r in revs:
3257 for r in revs:
3304 displayer.show(repo[r], **props)
3258 displayer.show(repo[r], **props)
3305 displayer.close()
3259 displayer.close()
3306
3260
3307 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'), inferrepo=True)
3261 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'), inferrepo=True)
3308 def debugwalk(ui, repo, *pats, **opts):
3262 def debugwalk(ui, repo, *pats, **opts):
3309 """show how files match on given patterns"""
3263 """show how files match on given patterns"""
3310 m = scmutil.match(repo[None], pats, opts)
3264 m = scmutil.match(repo[None], pats, opts)
3311 items = list(repo.walk(m))
3265 items = list(repo.walk(m))
3312 if not items:
3266 if not items:
3313 return
3267 return
3314 f = lambda fn: fn
3268 f = lambda fn: fn
3315 if ui.configbool('ui', 'slash') and pycompat.ossep != '/':
3269 if ui.configbool('ui', 'slash') and pycompat.ossep != '/':
3316 f = lambda fn: util.normpath(fn)
3270 f = lambda fn: util.normpath(fn)
3317 fmt = 'f %%-%ds %%-%ds %%s' % (
3271 fmt = 'f %%-%ds %%-%ds %%s' % (
3318 max([len(abs) for abs in items]),
3272 max([len(abs) for abs in items]),
3319 max([len(m.rel(abs)) for abs in items]))
3273 max([len(m.rel(abs)) for abs in items]))
3320 for abs in items:
3274 for abs in items:
3321 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
3275 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
3322 ui.write("%s\n" % line.rstrip())
3276 ui.write("%s\n" % line.rstrip())
3323
3277
3324 @command('debugwireargs',
3278 @command('debugwireargs',
3325 [('', 'three', '', 'three'),
3279 [('', 'three', '', 'three'),
3326 ('', 'four', '', 'four'),
3280 ('', 'four', '', 'four'),
3327 ('', 'five', '', 'five'),
3281 ('', 'five', '', 'five'),
3328 ] + remoteopts,
3282 ] + remoteopts,
3329 _('REPO [OPTIONS]... [ONE [TWO]]'),
3283 _('REPO [OPTIONS]... [ONE [TWO]]'),
3330 norepo=True)
3284 norepo=True)
3331 def debugwireargs(ui, repopath, *vals, **opts):
3285 def debugwireargs(ui, repopath, *vals, **opts):
3332 repo = hg.peer(ui, opts, repopath)
3286 repo = hg.peer(ui, opts, repopath)
3333 for opt in remoteopts:
3287 for opt in remoteopts:
3334 del opts[opt[1]]
3288 del opts[opt[1]]
3335 args = {}
3289 args = {}
3336 for k, v in opts.iteritems():
3290 for k, v in opts.iteritems():
3337 if v:
3291 if v:
3338 args[k] = v
3292 args[k] = v
3339 # run twice to check that we don't mess up the stream for the next command
3293 # run twice to check that we don't mess up the stream for the next command
3340 res1 = repo.debugwireargs(*vals, **args)
3294 res1 = repo.debugwireargs(*vals, **args)
3341 res2 = repo.debugwireargs(*vals, **args)
3295 res2 = repo.debugwireargs(*vals, **args)
3342 ui.write("%s\n" % res1)
3296 ui.write("%s\n" % res1)
3343 if res1 != res2:
3297 if res1 != res2:
3344 ui.warn("%s\n" % res2)
3298 ui.warn("%s\n" % res2)
3345
3299
3346 @command('^diff',
3300 @command('^diff',
3347 [('r', 'rev', [], _('revision'), _('REV')),
3301 [('r', 'rev', [], _('revision'), _('REV')),
3348 ('c', 'change', '', _('change made by revision'), _('REV'))
3302 ('c', 'change', '', _('change made by revision'), _('REV'))
3349 ] + diffopts + diffopts2 + walkopts + subrepoopts,
3303 ] + diffopts + diffopts2 + walkopts + subrepoopts,
3350 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
3304 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
3351 inferrepo=True)
3305 inferrepo=True)
3352 def diff(ui, repo, *pats, **opts):
3306 def diff(ui, repo, *pats, **opts):
3353 """diff repository (or selected files)
3307 """diff repository (or selected files)
3354
3308
3355 Show differences between revisions for the specified files.
3309 Show differences between revisions for the specified files.
3356
3310
3357 Differences between files are shown using the unified diff format.
3311 Differences between files are shown using the unified diff format.
3358
3312
3359 .. note::
3313 .. note::
3360
3314
3361 :hg:`diff` may generate unexpected results for merges, as it will
3315 :hg:`diff` may generate unexpected results for merges, as it will
3362 default to comparing against the working directory's first
3316 default to comparing against the working directory's first
3363 parent changeset if no revisions are specified.
3317 parent changeset if no revisions are specified.
3364
3318
3365 When two revision arguments are given, then changes are shown
3319 When two revision arguments are given, then changes are shown
3366 between those revisions. If only one revision is specified then
3320 between those revisions. If only one revision is specified then
3367 that revision is compared to the working directory, and, when no
3321 that revision is compared to the working directory, and, when no
3368 revisions are specified, the working directory files are compared
3322 revisions are specified, the working directory files are compared
3369 to its first parent.
3323 to its first parent.
3370
3324
3371 Alternatively you can specify -c/--change with a revision to see
3325 Alternatively you can specify -c/--change with a revision to see
3372 the changes in that changeset relative to its first parent.
3326 the changes in that changeset relative to its first parent.
3373
3327
3374 Without the -a/--text option, diff will avoid generating diffs of
3328 Without the -a/--text option, diff will avoid generating diffs of
3375 files it detects as binary. With -a, diff will generate a diff
3329 files it detects as binary. With -a, diff will generate a diff
3376 anyway, probably with undesirable results.
3330 anyway, probably with undesirable results.
3377
3331
3378 Use the -g/--git option to generate diffs in the git extended diff
3332 Use the -g/--git option to generate diffs in the git extended diff
3379 format. For more information, read :hg:`help diffs`.
3333 format. For more information, read :hg:`help diffs`.
3380
3334
3381 .. container:: verbose
3335 .. container:: verbose
3382
3336
3383 Examples:
3337 Examples:
3384
3338
3385 - compare a file in the current working directory to its parent::
3339 - compare a file in the current working directory to its parent::
3386
3340
3387 hg diff foo.c
3341 hg diff foo.c
3388
3342
3389 - compare two historical versions of a directory, with rename info::
3343 - compare two historical versions of a directory, with rename info::
3390
3344
3391 hg diff --git -r 1.0:1.2 lib/
3345 hg diff --git -r 1.0:1.2 lib/
3392
3346
3393 - get change stats relative to the last change on some date::
3347 - get change stats relative to the last change on some date::
3394
3348
3395 hg diff --stat -r "date('may 2')"
3349 hg diff --stat -r "date('may 2')"
3396
3350
3397 - diff all newly-added files that contain a keyword::
3351 - diff all newly-added files that contain a keyword::
3398
3352
3399 hg diff "set:added() and grep(GNU)"
3353 hg diff "set:added() and grep(GNU)"
3400
3354
3401 - compare a revision and its parents::
3355 - compare a revision and its parents::
3402
3356
3403 hg diff -c 9353 # compare against first parent
3357 hg diff -c 9353 # compare against first parent
3404 hg diff -r 9353^:9353 # same using revset syntax
3358 hg diff -r 9353^:9353 # same using revset syntax
3405 hg diff -r 9353^2:9353 # compare against the second parent
3359 hg diff -r 9353^2:9353 # compare against the second parent
3406
3360
3407 Returns 0 on success.
3361 Returns 0 on success.
3408 """
3362 """
3409
3363
3410 revs = opts.get('rev')
3364 revs = opts.get('rev')
3411 change = opts.get('change')
3365 change = opts.get('change')
3412 stat = opts.get('stat')
3366 stat = opts.get('stat')
3413 reverse = opts.get('reverse')
3367 reverse = opts.get('reverse')
3414
3368
3415 if revs and change:
3369 if revs and change:
3416 msg = _('cannot specify --rev and --change at the same time')
3370 msg = _('cannot specify --rev and --change at the same time')
3417 raise error.Abort(msg)
3371 raise error.Abort(msg)
3418 elif change:
3372 elif change:
3419 node2 = scmutil.revsingle(repo, change, None).node()
3373 node2 = scmutil.revsingle(repo, change, None).node()
3420 node1 = repo[node2].p1().node()
3374 node1 = repo[node2].p1().node()
3421 else:
3375 else:
3422 node1, node2 = scmutil.revpair(repo, revs)
3376 node1, node2 = scmutil.revpair(repo, revs)
3423
3377
3424 if reverse:
3378 if reverse:
3425 node1, node2 = node2, node1
3379 node1, node2 = node2, node1
3426
3380
3427 diffopts = patch.diffallopts(ui, opts)
3381 diffopts = patch.diffallopts(ui, opts)
3428 m = scmutil.match(repo[node2], pats, opts)
3382 m = scmutil.match(repo[node2], pats, opts)
3429 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
3383 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
3430 listsubrepos=opts.get('subrepos'),
3384 listsubrepos=opts.get('subrepos'),
3431 root=opts.get('root'))
3385 root=opts.get('root'))
3432
3386
3433 @command('^export',
3387 @command('^export',
3434 [('o', 'output', '',
3388 [('o', 'output', '',
3435 _('print output to file with formatted name'), _('FORMAT')),
3389 _('print output to file with formatted name'), _('FORMAT')),
3436 ('', 'switch-parent', None, _('diff against the second parent')),
3390 ('', 'switch-parent', None, _('diff against the second parent')),
3437 ('r', 'rev', [], _('revisions to export'), _('REV')),
3391 ('r', 'rev', [], _('revisions to export'), _('REV')),
3438 ] + diffopts,
3392 ] + diffopts,
3439 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
3393 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
3440 def export(ui, repo, *changesets, **opts):
3394 def export(ui, repo, *changesets, **opts):
3441 """dump the header and diffs for one or more changesets
3395 """dump the header and diffs for one or more changesets
3442
3396
3443 Print the changeset header and diffs for one or more revisions.
3397 Print the changeset header and diffs for one or more revisions.
3444 If no revision is given, the parent of the working directory is used.
3398 If no revision is given, the parent of the working directory is used.
3445
3399
3446 The information shown in the changeset header is: author, date,
3400 The information shown in the changeset header is: author, date,
3447 branch name (if non-default), changeset hash, parent(s) and commit
3401 branch name (if non-default), changeset hash, parent(s) and commit
3448 comment.
3402 comment.
3449
3403
3450 .. note::
3404 .. note::
3451
3405
3452 :hg:`export` may generate unexpected diff output for merge
3406 :hg:`export` may generate unexpected diff output for merge
3453 changesets, as it will compare the merge changeset against its
3407 changesets, as it will compare the merge changeset against its
3454 first parent only.
3408 first parent only.
3455
3409
3456 Output may be to a file, in which case the name of the file is
3410 Output may be to a file, in which case the name of the file is
3457 given using a format string. The formatting rules are as follows:
3411 given using a format string. The formatting rules are as follows:
3458
3412
3459 :``%%``: literal "%" character
3413 :``%%``: literal "%" character
3460 :``%H``: changeset hash (40 hexadecimal digits)
3414 :``%H``: changeset hash (40 hexadecimal digits)
3461 :``%N``: number of patches being generated
3415 :``%N``: number of patches being generated
3462 :``%R``: changeset revision number
3416 :``%R``: changeset revision number
3463 :``%b``: basename of the exporting repository
3417 :``%b``: basename of the exporting repository
3464 :``%h``: short-form changeset hash (12 hexadecimal digits)
3418 :``%h``: short-form changeset hash (12 hexadecimal digits)
3465 :``%m``: first line of the commit message (only alphanumeric characters)
3419 :``%m``: first line of the commit message (only alphanumeric characters)
3466 :``%n``: zero-padded sequence number, starting at 1
3420 :``%n``: zero-padded sequence number, starting at 1
3467 :``%r``: zero-padded changeset revision number
3421 :``%r``: zero-padded changeset revision number
3468
3422
3469 Without the -a/--text option, export will avoid generating diffs
3423 Without the -a/--text option, export will avoid generating diffs
3470 of files it detects as binary. With -a, export will generate a
3424 of files it detects as binary. With -a, export will generate a
3471 diff anyway, probably with undesirable results.
3425 diff anyway, probably with undesirable results.
3472
3426
3473 Use the -g/--git option to generate diffs in the git extended diff
3427 Use the -g/--git option to generate diffs in the git extended diff
3474 format. See :hg:`help diffs` for more information.
3428 format. See :hg:`help diffs` for more information.
3475
3429
3476 With the --switch-parent option, the diff will be against the
3430 With the --switch-parent option, the diff will be against the
3477 second parent. It can be useful to review a merge.
3431 second parent. It can be useful to review a merge.
3478
3432
3479 .. container:: verbose
3433 .. container:: verbose
3480
3434
3481 Examples:
3435 Examples:
3482
3436
3483 - use export and import to transplant a bugfix to the current
3437 - use export and import to transplant a bugfix to the current
3484 branch::
3438 branch::
3485
3439
3486 hg export -r 9353 | hg import -
3440 hg export -r 9353 | hg import -
3487
3441
3488 - export all the changesets between two revisions to a file with
3442 - export all the changesets between two revisions to a file with
3489 rename information::
3443 rename information::
3490
3444
3491 hg export --git -r 123:150 > changes.txt
3445 hg export --git -r 123:150 > changes.txt
3492
3446
3493 - split outgoing changes into a series of patches with
3447 - split outgoing changes into a series of patches with
3494 descriptive names::
3448 descriptive names::
3495
3449
3496 hg export -r "outgoing()" -o "%n-%m.patch"
3450 hg export -r "outgoing()" -o "%n-%m.patch"
3497
3451
3498 Returns 0 on success.
3452 Returns 0 on success.
3499 """
3453 """
3500 changesets += tuple(opts.get('rev', []))
3454 changesets += tuple(opts.get('rev', []))
3501 if not changesets:
3455 if not changesets:
3502 changesets = ['.']
3456 changesets = ['.']
3503 revs = scmutil.revrange(repo, changesets)
3457 revs = scmutil.revrange(repo, changesets)
3504 if not revs:
3458 if not revs:
3505 raise error.Abort(_("export requires at least one changeset"))
3459 raise error.Abort(_("export requires at least one changeset"))
3506 if len(revs) > 1:
3460 if len(revs) > 1:
3507 ui.note(_('exporting patches:\n'))
3461 ui.note(_('exporting patches:\n'))
3508 else:
3462 else:
3509 ui.note(_('exporting patch:\n'))
3463 ui.note(_('exporting patch:\n'))
3510 cmdutil.export(repo, revs, template=opts.get('output'),
3464 cmdutil.export(repo, revs, template=opts.get('output'),
3511 switch_parent=opts.get('switch_parent'),
3465 switch_parent=opts.get('switch_parent'),
3512 opts=patch.diffallopts(ui, opts))
3466 opts=patch.diffallopts(ui, opts))
3513
3467
3514 @command('files',
3468 @command('files',
3515 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3469 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3516 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3470 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3517 ] + walkopts + formatteropts + subrepoopts,
3471 ] + walkopts + formatteropts + subrepoopts,
3518 _('[OPTION]... [FILE]...'))
3472 _('[OPTION]... [FILE]...'))
3519 def files(ui, repo, *pats, **opts):
3473 def files(ui, repo, *pats, **opts):
3520 """list tracked files
3474 """list tracked files
3521
3475
3522 Print files under Mercurial control in the working directory or
3476 Print files under Mercurial control in the working directory or
3523 specified revision for given files (excluding removed files).
3477 specified revision for given files (excluding removed files).
3524 Files can be specified as filenames or filesets.
3478 Files can be specified as filenames or filesets.
3525
3479
3526 If no files are given to match, this command prints the names
3480 If no files are given to match, this command prints the names
3527 of all files under Mercurial control.
3481 of all files under Mercurial control.
3528
3482
3529 .. container:: verbose
3483 .. container:: verbose
3530
3484
3531 Examples:
3485 Examples:
3532
3486
3533 - list all files under the current directory::
3487 - list all files under the current directory::
3534
3488
3535 hg files .
3489 hg files .
3536
3490
3537 - shows sizes and flags for current revision::
3491 - shows sizes and flags for current revision::
3538
3492
3539 hg files -vr .
3493 hg files -vr .
3540
3494
3541 - list all files named README::
3495 - list all files named README::
3542
3496
3543 hg files -I "**/README"
3497 hg files -I "**/README"
3544
3498
3545 - list all binary files::
3499 - list all binary files::
3546
3500
3547 hg files "set:binary()"
3501 hg files "set:binary()"
3548
3502
3549 - find files containing a regular expression::
3503 - find files containing a regular expression::
3550
3504
3551 hg files "set:grep('bob')"
3505 hg files "set:grep('bob')"
3552
3506
3553 - search tracked file contents with xargs and grep::
3507 - search tracked file contents with xargs and grep::
3554
3508
3555 hg files -0 | xargs -0 grep foo
3509 hg files -0 | xargs -0 grep foo
3556
3510
3557 See :hg:`help patterns` and :hg:`help filesets` for more information
3511 See :hg:`help patterns` and :hg:`help filesets` for more information
3558 on specifying file patterns.
3512 on specifying file patterns.
3559
3513
3560 Returns 0 if a match is found, 1 otherwise.
3514 Returns 0 if a match is found, 1 otherwise.
3561
3515
3562 """
3516 """
3563 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3517 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3564
3518
3565 end = '\n'
3519 end = '\n'
3566 if opts.get('print0'):
3520 if opts.get('print0'):
3567 end = '\0'
3521 end = '\0'
3568 fmt = '%s' + end
3522 fmt = '%s' + end
3569
3523
3570 m = scmutil.match(ctx, pats, opts)
3524 m = scmutil.match(ctx, pats, opts)
3571 with ui.formatter('files', opts) as fm:
3525 with ui.formatter('files', opts) as fm:
3572 return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
3526 return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
3573
3527
3574 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
3528 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
3575 def forget(ui, repo, *pats, **opts):
3529 def forget(ui, repo, *pats, **opts):
3576 """forget the specified files on the next commit
3530 """forget the specified files on the next commit
3577
3531
3578 Mark the specified files so they will no longer be tracked
3532 Mark the specified files so they will no longer be tracked
3579 after the next commit.
3533 after the next commit.
3580
3534
3581 This only removes files from the current branch, not from the
3535 This only removes files from the current branch, not from the
3582 entire project history, and it does not delete them from the
3536 entire project history, and it does not delete them from the
3583 working directory.
3537 working directory.
3584
3538
3585 To delete the file from the working directory, see :hg:`remove`.
3539 To delete the file from the working directory, see :hg:`remove`.
3586
3540
3587 To undo a forget before the next commit, see :hg:`add`.
3541 To undo a forget before the next commit, see :hg:`add`.
3588
3542
3589 .. container:: verbose
3543 .. container:: verbose
3590
3544
3591 Examples:
3545 Examples:
3592
3546
3593 - forget newly-added binary files::
3547 - forget newly-added binary files::
3594
3548
3595 hg forget "set:added() and binary()"
3549 hg forget "set:added() and binary()"
3596
3550
3597 - forget files that would be excluded by .hgignore::
3551 - forget files that would be excluded by .hgignore::
3598
3552
3599 hg forget "set:hgignore()"
3553 hg forget "set:hgignore()"
3600
3554
3601 Returns 0 on success.
3555 Returns 0 on success.
3602 """
3556 """
3603
3557
3604 if not pats:
3558 if not pats:
3605 raise error.Abort(_('no files specified'))
3559 raise error.Abort(_('no files specified'))
3606
3560
3607 m = scmutil.match(repo[None], pats, opts)
3561 m = scmutil.match(repo[None], pats, opts)
3608 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
3562 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
3609 return rejected and 1 or 0
3563 return rejected and 1 or 0
3610
3564
3611 @command(
3565 @command(
3612 'graft',
3566 'graft',
3613 [('r', 'rev', [], _('revisions to graft'), _('REV')),
3567 [('r', 'rev', [], _('revisions to graft'), _('REV')),
3614 ('c', 'continue', False, _('resume interrupted graft')),
3568 ('c', 'continue', False, _('resume interrupted graft')),
3615 ('e', 'edit', False, _('invoke editor on commit messages')),
3569 ('e', 'edit', False, _('invoke editor on commit messages')),
3616 ('', 'log', None, _('append graft info to log message')),
3570 ('', 'log', None, _('append graft info to log message')),
3617 ('f', 'force', False, _('force graft')),
3571 ('f', 'force', False, _('force graft')),
3618 ('D', 'currentdate', False,
3572 ('D', 'currentdate', False,
3619 _('record the current date as commit date')),
3573 _('record the current date as commit date')),
3620 ('U', 'currentuser', False,
3574 ('U', 'currentuser', False,
3621 _('record the current user as committer'), _('DATE'))]
3575 _('record the current user as committer'), _('DATE'))]
3622 + commitopts2 + mergetoolopts + dryrunopts,
3576 + commitopts2 + mergetoolopts + dryrunopts,
3623 _('[OPTION]... [-r REV]... REV...'))
3577 _('[OPTION]... [-r REV]... REV...'))
3624 def graft(ui, repo, *revs, **opts):
3578 def graft(ui, repo, *revs, **opts):
3625 '''copy changes from other branches onto the current branch
3579 '''copy changes from other branches onto the current branch
3626
3580
3627 This command uses Mercurial's merge logic to copy individual
3581 This command uses Mercurial's merge logic to copy individual
3628 changes from other branches without merging branches in the
3582 changes from other branches without merging branches in the
3629 history graph. This is sometimes known as 'backporting' or
3583 history graph. This is sometimes known as 'backporting' or
3630 'cherry-picking'. By default, graft will copy user, date, and
3584 'cherry-picking'. By default, graft will copy user, date, and
3631 description from the source changesets.
3585 description from the source changesets.
3632
3586
3633 Changesets that are ancestors of the current revision, that have
3587 Changesets that are ancestors of the current revision, that have
3634 already been grafted, or that are merges will be skipped.
3588 already been grafted, or that are merges will be skipped.
3635
3589
3636 If --log is specified, log messages will have a comment appended
3590 If --log is specified, log messages will have a comment appended
3637 of the form::
3591 of the form::
3638
3592
3639 (grafted from CHANGESETHASH)
3593 (grafted from CHANGESETHASH)
3640
3594
3641 If --force is specified, revisions will be grafted even if they
3595 If --force is specified, revisions will be grafted even if they
3642 are already ancestors of or have been grafted to the destination.
3596 are already ancestors of or have been grafted to the destination.
3643 This is useful when the revisions have since been backed out.
3597 This is useful when the revisions have since been backed out.
3644
3598
3645 If a graft merge results in conflicts, the graft process is
3599 If a graft merge results in conflicts, the graft process is
3646 interrupted so that the current merge can be manually resolved.
3600 interrupted so that the current merge can be manually resolved.
3647 Once all conflicts are addressed, the graft process can be
3601 Once all conflicts are addressed, the graft process can be
3648 continued with the -c/--continue option.
3602 continued with the -c/--continue option.
3649
3603
3650 .. note::
3604 .. note::
3651
3605
3652 The -c/--continue option does not reapply earlier options, except
3606 The -c/--continue option does not reapply earlier options, except
3653 for --force.
3607 for --force.
3654
3608
3655 .. container:: verbose
3609 .. container:: verbose
3656
3610
3657 Examples:
3611 Examples:
3658
3612
3659 - copy a single change to the stable branch and edit its description::
3613 - copy a single change to the stable branch and edit its description::
3660
3614
3661 hg update stable
3615 hg update stable
3662 hg graft --edit 9393
3616 hg graft --edit 9393
3663
3617
3664 - graft a range of changesets with one exception, updating dates::
3618 - graft a range of changesets with one exception, updating dates::
3665
3619
3666 hg graft -D "2085::2093 and not 2091"
3620 hg graft -D "2085::2093 and not 2091"
3667
3621
3668 - continue a graft after resolving conflicts::
3622 - continue a graft after resolving conflicts::
3669
3623
3670 hg graft -c
3624 hg graft -c
3671
3625
3672 - show the source of a grafted changeset::
3626 - show the source of a grafted changeset::
3673
3627
3674 hg log --debug -r .
3628 hg log --debug -r .
3675
3629
3676 - show revisions sorted by date::
3630 - show revisions sorted by date::
3677
3631
3678 hg log -r "sort(all(), date)"
3632 hg log -r "sort(all(), date)"
3679
3633
3680 See :hg:`help revisions` and :hg:`help revsets` for more about
3634 See :hg:`help revisions` and :hg:`help revsets` for more about
3681 specifying revisions.
3635 specifying revisions.
3682
3636
3683 Returns 0 on successful completion.
3637 Returns 0 on successful completion.
3684 '''
3638 '''
3685 with repo.wlock():
3639 with repo.wlock():
3686 return _dograft(ui, repo, *revs, **opts)
3640 return _dograft(ui, repo, *revs, **opts)
3687
3641
3688 def _dograft(ui, repo, *revs, **opts):
3642 def _dograft(ui, repo, *revs, **opts):
3689 if revs and opts.get('rev'):
3643 if revs and opts.get('rev'):
3690 ui.warn(_('warning: inconsistent use of --rev might give unexpected '
3644 ui.warn(_('warning: inconsistent use of --rev might give unexpected '
3691 'revision ordering!\n'))
3645 'revision ordering!\n'))
3692
3646
3693 revs = list(revs)
3647 revs = list(revs)
3694 revs.extend(opts.get('rev'))
3648 revs.extend(opts.get('rev'))
3695
3649
3696 if not opts.get('user') and opts.get('currentuser'):
3650 if not opts.get('user') and opts.get('currentuser'):
3697 opts['user'] = ui.username()
3651 opts['user'] = ui.username()
3698 if not opts.get('date') and opts.get('currentdate'):
3652 if not opts.get('date') and opts.get('currentdate'):
3699 opts['date'] = "%d %d" % util.makedate()
3653 opts['date'] = "%d %d" % util.makedate()
3700
3654
3701 editor = cmdutil.getcommiteditor(editform='graft', **opts)
3655 editor = cmdutil.getcommiteditor(editform='graft', **opts)
3702
3656
3703 cont = False
3657 cont = False
3704 if opts.get('continue'):
3658 if opts.get('continue'):
3705 cont = True
3659 cont = True
3706 if revs:
3660 if revs:
3707 raise error.Abort(_("can't specify --continue and revisions"))
3661 raise error.Abort(_("can't specify --continue and revisions"))
3708 # read in unfinished revisions
3662 # read in unfinished revisions
3709 try:
3663 try:
3710 nodes = repo.vfs.read('graftstate').splitlines()
3664 nodes = repo.vfs.read('graftstate').splitlines()
3711 revs = [repo[node].rev() for node in nodes]
3665 revs = [repo[node].rev() for node in nodes]
3712 except IOError as inst:
3666 except IOError as inst:
3713 if inst.errno != errno.ENOENT:
3667 if inst.errno != errno.ENOENT:
3714 raise
3668 raise
3715 cmdutil.wrongtooltocontinue(repo, _('graft'))
3669 cmdutil.wrongtooltocontinue(repo, _('graft'))
3716 else:
3670 else:
3717 cmdutil.checkunfinished(repo)
3671 cmdutil.checkunfinished(repo)
3718 cmdutil.bailifchanged(repo)
3672 cmdutil.bailifchanged(repo)
3719 if not revs:
3673 if not revs:
3720 raise error.Abort(_('no revisions specified'))
3674 raise error.Abort(_('no revisions specified'))
3721 revs = scmutil.revrange(repo, revs)
3675 revs = scmutil.revrange(repo, revs)
3722
3676
3723 skipped = set()
3677 skipped = set()
3724 # check for merges
3678 # check for merges
3725 for rev in repo.revs('%ld and merge()', revs):
3679 for rev in repo.revs('%ld and merge()', revs):
3726 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
3680 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
3727 skipped.add(rev)
3681 skipped.add(rev)
3728 revs = [r for r in revs if r not in skipped]
3682 revs = [r for r in revs if r not in skipped]
3729 if not revs:
3683 if not revs:
3730 return -1
3684 return -1
3731
3685
3732 # Don't check in the --continue case, in effect retaining --force across
3686 # Don't check in the --continue case, in effect retaining --force across
3733 # --continues. That's because without --force, any revisions we decided to
3687 # --continues. That's because without --force, any revisions we decided to
3734 # skip would have been filtered out here, so they wouldn't have made their
3688 # skip would have been filtered out here, so they wouldn't have made their
3735 # way to the graftstate. With --force, any revisions we would have otherwise
3689 # way to the graftstate. With --force, any revisions we would have otherwise
3736 # skipped would not have been filtered out, and if they hadn't been applied
3690 # skipped would not have been filtered out, and if they hadn't been applied
3737 # already, they'd have been in the graftstate.
3691 # already, they'd have been in the graftstate.
3738 if not (cont or opts.get('force')):
3692 if not (cont or opts.get('force')):
3739 # check for ancestors of dest branch
3693 # check for ancestors of dest branch
3740 crev = repo['.'].rev()
3694 crev = repo['.'].rev()
3741 ancestors = repo.changelog.ancestors([crev], inclusive=True)
3695 ancestors = repo.changelog.ancestors([crev], inclusive=True)
3742 # XXX make this lazy in the future
3696 # XXX make this lazy in the future
3743 # don't mutate while iterating, create a copy
3697 # don't mutate while iterating, create a copy
3744 for rev in list(revs):
3698 for rev in list(revs):
3745 if rev in ancestors:
3699 if rev in ancestors:
3746 ui.warn(_('skipping ancestor revision %d:%s\n') %
3700 ui.warn(_('skipping ancestor revision %d:%s\n') %
3747 (rev, repo[rev]))
3701 (rev, repo[rev]))
3748 # XXX remove on list is slow
3702 # XXX remove on list is slow
3749 revs.remove(rev)
3703 revs.remove(rev)
3750 if not revs:
3704 if not revs:
3751 return -1
3705 return -1
3752
3706
3753 # analyze revs for earlier grafts
3707 # analyze revs for earlier grafts
3754 ids = {}
3708 ids = {}
3755 for ctx in repo.set("%ld", revs):
3709 for ctx in repo.set("%ld", revs):
3756 ids[ctx.hex()] = ctx.rev()
3710 ids[ctx.hex()] = ctx.rev()
3757 n = ctx.extra().get('source')
3711 n = ctx.extra().get('source')
3758 if n:
3712 if n:
3759 ids[n] = ctx.rev()
3713 ids[n] = ctx.rev()
3760
3714
3761 # check ancestors for earlier grafts
3715 # check ancestors for earlier grafts
3762 ui.debug('scanning for duplicate grafts\n')
3716 ui.debug('scanning for duplicate grafts\n')
3763
3717
3764 for rev in repo.changelog.findmissingrevs(revs, [crev]):
3718 for rev in repo.changelog.findmissingrevs(revs, [crev]):
3765 ctx = repo[rev]
3719 ctx = repo[rev]
3766 n = ctx.extra().get('source')
3720 n = ctx.extra().get('source')
3767 if n in ids:
3721 if n in ids:
3768 try:
3722 try:
3769 r = repo[n].rev()
3723 r = repo[n].rev()
3770 except error.RepoLookupError:
3724 except error.RepoLookupError:
3771 r = None
3725 r = None
3772 if r in revs:
3726 if r in revs:
3773 ui.warn(_('skipping revision %d:%s '
3727 ui.warn(_('skipping revision %d:%s '
3774 '(already grafted to %d:%s)\n')
3728 '(already grafted to %d:%s)\n')
3775 % (r, repo[r], rev, ctx))
3729 % (r, repo[r], rev, ctx))
3776 revs.remove(r)
3730 revs.remove(r)
3777 elif ids[n] in revs:
3731 elif ids[n] in revs:
3778 if r is None:
3732 if r is None:
3779 ui.warn(_('skipping already grafted revision %d:%s '
3733 ui.warn(_('skipping already grafted revision %d:%s '
3780 '(%d:%s also has unknown origin %s)\n')
3734 '(%d:%s also has unknown origin %s)\n')
3781 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
3735 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
3782 else:
3736 else:
3783 ui.warn(_('skipping already grafted revision %d:%s '
3737 ui.warn(_('skipping already grafted revision %d:%s '
3784 '(%d:%s also has origin %d:%s)\n')
3738 '(%d:%s also has origin %d:%s)\n')
3785 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
3739 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
3786 revs.remove(ids[n])
3740 revs.remove(ids[n])
3787 elif ctx.hex() in ids:
3741 elif ctx.hex() in ids:
3788 r = ids[ctx.hex()]
3742 r = ids[ctx.hex()]
3789 ui.warn(_('skipping already grafted revision %d:%s '
3743 ui.warn(_('skipping already grafted revision %d:%s '
3790 '(was grafted from %d:%s)\n') %
3744 '(was grafted from %d:%s)\n') %
3791 (r, repo[r], rev, ctx))
3745 (r, repo[r], rev, ctx))
3792 revs.remove(r)
3746 revs.remove(r)
3793 if not revs:
3747 if not revs:
3794 return -1
3748 return -1
3795
3749
3796 for pos, ctx in enumerate(repo.set("%ld", revs)):
3750 for pos, ctx in enumerate(repo.set("%ld", revs)):
3797 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
3751 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
3798 ctx.description().split('\n', 1)[0])
3752 ctx.description().split('\n', 1)[0])
3799 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
3753 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
3800 if names:
3754 if names:
3801 desc += ' (%s)' % ' '.join(names)
3755 desc += ' (%s)' % ' '.join(names)
3802 ui.status(_('grafting %s\n') % desc)
3756 ui.status(_('grafting %s\n') % desc)
3803 if opts.get('dry_run'):
3757 if opts.get('dry_run'):
3804 continue
3758 continue
3805
3759
3806 source = ctx.extra().get('source')
3760 source = ctx.extra().get('source')
3807 extra = {}
3761 extra = {}
3808 if source:
3762 if source:
3809 extra['source'] = source
3763 extra['source'] = source
3810 extra['intermediate-source'] = ctx.hex()
3764 extra['intermediate-source'] = ctx.hex()
3811 else:
3765 else:
3812 extra['source'] = ctx.hex()
3766 extra['source'] = ctx.hex()
3813 user = ctx.user()
3767 user = ctx.user()
3814 if opts.get('user'):
3768 if opts.get('user'):
3815 user = opts['user']
3769 user = opts['user']
3816 date = ctx.date()
3770 date = ctx.date()
3817 if opts.get('date'):
3771 if opts.get('date'):
3818 date = opts['date']
3772 date = opts['date']
3819 message = ctx.description()
3773 message = ctx.description()
3820 if opts.get('log'):
3774 if opts.get('log'):
3821 message += '\n(grafted from %s)' % ctx.hex()
3775 message += '\n(grafted from %s)' % ctx.hex()
3822
3776
3823 # we don't merge the first commit when continuing
3777 # we don't merge the first commit when continuing
3824 if not cont:
3778 if not cont:
3825 # perform the graft merge with p1(rev) as 'ancestor'
3779 # perform the graft merge with p1(rev) as 'ancestor'
3826 try:
3780 try:
3827 # ui.forcemerge is an internal variable, do not document
3781 # ui.forcemerge is an internal variable, do not document
3828 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
3782 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
3829 'graft')
3783 'graft')
3830 stats = mergemod.graft(repo, ctx, ctx.p1(),
3784 stats = mergemod.graft(repo, ctx, ctx.p1(),
3831 ['local', 'graft'])
3785 ['local', 'graft'])
3832 finally:
3786 finally:
3833 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
3787 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
3834 # report any conflicts
3788 # report any conflicts
3835 if stats and stats[3] > 0:
3789 if stats and stats[3] > 0:
3836 # write out state for --continue
3790 # write out state for --continue
3837 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
3791 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
3838 repo.vfs.write('graftstate', ''.join(nodelines))
3792 repo.vfs.write('graftstate', ''.join(nodelines))
3839 extra = ''
3793 extra = ''
3840 if opts.get('user'):
3794 if opts.get('user'):
3841 extra += ' --user %s' % util.shellquote(opts['user'])
3795 extra += ' --user %s' % util.shellquote(opts['user'])
3842 if opts.get('date'):
3796 if opts.get('date'):
3843 extra += ' --date %s' % util.shellquote(opts['date'])
3797 extra += ' --date %s' % util.shellquote(opts['date'])
3844 if opts.get('log'):
3798 if opts.get('log'):
3845 extra += ' --log'
3799 extra += ' --log'
3846 hint=_("use 'hg resolve' and 'hg graft --continue%s'") % extra
3800 hint=_("use 'hg resolve' and 'hg graft --continue%s'") % extra
3847 raise error.Abort(
3801 raise error.Abort(
3848 _("unresolved conflicts, can't continue"),
3802 _("unresolved conflicts, can't continue"),
3849 hint=hint)
3803 hint=hint)
3850 else:
3804 else:
3851 cont = False
3805 cont = False
3852
3806
3853 # commit
3807 # commit
3854 node = repo.commit(text=message, user=user,
3808 node = repo.commit(text=message, user=user,
3855 date=date, extra=extra, editor=editor)
3809 date=date, extra=extra, editor=editor)
3856 if node is None:
3810 if node is None:
3857 ui.warn(
3811 ui.warn(
3858 _('note: graft of %d:%s created no changes to commit\n') %
3812 _('note: graft of %d:%s created no changes to commit\n') %
3859 (ctx.rev(), ctx))
3813 (ctx.rev(), ctx))
3860
3814
3861 # remove state when we complete successfully
3815 # remove state when we complete successfully
3862 if not opts.get('dry_run'):
3816 if not opts.get('dry_run'):
3863 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
3817 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
3864
3818
3865 return 0
3819 return 0
3866
3820
3867 @command('grep',
3821 @command('grep',
3868 [('0', 'print0', None, _('end fields with NUL')),
3822 [('0', 'print0', None, _('end fields with NUL')),
3869 ('', 'all', None, _('print all revisions that match')),
3823 ('', 'all', None, _('print all revisions that match')),
3870 ('a', 'text', None, _('treat all files as text')),
3824 ('a', 'text', None, _('treat all files as text')),
3871 ('f', 'follow', None,
3825 ('f', 'follow', None,
3872 _('follow changeset history,'
3826 _('follow changeset history,'
3873 ' or file history across copies and renames')),
3827 ' or file history across copies and renames')),
3874 ('i', 'ignore-case', None, _('ignore case when matching')),
3828 ('i', 'ignore-case', None, _('ignore case when matching')),
3875 ('l', 'files-with-matches', None,
3829 ('l', 'files-with-matches', None,
3876 _('print only filenames and revisions that match')),
3830 _('print only filenames and revisions that match')),
3877 ('n', 'line-number', None, _('print matching line numbers')),
3831 ('n', 'line-number', None, _('print matching line numbers')),
3878 ('r', 'rev', [],
3832 ('r', 'rev', [],
3879 _('only search files changed within revision range'), _('REV')),
3833 _('only search files changed within revision range'), _('REV')),
3880 ('u', 'user', None, _('list the author (long with -v)')),
3834 ('u', 'user', None, _('list the author (long with -v)')),
3881 ('d', 'date', None, _('list the date (short with -q)')),
3835 ('d', 'date', None, _('list the date (short with -q)')),
3882 ] + formatteropts + walkopts,
3836 ] + formatteropts + walkopts,
3883 _('[OPTION]... PATTERN [FILE]...'),
3837 _('[OPTION]... PATTERN [FILE]...'),
3884 inferrepo=True)
3838 inferrepo=True)
3885 def grep(ui, repo, pattern, *pats, **opts):
3839 def grep(ui, repo, pattern, *pats, **opts):
3886 """search revision history for a pattern in specified files
3840 """search revision history for a pattern in specified files
3887
3841
3888 Search revision history for a regular expression in the specified
3842 Search revision history for a regular expression in the specified
3889 files or the entire project.
3843 files or the entire project.
3890
3844
3891 By default, grep prints the most recent revision number for each
3845 By default, grep prints the most recent revision number for each
3892 file in which it finds a match. To get it to print every revision
3846 file in which it finds a match. To get it to print every revision
3893 that contains a change in match status ("-" for a match that becomes
3847 that contains a change in match status ("-" for a match that becomes
3894 a non-match, or "+" for a non-match that becomes a match), use the
3848 a non-match, or "+" for a non-match that becomes a match), use the
3895 --all flag.
3849 --all flag.
3896
3850
3897 PATTERN can be any Python (roughly Perl-compatible) regular
3851 PATTERN can be any Python (roughly Perl-compatible) regular
3898 expression.
3852 expression.
3899
3853
3900 If no FILEs are specified (and -f/--follow isn't set), all files in
3854 If no FILEs are specified (and -f/--follow isn't set), all files in
3901 the repository are searched, including those that don't exist in the
3855 the repository are searched, including those that don't exist in the
3902 current branch or have been deleted in a prior changeset.
3856 current branch or have been deleted in a prior changeset.
3903
3857
3904 Returns 0 if a match is found, 1 otherwise.
3858 Returns 0 if a match is found, 1 otherwise.
3905 """
3859 """
3906 reflags = re.M
3860 reflags = re.M
3907 if opts.get('ignore_case'):
3861 if opts.get('ignore_case'):
3908 reflags |= re.I
3862 reflags |= re.I
3909 try:
3863 try:
3910 regexp = util.re.compile(pattern, reflags)
3864 regexp = util.re.compile(pattern, reflags)
3911 except re.error as inst:
3865 except re.error as inst:
3912 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
3866 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
3913 return 1
3867 return 1
3914 sep, eol = ':', '\n'
3868 sep, eol = ':', '\n'
3915 if opts.get('print0'):
3869 if opts.get('print0'):
3916 sep = eol = '\0'
3870 sep = eol = '\0'
3917
3871
3918 getfile = util.lrucachefunc(repo.file)
3872 getfile = util.lrucachefunc(repo.file)
3919
3873
3920 def matchlines(body):
3874 def matchlines(body):
3921 begin = 0
3875 begin = 0
3922 linenum = 0
3876 linenum = 0
3923 while begin < len(body):
3877 while begin < len(body):
3924 match = regexp.search(body, begin)
3878 match = regexp.search(body, begin)
3925 if not match:
3879 if not match:
3926 break
3880 break
3927 mstart, mend = match.span()
3881 mstart, mend = match.span()
3928 linenum += body.count('\n', begin, mstart) + 1
3882 linenum += body.count('\n', begin, mstart) + 1
3929 lstart = body.rfind('\n', begin, mstart) + 1 or begin
3883 lstart = body.rfind('\n', begin, mstart) + 1 or begin
3930 begin = body.find('\n', mend) + 1 or len(body) + 1
3884 begin = body.find('\n', mend) + 1 or len(body) + 1
3931 lend = begin - 1
3885 lend = begin - 1
3932 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
3886 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
3933
3887
3934 class linestate(object):
3888 class linestate(object):
3935 def __init__(self, line, linenum, colstart, colend):
3889 def __init__(self, line, linenum, colstart, colend):
3936 self.line = line
3890 self.line = line
3937 self.linenum = linenum
3891 self.linenum = linenum
3938 self.colstart = colstart
3892 self.colstart = colstart
3939 self.colend = colend
3893 self.colend = colend
3940
3894
3941 def __hash__(self):
3895 def __hash__(self):
3942 return hash((self.linenum, self.line))
3896 return hash((self.linenum, self.line))
3943
3897
3944 def __eq__(self, other):
3898 def __eq__(self, other):
3945 return self.line == other.line
3899 return self.line == other.line
3946
3900
3947 def findpos(self):
3901 def findpos(self):
3948 """Iterate all (start, end) indices of matches"""
3902 """Iterate all (start, end) indices of matches"""
3949 yield self.colstart, self.colend
3903 yield self.colstart, self.colend
3950 p = self.colend
3904 p = self.colend
3951 while p < len(self.line):
3905 while p < len(self.line):
3952 m = regexp.search(self.line, p)
3906 m = regexp.search(self.line, p)
3953 if not m:
3907 if not m:
3954 break
3908 break
3955 yield m.span()
3909 yield m.span()
3956 p = m.end()
3910 p = m.end()
3957
3911
3958 matches = {}
3912 matches = {}
3959 copies = {}
3913 copies = {}
3960 def grepbody(fn, rev, body):
3914 def grepbody(fn, rev, body):
3961 matches[rev].setdefault(fn, [])
3915 matches[rev].setdefault(fn, [])
3962 m = matches[rev][fn]
3916 m = matches[rev][fn]
3963 for lnum, cstart, cend, line in matchlines(body):
3917 for lnum, cstart, cend, line in matchlines(body):
3964 s = linestate(line, lnum, cstart, cend)
3918 s = linestate(line, lnum, cstart, cend)
3965 m.append(s)
3919 m.append(s)
3966
3920
3967 def difflinestates(a, b):
3921 def difflinestates(a, b):
3968 sm = difflib.SequenceMatcher(None, a, b)
3922 sm = difflib.SequenceMatcher(None, a, b)
3969 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3923 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3970 if tag == 'insert':
3924 if tag == 'insert':
3971 for i in xrange(blo, bhi):
3925 for i in xrange(blo, bhi):
3972 yield ('+', b[i])
3926 yield ('+', b[i])
3973 elif tag == 'delete':
3927 elif tag == 'delete':
3974 for i in xrange(alo, ahi):
3928 for i in xrange(alo, ahi):
3975 yield ('-', a[i])
3929 yield ('-', a[i])
3976 elif tag == 'replace':
3930 elif tag == 'replace':
3977 for i in xrange(alo, ahi):
3931 for i in xrange(alo, ahi):
3978 yield ('-', a[i])
3932 yield ('-', a[i])
3979 for i in xrange(blo, bhi):
3933 for i in xrange(blo, bhi):
3980 yield ('+', b[i])
3934 yield ('+', b[i])
3981
3935
3982 def display(fm, fn, ctx, pstates, states):
3936 def display(fm, fn, ctx, pstates, states):
3983 rev = ctx.rev()
3937 rev = ctx.rev()
3984 if fm.isplain():
3938 if fm.isplain():
3985 formatuser = ui.shortuser
3939 formatuser = ui.shortuser
3986 else:
3940 else:
3987 formatuser = str
3941 formatuser = str
3988 if ui.quiet:
3942 if ui.quiet:
3989 datefmt = '%Y-%m-%d'
3943 datefmt = '%Y-%m-%d'
3990 else:
3944 else:
3991 datefmt = '%a %b %d %H:%M:%S %Y %1%2'
3945 datefmt = '%a %b %d %H:%M:%S %Y %1%2'
3992 found = False
3946 found = False
3993 @util.cachefunc
3947 @util.cachefunc
3994 def binary():
3948 def binary():
3995 flog = getfile(fn)
3949 flog = getfile(fn)
3996 return util.binary(flog.read(ctx.filenode(fn)))
3950 return util.binary(flog.read(ctx.filenode(fn)))
3997
3951
3998 fieldnamemap = {'filename': 'file', 'linenumber': 'line_number'}
3952 fieldnamemap = {'filename': 'file', 'linenumber': 'line_number'}
3999 if opts.get('all'):
3953 if opts.get('all'):
4000 iter = difflinestates(pstates, states)
3954 iter = difflinestates(pstates, states)
4001 else:
3955 else:
4002 iter = [('', l) for l in states]
3956 iter = [('', l) for l in states]
4003 for change, l in iter:
3957 for change, l in iter:
4004 fm.startitem()
3958 fm.startitem()
4005 fm.data(node=fm.hexfunc(ctx.node()))
3959 fm.data(node=fm.hexfunc(ctx.node()))
4006 cols = [
3960 cols = [
4007 ('filename', fn, True),
3961 ('filename', fn, True),
4008 ('rev', rev, True),
3962 ('rev', rev, True),
4009 ('linenumber', l.linenum, opts.get('line_number')),
3963 ('linenumber', l.linenum, opts.get('line_number')),
4010 ]
3964 ]
4011 if opts.get('all'):
3965 if opts.get('all'):
4012 cols.append(('change', change, True))
3966 cols.append(('change', change, True))
4013 cols.extend([
3967 cols.extend([
4014 ('user', formatuser(ctx.user()), opts.get('user')),
3968 ('user', formatuser(ctx.user()), opts.get('user')),
4015 ('date', fm.formatdate(ctx.date(), datefmt), opts.get('date')),
3969 ('date', fm.formatdate(ctx.date(), datefmt), opts.get('date')),
4016 ])
3970 ])
4017 lastcol = next(name for name, data, cond in reversed(cols) if cond)
3971 lastcol = next(name for name, data, cond in reversed(cols) if cond)
4018 for name, data, cond in cols:
3972 for name, data, cond in cols:
4019 field = fieldnamemap.get(name, name)
3973 field = fieldnamemap.get(name, name)
4020 fm.condwrite(cond, field, '%s', data, label='grep.%s' % name)
3974 fm.condwrite(cond, field, '%s', data, label='grep.%s' % name)
4021 if cond and name != lastcol:
3975 if cond and name != lastcol:
4022 fm.plain(sep, label='grep.sep')
3976 fm.plain(sep, label='grep.sep')
4023 if not opts.get('files_with_matches'):
3977 if not opts.get('files_with_matches'):
4024 fm.plain(sep, label='grep.sep')
3978 fm.plain(sep, label='grep.sep')
4025 if not opts.get('text') and binary():
3979 if not opts.get('text') and binary():
4026 fm.plain(_(" Binary file matches"))
3980 fm.plain(_(" Binary file matches"))
4027 else:
3981 else:
4028 displaymatches(fm.nested('texts'), l)
3982 displaymatches(fm.nested('texts'), l)
4029 fm.plain(eol)
3983 fm.plain(eol)
4030 found = True
3984 found = True
4031 if opts.get('files_with_matches'):
3985 if opts.get('files_with_matches'):
4032 break
3986 break
4033 return found
3987 return found
4034
3988
4035 def displaymatches(fm, l):
3989 def displaymatches(fm, l):
4036 p = 0
3990 p = 0
4037 for s, e in l.findpos():
3991 for s, e in l.findpos():
4038 if p < s:
3992 if p < s:
4039 fm.startitem()
3993 fm.startitem()
4040 fm.write('text', '%s', l.line[p:s])
3994 fm.write('text', '%s', l.line[p:s])
4041 fm.data(matched=False)
3995 fm.data(matched=False)
4042 fm.startitem()
3996 fm.startitem()
4043 fm.write('text', '%s', l.line[s:e], label='grep.match')
3997 fm.write('text', '%s', l.line[s:e], label='grep.match')
4044 fm.data(matched=True)
3998 fm.data(matched=True)
4045 p = e
3999 p = e
4046 if p < len(l.line):
4000 if p < len(l.line):
4047 fm.startitem()
4001 fm.startitem()
4048 fm.write('text', '%s', l.line[p:])
4002 fm.write('text', '%s', l.line[p:])
4049 fm.data(matched=False)
4003 fm.data(matched=False)
4050 fm.end()
4004 fm.end()
4051
4005
4052 skip = {}
4006 skip = {}
4053 revfiles = {}
4007 revfiles = {}
4054 matchfn = scmutil.match(repo[None], pats, opts)
4008 matchfn = scmutil.match(repo[None], pats, opts)
4055 found = False
4009 found = False
4056 follow = opts.get('follow')
4010 follow = opts.get('follow')
4057
4011
4058 def prep(ctx, fns):
4012 def prep(ctx, fns):
4059 rev = ctx.rev()
4013 rev = ctx.rev()
4060 pctx = ctx.p1()
4014 pctx = ctx.p1()
4061 parent = pctx.rev()
4015 parent = pctx.rev()
4062 matches.setdefault(rev, {})
4016 matches.setdefault(rev, {})
4063 matches.setdefault(parent, {})
4017 matches.setdefault(parent, {})
4064 files = revfiles.setdefault(rev, [])
4018 files = revfiles.setdefault(rev, [])
4065 for fn in fns:
4019 for fn in fns:
4066 flog = getfile(fn)
4020 flog = getfile(fn)
4067 try:
4021 try:
4068 fnode = ctx.filenode(fn)
4022 fnode = ctx.filenode(fn)
4069 except error.LookupError:
4023 except error.LookupError:
4070 continue
4024 continue
4071
4025
4072 copied = flog.renamed(fnode)
4026 copied = flog.renamed(fnode)
4073 copy = follow and copied and copied[0]
4027 copy = follow and copied and copied[0]
4074 if copy:
4028 if copy:
4075 copies.setdefault(rev, {})[fn] = copy
4029 copies.setdefault(rev, {})[fn] = copy
4076 if fn in skip:
4030 if fn in skip:
4077 if copy:
4031 if copy:
4078 skip[copy] = True
4032 skip[copy] = True
4079 continue
4033 continue
4080 files.append(fn)
4034 files.append(fn)
4081
4035
4082 if fn not in matches[rev]:
4036 if fn not in matches[rev]:
4083 grepbody(fn, rev, flog.read(fnode))
4037 grepbody(fn, rev, flog.read(fnode))
4084
4038
4085 pfn = copy or fn
4039 pfn = copy or fn
4086 if pfn not in matches[parent]:
4040 if pfn not in matches[parent]:
4087 try:
4041 try:
4088 fnode = pctx.filenode(pfn)
4042 fnode = pctx.filenode(pfn)
4089 grepbody(pfn, parent, flog.read(fnode))
4043 grepbody(pfn, parent, flog.read(fnode))
4090 except error.LookupError:
4044 except error.LookupError:
4091 pass
4045 pass
4092
4046
4093 fm = ui.formatter('grep', opts)
4047 fm = ui.formatter('grep', opts)
4094 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
4048 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
4095 rev = ctx.rev()
4049 rev = ctx.rev()
4096 parent = ctx.p1().rev()
4050 parent = ctx.p1().rev()
4097 for fn in sorted(revfiles.get(rev, [])):
4051 for fn in sorted(revfiles.get(rev, [])):
4098 states = matches[rev][fn]
4052 states = matches[rev][fn]
4099 copy = copies.get(rev, {}).get(fn)
4053 copy = copies.get(rev, {}).get(fn)
4100 if fn in skip:
4054 if fn in skip:
4101 if copy:
4055 if copy:
4102 skip[copy] = True
4056 skip[copy] = True
4103 continue
4057 continue
4104 pstates = matches.get(parent, {}).get(copy or fn, [])
4058 pstates = matches.get(parent, {}).get(copy or fn, [])
4105 if pstates or states:
4059 if pstates or states:
4106 r = display(fm, fn, ctx, pstates, states)
4060 r = display(fm, fn, ctx, pstates, states)
4107 found = found or r
4061 found = found or r
4108 if r and not opts.get('all'):
4062 if r and not opts.get('all'):
4109 skip[fn] = True
4063 skip[fn] = True
4110 if copy:
4064 if copy:
4111 skip[copy] = True
4065 skip[copy] = True
4112 del matches[rev]
4066 del matches[rev]
4113 del revfiles[rev]
4067 del revfiles[rev]
4114 fm.end()
4068 fm.end()
4115
4069
4116 return not found
4070 return not found
4117
4071
4118 @command('heads',
4072 @command('heads',
4119 [('r', 'rev', '',
4073 [('r', 'rev', '',
4120 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
4074 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
4121 ('t', 'topo', False, _('show topological heads only')),
4075 ('t', 'topo', False, _('show topological heads only')),
4122 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
4076 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
4123 ('c', 'closed', False, _('show normal and closed branch heads')),
4077 ('c', 'closed', False, _('show normal and closed branch heads')),
4124 ] + templateopts,
4078 ] + templateopts,
4125 _('[-ct] [-r STARTREV] [REV]...'))
4079 _('[-ct] [-r STARTREV] [REV]...'))
4126 def heads(ui, repo, *branchrevs, **opts):
4080 def heads(ui, repo, *branchrevs, **opts):
4127 """show branch heads
4081 """show branch heads
4128
4082
4129 With no arguments, show all open branch heads in the repository.
4083 With no arguments, show all open branch heads in the repository.
4130 Branch heads are changesets that have no descendants on the
4084 Branch heads are changesets that have no descendants on the
4131 same branch. They are where development generally takes place and
4085 same branch. They are where development generally takes place and
4132 are the usual targets for update and merge operations.
4086 are the usual targets for update and merge operations.
4133
4087
4134 If one or more REVs are given, only open branch heads on the
4088 If one or more REVs are given, only open branch heads on the
4135 branches associated with the specified changesets are shown. This
4089 branches associated with the specified changesets are shown. This
4136 means that you can use :hg:`heads .` to see the heads on the
4090 means that you can use :hg:`heads .` to see the heads on the
4137 currently checked-out branch.
4091 currently checked-out branch.
4138
4092
4139 If -c/--closed is specified, also show branch heads marked closed
4093 If -c/--closed is specified, also show branch heads marked closed
4140 (see :hg:`commit --close-branch`).
4094 (see :hg:`commit --close-branch`).
4141
4095
4142 If STARTREV is specified, only those heads that are descendants of
4096 If STARTREV is specified, only those heads that are descendants of
4143 STARTREV will be displayed.
4097 STARTREV will be displayed.
4144
4098
4145 If -t/--topo is specified, named branch mechanics will be ignored and only
4099 If -t/--topo is specified, named branch mechanics will be ignored and only
4146 topological heads (changesets with no children) will be shown.
4100 topological heads (changesets with no children) will be shown.
4147
4101
4148 Returns 0 if matching heads are found, 1 if not.
4102 Returns 0 if matching heads are found, 1 if not.
4149 """
4103 """
4150
4104
4151 start = None
4105 start = None
4152 if 'rev' in opts:
4106 if 'rev' in opts:
4153 start = scmutil.revsingle(repo, opts['rev'], None).node()
4107 start = scmutil.revsingle(repo, opts['rev'], None).node()
4154
4108
4155 if opts.get('topo'):
4109 if opts.get('topo'):
4156 heads = [repo[h] for h in repo.heads(start)]
4110 heads = [repo[h] for h in repo.heads(start)]
4157 else:
4111 else:
4158 heads = []
4112 heads = []
4159 for branch in repo.branchmap():
4113 for branch in repo.branchmap():
4160 heads += repo.branchheads(branch, start, opts.get('closed'))
4114 heads += repo.branchheads(branch, start, opts.get('closed'))
4161 heads = [repo[h] for h in heads]
4115 heads = [repo[h] for h in heads]
4162
4116
4163 if branchrevs:
4117 if branchrevs:
4164 branches = set(repo[br].branch() for br in branchrevs)
4118 branches = set(repo[br].branch() for br in branchrevs)
4165 heads = [h for h in heads if h.branch() in branches]
4119 heads = [h for h in heads if h.branch() in branches]
4166
4120
4167 if opts.get('active') and branchrevs:
4121 if opts.get('active') and branchrevs:
4168 dagheads = repo.heads(start)
4122 dagheads = repo.heads(start)
4169 heads = [h for h in heads if h.node() in dagheads]
4123 heads = [h for h in heads if h.node() in dagheads]
4170
4124
4171 if branchrevs:
4125 if branchrevs:
4172 haveheads = set(h.branch() for h in heads)
4126 haveheads = set(h.branch() for h in heads)
4173 if branches - haveheads:
4127 if branches - haveheads:
4174 headless = ', '.join(b for b in branches - haveheads)
4128 headless = ', '.join(b for b in branches - haveheads)
4175 msg = _('no open branch heads found on branches %s')
4129 msg = _('no open branch heads found on branches %s')
4176 if opts.get('rev'):
4130 if opts.get('rev'):
4177 msg += _(' (started at %s)') % opts['rev']
4131 msg += _(' (started at %s)') % opts['rev']
4178 ui.warn((msg + '\n') % headless)
4132 ui.warn((msg + '\n') % headless)
4179
4133
4180 if not heads:
4134 if not heads:
4181 return 1
4135 return 1
4182
4136
4183 heads = sorted(heads, key=lambda x: -x.rev())
4137 heads = sorted(heads, key=lambda x: -x.rev())
4184 displayer = cmdutil.show_changeset(ui, repo, opts)
4138 displayer = cmdutil.show_changeset(ui, repo, opts)
4185 for ctx in heads:
4139 for ctx in heads:
4186 displayer.show(ctx)
4140 displayer.show(ctx)
4187 displayer.close()
4141 displayer.close()
4188
4142
4189 @command('help',
4143 @command('help',
4190 [('e', 'extension', None, _('show only help for extensions')),
4144 [('e', 'extension', None, _('show only help for extensions')),
4191 ('c', 'command', None, _('show only help for commands')),
4145 ('c', 'command', None, _('show only help for commands')),
4192 ('k', 'keyword', None, _('show topics matching keyword')),
4146 ('k', 'keyword', None, _('show topics matching keyword')),
4193 ('s', 'system', [], _('show help for specific platform(s)')),
4147 ('s', 'system', [], _('show help for specific platform(s)')),
4194 ],
4148 ],
4195 _('[-ecks] [TOPIC]'),
4149 _('[-ecks] [TOPIC]'),
4196 norepo=True)
4150 norepo=True)
4197 def help_(ui, name=None, **opts):
4151 def help_(ui, name=None, **opts):
4198 """show help for a given topic or a help overview
4152 """show help for a given topic or a help overview
4199
4153
4200 With no arguments, print a list of commands with short help messages.
4154 With no arguments, print a list of commands with short help messages.
4201
4155
4202 Given a topic, extension, or command name, print help for that
4156 Given a topic, extension, or command name, print help for that
4203 topic.
4157 topic.
4204
4158
4205 Returns 0 if successful.
4159 Returns 0 if successful.
4206 """
4160 """
4207
4161
4208 textwidth = ui.configint('ui', 'textwidth', 78)
4162 textwidth = ui.configint('ui', 'textwidth', 78)
4209 termwidth = ui.termwidth() - 2
4163 termwidth = ui.termwidth() - 2
4210 if textwidth <= 0 or termwidth < textwidth:
4164 if textwidth <= 0 or termwidth < textwidth:
4211 textwidth = termwidth
4165 textwidth = termwidth
4212
4166
4213 keep = opts.get('system') or []
4167 keep = opts.get('system') or []
4214 if len(keep) == 0:
4168 if len(keep) == 0:
4215 if sys.platform.startswith('win'):
4169 if sys.platform.startswith('win'):
4216 keep.append('windows')
4170 keep.append('windows')
4217 elif sys.platform == 'OpenVMS':
4171 elif sys.platform == 'OpenVMS':
4218 keep.append('vms')
4172 keep.append('vms')
4219 elif sys.platform == 'plan9':
4173 elif sys.platform == 'plan9':
4220 keep.append('plan9')
4174 keep.append('plan9')
4221 else:
4175 else:
4222 keep.append('unix')
4176 keep.append('unix')
4223 keep.append(sys.platform.lower())
4177 keep.append(sys.platform.lower())
4224 if ui.verbose:
4178 if ui.verbose:
4225 keep.append('verbose')
4179 keep.append('verbose')
4226
4180
4227 section = None
4181 section = None
4228 subtopic = None
4182 subtopic = None
4229 if name and '.' in name:
4183 if name and '.' in name:
4230 name, remaining = name.split('.', 1)
4184 name, remaining = name.split('.', 1)
4231 remaining = encoding.lower(remaining)
4185 remaining = encoding.lower(remaining)
4232 if '.' in remaining:
4186 if '.' in remaining:
4233 subtopic, section = remaining.split('.', 1)
4187 subtopic, section = remaining.split('.', 1)
4234 else:
4188 else:
4235 if name in help.subtopics:
4189 if name in help.subtopics:
4236 subtopic = remaining
4190 subtopic = remaining
4237 else:
4191 else:
4238 section = remaining
4192 section = remaining
4239
4193
4240 text = help.help_(ui, name, subtopic=subtopic, **opts)
4194 text = help.help_(ui, name, subtopic=subtopic, **opts)
4241
4195
4242 formatted, pruned = minirst.format(text, textwidth, keep=keep,
4196 formatted, pruned = minirst.format(text, textwidth, keep=keep,
4243 section=section)
4197 section=section)
4244
4198
4245 # We could have been given a weird ".foo" section without a name
4199 # We could have been given a weird ".foo" section without a name
4246 # to look for, or we could have simply failed to found "foo.bar"
4200 # to look for, or we could have simply failed to found "foo.bar"
4247 # because bar isn't a section of foo
4201 # because bar isn't a section of foo
4248 if section and not (formatted and name):
4202 if section and not (formatted and name):
4249 raise error.Abort(_("help section not found"))
4203 raise error.Abort(_("help section not found"))
4250
4204
4251 if 'verbose' in pruned:
4205 if 'verbose' in pruned:
4252 keep.append('omitted')
4206 keep.append('omitted')
4253 else:
4207 else:
4254 keep.append('notomitted')
4208 keep.append('notomitted')
4255 formatted, pruned = minirst.format(text, textwidth, keep=keep,
4209 formatted, pruned = minirst.format(text, textwidth, keep=keep,
4256 section=section)
4210 section=section)
4257 ui.write(formatted)
4211 ui.write(formatted)
4258
4212
4259
4213
4260 @command('identify|id',
4214 @command('identify|id',
4261 [('r', 'rev', '',
4215 [('r', 'rev', '',
4262 _('identify the specified revision'), _('REV')),
4216 _('identify the specified revision'), _('REV')),
4263 ('n', 'num', None, _('show local revision number')),
4217 ('n', 'num', None, _('show local revision number')),
4264 ('i', 'id', None, _('show global revision id')),
4218 ('i', 'id', None, _('show global revision id')),
4265 ('b', 'branch', None, _('show branch')),
4219 ('b', 'branch', None, _('show branch')),
4266 ('t', 'tags', None, _('show tags')),
4220 ('t', 'tags', None, _('show tags')),
4267 ('B', 'bookmarks', None, _('show bookmarks')),
4221 ('B', 'bookmarks', None, _('show bookmarks')),
4268 ] + remoteopts,
4222 ] + remoteopts,
4269 _('[-nibtB] [-r REV] [SOURCE]'),
4223 _('[-nibtB] [-r REV] [SOURCE]'),
4270 optionalrepo=True)
4224 optionalrepo=True)
4271 def identify(ui, repo, source=None, rev=None,
4225 def identify(ui, repo, source=None, rev=None,
4272 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
4226 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
4273 """identify the working directory or specified revision
4227 """identify the working directory or specified revision
4274
4228
4275 Print a summary identifying the repository state at REV using one or
4229 Print a summary identifying the repository state at REV using one or
4276 two parent hash identifiers, followed by a "+" if the working
4230 two parent hash identifiers, followed by a "+" if the working
4277 directory has uncommitted changes, the branch name (if not default),
4231 directory has uncommitted changes, the branch name (if not default),
4278 a list of tags, and a list of bookmarks.
4232 a list of tags, and a list of bookmarks.
4279
4233
4280 When REV is not given, print a summary of the current state of the
4234 When REV is not given, print a summary of the current state of the
4281 repository.
4235 repository.
4282
4236
4283 Specifying a path to a repository root or Mercurial bundle will
4237 Specifying a path to a repository root or Mercurial bundle will
4284 cause lookup to operate on that repository/bundle.
4238 cause lookup to operate on that repository/bundle.
4285
4239
4286 .. container:: verbose
4240 .. container:: verbose
4287
4241
4288 Examples:
4242 Examples:
4289
4243
4290 - generate a build identifier for the working directory::
4244 - generate a build identifier for the working directory::
4291
4245
4292 hg id --id > build-id.dat
4246 hg id --id > build-id.dat
4293
4247
4294 - find the revision corresponding to a tag::
4248 - find the revision corresponding to a tag::
4295
4249
4296 hg id -n -r 1.3
4250 hg id -n -r 1.3
4297
4251
4298 - check the most recent revision of a remote repository::
4252 - check the most recent revision of a remote repository::
4299
4253
4300 hg id -r tip https://www.mercurial-scm.org/repo/hg/
4254 hg id -r tip https://www.mercurial-scm.org/repo/hg/
4301
4255
4302 See :hg:`log` for generating more information about specific revisions,
4256 See :hg:`log` for generating more information about specific revisions,
4303 including full hash identifiers.
4257 including full hash identifiers.
4304
4258
4305 Returns 0 if successful.
4259 Returns 0 if successful.
4306 """
4260 """
4307
4261
4308 if not repo and not source:
4262 if not repo and not source:
4309 raise error.Abort(_("there is no Mercurial repository here "
4263 raise error.Abort(_("there is no Mercurial repository here "
4310 "(.hg not found)"))
4264 "(.hg not found)"))
4311
4265
4312 if ui.debugflag:
4266 if ui.debugflag:
4313 hexfunc = hex
4267 hexfunc = hex
4314 else:
4268 else:
4315 hexfunc = short
4269 hexfunc = short
4316 default = not (num or id or branch or tags or bookmarks)
4270 default = not (num or id or branch or tags or bookmarks)
4317 output = []
4271 output = []
4318 revs = []
4272 revs = []
4319
4273
4320 if source:
4274 if source:
4321 source, branches = hg.parseurl(ui.expandpath(source))
4275 source, branches = hg.parseurl(ui.expandpath(source))
4322 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
4276 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
4323 repo = peer.local()
4277 repo = peer.local()
4324 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
4278 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
4325
4279
4326 if not repo:
4280 if not repo:
4327 if num or branch or tags:
4281 if num or branch or tags:
4328 raise error.Abort(
4282 raise error.Abort(
4329 _("can't query remote revision number, branch, or tags"))
4283 _("can't query remote revision number, branch, or tags"))
4330 if not rev and revs:
4284 if not rev and revs:
4331 rev = revs[0]
4285 rev = revs[0]
4332 if not rev:
4286 if not rev:
4333 rev = "tip"
4287 rev = "tip"
4334
4288
4335 remoterev = peer.lookup(rev)
4289 remoterev = peer.lookup(rev)
4336 if default or id:
4290 if default or id:
4337 output = [hexfunc(remoterev)]
4291 output = [hexfunc(remoterev)]
4338
4292
4339 def getbms():
4293 def getbms():
4340 bms = []
4294 bms = []
4341
4295
4342 if 'bookmarks' in peer.listkeys('namespaces'):
4296 if 'bookmarks' in peer.listkeys('namespaces'):
4343 hexremoterev = hex(remoterev)
4297 hexremoterev = hex(remoterev)
4344 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
4298 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
4345 if bmr == hexremoterev]
4299 if bmr == hexremoterev]
4346
4300
4347 return sorted(bms)
4301 return sorted(bms)
4348
4302
4349 if bookmarks:
4303 if bookmarks:
4350 output.extend(getbms())
4304 output.extend(getbms())
4351 elif default and not ui.quiet:
4305 elif default and not ui.quiet:
4352 # multiple bookmarks for a single parent separated by '/'
4306 # multiple bookmarks for a single parent separated by '/'
4353 bm = '/'.join(getbms())
4307 bm = '/'.join(getbms())
4354 if bm:
4308 if bm:
4355 output.append(bm)
4309 output.append(bm)
4356 else:
4310 else:
4357 ctx = scmutil.revsingle(repo, rev, None)
4311 ctx = scmutil.revsingle(repo, rev, None)
4358
4312
4359 if ctx.rev() is None:
4313 if ctx.rev() is None:
4360 ctx = repo[None]
4314 ctx = repo[None]
4361 parents = ctx.parents()
4315 parents = ctx.parents()
4362 taglist = []
4316 taglist = []
4363 for p in parents:
4317 for p in parents:
4364 taglist.extend(p.tags())
4318 taglist.extend(p.tags())
4365
4319
4366 changed = ""
4320 changed = ""
4367 if default or id or num:
4321 if default or id or num:
4368 if (any(repo.status())
4322 if (any(repo.status())
4369 or any(ctx.sub(s).dirty() for s in ctx.substate)):
4323 or any(ctx.sub(s).dirty() for s in ctx.substate)):
4370 changed = '+'
4324 changed = '+'
4371 if default or id:
4325 if default or id:
4372 output = ["%s%s" %
4326 output = ["%s%s" %
4373 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
4327 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
4374 if num:
4328 if num:
4375 output.append("%s%s" %
4329 output.append("%s%s" %
4376 ('+'.join([str(p.rev()) for p in parents]), changed))
4330 ('+'.join([str(p.rev()) for p in parents]), changed))
4377 else:
4331 else:
4378 if default or id:
4332 if default or id:
4379 output = [hexfunc(ctx.node())]
4333 output = [hexfunc(ctx.node())]
4380 if num:
4334 if num:
4381 output.append(str(ctx.rev()))
4335 output.append(str(ctx.rev()))
4382 taglist = ctx.tags()
4336 taglist = ctx.tags()
4383
4337
4384 if default and not ui.quiet:
4338 if default and not ui.quiet:
4385 b = ctx.branch()
4339 b = ctx.branch()
4386 if b != 'default':
4340 if b != 'default':
4387 output.append("(%s)" % b)
4341 output.append("(%s)" % b)
4388
4342
4389 # multiple tags for a single parent separated by '/'
4343 # multiple tags for a single parent separated by '/'
4390 t = '/'.join(taglist)
4344 t = '/'.join(taglist)
4391 if t:
4345 if t:
4392 output.append(t)
4346 output.append(t)
4393
4347
4394 # multiple bookmarks for a single parent separated by '/'
4348 # multiple bookmarks for a single parent separated by '/'
4395 bm = '/'.join(ctx.bookmarks())
4349 bm = '/'.join(ctx.bookmarks())
4396 if bm:
4350 if bm:
4397 output.append(bm)
4351 output.append(bm)
4398 else:
4352 else:
4399 if branch:
4353 if branch:
4400 output.append(ctx.branch())
4354 output.append(ctx.branch())
4401
4355
4402 if tags:
4356 if tags:
4403 output.extend(taglist)
4357 output.extend(taglist)
4404
4358
4405 if bookmarks:
4359 if bookmarks:
4406 output.extend(ctx.bookmarks())
4360 output.extend(ctx.bookmarks())
4407
4361
4408 ui.write("%s\n" % ' '.join(output))
4362 ui.write("%s\n" % ' '.join(output))
4409
4363
4410 @command('import|patch',
4364 @command('import|patch',
4411 [('p', 'strip', 1,
4365 [('p', 'strip', 1,
4412 _('directory strip option for patch. This has the same '
4366 _('directory strip option for patch. This has the same '
4413 'meaning as the corresponding patch option'), _('NUM')),
4367 'meaning as the corresponding patch option'), _('NUM')),
4414 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
4368 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
4415 ('e', 'edit', False, _('invoke editor on commit messages')),
4369 ('e', 'edit', False, _('invoke editor on commit messages')),
4416 ('f', 'force', None,
4370 ('f', 'force', None,
4417 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
4371 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
4418 ('', 'no-commit', None,
4372 ('', 'no-commit', None,
4419 _("don't commit, just update the working directory")),
4373 _("don't commit, just update the working directory")),
4420 ('', 'bypass', None,
4374 ('', 'bypass', None,
4421 _("apply patch without touching the working directory")),
4375 _("apply patch without touching the working directory")),
4422 ('', 'partial', None,
4376 ('', 'partial', None,
4423 _('commit even if some hunks fail')),
4377 _('commit even if some hunks fail')),
4424 ('', 'exact', None,
4378 ('', 'exact', None,
4425 _('abort if patch would apply lossily')),
4379 _('abort if patch would apply lossily')),
4426 ('', 'prefix', '',
4380 ('', 'prefix', '',
4427 _('apply patch to subdirectory'), _('DIR')),
4381 _('apply patch to subdirectory'), _('DIR')),
4428 ('', 'import-branch', None,
4382 ('', 'import-branch', None,
4429 _('use any branch information in patch (implied by --exact)'))] +
4383 _('use any branch information in patch (implied by --exact)'))] +
4430 commitopts + commitopts2 + similarityopts,
4384 commitopts + commitopts2 + similarityopts,
4431 _('[OPTION]... PATCH...'))
4385 _('[OPTION]... PATCH...'))
4432 def import_(ui, repo, patch1=None, *patches, **opts):
4386 def import_(ui, repo, patch1=None, *patches, **opts):
4433 """import an ordered set of patches
4387 """import an ordered set of patches
4434
4388
4435 Import a list of patches and commit them individually (unless
4389 Import a list of patches and commit them individually (unless
4436 --no-commit is specified).
4390 --no-commit is specified).
4437
4391
4438 To read a patch from standard input, use "-" as the patch name. If
4392 To read a patch from standard input, use "-" as the patch name. If
4439 a URL is specified, the patch will be downloaded from there.
4393 a URL is specified, the patch will be downloaded from there.
4440
4394
4441 Import first applies changes to the working directory (unless
4395 Import first applies changes to the working directory (unless
4442 --bypass is specified), import will abort if there are outstanding
4396 --bypass is specified), import will abort if there are outstanding
4443 changes.
4397 changes.
4444
4398
4445 Use --bypass to apply and commit patches directly to the
4399 Use --bypass to apply and commit patches directly to the
4446 repository, without affecting the working directory. Without
4400 repository, without affecting the working directory. Without
4447 --exact, patches will be applied on top of the working directory
4401 --exact, patches will be applied on top of the working directory
4448 parent revision.
4402 parent revision.
4449
4403
4450 You can import a patch straight from a mail message. Even patches
4404 You can import a patch straight from a mail message. Even patches
4451 as attachments work (to use the body part, it must have type
4405 as attachments work (to use the body part, it must have type
4452 text/plain or text/x-patch). From and Subject headers of email
4406 text/plain or text/x-patch). From and Subject headers of email
4453 message are used as default committer and commit message. All
4407 message are used as default committer and commit message. All
4454 text/plain body parts before first diff are added to the commit
4408 text/plain body parts before first diff are added to the commit
4455 message.
4409 message.
4456
4410
4457 If the imported patch was generated by :hg:`export`, user and
4411 If the imported patch was generated by :hg:`export`, user and
4458 description from patch override values from message headers and
4412 description from patch override values from message headers and
4459 body. Values given on command line with -m/--message and -u/--user
4413 body. Values given on command line with -m/--message and -u/--user
4460 override these.
4414 override these.
4461
4415
4462 If --exact is specified, import will set the working directory to
4416 If --exact is specified, import will set the working directory to
4463 the parent of each patch before applying it, and will abort if the
4417 the parent of each patch before applying it, and will abort if the
4464 resulting changeset has a different ID than the one recorded in
4418 resulting changeset has a different ID than the one recorded in
4465 the patch. This will guard against various ways that portable
4419 the patch. This will guard against various ways that portable
4466 patch formats and mail systems might fail to transfer Mercurial
4420 patch formats and mail systems might fail to transfer Mercurial
4467 data or metadata. See :hg:`bundle` for lossless transmission.
4421 data or metadata. See :hg:`bundle` for lossless transmission.
4468
4422
4469 Use --partial to ensure a changeset will be created from the patch
4423 Use --partial to ensure a changeset will be created from the patch
4470 even if some hunks fail to apply. Hunks that fail to apply will be
4424 even if some hunks fail to apply. Hunks that fail to apply will be
4471 written to a <target-file>.rej file. Conflicts can then be resolved
4425 written to a <target-file>.rej file. Conflicts can then be resolved
4472 by hand before :hg:`commit --amend` is run to update the created
4426 by hand before :hg:`commit --amend` is run to update the created
4473 changeset. This flag exists to let people import patches that
4427 changeset. This flag exists to let people import patches that
4474 partially apply without losing the associated metadata (author,
4428 partially apply without losing the associated metadata (author,
4475 date, description, ...).
4429 date, description, ...).
4476
4430
4477 .. note::
4431 .. note::
4478
4432
4479 When no hunks apply cleanly, :hg:`import --partial` will create
4433 When no hunks apply cleanly, :hg:`import --partial` will create
4480 an empty changeset, importing only the patch metadata.
4434 an empty changeset, importing only the patch metadata.
4481
4435
4482 With -s/--similarity, hg will attempt to discover renames and
4436 With -s/--similarity, hg will attempt to discover renames and
4483 copies in the patch in the same way as :hg:`addremove`.
4437 copies in the patch in the same way as :hg:`addremove`.
4484
4438
4485 It is possible to use external patch programs to perform the patch
4439 It is possible to use external patch programs to perform the patch
4486 by setting the ``ui.patch`` configuration option. For the default
4440 by setting the ``ui.patch`` configuration option. For the default
4487 internal tool, the fuzz can also be configured via ``patch.fuzz``.
4441 internal tool, the fuzz can also be configured via ``patch.fuzz``.
4488 See :hg:`help config` for more information about configuration
4442 See :hg:`help config` for more information about configuration
4489 files and how to use these options.
4443 files and how to use these options.
4490
4444
4491 See :hg:`help dates` for a list of formats valid for -d/--date.
4445 See :hg:`help dates` for a list of formats valid for -d/--date.
4492
4446
4493 .. container:: verbose
4447 .. container:: verbose
4494
4448
4495 Examples:
4449 Examples:
4496
4450
4497 - import a traditional patch from a website and detect renames::
4451 - import a traditional patch from a website and detect renames::
4498
4452
4499 hg import -s 80 http://example.com/bugfix.patch
4453 hg import -s 80 http://example.com/bugfix.patch
4500
4454
4501 - import a changeset from an hgweb server::
4455 - import a changeset from an hgweb server::
4502
4456
4503 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
4457 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
4504
4458
4505 - import all the patches in an Unix-style mbox::
4459 - import all the patches in an Unix-style mbox::
4506
4460
4507 hg import incoming-patches.mbox
4461 hg import incoming-patches.mbox
4508
4462
4509 - attempt to exactly restore an exported changeset (not always
4463 - attempt to exactly restore an exported changeset (not always
4510 possible)::
4464 possible)::
4511
4465
4512 hg import --exact proposed-fix.patch
4466 hg import --exact proposed-fix.patch
4513
4467
4514 - use an external tool to apply a patch which is too fuzzy for
4468 - use an external tool to apply a patch which is too fuzzy for
4515 the default internal tool.
4469 the default internal tool.
4516
4470
4517 hg import --config ui.patch="patch --merge" fuzzy.patch
4471 hg import --config ui.patch="patch --merge" fuzzy.patch
4518
4472
4519 - change the default fuzzing from 2 to a less strict 7
4473 - change the default fuzzing from 2 to a less strict 7
4520
4474
4521 hg import --config ui.fuzz=7 fuzz.patch
4475 hg import --config ui.fuzz=7 fuzz.patch
4522
4476
4523 Returns 0 on success, 1 on partial success (see --partial).
4477 Returns 0 on success, 1 on partial success (see --partial).
4524 """
4478 """
4525
4479
4526 if not patch1:
4480 if not patch1:
4527 raise error.Abort(_('need at least one patch to import'))
4481 raise error.Abort(_('need at least one patch to import'))
4528
4482
4529 patches = (patch1,) + patches
4483 patches = (patch1,) + patches
4530
4484
4531 date = opts.get('date')
4485 date = opts.get('date')
4532 if date:
4486 if date:
4533 opts['date'] = util.parsedate(date)
4487 opts['date'] = util.parsedate(date)
4534
4488
4535 exact = opts.get('exact')
4489 exact = opts.get('exact')
4536 update = not opts.get('bypass')
4490 update = not opts.get('bypass')
4537 if not update and opts.get('no_commit'):
4491 if not update and opts.get('no_commit'):
4538 raise error.Abort(_('cannot use --no-commit with --bypass'))
4492 raise error.Abort(_('cannot use --no-commit with --bypass'))
4539 try:
4493 try:
4540 sim = float(opts.get('similarity') or 0)
4494 sim = float(opts.get('similarity') or 0)
4541 except ValueError:
4495 except ValueError:
4542 raise error.Abort(_('similarity must be a number'))
4496 raise error.Abort(_('similarity must be a number'))
4543 if sim < 0 or sim > 100:
4497 if sim < 0 or sim > 100:
4544 raise error.Abort(_('similarity must be between 0 and 100'))
4498 raise error.Abort(_('similarity must be between 0 and 100'))
4545 if sim and not update:
4499 if sim and not update:
4546 raise error.Abort(_('cannot use --similarity with --bypass'))
4500 raise error.Abort(_('cannot use --similarity with --bypass'))
4547 if exact:
4501 if exact:
4548 if opts.get('edit'):
4502 if opts.get('edit'):
4549 raise error.Abort(_('cannot use --exact with --edit'))
4503 raise error.Abort(_('cannot use --exact with --edit'))
4550 if opts.get('prefix'):
4504 if opts.get('prefix'):
4551 raise error.Abort(_('cannot use --exact with --prefix'))
4505 raise error.Abort(_('cannot use --exact with --prefix'))
4552
4506
4553 base = opts["base"]
4507 base = opts["base"]
4554 wlock = dsguard = lock = tr = None
4508 wlock = dsguard = lock = tr = None
4555 msgs = []
4509 msgs = []
4556 ret = 0
4510 ret = 0
4557
4511
4558
4512
4559 try:
4513 try:
4560 wlock = repo.wlock()
4514 wlock = repo.wlock()
4561
4515
4562 if update:
4516 if update:
4563 cmdutil.checkunfinished(repo)
4517 cmdutil.checkunfinished(repo)
4564 if (exact or not opts.get('force')):
4518 if (exact or not opts.get('force')):
4565 cmdutil.bailifchanged(repo)
4519 cmdutil.bailifchanged(repo)
4566
4520
4567 if not opts.get('no_commit'):
4521 if not opts.get('no_commit'):
4568 lock = repo.lock()
4522 lock = repo.lock()
4569 tr = repo.transaction('import')
4523 tr = repo.transaction('import')
4570 else:
4524 else:
4571 dsguard = dirstateguard.dirstateguard(repo, 'import')
4525 dsguard = dirstateguard.dirstateguard(repo, 'import')
4572 parents = repo[None].parents()
4526 parents = repo[None].parents()
4573 for patchurl in patches:
4527 for patchurl in patches:
4574 if patchurl == '-':
4528 if patchurl == '-':
4575 ui.status(_('applying patch from stdin\n'))
4529 ui.status(_('applying patch from stdin\n'))
4576 patchfile = ui.fin
4530 patchfile = ui.fin
4577 patchurl = 'stdin' # for error message
4531 patchurl = 'stdin' # for error message
4578 else:
4532 else:
4579 patchurl = os.path.join(base, patchurl)
4533 patchurl = os.path.join(base, patchurl)
4580 ui.status(_('applying %s\n') % patchurl)
4534 ui.status(_('applying %s\n') % patchurl)
4581 patchfile = hg.openpath(ui, patchurl)
4535 patchfile = hg.openpath(ui, patchurl)
4582
4536
4583 haspatch = False
4537 haspatch = False
4584 for hunk in patch.split(patchfile):
4538 for hunk in patch.split(patchfile):
4585 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
4539 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
4586 parents, opts,
4540 parents, opts,
4587 msgs, hg.clean)
4541 msgs, hg.clean)
4588 if msg:
4542 if msg:
4589 haspatch = True
4543 haspatch = True
4590 ui.note(msg + '\n')
4544 ui.note(msg + '\n')
4591 if update or exact:
4545 if update or exact:
4592 parents = repo[None].parents()
4546 parents = repo[None].parents()
4593 else:
4547 else:
4594 parents = [repo[node]]
4548 parents = [repo[node]]
4595 if rej:
4549 if rej:
4596 ui.write_err(_("patch applied partially\n"))
4550 ui.write_err(_("patch applied partially\n"))
4597 ui.write_err(_("(fix the .rej files and run "
4551 ui.write_err(_("(fix the .rej files and run "
4598 "`hg commit --amend`)\n"))
4552 "`hg commit --amend`)\n"))
4599 ret = 1
4553 ret = 1
4600 break
4554 break
4601
4555
4602 if not haspatch:
4556 if not haspatch:
4603 raise error.Abort(_('%s: no diffs found') % patchurl)
4557 raise error.Abort(_('%s: no diffs found') % patchurl)
4604
4558
4605 if tr:
4559 if tr:
4606 tr.close()
4560 tr.close()
4607 if msgs:
4561 if msgs:
4608 repo.savecommitmessage('\n* * *\n'.join(msgs))
4562 repo.savecommitmessage('\n* * *\n'.join(msgs))
4609 if dsguard:
4563 if dsguard:
4610 dsguard.close()
4564 dsguard.close()
4611 return ret
4565 return ret
4612 finally:
4566 finally:
4613 if tr:
4567 if tr:
4614 tr.release()
4568 tr.release()
4615 release(lock, dsguard, wlock)
4569 release(lock, dsguard, wlock)
4616
4570
4617 @command('incoming|in',
4571 @command('incoming|in',
4618 [('f', 'force', None,
4572 [('f', 'force', None,
4619 _('run even if remote repository is unrelated')),
4573 _('run even if remote repository is unrelated')),
4620 ('n', 'newest-first', None, _('show newest record first')),
4574 ('n', 'newest-first', None, _('show newest record first')),
4621 ('', 'bundle', '',
4575 ('', 'bundle', '',
4622 _('file to store the bundles into'), _('FILE')),
4576 _('file to store the bundles into'), _('FILE')),
4623 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4577 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4624 ('B', 'bookmarks', False, _("compare bookmarks")),
4578 ('B', 'bookmarks', False, _("compare bookmarks")),
4625 ('b', 'branch', [],
4579 ('b', 'branch', [],
4626 _('a specific branch you would like to pull'), _('BRANCH')),
4580 _('a specific branch you would like to pull'), _('BRANCH')),
4627 ] + logopts + remoteopts + subrepoopts,
4581 ] + logopts + remoteopts + subrepoopts,
4628 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
4582 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
4629 def incoming(ui, repo, source="default", **opts):
4583 def incoming(ui, repo, source="default", **opts):
4630 """show new changesets found in source
4584 """show new changesets found in source
4631
4585
4632 Show new changesets found in the specified path/URL or the default
4586 Show new changesets found in the specified path/URL or the default
4633 pull location. These are the changesets that would have been pulled
4587 pull location. These are the changesets that would have been pulled
4634 if a pull at the time you issued this command.
4588 if a pull at the time you issued this command.
4635
4589
4636 See pull for valid source format details.
4590 See pull for valid source format details.
4637
4591
4638 .. container:: verbose
4592 .. container:: verbose
4639
4593
4640 With -B/--bookmarks, the result of bookmark comparison between
4594 With -B/--bookmarks, the result of bookmark comparison between
4641 local and remote repositories is displayed. With -v/--verbose,
4595 local and remote repositories is displayed. With -v/--verbose,
4642 status is also displayed for each bookmark like below::
4596 status is also displayed for each bookmark like below::
4643
4597
4644 BM1 01234567890a added
4598 BM1 01234567890a added
4645 BM2 1234567890ab advanced
4599 BM2 1234567890ab advanced
4646 BM3 234567890abc diverged
4600 BM3 234567890abc diverged
4647 BM4 34567890abcd changed
4601 BM4 34567890abcd changed
4648
4602
4649 The action taken locally when pulling depends on the
4603 The action taken locally when pulling depends on the
4650 status of each bookmark:
4604 status of each bookmark:
4651
4605
4652 :``added``: pull will create it
4606 :``added``: pull will create it
4653 :``advanced``: pull will update it
4607 :``advanced``: pull will update it
4654 :``diverged``: pull will create a divergent bookmark
4608 :``diverged``: pull will create a divergent bookmark
4655 :``changed``: result depends on remote changesets
4609 :``changed``: result depends on remote changesets
4656
4610
4657 From the point of view of pulling behavior, bookmark
4611 From the point of view of pulling behavior, bookmark
4658 existing only in the remote repository are treated as ``added``,
4612 existing only in the remote repository are treated as ``added``,
4659 even if it is in fact locally deleted.
4613 even if it is in fact locally deleted.
4660
4614
4661 .. container:: verbose
4615 .. container:: verbose
4662
4616
4663 For remote repository, using --bundle avoids downloading the
4617 For remote repository, using --bundle avoids downloading the
4664 changesets twice if the incoming is followed by a pull.
4618 changesets twice if the incoming is followed by a pull.
4665
4619
4666 Examples:
4620 Examples:
4667
4621
4668 - show incoming changes with patches and full description::
4622 - show incoming changes with patches and full description::
4669
4623
4670 hg incoming -vp
4624 hg incoming -vp
4671
4625
4672 - show incoming changes excluding merges, store a bundle::
4626 - show incoming changes excluding merges, store a bundle::
4673
4627
4674 hg in -vpM --bundle incoming.hg
4628 hg in -vpM --bundle incoming.hg
4675 hg pull incoming.hg
4629 hg pull incoming.hg
4676
4630
4677 - briefly list changes inside a bundle::
4631 - briefly list changes inside a bundle::
4678
4632
4679 hg in changes.hg -T "{desc|firstline}\\n"
4633 hg in changes.hg -T "{desc|firstline}\\n"
4680
4634
4681 Returns 0 if there are incoming changes, 1 otherwise.
4635 Returns 0 if there are incoming changes, 1 otherwise.
4682 """
4636 """
4683 if opts.get('graph'):
4637 if opts.get('graph'):
4684 cmdutil.checkunsupportedgraphflags([], opts)
4638 cmdutil.checkunsupportedgraphflags([], opts)
4685 def display(other, chlist, displayer):
4639 def display(other, chlist, displayer):
4686 revdag = cmdutil.graphrevs(other, chlist, opts)
4640 revdag = cmdutil.graphrevs(other, chlist, opts)
4687 cmdutil.displaygraph(ui, repo, revdag, displayer,
4641 cmdutil.displaygraph(ui, repo, revdag, displayer,
4688 graphmod.asciiedges)
4642 graphmod.asciiedges)
4689
4643
4690 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4644 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4691 return 0
4645 return 0
4692
4646
4693 if opts.get('bundle') and opts.get('subrepos'):
4647 if opts.get('bundle') and opts.get('subrepos'):
4694 raise error.Abort(_('cannot combine --bundle and --subrepos'))
4648 raise error.Abort(_('cannot combine --bundle and --subrepos'))
4695
4649
4696 if opts.get('bookmarks'):
4650 if opts.get('bookmarks'):
4697 source, branches = hg.parseurl(ui.expandpath(source),
4651 source, branches = hg.parseurl(ui.expandpath(source),
4698 opts.get('branch'))
4652 opts.get('branch'))
4699 other = hg.peer(repo, opts, source)
4653 other = hg.peer(repo, opts, source)
4700 if 'bookmarks' not in other.listkeys('namespaces'):
4654 if 'bookmarks' not in other.listkeys('namespaces'):
4701 ui.warn(_("remote doesn't support bookmarks\n"))
4655 ui.warn(_("remote doesn't support bookmarks\n"))
4702 return 0
4656 return 0
4703 ui.status(_('comparing with %s\n') % util.hidepassword(source))
4657 ui.status(_('comparing with %s\n') % util.hidepassword(source))
4704 return bookmarks.incoming(ui, repo, other)
4658 return bookmarks.incoming(ui, repo, other)
4705
4659
4706 repo._subtoppath = ui.expandpath(source)
4660 repo._subtoppath = ui.expandpath(source)
4707 try:
4661 try:
4708 return hg.incoming(ui, repo, source, opts)
4662 return hg.incoming(ui, repo, source, opts)
4709 finally:
4663 finally:
4710 del repo._subtoppath
4664 del repo._subtoppath
4711
4665
4712
4666
4713 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
4667 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
4714 norepo=True)
4668 norepo=True)
4715 def init(ui, dest=".", **opts):
4669 def init(ui, dest=".", **opts):
4716 """create a new repository in the given directory
4670 """create a new repository in the given directory
4717
4671
4718 Initialize a new repository in the given directory. If the given
4672 Initialize a new repository in the given directory. If the given
4719 directory does not exist, it will be created.
4673 directory does not exist, it will be created.
4720
4674
4721 If no directory is given, the current directory is used.
4675 If no directory is given, the current directory is used.
4722
4676
4723 It is possible to specify an ``ssh://`` URL as the destination.
4677 It is possible to specify an ``ssh://`` URL as the destination.
4724 See :hg:`help urls` for more information.
4678 See :hg:`help urls` for more information.
4725
4679
4726 Returns 0 on success.
4680 Returns 0 on success.
4727 """
4681 """
4728 hg.peer(ui, opts, ui.expandpath(dest), create=True)
4682 hg.peer(ui, opts, ui.expandpath(dest), create=True)
4729
4683
4730 @command('locate',
4684 @command('locate',
4731 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
4685 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
4732 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4686 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4733 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
4687 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
4734 ] + walkopts,
4688 ] + walkopts,
4735 _('[OPTION]... [PATTERN]...'))
4689 _('[OPTION]... [PATTERN]...'))
4736 def locate(ui, repo, *pats, **opts):
4690 def locate(ui, repo, *pats, **opts):
4737 """locate files matching specific patterns (DEPRECATED)
4691 """locate files matching specific patterns (DEPRECATED)
4738
4692
4739 Print files under Mercurial control in the working directory whose
4693 Print files under Mercurial control in the working directory whose
4740 names match the given patterns.
4694 names match the given patterns.
4741
4695
4742 By default, this command searches all directories in the working
4696 By default, this command searches all directories in the working
4743 directory. To search just the current directory and its
4697 directory. To search just the current directory and its
4744 subdirectories, use "--include .".
4698 subdirectories, use "--include .".
4745
4699
4746 If no patterns are given to match, this command prints the names
4700 If no patterns are given to match, this command prints the names
4747 of all files under Mercurial control in the working directory.
4701 of all files under Mercurial control in the working directory.
4748
4702
4749 If you want to feed the output of this command into the "xargs"
4703 If you want to feed the output of this command into the "xargs"
4750 command, use the -0 option to both this command and "xargs". This
4704 command, use the -0 option to both this command and "xargs". This
4751 will avoid the problem of "xargs" treating single filenames that
4705 will avoid the problem of "xargs" treating single filenames that
4752 contain whitespace as multiple filenames.
4706 contain whitespace as multiple filenames.
4753
4707
4754 See :hg:`help files` for a more versatile command.
4708 See :hg:`help files` for a more versatile command.
4755
4709
4756 Returns 0 if a match is found, 1 otherwise.
4710 Returns 0 if a match is found, 1 otherwise.
4757 """
4711 """
4758 if opts.get('print0'):
4712 if opts.get('print0'):
4759 end = '\0'
4713 end = '\0'
4760 else:
4714 else:
4761 end = '\n'
4715 end = '\n'
4762 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
4716 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
4763
4717
4764 ret = 1
4718 ret = 1
4765 ctx = repo[rev]
4719 ctx = repo[rev]
4766 m = scmutil.match(ctx, pats, opts, default='relglob',
4720 m = scmutil.match(ctx, pats, opts, default='relglob',
4767 badfn=lambda x, y: False)
4721 badfn=lambda x, y: False)
4768
4722
4769 for abs in ctx.matches(m):
4723 for abs in ctx.matches(m):
4770 if opts.get('fullpath'):
4724 if opts.get('fullpath'):
4771 ui.write(repo.wjoin(abs), end)
4725 ui.write(repo.wjoin(abs), end)
4772 else:
4726 else:
4773 ui.write(((pats and m.rel(abs)) or abs), end)
4727 ui.write(((pats and m.rel(abs)) or abs), end)
4774 ret = 0
4728 ret = 0
4775
4729
4776 return ret
4730 return ret
4777
4731
4778 @command('^log|history',
4732 @command('^log|history',
4779 [('f', 'follow', None,
4733 [('f', 'follow', None,
4780 _('follow changeset history, or file history across copies and renames')),
4734 _('follow changeset history, or file history across copies and renames')),
4781 ('', 'follow-first', None,
4735 ('', 'follow-first', None,
4782 _('only follow the first parent of merge changesets (DEPRECATED)')),
4736 _('only follow the first parent of merge changesets (DEPRECATED)')),
4783 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
4737 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
4784 ('C', 'copies', None, _('show copied files')),
4738 ('C', 'copies', None, _('show copied files')),
4785 ('k', 'keyword', [],
4739 ('k', 'keyword', [],
4786 _('do case-insensitive search for a given text'), _('TEXT')),
4740 _('do case-insensitive search for a given text'), _('TEXT')),
4787 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
4741 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
4788 ('', 'removed', None, _('include revisions where files were removed')),
4742 ('', 'removed', None, _('include revisions where files were removed')),
4789 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4743 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4790 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4744 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4791 ('', 'only-branch', [],
4745 ('', 'only-branch', [],
4792 _('show only changesets within the given named branch (DEPRECATED)'),
4746 _('show only changesets within the given named branch (DEPRECATED)'),
4793 _('BRANCH')),
4747 _('BRANCH')),
4794 ('b', 'branch', [],
4748 ('b', 'branch', [],
4795 _('show changesets within the given named branch'), _('BRANCH')),
4749 _('show changesets within the given named branch'), _('BRANCH')),
4796 ('P', 'prune', [],
4750 ('P', 'prune', [],
4797 _('do not display revision or any of its ancestors'), _('REV')),
4751 _('do not display revision or any of its ancestors'), _('REV')),
4798 ] + logopts + walkopts,
4752 ] + logopts + walkopts,
4799 _('[OPTION]... [FILE]'),
4753 _('[OPTION]... [FILE]'),
4800 inferrepo=True)
4754 inferrepo=True)
4801 def log(ui, repo, *pats, **opts):
4755 def log(ui, repo, *pats, **opts):
4802 """show revision history of entire repository or files
4756 """show revision history of entire repository or files
4803
4757
4804 Print the revision history of the specified files or the entire
4758 Print the revision history of the specified files or the entire
4805 project.
4759 project.
4806
4760
4807 If no revision range is specified, the default is ``tip:0`` unless
4761 If no revision range is specified, the default is ``tip:0`` unless
4808 --follow is set, in which case the working directory parent is
4762 --follow is set, in which case the working directory parent is
4809 used as the starting revision.
4763 used as the starting revision.
4810
4764
4811 File history is shown without following rename or copy history of
4765 File history is shown without following rename or copy history of
4812 files. Use -f/--follow with a filename to follow history across
4766 files. Use -f/--follow with a filename to follow history across
4813 renames and copies. --follow without a filename will only show
4767 renames and copies. --follow without a filename will only show
4814 ancestors or descendants of the starting revision.
4768 ancestors or descendants of the starting revision.
4815
4769
4816 By default this command prints revision number and changeset id,
4770 By default this command prints revision number and changeset id,
4817 tags, non-trivial parents, user, date and time, and a summary for
4771 tags, non-trivial parents, user, date and time, and a summary for
4818 each commit. When the -v/--verbose switch is used, the list of
4772 each commit. When the -v/--verbose switch is used, the list of
4819 changed files and full commit message are shown.
4773 changed files and full commit message are shown.
4820
4774
4821 With --graph the revisions are shown as an ASCII art DAG with the most
4775 With --graph the revisions are shown as an ASCII art DAG with the most
4822 recent changeset at the top.
4776 recent changeset at the top.
4823 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
4777 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
4824 and '+' represents a fork where the changeset from the lines below is a
4778 and '+' represents a fork where the changeset from the lines below is a
4825 parent of the 'o' merge on the same line.
4779 parent of the 'o' merge on the same line.
4826
4780
4827 .. note::
4781 .. note::
4828
4782
4829 :hg:`log --patch` may generate unexpected diff output for merge
4783 :hg:`log --patch` may generate unexpected diff output for merge
4830 changesets, as it will only compare the merge changeset against
4784 changesets, as it will only compare the merge changeset against
4831 its first parent. Also, only files different from BOTH parents
4785 its first parent. Also, only files different from BOTH parents
4832 will appear in files:.
4786 will appear in files:.
4833
4787
4834 .. note::
4788 .. note::
4835
4789
4836 For performance reasons, :hg:`log FILE` may omit duplicate changes
4790 For performance reasons, :hg:`log FILE` may omit duplicate changes
4837 made on branches and will not show removals or mode changes. To
4791 made on branches and will not show removals or mode changes. To
4838 see all such changes, use the --removed switch.
4792 see all such changes, use the --removed switch.
4839
4793
4840 .. container:: verbose
4794 .. container:: verbose
4841
4795
4842 Some examples:
4796 Some examples:
4843
4797
4844 - changesets with full descriptions and file lists::
4798 - changesets with full descriptions and file lists::
4845
4799
4846 hg log -v
4800 hg log -v
4847
4801
4848 - changesets ancestral to the working directory::
4802 - changesets ancestral to the working directory::
4849
4803
4850 hg log -f
4804 hg log -f
4851
4805
4852 - last 10 commits on the current branch::
4806 - last 10 commits on the current branch::
4853
4807
4854 hg log -l 10 -b .
4808 hg log -l 10 -b .
4855
4809
4856 - changesets showing all modifications of a file, including removals::
4810 - changesets showing all modifications of a file, including removals::
4857
4811
4858 hg log --removed file.c
4812 hg log --removed file.c
4859
4813
4860 - all changesets that touch a directory, with diffs, excluding merges::
4814 - all changesets that touch a directory, with diffs, excluding merges::
4861
4815
4862 hg log -Mp lib/
4816 hg log -Mp lib/
4863
4817
4864 - all revision numbers that match a keyword::
4818 - all revision numbers that match a keyword::
4865
4819
4866 hg log -k bug --template "{rev}\\n"
4820 hg log -k bug --template "{rev}\\n"
4867
4821
4868 - the full hash identifier of the working directory parent::
4822 - the full hash identifier of the working directory parent::
4869
4823
4870 hg log -r . --template "{node}\\n"
4824 hg log -r . --template "{node}\\n"
4871
4825
4872 - list available log templates::
4826 - list available log templates::
4873
4827
4874 hg log -T list
4828 hg log -T list
4875
4829
4876 - check if a given changeset is included in a tagged release::
4830 - check if a given changeset is included in a tagged release::
4877
4831
4878 hg log -r "a21ccf and ancestor(1.9)"
4832 hg log -r "a21ccf and ancestor(1.9)"
4879
4833
4880 - find all changesets by some user in a date range::
4834 - find all changesets by some user in a date range::
4881
4835
4882 hg log -k alice -d "may 2008 to jul 2008"
4836 hg log -k alice -d "may 2008 to jul 2008"
4883
4837
4884 - summary of all changesets after the last tag::
4838 - summary of all changesets after the last tag::
4885
4839
4886 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4840 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4887
4841
4888 See :hg:`help dates` for a list of formats valid for -d/--date.
4842 See :hg:`help dates` for a list of formats valid for -d/--date.
4889
4843
4890 See :hg:`help revisions` and :hg:`help revsets` for more about
4844 See :hg:`help revisions` and :hg:`help revsets` for more about
4891 specifying and ordering revisions.
4845 specifying and ordering revisions.
4892
4846
4893 See :hg:`help templates` for more about pre-packaged styles and
4847 See :hg:`help templates` for more about pre-packaged styles and
4894 specifying custom templates.
4848 specifying custom templates.
4895
4849
4896 Returns 0 on success.
4850 Returns 0 on success.
4897
4851
4898 """
4852 """
4899 if opts.get('follow') and opts.get('rev'):
4853 if opts.get('follow') and opts.get('rev'):
4900 opts['rev'] = [revset.formatspec('reverse(::%lr)', opts.get('rev'))]
4854 opts['rev'] = [revset.formatspec('reverse(::%lr)', opts.get('rev'))]
4901 del opts['follow']
4855 del opts['follow']
4902
4856
4903 if opts.get('graph'):
4857 if opts.get('graph'):
4904 return cmdutil.graphlog(ui, repo, *pats, **opts)
4858 return cmdutil.graphlog(ui, repo, *pats, **opts)
4905
4859
4906 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
4860 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
4907 limit = cmdutil.loglimit(opts)
4861 limit = cmdutil.loglimit(opts)
4908 count = 0
4862 count = 0
4909
4863
4910 getrenamed = None
4864 getrenamed = None
4911 if opts.get('copies'):
4865 if opts.get('copies'):
4912 endrev = None
4866 endrev = None
4913 if opts.get('rev'):
4867 if opts.get('rev'):
4914 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
4868 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
4915 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4869 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4916
4870
4917 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4871 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4918 for rev in revs:
4872 for rev in revs:
4919 if count == limit:
4873 if count == limit:
4920 break
4874 break
4921 ctx = repo[rev]
4875 ctx = repo[rev]
4922 copies = None
4876 copies = None
4923 if getrenamed is not None and rev:
4877 if getrenamed is not None and rev:
4924 copies = []
4878 copies = []
4925 for fn in ctx.files():
4879 for fn in ctx.files():
4926 rename = getrenamed(fn, rev)
4880 rename = getrenamed(fn, rev)
4927 if rename:
4881 if rename:
4928 copies.append((fn, rename[0]))
4882 copies.append((fn, rename[0]))
4929 if filematcher:
4883 if filematcher:
4930 revmatchfn = filematcher(ctx.rev())
4884 revmatchfn = filematcher(ctx.rev())
4931 else:
4885 else:
4932 revmatchfn = None
4886 revmatchfn = None
4933 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4887 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4934 if displayer.flush(ctx):
4888 if displayer.flush(ctx):
4935 count += 1
4889 count += 1
4936
4890
4937 displayer.close()
4891 displayer.close()
4938
4892
4939 @command('manifest',
4893 @command('manifest',
4940 [('r', 'rev', '', _('revision to display'), _('REV')),
4894 [('r', 'rev', '', _('revision to display'), _('REV')),
4941 ('', 'all', False, _("list files from all revisions"))]
4895 ('', 'all', False, _("list files from all revisions"))]
4942 + formatteropts,
4896 + formatteropts,
4943 _('[-r REV]'))
4897 _('[-r REV]'))
4944 def manifest(ui, repo, node=None, rev=None, **opts):
4898 def manifest(ui, repo, node=None, rev=None, **opts):
4945 """output the current or given revision of the project manifest
4899 """output the current or given revision of the project manifest
4946
4900
4947 Print a list of version controlled files for the given revision.
4901 Print a list of version controlled files for the given revision.
4948 If no revision is given, the first parent of the working directory
4902 If no revision is given, the first parent of the working directory
4949 is used, or the null revision if no revision is checked out.
4903 is used, or the null revision if no revision is checked out.
4950
4904
4951 With -v, print file permissions, symlink and executable bits.
4905 With -v, print file permissions, symlink and executable bits.
4952 With --debug, print file revision hashes.
4906 With --debug, print file revision hashes.
4953
4907
4954 If option --all is specified, the list of all files from all revisions
4908 If option --all is specified, the list of all files from all revisions
4955 is printed. This includes deleted and renamed files.
4909 is printed. This includes deleted and renamed files.
4956
4910
4957 Returns 0 on success.
4911 Returns 0 on success.
4958 """
4912 """
4959
4913
4960 fm = ui.formatter('manifest', opts)
4914 fm = ui.formatter('manifest', opts)
4961
4915
4962 if opts.get('all'):
4916 if opts.get('all'):
4963 if rev or node:
4917 if rev or node:
4964 raise error.Abort(_("can't specify a revision with --all"))
4918 raise error.Abort(_("can't specify a revision with --all"))
4965
4919
4966 res = []
4920 res = []
4967 prefix = "data/"
4921 prefix = "data/"
4968 suffix = ".i"
4922 suffix = ".i"
4969 plen = len(prefix)
4923 plen = len(prefix)
4970 slen = len(suffix)
4924 slen = len(suffix)
4971 with repo.lock():
4925 with repo.lock():
4972 for fn, b, size in repo.store.datafiles():
4926 for fn, b, size in repo.store.datafiles():
4973 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4927 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4974 res.append(fn[plen:-slen])
4928 res.append(fn[plen:-slen])
4975 for f in res:
4929 for f in res:
4976 fm.startitem()
4930 fm.startitem()
4977 fm.write("path", '%s\n', f)
4931 fm.write("path", '%s\n', f)
4978 fm.end()
4932 fm.end()
4979 return
4933 return
4980
4934
4981 if rev and node:
4935 if rev and node:
4982 raise error.Abort(_("please specify just one revision"))
4936 raise error.Abort(_("please specify just one revision"))
4983
4937
4984 if not node:
4938 if not node:
4985 node = rev
4939 node = rev
4986
4940
4987 char = {'l': '@', 'x': '*', '': ''}
4941 char = {'l': '@', 'x': '*', '': ''}
4988 mode = {'l': '644', 'x': '755', '': '644'}
4942 mode = {'l': '644', 'x': '755', '': '644'}
4989 ctx = scmutil.revsingle(repo, node)
4943 ctx = scmutil.revsingle(repo, node)
4990 mf = ctx.manifest()
4944 mf = ctx.manifest()
4991 for f in ctx:
4945 for f in ctx:
4992 fm.startitem()
4946 fm.startitem()
4993 fl = ctx[f].flags()
4947 fl = ctx[f].flags()
4994 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4948 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4995 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4949 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4996 fm.write('path', '%s\n', f)
4950 fm.write('path', '%s\n', f)
4997 fm.end()
4951 fm.end()
4998
4952
4999 @command('^merge',
4953 @command('^merge',
5000 [('f', 'force', None,
4954 [('f', 'force', None,
5001 _('force a merge including outstanding changes (DEPRECATED)')),
4955 _('force a merge including outstanding changes (DEPRECATED)')),
5002 ('r', 'rev', '', _('revision to merge'), _('REV')),
4956 ('r', 'rev', '', _('revision to merge'), _('REV')),
5003 ('P', 'preview', None,
4957 ('P', 'preview', None,
5004 _('review revisions to merge (no merge is performed)'))
4958 _('review revisions to merge (no merge is performed)'))
5005 ] + mergetoolopts,
4959 ] + mergetoolopts,
5006 _('[-P] [[-r] REV]'))
4960 _('[-P] [[-r] REV]'))
5007 def merge(ui, repo, node=None, **opts):
4961 def merge(ui, repo, node=None, **opts):
5008 """merge another revision into working directory
4962 """merge another revision into working directory
5009
4963
5010 The current working directory is updated with all changes made in
4964 The current working directory is updated with all changes made in
5011 the requested revision since the last common predecessor revision.
4965 the requested revision since the last common predecessor revision.
5012
4966
5013 Files that changed between either parent are marked as changed for
4967 Files that changed between either parent are marked as changed for
5014 the next commit and a commit must be performed before any further
4968 the next commit and a commit must be performed before any further
5015 updates to the repository are allowed. The next commit will have
4969 updates to the repository are allowed. The next commit will have
5016 two parents.
4970 two parents.
5017
4971
5018 ``--tool`` can be used to specify the merge tool used for file
4972 ``--tool`` can be used to specify the merge tool used for file
5019 merges. It overrides the HGMERGE environment variable and your
4973 merges. It overrides the HGMERGE environment variable and your
5020 configuration files. See :hg:`help merge-tools` for options.
4974 configuration files. See :hg:`help merge-tools` for options.
5021
4975
5022 If no revision is specified, the working directory's parent is a
4976 If no revision is specified, the working directory's parent is a
5023 head revision, and the current branch contains exactly one other
4977 head revision, and the current branch contains exactly one other
5024 head, the other head is merged with by default. Otherwise, an
4978 head, the other head is merged with by default. Otherwise, an
5025 explicit revision with which to merge with must be provided.
4979 explicit revision with which to merge with must be provided.
5026
4980
5027 See :hg:`help resolve` for information on handling file conflicts.
4981 See :hg:`help resolve` for information on handling file conflicts.
5028
4982
5029 To undo an uncommitted merge, use :hg:`update --clean .` which
4983 To undo an uncommitted merge, use :hg:`update --clean .` which
5030 will check out a clean copy of the original merge parent, losing
4984 will check out a clean copy of the original merge parent, losing
5031 all changes.
4985 all changes.
5032
4986
5033 Returns 0 on success, 1 if there are unresolved files.
4987 Returns 0 on success, 1 if there are unresolved files.
5034 """
4988 """
5035
4989
5036 if opts.get('rev') and node:
4990 if opts.get('rev') and node:
5037 raise error.Abort(_("please specify just one revision"))
4991 raise error.Abort(_("please specify just one revision"))
5038 if not node:
4992 if not node:
5039 node = opts.get('rev')
4993 node = opts.get('rev')
5040
4994
5041 if node:
4995 if node:
5042 node = scmutil.revsingle(repo, node).node()
4996 node = scmutil.revsingle(repo, node).node()
5043
4997
5044 if not node:
4998 if not node:
5045 node = repo[destutil.destmerge(repo)].node()
4999 node = repo[destutil.destmerge(repo)].node()
5046
5000
5047 if opts.get('preview'):
5001 if opts.get('preview'):
5048 # find nodes that are ancestors of p2 but not of p1
5002 # find nodes that are ancestors of p2 but not of p1
5049 p1 = repo.lookup('.')
5003 p1 = repo.lookup('.')
5050 p2 = repo.lookup(node)
5004 p2 = repo.lookup(node)
5051 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
5005 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
5052
5006
5053 displayer = cmdutil.show_changeset(ui, repo, opts)
5007 displayer = cmdutil.show_changeset(ui, repo, opts)
5054 for node in nodes:
5008 for node in nodes:
5055 displayer.show(repo[node])
5009 displayer.show(repo[node])
5056 displayer.close()
5010 displayer.close()
5057 return 0
5011 return 0
5058
5012
5059 try:
5013 try:
5060 # ui.forcemerge is an internal variable, do not document
5014 # ui.forcemerge is an internal variable, do not document
5061 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
5015 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
5062 force = opts.get('force')
5016 force = opts.get('force')
5063 labels = ['working copy', 'merge rev']
5017 labels = ['working copy', 'merge rev']
5064 return hg.merge(repo, node, force=force, mergeforce=force,
5018 return hg.merge(repo, node, force=force, mergeforce=force,
5065 labels=labels)
5019 labels=labels)
5066 finally:
5020 finally:
5067 ui.setconfig('ui', 'forcemerge', '', 'merge')
5021 ui.setconfig('ui', 'forcemerge', '', 'merge')
5068
5022
5069 @command('outgoing|out',
5023 @command('outgoing|out',
5070 [('f', 'force', None, _('run even when the destination is unrelated')),
5024 [('f', 'force', None, _('run even when the destination is unrelated')),
5071 ('r', 'rev', [],
5025 ('r', 'rev', [],
5072 _('a changeset intended to be included in the destination'), _('REV')),
5026 _('a changeset intended to be included in the destination'), _('REV')),
5073 ('n', 'newest-first', None, _('show newest record first')),
5027 ('n', 'newest-first', None, _('show newest record first')),
5074 ('B', 'bookmarks', False, _('compare bookmarks')),
5028 ('B', 'bookmarks', False, _('compare bookmarks')),
5075 ('b', 'branch', [], _('a specific branch you would like to push'),
5029 ('b', 'branch', [], _('a specific branch you would like to push'),
5076 _('BRANCH')),
5030 _('BRANCH')),
5077 ] + logopts + remoteopts + subrepoopts,
5031 ] + logopts + remoteopts + subrepoopts,
5078 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
5032 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
5079 def outgoing(ui, repo, dest=None, **opts):
5033 def outgoing(ui, repo, dest=None, **opts):
5080 """show changesets not found in the destination
5034 """show changesets not found in the destination
5081
5035
5082 Show changesets not found in the specified destination repository
5036 Show changesets not found in the specified destination repository
5083 or the default push location. These are the changesets that would
5037 or the default push location. These are the changesets that would
5084 be pushed if a push was requested.
5038 be pushed if a push was requested.
5085
5039
5086 See pull for details of valid destination formats.
5040 See pull for details of valid destination formats.
5087
5041
5088 .. container:: verbose
5042 .. container:: verbose
5089
5043
5090 With -B/--bookmarks, the result of bookmark comparison between
5044 With -B/--bookmarks, the result of bookmark comparison between
5091 local and remote repositories is displayed. With -v/--verbose,
5045 local and remote repositories is displayed. With -v/--verbose,
5092 status is also displayed for each bookmark like below::
5046 status is also displayed for each bookmark like below::
5093
5047
5094 BM1 01234567890a added
5048 BM1 01234567890a added
5095 BM2 deleted
5049 BM2 deleted
5096 BM3 234567890abc advanced
5050 BM3 234567890abc advanced
5097 BM4 34567890abcd diverged
5051 BM4 34567890abcd diverged
5098 BM5 4567890abcde changed
5052 BM5 4567890abcde changed
5099
5053
5100 The action taken when pushing depends on the
5054 The action taken when pushing depends on the
5101 status of each bookmark:
5055 status of each bookmark:
5102
5056
5103 :``added``: push with ``-B`` will create it
5057 :``added``: push with ``-B`` will create it
5104 :``deleted``: push with ``-B`` will delete it
5058 :``deleted``: push with ``-B`` will delete it
5105 :``advanced``: push will update it
5059 :``advanced``: push will update it
5106 :``diverged``: push with ``-B`` will update it
5060 :``diverged``: push with ``-B`` will update it
5107 :``changed``: push with ``-B`` will update it
5061 :``changed``: push with ``-B`` will update it
5108
5062
5109 From the point of view of pushing behavior, bookmarks
5063 From the point of view of pushing behavior, bookmarks
5110 existing only in the remote repository are treated as
5064 existing only in the remote repository are treated as
5111 ``deleted``, even if it is in fact added remotely.
5065 ``deleted``, even if it is in fact added remotely.
5112
5066
5113 Returns 0 if there are outgoing changes, 1 otherwise.
5067 Returns 0 if there are outgoing changes, 1 otherwise.
5114 """
5068 """
5115 if opts.get('graph'):
5069 if opts.get('graph'):
5116 cmdutil.checkunsupportedgraphflags([], opts)
5070 cmdutil.checkunsupportedgraphflags([], opts)
5117 o, other = hg._outgoing(ui, repo, dest, opts)
5071 o, other = hg._outgoing(ui, repo, dest, opts)
5118 if not o:
5072 if not o:
5119 cmdutil.outgoinghooks(ui, repo, other, opts, o)
5073 cmdutil.outgoinghooks(ui, repo, other, opts, o)
5120 return
5074 return
5121
5075
5122 revdag = cmdutil.graphrevs(repo, o, opts)
5076 revdag = cmdutil.graphrevs(repo, o, opts)
5123 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
5077 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
5124 cmdutil.displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges)
5078 cmdutil.displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges)
5125 cmdutil.outgoinghooks(ui, repo, other, opts, o)
5079 cmdutil.outgoinghooks(ui, repo, other, opts, o)
5126 return 0
5080 return 0
5127
5081
5128 if opts.get('bookmarks'):
5082 if opts.get('bookmarks'):
5129 dest = ui.expandpath(dest or 'default-push', dest or 'default')
5083 dest = ui.expandpath(dest or 'default-push', dest or 'default')
5130 dest, branches = hg.parseurl(dest, opts.get('branch'))
5084 dest, branches = hg.parseurl(dest, opts.get('branch'))
5131 other = hg.peer(repo, opts, dest)
5085 other = hg.peer(repo, opts, dest)
5132 if 'bookmarks' not in other.listkeys('namespaces'):
5086 if 'bookmarks' not in other.listkeys('namespaces'):
5133 ui.warn(_("remote doesn't support bookmarks\n"))
5087 ui.warn(_("remote doesn't support bookmarks\n"))
5134 return 0
5088 return 0
5135 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
5089 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
5136 return bookmarks.outgoing(ui, repo, other)
5090 return bookmarks.outgoing(ui, repo, other)
5137
5091
5138 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
5092 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
5139 try:
5093 try:
5140 return hg.outgoing(ui, repo, dest, opts)
5094 return hg.outgoing(ui, repo, dest, opts)
5141 finally:
5095 finally:
5142 del repo._subtoppath
5096 del repo._subtoppath
5143
5097
5144 @command('parents',
5098 @command('parents',
5145 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
5099 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
5146 ] + templateopts,
5100 ] + templateopts,
5147 _('[-r REV] [FILE]'),
5101 _('[-r REV] [FILE]'),
5148 inferrepo=True)
5102 inferrepo=True)
5149 def parents(ui, repo, file_=None, **opts):
5103 def parents(ui, repo, file_=None, **opts):
5150 """show the parents of the working directory or revision (DEPRECATED)
5104 """show the parents of the working directory or revision (DEPRECATED)
5151
5105
5152 Print the working directory's parent revisions. If a revision is
5106 Print the working directory's parent revisions. If a revision is
5153 given via -r/--rev, the parent of that revision will be printed.
5107 given via -r/--rev, the parent of that revision will be printed.
5154 If a file argument is given, the revision in which the file was
5108 If a file argument is given, the revision in which the file was
5155 last changed (before the working directory revision or the
5109 last changed (before the working directory revision or the
5156 argument to --rev if given) is printed.
5110 argument to --rev if given) is printed.
5157
5111
5158 This command is equivalent to::
5112 This command is equivalent to::
5159
5113
5160 hg log -r "p1()+p2()" or
5114 hg log -r "p1()+p2()" or
5161 hg log -r "p1(REV)+p2(REV)" or
5115 hg log -r "p1(REV)+p2(REV)" or
5162 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
5116 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
5163 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
5117 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
5164
5118
5165 See :hg:`summary` and :hg:`help revsets` for related information.
5119 See :hg:`summary` and :hg:`help revsets` for related information.
5166
5120
5167 Returns 0 on success.
5121 Returns 0 on success.
5168 """
5122 """
5169
5123
5170 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
5124 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
5171
5125
5172 if file_:
5126 if file_:
5173 m = scmutil.match(ctx, (file_,), opts)
5127 m = scmutil.match(ctx, (file_,), opts)
5174 if m.anypats() or len(m.files()) != 1:
5128 if m.anypats() or len(m.files()) != 1:
5175 raise error.Abort(_('can only specify an explicit filename'))
5129 raise error.Abort(_('can only specify an explicit filename'))
5176 file_ = m.files()[0]
5130 file_ = m.files()[0]
5177 filenodes = []
5131 filenodes = []
5178 for cp in ctx.parents():
5132 for cp in ctx.parents():
5179 if not cp:
5133 if not cp:
5180 continue
5134 continue
5181 try:
5135 try:
5182 filenodes.append(cp.filenode(file_))
5136 filenodes.append(cp.filenode(file_))
5183 except error.LookupError:
5137 except error.LookupError:
5184 pass
5138 pass
5185 if not filenodes:
5139 if not filenodes:
5186 raise error.Abort(_("'%s' not found in manifest!") % file_)
5140 raise error.Abort(_("'%s' not found in manifest!") % file_)
5187 p = []
5141 p = []
5188 for fn in filenodes:
5142 for fn in filenodes:
5189 fctx = repo.filectx(file_, fileid=fn)
5143 fctx = repo.filectx(file_, fileid=fn)
5190 p.append(fctx.node())
5144 p.append(fctx.node())
5191 else:
5145 else:
5192 p = [cp.node() for cp in ctx.parents()]
5146 p = [cp.node() for cp in ctx.parents()]
5193
5147
5194 displayer = cmdutil.show_changeset(ui, repo, opts)
5148 displayer = cmdutil.show_changeset(ui, repo, opts)
5195 for n in p:
5149 for n in p:
5196 if n != nullid:
5150 if n != nullid:
5197 displayer.show(repo[n])
5151 displayer.show(repo[n])
5198 displayer.close()
5152 displayer.close()
5199
5153
5200 @command('paths', formatteropts, _('[NAME]'), optionalrepo=True)
5154 @command('paths', formatteropts, _('[NAME]'), optionalrepo=True)
5201 def paths(ui, repo, search=None, **opts):
5155 def paths(ui, repo, search=None, **opts):
5202 """show aliases for remote repositories
5156 """show aliases for remote repositories
5203
5157
5204 Show definition of symbolic path name NAME. If no name is given,
5158 Show definition of symbolic path name NAME. If no name is given,
5205 show definition of all available names.
5159 show definition of all available names.
5206
5160
5207 Option -q/--quiet suppresses all output when searching for NAME
5161 Option -q/--quiet suppresses all output when searching for NAME
5208 and shows only the path names when listing all definitions.
5162 and shows only the path names when listing all definitions.
5209
5163
5210 Path names are defined in the [paths] section of your
5164 Path names are defined in the [paths] section of your
5211 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
5165 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
5212 repository, ``.hg/hgrc`` is used, too.
5166 repository, ``.hg/hgrc`` is used, too.
5213
5167
5214 The path names ``default`` and ``default-push`` have a special
5168 The path names ``default`` and ``default-push`` have a special
5215 meaning. When performing a push or pull operation, they are used
5169 meaning. When performing a push or pull operation, they are used
5216 as fallbacks if no location is specified on the command-line.
5170 as fallbacks if no location is specified on the command-line.
5217 When ``default-push`` is set, it will be used for push and
5171 When ``default-push`` is set, it will be used for push and
5218 ``default`` will be used for pull; otherwise ``default`` is used
5172 ``default`` will be used for pull; otherwise ``default`` is used
5219 as the fallback for both. When cloning a repository, the clone
5173 as the fallback for both. When cloning a repository, the clone
5220 source is written as ``default`` in ``.hg/hgrc``.
5174 source is written as ``default`` in ``.hg/hgrc``.
5221
5175
5222 .. note::
5176 .. note::
5223
5177
5224 ``default`` and ``default-push`` apply to all inbound (e.g.
5178 ``default`` and ``default-push`` apply to all inbound (e.g.
5225 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
5179 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
5226 and :hg:`bundle`) operations.
5180 and :hg:`bundle`) operations.
5227
5181
5228 See :hg:`help urls` for more information.
5182 See :hg:`help urls` for more information.
5229
5183
5230 Returns 0 on success.
5184 Returns 0 on success.
5231 """
5185 """
5232 if search:
5186 if search:
5233 pathitems = [(name, path) for name, path in ui.paths.iteritems()
5187 pathitems = [(name, path) for name, path in ui.paths.iteritems()
5234 if name == search]
5188 if name == search]
5235 else:
5189 else:
5236 pathitems = sorted(ui.paths.iteritems())
5190 pathitems = sorted(ui.paths.iteritems())
5237
5191
5238 fm = ui.formatter('paths', opts)
5192 fm = ui.formatter('paths', opts)
5239 if fm.isplain():
5193 if fm.isplain():
5240 hidepassword = util.hidepassword
5194 hidepassword = util.hidepassword
5241 else:
5195 else:
5242 hidepassword = str
5196 hidepassword = str
5243 if ui.quiet:
5197 if ui.quiet:
5244 namefmt = '%s\n'
5198 namefmt = '%s\n'
5245 else:
5199 else:
5246 namefmt = '%s = '
5200 namefmt = '%s = '
5247 showsubopts = not search and not ui.quiet
5201 showsubopts = not search and not ui.quiet
5248
5202
5249 for name, path in pathitems:
5203 for name, path in pathitems:
5250 fm.startitem()
5204 fm.startitem()
5251 fm.condwrite(not search, 'name', namefmt, name)
5205 fm.condwrite(not search, 'name', namefmt, name)
5252 fm.condwrite(not ui.quiet, 'url', '%s\n', hidepassword(path.rawloc))
5206 fm.condwrite(not ui.quiet, 'url', '%s\n', hidepassword(path.rawloc))
5253 for subopt, value in sorted(path.suboptions.items()):
5207 for subopt, value in sorted(path.suboptions.items()):
5254 assert subopt not in ('name', 'url')
5208 assert subopt not in ('name', 'url')
5255 if showsubopts:
5209 if showsubopts:
5256 fm.plain('%s:%s = ' % (name, subopt))
5210 fm.plain('%s:%s = ' % (name, subopt))
5257 fm.condwrite(showsubopts, subopt, '%s\n', value)
5211 fm.condwrite(showsubopts, subopt, '%s\n', value)
5258
5212
5259 fm.end()
5213 fm.end()
5260
5214
5261 if search and not pathitems:
5215 if search and not pathitems:
5262 if not ui.quiet:
5216 if not ui.quiet:
5263 ui.warn(_("not found!\n"))
5217 ui.warn(_("not found!\n"))
5264 return 1
5218 return 1
5265 else:
5219 else:
5266 return 0
5220 return 0
5267
5221
5268 @command('phase',
5222 @command('phase',
5269 [('p', 'public', False, _('set changeset phase to public')),
5223 [('p', 'public', False, _('set changeset phase to public')),
5270 ('d', 'draft', False, _('set changeset phase to draft')),
5224 ('d', 'draft', False, _('set changeset phase to draft')),
5271 ('s', 'secret', False, _('set changeset phase to secret')),
5225 ('s', 'secret', False, _('set changeset phase to secret')),
5272 ('f', 'force', False, _('allow to move boundary backward')),
5226 ('f', 'force', False, _('allow to move boundary backward')),
5273 ('r', 'rev', [], _('target revision'), _('REV')),
5227 ('r', 'rev', [], _('target revision'), _('REV')),
5274 ],
5228 ],
5275 _('[-p|-d|-s] [-f] [-r] [REV...]'))
5229 _('[-p|-d|-s] [-f] [-r] [REV...]'))
5276 def phase(ui, repo, *revs, **opts):
5230 def phase(ui, repo, *revs, **opts):
5277 """set or show the current phase name
5231 """set or show the current phase name
5278
5232
5279 With no argument, show the phase name of the current revision(s).
5233 With no argument, show the phase name of the current revision(s).
5280
5234
5281 With one of -p/--public, -d/--draft or -s/--secret, change the
5235 With one of -p/--public, -d/--draft or -s/--secret, change the
5282 phase value of the specified revisions.
5236 phase value of the specified revisions.
5283
5237
5284 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
5238 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
5285 lower phase to an higher phase. Phases are ordered as follows::
5239 lower phase to an higher phase. Phases are ordered as follows::
5286
5240
5287 public < draft < secret
5241 public < draft < secret
5288
5242
5289 Returns 0 on success, 1 if some phases could not be changed.
5243 Returns 0 on success, 1 if some phases could not be changed.
5290
5244
5291 (For more information about the phases concept, see :hg:`help phases`.)
5245 (For more information about the phases concept, see :hg:`help phases`.)
5292 """
5246 """
5293 # search for a unique phase argument
5247 # search for a unique phase argument
5294 targetphase = None
5248 targetphase = None
5295 for idx, name in enumerate(phases.phasenames):
5249 for idx, name in enumerate(phases.phasenames):
5296 if opts[name]:
5250 if opts[name]:
5297 if targetphase is not None:
5251 if targetphase is not None:
5298 raise error.Abort(_('only one phase can be specified'))
5252 raise error.Abort(_('only one phase can be specified'))
5299 targetphase = idx
5253 targetphase = idx
5300
5254
5301 # look for specified revision
5255 # look for specified revision
5302 revs = list(revs)
5256 revs = list(revs)
5303 revs.extend(opts['rev'])
5257 revs.extend(opts['rev'])
5304 if not revs:
5258 if not revs:
5305 # display both parents as the second parent phase can influence
5259 # display both parents as the second parent phase can influence
5306 # the phase of a merge commit
5260 # the phase of a merge commit
5307 revs = [c.rev() for c in repo[None].parents()]
5261 revs = [c.rev() for c in repo[None].parents()]
5308
5262
5309 revs = scmutil.revrange(repo, revs)
5263 revs = scmutil.revrange(repo, revs)
5310
5264
5311 lock = None
5265 lock = None
5312 ret = 0
5266 ret = 0
5313 if targetphase is None:
5267 if targetphase is None:
5314 # display
5268 # display
5315 for r in revs:
5269 for r in revs:
5316 ctx = repo[r]
5270 ctx = repo[r]
5317 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
5271 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
5318 else:
5272 else:
5319 tr = None
5273 tr = None
5320 lock = repo.lock()
5274 lock = repo.lock()
5321 try:
5275 try:
5322 tr = repo.transaction("phase")
5276 tr = repo.transaction("phase")
5323 # set phase
5277 # set phase
5324 if not revs:
5278 if not revs:
5325 raise error.Abort(_('empty revision set'))
5279 raise error.Abort(_('empty revision set'))
5326 nodes = [repo[r].node() for r in revs]
5280 nodes = [repo[r].node() for r in revs]
5327 # moving revision from public to draft may hide them
5281 # moving revision from public to draft may hide them
5328 # We have to check result on an unfiltered repository
5282 # We have to check result on an unfiltered repository
5329 unfi = repo.unfiltered()
5283 unfi = repo.unfiltered()
5330 getphase = unfi._phasecache.phase
5284 getphase = unfi._phasecache.phase
5331 olddata = [getphase(unfi, r) for r in unfi]
5285 olddata = [getphase(unfi, r) for r in unfi]
5332 phases.advanceboundary(repo, tr, targetphase, nodes)
5286 phases.advanceboundary(repo, tr, targetphase, nodes)
5333 if opts['force']:
5287 if opts['force']:
5334 phases.retractboundary(repo, tr, targetphase, nodes)
5288 phases.retractboundary(repo, tr, targetphase, nodes)
5335 tr.close()
5289 tr.close()
5336 finally:
5290 finally:
5337 if tr is not None:
5291 if tr is not None:
5338 tr.release()
5292 tr.release()
5339 lock.release()
5293 lock.release()
5340 getphase = unfi._phasecache.phase
5294 getphase = unfi._phasecache.phase
5341 newdata = [getphase(unfi, r) for r in unfi]
5295 newdata = [getphase(unfi, r) for r in unfi]
5342 changes = sum(newdata[r] != olddata[r] for r in unfi)
5296 changes = sum(newdata[r] != olddata[r] for r in unfi)
5343 cl = unfi.changelog
5297 cl = unfi.changelog
5344 rejected = [n for n in nodes
5298 rejected = [n for n in nodes
5345 if newdata[cl.rev(n)] < targetphase]
5299 if newdata[cl.rev(n)] < targetphase]
5346 if rejected:
5300 if rejected:
5347 ui.warn(_('cannot move %i changesets to a higher '
5301 ui.warn(_('cannot move %i changesets to a higher '
5348 'phase, use --force\n') % len(rejected))
5302 'phase, use --force\n') % len(rejected))
5349 ret = 1
5303 ret = 1
5350 if changes:
5304 if changes:
5351 msg = _('phase changed for %i changesets\n') % changes
5305 msg = _('phase changed for %i changesets\n') % changes
5352 if ret:
5306 if ret:
5353 ui.status(msg)
5307 ui.status(msg)
5354 else:
5308 else:
5355 ui.note(msg)
5309 ui.note(msg)
5356 else:
5310 else:
5357 ui.warn(_('no phases changed\n'))
5311 ui.warn(_('no phases changed\n'))
5358 return ret
5312 return ret
5359
5313
5360 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
5314 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
5361 """Run after a changegroup has been added via pull/unbundle
5315 """Run after a changegroup has been added via pull/unbundle
5362
5316
5363 This takes arguments below:
5317 This takes arguments below:
5364
5318
5365 :modheads: change of heads by pull/unbundle
5319 :modheads: change of heads by pull/unbundle
5366 :optupdate: updating working directory is needed or not
5320 :optupdate: updating working directory is needed or not
5367 :checkout: update destination revision (or None to default destination)
5321 :checkout: update destination revision (or None to default destination)
5368 :brev: a name, which might be a bookmark to be activated after updating
5322 :brev: a name, which might be a bookmark to be activated after updating
5369 """
5323 """
5370 if modheads == 0:
5324 if modheads == 0:
5371 return
5325 return
5372 if optupdate:
5326 if optupdate:
5373 try:
5327 try:
5374 return hg.updatetotally(ui, repo, checkout, brev)
5328 return hg.updatetotally(ui, repo, checkout, brev)
5375 except error.UpdateAbort as inst:
5329 except error.UpdateAbort as inst:
5376 msg = _("not updating: %s") % str(inst)
5330 msg = _("not updating: %s") % str(inst)
5377 hint = inst.hint
5331 hint = inst.hint
5378 raise error.UpdateAbort(msg, hint=hint)
5332 raise error.UpdateAbort(msg, hint=hint)
5379 if modheads > 1:
5333 if modheads > 1:
5380 currentbranchheads = len(repo.branchheads())
5334 currentbranchheads = len(repo.branchheads())
5381 if currentbranchheads == modheads:
5335 if currentbranchheads == modheads:
5382 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
5336 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
5383 elif currentbranchheads > 1:
5337 elif currentbranchheads > 1:
5384 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
5338 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
5385 "merge)\n"))
5339 "merge)\n"))
5386 else:
5340 else:
5387 ui.status(_("(run 'hg heads' to see heads)\n"))
5341 ui.status(_("(run 'hg heads' to see heads)\n"))
5388 else:
5342 else:
5389 ui.status(_("(run 'hg update' to get a working copy)\n"))
5343 ui.status(_("(run 'hg update' to get a working copy)\n"))
5390
5344
5391 @command('^pull',
5345 @command('^pull',
5392 [('u', 'update', None,
5346 [('u', 'update', None,
5393 _('update to new branch head if changesets were pulled')),
5347 _('update to new branch head if changesets were pulled')),
5394 ('f', 'force', None, _('run even when remote repository is unrelated')),
5348 ('f', 'force', None, _('run even when remote repository is unrelated')),
5395 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
5349 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
5396 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
5350 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
5397 ('b', 'branch', [], _('a specific branch you would like to pull'),
5351 ('b', 'branch', [], _('a specific branch you would like to pull'),
5398 _('BRANCH')),
5352 _('BRANCH')),
5399 ] + remoteopts,
5353 ] + remoteopts,
5400 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
5354 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
5401 def pull(ui, repo, source="default", **opts):
5355 def pull(ui, repo, source="default", **opts):
5402 """pull changes from the specified source
5356 """pull changes from the specified source
5403
5357
5404 Pull changes from a remote repository to a local one.
5358 Pull changes from a remote repository to a local one.
5405
5359
5406 This finds all changes from the repository at the specified path
5360 This finds all changes from the repository at the specified path
5407 or URL and adds them to a local repository (the current one unless
5361 or URL and adds them to a local repository (the current one unless
5408 -R is specified). By default, this does not update the copy of the
5362 -R is specified). By default, this does not update the copy of the
5409 project in the working directory.
5363 project in the working directory.
5410
5364
5411 Use :hg:`incoming` if you want to see what would have been added
5365 Use :hg:`incoming` if you want to see what would have been added
5412 by a pull at the time you issued this command. If you then decide
5366 by a pull at the time you issued this command. If you then decide
5413 to add those changes to the repository, you should use :hg:`pull
5367 to add those changes to the repository, you should use :hg:`pull
5414 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
5368 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
5415
5369
5416 If SOURCE is omitted, the 'default' path will be used.
5370 If SOURCE is omitted, the 'default' path will be used.
5417 See :hg:`help urls` for more information.
5371 See :hg:`help urls` for more information.
5418
5372
5419 Specifying bookmark as ``.`` is equivalent to specifying the active
5373 Specifying bookmark as ``.`` is equivalent to specifying the active
5420 bookmark's name.
5374 bookmark's name.
5421
5375
5422 Returns 0 on success, 1 if an update had unresolved files.
5376 Returns 0 on success, 1 if an update had unresolved files.
5423 """
5377 """
5424 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
5378 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
5425 ui.status(_('pulling from %s\n') % util.hidepassword(source))
5379 ui.status(_('pulling from %s\n') % util.hidepassword(source))
5426 other = hg.peer(repo, opts, source)
5380 other = hg.peer(repo, opts, source)
5427 try:
5381 try:
5428 revs, checkout = hg.addbranchrevs(repo, other, branches,
5382 revs, checkout = hg.addbranchrevs(repo, other, branches,
5429 opts.get('rev'))
5383 opts.get('rev'))
5430
5384
5431
5385
5432 pullopargs = {}
5386 pullopargs = {}
5433 if opts.get('bookmark'):
5387 if opts.get('bookmark'):
5434 if not revs:
5388 if not revs:
5435 revs = []
5389 revs = []
5436 # The list of bookmark used here is not the one used to actually
5390 # The list of bookmark used here is not the one used to actually
5437 # update the bookmark name. This can result in the revision pulled
5391 # update the bookmark name. This can result in the revision pulled
5438 # not ending up with the name of the bookmark because of a race
5392 # not ending up with the name of the bookmark because of a race
5439 # condition on the server. (See issue 4689 for details)
5393 # condition on the server. (See issue 4689 for details)
5440 remotebookmarks = other.listkeys('bookmarks')
5394 remotebookmarks = other.listkeys('bookmarks')
5441 pullopargs['remotebookmarks'] = remotebookmarks
5395 pullopargs['remotebookmarks'] = remotebookmarks
5442 for b in opts['bookmark']:
5396 for b in opts['bookmark']:
5443 b = repo._bookmarks.expandname(b)
5397 b = repo._bookmarks.expandname(b)
5444 if b not in remotebookmarks:
5398 if b not in remotebookmarks:
5445 raise error.Abort(_('remote bookmark %s not found!') % b)
5399 raise error.Abort(_('remote bookmark %s not found!') % b)
5446 revs.append(remotebookmarks[b])
5400 revs.append(remotebookmarks[b])
5447
5401
5448 if revs:
5402 if revs:
5449 try:
5403 try:
5450 # When 'rev' is a bookmark name, we cannot guarantee that it
5404 # When 'rev' is a bookmark name, we cannot guarantee that it
5451 # will be updated with that name because of a race condition
5405 # will be updated with that name because of a race condition
5452 # server side. (See issue 4689 for details)
5406 # server side. (See issue 4689 for details)
5453 oldrevs = revs
5407 oldrevs = revs
5454 revs = [] # actually, nodes
5408 revs = [] # actually, nodes
5455 for r in oldrevs:
5409 for r in oldrevs:
5456 node = other.lookup(r)
5410 node = other.lookup(r)
5457 revs.append(node)
5411 revs.append(node)
5458 if r == checkout:
5412 if r == checkout:
5459 checkout = node
5413 checkout = node
5460 except error.CapabilityError:
5414 except error.CapabilityError:
5461 err = _("other repository doesn't support revision lookup, "
5415 err = _("other repository doesn't support revision lookup, "
5462 "so a rev cannot be specified.")
5416 "so a rev cannot be specified.")
5463 raise error.Abort(err)
5417 raise error.Abort(err)
5464
5418
5465 pullopargs.update(opts.get('opargs', {}))
5419 pullopargs.update(opts.get('opargs', {}))
5466 modheads = exchange.pull(repo, other, heads=revs,
5420 modheads = exchange.pull(repo, other, heads=revs,
5467 force=opts.get('force'),
5421 force=opts.get('force'),
5468 bookmarks=opts.get('bookmark', ()),
5422 bookmarks=opts.get('bookmark', ()),
5469 opargs=pullopargs).cgresult
5423 opargs=pullopargs).cgresult
5470
5424
5471 # brev is a name, which might be a bookmark to be activated at
5425 # brev is a name, which might be a bookmark to be activated at
5472 # the end of the update. In other words, it is an explicit
5426 # the end of the update. In other words, it is an explicit
5473 # destination of the update
5427 # destination of the update
5474 brev = None
5428 brev = None
5475
5429
5476 if checkout:
5430 if checkout:
5477 checkout = str(repo.changelog.rev(checkout))
5431 checkout = str(repo.changelog.rev(checkout))
5478
5432
5479 # order below depends on implementation of
5433 # order below depends on implementation of
5480 # hg.addbranchrevs(). opts['bookmark'] is ignored,
5434 # hg.addbranchrevs(). opts['bookmark'] is ignored,
5481 # because 'checkout' is determined without it.
5435 # because 'checkout' is determined without it.
5482 if opts.get('rev'):
5436 if opts.get('rev'):
5483 brev = opts['rev'][0]
5437 brev = opts['rev'][0]
5484 elif opts.get('branch'):
5438 elif opts.get('branch'):
5485 brev = opts['branch'][0]
5439 brev = opts['branch'][0]
5486 else:
5440 else:
5487 brev = branches[0]
5441 brev = branches[0]
5488 repo._subtoppath = source
5442 repo._subtoppath = source
5489 try:
5443 try:
5490 ret = postincoming(ui, repo, modheads, opts.get('update'),
5444 ret = postincoming(ui, repo, modheads, opts.get('update'),
5491 checkout, brev)
5445 checkout, brev)
5492
5446
5493 finally:
5447 finally:
5494 del repo._subtoppath
5448 del repo._subtoppath
5495
5449
5496 finally:
5450 finally:
5497 other.close()
5451 other.close()
5498 return ret
5452 return ret
5499
5453
5500 @command('^push',
5454 @command('^push',
5501 [('f', 'force', None, _('force push')),
5455 [('f', 'force', None, _('force push')),
5502 ('r', 'rev', [],
5456 ('r', 'rev', [],
5503 _('a changeset intended to be included in the destination'),
5457 _('a changeset intended to be included in the destination'),
5504 _('REV')),
5458 _('REV')),
5505 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
5459 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
5506 ('b', 'branch', [],
5460 ('b', 'branch', [],
5507 _('a specific branch you would like to push'), _('BRANCH')),
5461 _('a specific branch you would like to push'), _('BRANCH')),
5508 ('', 'new-branch', False, _('allow pushing a new branch')),
5462 ('', 'new-branch', False, _('allow pushing a new branch')),
5509 ] + remoteopts,
5463 ] + remoteopts,
5510 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
5464 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
5511 def push(ui, repo, dest=None, **opts):
5465 def push(ui, repo, dest=None, **opts):
5512 """push changes to the specified destination
5466 """push changes to the specified destination
5513
5467
5514 Push changesets from the local repository to the specified
5468 Push changesets from the local repository to the specified
5515 destination.
5469 destination.
5516
5470
5517 This operation is symmetrical to pull: it is identical to a pull
5471 This operation is symmetrical to pull: it is identical to a pull
5518 in the destination repository from the current one.
5472 in the destination repository from the current one.
5519
5473
5520 By default, push will not allow creation of new heads at the
5474 By default, push will not allow creation of new heads at the
5521 destination, since multiple heads would make it unclear which head
5475 destination, since multiple heads would make it unclear which head
5522 to use. In this situation, it is recommended to pull and merge
5476 to use. In this situation, it is recommended to pull and merge
5523 before pushing.
5477 before pushing.
5524
5478
5525 Use --new-branch if you want to allow push to create a new named
5479 Use --new-branch if you want to allow push to create a new named
5526 branch that is not present at the destination. This allows you to
5480 branch that is not present at the destination. This allows you to
5527 only create a new branch without forcing other changes.
5481 only create a new branch without forcing other changes.
5528
5482
5529 .. note::
5483 .. note::
5530
5484
5531 Extra care should be taken with the -f/--force option,
5485 Extra care should be taken with the -f/--force option,
5532 which will push all new heads on all branches, an action which will
5486 which will push all new heads on all branches, an action which will
5533 almost always cause confusion for collaborators.
5487 almost always cause confusion for collaborators.
5534
5488
5535 If -r/--rev is used, the specified revision and all its ancestors
5489 If -r/--rev is used, the specified revision and all its ancestors
5536 will be pushed to the remote repository.
5490 will be pushed to the remote repository.
5537
5491
5538 If -B/--bookmark is used, the specified bookmarked revision, its
5492 If -B/--bookmark is used, the specified bookmarked revision, its
5539 ancestors, and the bookmark will be pushed to the remote
5493 ancestors, and the bookmark will be pushed to the remote
5540 repository. Specifying ``.`` is equivalent to specifying the active
5494 repository. Specifying ``.`` is equivalent to specifying the active
5541 bookmark's name.
5495 bookmark's name.
5542
5496
5543 Please see :hg:`help urls` for important details about ``ssh://``
5497 Please see :hg:`help urls` for important details about ``ssh://``
5544 URLs. If DESTINATION is omitted, a default path will be used.
5498 URLs. If DESTINATION is omitted, a default path will be used.
5545
5499
5546 Returns 0 if push was successful, 1 if nothing to push.
5500 Returns 0 if push was successful, 1 if nothing to push.
5547 """
5501 """
5548
5502
5549 if opts.get('bookmark'):
5503 if opts.get('bookmark'):
5550 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
5504 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
5551 for b in opts['bookmark']:
5505 for b in opts['bookmark']:
5552 # translate -B options to -r so changesets get pushed
5506 # translate -B options to -r so changesets get pushed
5553 b = repo._bookmarks.expandname(b)
5507 b = repo._bookmarks.expandname(b)
5554 if b in repo._bookmarks:
5508 if b in repo._bookmarks:
5555 opts.setdefault('rev', []).append(b)
5509 opts.setdefault('rev', []).append(b)
5556 else:
5510 else:
5557 # if we try to push a deleted bookmark, translate it to null
5511 # if we try to push a deleted bookmark, translate it to null
5558 # this lets simultaneous -r, -b options continue working
5512 # this lets simultaneous -r, -b options continue working
5559 opts.setdefault('rev', []).append("null")
5513 opts.setdefault('rev', []).append("null")
5560
5514
5561 path = ui.paths.getpath(dest, default=('default-push', 'default'))
5515 path = ui.paths.getpath(dest, default=('default-push', 'default'))
5562 if not path:
5516 if not path:
5563 raise error.Abort(_('default repository not configured!'),
5517 raise error.Abort(_('default repository not configured!'),
5564 hint=_("see 'hg help config.paths'"))
5518 hint=_("see 'hg help config.paths'"))
5565 dest = path.pushloc or path.loc
5519 dest = path.pushloc or path.loc
5566 branches = (path.branch, opts.get('branch') or [])
5520 branches = (path.branch, opts.get('branch') or [])
5567 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
5521 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
5568 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
5522 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
5569 other = hg.peer(repo, opts, dest)
5523 other = hg.peer(repo, opts, dest)
5570
5524
5571 if revs:
5525 if revs:
5572 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
5526 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
5573 if not revs:
5527 if not revs:
5574 raise error.Abort(_("specified revisions evaluate to an empty set"),
5528 raise error.Abort(_("specified revisions evaluate to an empty set"),
5575 hint=_("use different revision arguments"))
5529 hint=_("use different revision arguments"))
5576 elif path.pushrev:
5530 elif path.pushrev:
5577 # It doesn't make any sense to specify ancestor revisions. So limit
5531 # It doesn't make any sense to specify ancestor revisions. So limit
5578 # to DAG heads to make discovery simpler.
5532 # to DAG heads to make discovery simpler.
5579 expr = revset.formatspec('heads(%r)', path.pushrev)
5533 expr = revset.formatspec('heads(%r)', path.pushrev)
5580 revs = scmutil.revrange(repo, [expr])
5534 revs = scmutil.revrange(repo, [expr])
5581 revs = [repo[rev].node() for rev in revs]
5535 revs = [repo[rev].node() for rev in revs]
5582 if not revs:
5536 if not revs:
5583 raise error.Abort(_('default push revset for path evaluates to an '
5537 raise error.Abort(_('default push revset for path evaluates to an '
5584 'empty set'))
5538 'empty set'))
5585
5539
5586 repo._subtoppath = dest
5540 repo._subtoppath = dest
5587 try:
5541 try:
5588 # push subrepos depth-first for coherent ordering
5542 # push subrepos depth-first for coherent ordering
5589 c = repo['']
5543 c = repo['']
5590 subs = c.substate # only repos that are committed
5544 subs = c.substate # only repos that are committed
5591 for s in sorted(subs):
5545 for s in sorted(subs):
5592 result = c.sub(s).push(opts)
5546 result = c.sub(s).push(opts)
5593 if result == 0:
5547 if result == 0:
5594 return not result
5548 return not result
5595 finally:
5549 finally:
5596 del repo._subtoppath
5550 del repo._subtoppath
5597 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
5551 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
5598 newbranch=opts.get('new_branch'),
5552 newbranch=opts.get('new_branch'),
5599 bookmarks=opts.get('bookmark', ()),
5553 bookmarks=opts.get('bookmark', ()),
5600 opargs=opts.get('opargs'))
5554 opargs=opts.get('opargs'))
5601
5555
5602 result = not pushop.cgresult
5556 result = not pushop.cgresult
5603
5557
5604 if pushop.bkresult is not None:
5558 if pushop.bkresult is not None:
5605 if pushop.bkresult == 2:
5559 if pushop.bkresult == 2:
5606 result = 2
5560 result = 2
5607 elif not result and pushop.bkresult:
5561 elif not result and pushop.bkresult:
5608 result = 2
5562 result = 2
5609
5563
5610 return result
5564 return result
5611
5565
5612 @command('recover', [])
5566 @command('recover', [])
5613 def recover(ui, repo):
5567 def recover(ui, repo):
5614 """roll back an interrupted transaction
5568 """roll back an interrupted transaction
5615
5569
5616 Recover from an interrupted commit or pull.
5570 Recover from an interrupted commit or pull.
5617
5571
5618 This command tries to fix the repository status after an
5572 This command tries to fix the repository status after an
5619 interrupted operation. It should only be necessary when Mercurial
5573 interrupted operation. It should only be necessary when Mercurial
5620 suggests it.
5574 suggests it.
5621
5575
5622 Returns 0 if successful, 1 if nothing to recover or verify fails.
5576 Returns 0 if successful, 1 if nothing to recover or verify fails.
5623 """
5577 """
5624 if repo.recover():
5578 if repo.recover():
5625 return hg.verify(repo)
5579 return hg.verify(repo)
5626 return 1
5580 return 1
5627
5581
5628 @command('^remove|rm',
5582 @command('^remove|rm',
5629 [('A', 'after', None, _('record delete for missing files')),
5583 [('A', 'after', None, _('record delete for missing files')),
5630 ('f', 'force', None,
5584 ('f', 'force', None,
5631 _('forget added files, delete modified files')),
5585 _('forget added files, delete modified files')),
5632 ] + subrepoopts + walkopts,
5586 ] + subrepoopts + walkopts,
5633 _('[OPTION]... FILE...'),
5587 _('[OPTION]... FILE...'),
5634 inferrepo=True)
5588 inferrepo=True)
5635 def remove(ui, repo, *pats, **opts):
5589 def remove(ui, repo, *pats, **opts):
5636 """remove the specified files on the next commit
5590 """remove the specified files on the next commit
5637
5591
5638 Schedule the indicated files for removal from the current branch.
5592 Schedule the indicated files for removal from the current branch.
5639
5593
5640 This command schedules the files to be removed at the next commit.
5594 This command schedules the files to be removed at the next commit.
5641 To undo a remove before that, see :hg:`revert`. To undo added
5595 To undo a remove before that, see :hg:`revert`. To undo added
5642 files, see :hg:`forget`.
5596 files, see :hg:`forget`.
5643
5597
5644 .. container:: verbose
5598 .. container:: verbose
5645
5599
5646 -A/--after can be used to remove only files that have already
5600 -A/--after can be used to remove only files that have already
5647 been deleted, -f/--force can be used to force deletion, and -Af
5601 been deleted, -f/--force can be used to force deletion, and -Af
5648 can be used to remove files from the next revision without
5602 can be used to remove files from the next revision without
5649 deleting them from the working directory.
5603 deleting them from the working directory.
5650
5604
5651 The following table details the behavior of remove for different
5605 The following table details the behavior of remove for different
5652 file states (columns) and option combinations (rows). The file
5606 file states (columns) and option combinations (rows). The file
5653 states are Added [A], Clean [C], Modified [M] and Missing [!]
5607 states are Added [A], Clean [C], Modified [M] and Missing [!]
5654 (as reported by :hg:`status`). The actions are Warn, Remove
5608 (as reported by :hg:`status`). The actions are Warn, Remove
5655 (from branch) and Delete (from disk):
5609 (from branch) and Delete (from disk):
5656
5610
5657 ========= == == == ==
5611 ========= == == == ==
5658 opt/state A C M !
5612 opt/state A C M !
5659 ========= == == == ==
5613 ========= == == == ==
5660 none W RD W R
5614 none W RD W R
5661 -f R RD RD R
5615 -f R RD RD R
5662 -A W W W R
5616 -A W W W R
5663 -Af R R R R
5617 -Af R R R R
5664 ========= == == == ==
5618 ========= == == == ==
5665
5619
5666 .. note::
5620 .. note::
5667
5621
5668 :hg:`remove` never deletes files in Added [A] state from the
5622 :hg:`remove` never deletes files in Added [A] state from the
5669 working directory, not even if ``--force`` is specified.
5623 working directory, not even if ``--force`` is specified.
5670
5624
5671 Returns 0 on success, 1 if any warnings encountered.
5625 Returns 0 on success, 1 if any warnings encountered.
5672 """
5626 """
5673
5627
5674 after, force = opts.get('after'), opts.get('force')
5628 after, force = opts.get('after'), opts.get('force')
5675 if not pats and not after:
5629 if not pats and not after:
5676 raise error.Abort(_('no files specified'))
5630 raise error.Abort(_('no files specified'))
5677
5631
5678 m = scmutil.match(repo[None], pats, opts)
5632 m = scmutil.match(repo[None], pats, opts)
5679 subrepos = opts.get('subrepos')
5633 subrepos = opts.get('subrepos')
5680 return cmdutil.remove(ui, repo, m, "", after, force, subrepos)
5634 return cmdutil.remove(ui, repo, m, "", after, force, subrepos)
5681
5635
5682 @command('rename|move|mv',
5636 @command('rename|move|mv',
5683 [('A', 'after', None, _('record a rename that has already occurred')),
5637 [('A', 'after', None, _('record a rename that has already occurred')),
5684 ('f', 'force', None, _('forcibly copy over an existing managed file')),
5638 ('f', 'force', None, _('forcibly copy over an existing managed file')),
5685 ] + walkopts + dryrunopts,
5639 ] + walkopts + dryrunopts,
5686 _('[OPTION]... SOURCE... DEST'))
5640 _('[OPTION]... SOURCE... DEST'))
5687 def rename(ui, repo, *pats, **opts):
5641 def rename(ui, repo, *pats, **opts):
5688 """rename files; equivalent of copy + remove
5642 """rename files; equivalent of copy + remove
5689
5643
5690 Mark dest as copies of sources; mark sources for deletion. If dest
5644 Mark dest as copies of sources; mark sources for deletion. If dest
5691 is a directory, copies are put in that directory. If dest is a
5645 is a directory, copies are put in that directory. If dest is a
5692 file, there can only be one source.
5646 file, there can only be one source.
5693
5647
5694 By default, this command copies the contents of files as they
5648 By default, this command copies the contents of files as they
5695 exist in the working directory. If invoked with -A/--after, the
5649 exist in the working directory. If invoked with -A/--after, the
5696 operation is recorded, but no copying is performed.
5650 operation is recorded, but no copying is performed.
5697
5651
5698 This command takes effect at the next commit. To undo a rename
5652 This command takes effect at the next commit. To undo a rename
5699 before that, see :hg:`revert`.
5653 before that, see :hg:`revert`.
5700
5654
5701 Returns 0 on success, 1 if errors are encountered.
5655 Returns 0 on success, 1 if errors are encountered.
5702 """
5656 """
5703 with repo.wlock(False):
5657 with repo.wlock(False):
5704 return cmdutil.copy(ui, repo, pats, opts, rename=True)
5658 return cmdutil.copy(ui, repo, pats, opts, rename=True)
5705
5659
5706 @command('resolve',
5660 @command('resolve',
5707 [('a', 'all', None, _('select all unresolved files')),
5661 [('a', 'all', None, _('select all unresolved files')),
5708 ('l', 'list', None, _('list state of files needing merge')),
5662 ('l', 'list', None, _('list state of files needing merge')),
5709 ('m', 'mark', None, _('mark files as resolved')),
5663 ('m', 'mark', None, _('mark files as resolved')),
5710 ('u', 'unmark', None, _('mark files as unresolved')),
5664 ('u', 'unmark', None, _('mark files as unresolved')),
5711 ('n', 'no-status', None, _('hide status prefix'))]
5665 ('n', 'no-status', None, _('hide status prefix'))]
5712 + mergetoolopts + walkopts + formatteropts,
5666 + mergetoolopts + walkopts + formatteropts,
5713 _('[OPTION]... [FILE]...'),
5667 _('[OPTION]... [FILE]...'),
5714 inferrepo=True)
5668 inferrepo=True)
5715 def resolve(ui, repo, *pats, **opts):
5669 def resolve(ui, repo, *pats, **opts):
5716 """redo merges or set/view the merge status of files
5670 """redo merges or set/view the merge status of files
5717
5671
5718 Merges with unresolved conflicts are often the result of
5672 Merges with unresolved conflicts are often the result of
5719 non-interactive merging using the ``internal:merge`` configuration
5673 non-interactive merging using the ``internal:merge`` configuration
5720 setting, or a command-line merge tool like ``diff3``. The resolve
5674 setting, or a command-line merge tool like ``diff3``. The resolve
5721 command is used to manage the files involved in a merge, after
5675 command is used to manage the files involved in a merge, after
5722 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
5676 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
5723 working directory must have two parents). See :hg:`help
5677 working directory must have two parents). See :hg:`help
5724 merge-tools` for information on configuring merge tools.
5678 merge-tools` for information on configuring merge tools.
5725
5679
5726 The resolve command can be used in the following ways:
5680 The resolve command can be used in the following ways:
5727
5681
5728 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
5682 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
5729 files, discarding any previous merge attempts. Re-merging is not
5683 files, discarding any previous merge attempts. Re-merging is not
5730 performed for files already marked as resolved. Use ``--all/-a``
5684 performed for files already marked as resolved. Use ``--all/-a``
5731 to select all unresolved files. ``--tool`` can be used to specify
5685 to select all unresolved files. ``--tool`` can be used to specify
5732 the merge tool used for the given files. It overrides the HGMERGE
5686 the merge tool used for the given files. It overrides the HGMERGE
5733 environment variable and your configuration files. Previous file
5687 environment variable and your configuration files. Previous file
5734 contents are saved with a ``.orig`` suffix.
5688 contents are saved with a ``.orig`` suffix.
5735
5689
5736 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
5690 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
5737 (e.g. after having manually fixed-up the files). The default is
5691 (e.g. after having manually fixed-up the files). The default is
5738 to mark all unresolved files.
5692 to mark all unresolved files.
5739
5693
5740 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
5694 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
5741 default is to mark all resolved files.
5695 default is to mark all resolved files.
5742
5696
5743 - :hg:`resolve -l`: list files which had or still have conflicts.
5697 - :hg:`resolve -l`: list files which had or still have conflicts.
5744 In the printed list, ``U`` = unresolved and ``R`` = resolved.
5698 In the printed list, ``U`` = unresolved and ``R`` = resolved.
5745
5699
5746 .. note::
5700 .. note::
5747
5701
5748 Mercurial will not let you commit files with unresolved merge
5702 Mercurial will not let you commit files with unresolved merge
5749 conflicts. You must use :hg:`resolve -m ...` before you can
5703 conflicts. You must use :hg:`resolve -m ...` before you can
5750 commit after a conflicting merge.
5704 commit after a conflicting merge.
5751
5705
5752 Returns 0 on success, 1 if any files fail a resolve attempt.
5706 Returns 0 on success, 1 if any files fail a resolve attempt.
5753 """
5707 """
5754
5708
5755 flaglist = 'all mark unmark list no_status'.split()
5709 flaglist = 'all mark unmark list no_status'.split()
5756 all, mark, unmark, show, nostatus = \
5710 all, mark, unmark, show, nostatus = \
5757 [opts.get(o) for o in flaglist]
5711 [opts.get(o) for o in flaglist]
5758
5712
5759 if (show and (mark or unmark)) or (mark and unmark):
5713 if (show and (mark or unmark)) or (mark and unmark):
5760 raise error.Abort(_("too many options specified"))
5714 raise error.Abort(_("too many options specified"))
5761 if pats and all:
5715 if pats and all:
5762 raise error.Abort(_("can't specify --all and patterns"))
5716 raise error.Abort(_("can't specify --all and patterns"))
5763 if not (all or pats or show or mark or unmark):
5717 if not (all or pats or show or mark or unmark):
5764 raise error.Abort(_('no files or directories specified'),
5718 raise error.Abort(_('no files or directories specified'),
5765 hint=('use --all to re-merge all unresolved files'))
5719 hint=('use --all to re-merge all unresolved files'))
5766
5720
5767 if show:
5721 if show:
5768 fm = ui.formatter('resolve', opts)
5722 fm = ui.formatter('resolve', opts)
5769 ms = mergemod.mergestate.read(repo)
5723 ms = mergemod.mergestate.read(repo)
5770 m = scmutil.match(repo[None], pats, opts)
5724 m = scmutil.match(repo[None], pats, opts)
5771 for f in ms:
5725 for f in ms:
5772 if not m(f):
5726 if not m(f):
5773 continue
5727 continue
5774 l = 'resolve.' + {'u': 'unresolved', 'r': 'resolved',
5728 l = 'resolve.' + {'u': 'unresolved', 'r': 'resolved',
5775 'd': 'driverresolved'}[ms[f]]
5729 'd': 'driverresolved'}[ms[f]]
5776 fm.startitem()
5730 fm.startitem()
5777 fm.condwrite(not nostatus, 'status', '%s ', ms[f].upper(), label=l)
5731 fm.condwrite(not nostatus, 'status', '%s ', ms[f].upper(), label=l)
5778 fm.write('path', '%s\n', f, label=l)
5732 fm.write('path', '%s\n', f, label=l)
5779 fm.end()
5733 fm.end()
5780 return 0
5734 return 0
5781
5735
5782 with repo.wlock():
5736 with repo.wlock():
5783 ms = mergemod.mergestate.read(repo)
5737 ms = mergemod.mergestate.read(repo)
5784
5738
5785 if not (ms.active() or repo.dirstate.p2() != nullid):
5739 if not (ms.active() or repo.dirstate.p2() != nullid):
5786 raise error.Abort(
5740 raise error.Abort(
5787 _('resolve command not applicable when not merging'))
5741 _('resolve command not applicable when not merging'))
5788
5742
5789 wctx = repo[None]
5743 wctx = repo[None]
5790
5744
5791 if ms.mergedriver and ms.mdstate() == 'u':
5745 if ms.mergedriver and ms.mdstate() == 'u':
5792 proceed = mergemod.driverpreprocess(repo, ms, wctx)
5746 proceed = mergemod.driverpreprocess(repo, ms, wctx)
5793 ms.commit()
5747 ms.commit()
5794 # allow mark and unmark to go through
5748 # allow mark and unmark to go through
5795 if not mark and not unmark and not proceed:
5749 if not mark and not unmark and not proceed:
5796 return 1
5750 return 1
5797
5751
5798 m = scmutil.match(wctx, pats, opts)
5752 m = scmutil.match(wctx, pats, opts)
5799 ret = 0
5753 ret = 0
5800 didwork = False
5754 didwork = False
5801 runconclude = False
5755 runconclude = False
5802
5756
5803 tocomplete = []
5757 tocomplete = []
5804 for f in ms:
5758 for f in ms:
5805 if not m(f):
5759 if not m(f):
5806 continue
5760 continue
5807
5761
5808 didwork = True
5762 didwork = True
5809
5763
5810 # don't let driver-resolved files be marked, and run the conclude
5764 # don't let driver-resolved files be marked, and run the conclude
5811 # step if asked to resolve
5765 # step if asked to resolve
5812 if ms[f] == "d":
5766 if ms[f] == "d":
5813 exact = m.exact(f)
5767 exact = m.exact(f)
5814 if mark:
5768 if mark:
5815 if exact:
5769 if exact:
5816 ui.warn(_('not marking %s as it is driver-resolved\n')
5770 ui.warn(_('not marking %s as it is driver-resolved\n')
5817 % f)
5771 % f)
5818 elif unmark:
5772 elif unmark:
5819 if exact:
5773 if exact:
5820 ui.warn(_('not unmarking %s as it is driver-resolved\n')
5774 ui.warn(_('not unmarking %s as it is driver-resolved\n')
5821 % f)
5775 % f)
5822 else:
5776 else:
5823 runconclude = True
5777 runconclude = True
5824 continue
5778 continue
5825
5779
5826 if mark:
5780 if mark:
5827 ms.mark(f, "r")
5781 ms.mark(f, "r")
5828 elif unmark:
5782 elif unmark:
5829 ms.mark(f, "u")
5783 ms.mark(f, "u")
5830 else:
5784 else:
5831 # backup pre-resolve (merge uses .orig for its own purposes)
5785 # backup pre-resolve (merge uses .orig for its own purposes)
5832 a = repo.wjoin(f)
5786 a = repo.wjoin(f)
5833 try:
5787 try:
5834 util.copyfile(a, a + ".resolve")
5788 util.copyfile(a, a + ".resolve")
5835 except (IOError, OSError) as inst:
5789 except (IOError, OSError) as inst:
5836 if inst.errno != errno.ENOENT:
5790 if inst.errno != errno.ENOENT:
5837 raise
5791 raise
5838
5792
5839 try:
5793 try:
5840 # preresolve file
5794 # preresolve file
5841 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
5795 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
5842 'resolve')
5796 'resolve')
5843 complete, r = ms.preresolve(f, wctx)
5797 complete, r = ms.preresolve(f, wctx)
5844 if not complete:
5798 if not complete:
5845 tocomplete.append(f)
5799 tocomplete.append(f)
5846 elif r:
5800 elif r:
5847 ret = 1
5801 ret = 1
5848 finally:
5802 finally:
5849 ui.setconfig('ui', 'forcemerge', '', 'resolve')
5803 ui.setconfig('ui', 'forcemerge', '', 'resolve')
5850 ms.commit()
5804 ms.commit()
5851
5805
5852 # replace filemerge's .orig file with our resolve file, but only
5806 # replace filemerge's .orig file with our resolve file, but only
5853 # for merges that are complete
5807 # for merges that are complete
5854 if complete:
5808 if complete:
5855 try:
5809 try:
5856 util.rename(a + ".resolve",
5810 util.rename(a + ".resolve",
5857 scmutil.origpath(ui, repo, a))
5811 scmutil.origpath(ui, repo, a))
5858 except OSError as inst:
5812 except OSError as inst:
5859 if inst.errno != errno.ENOENT:
5813 if inst.errno != errno.ENOENT:
5860 raise
5814 raise
5861
5815
5862 for f in tocomplete:
5816 for f in tocomplete:
5863 try:
5817 try:
5864 # resolve file
5818 # resolve file
5865 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
5819 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
5866 'resolve')
5820 'resolve')
5867 r = ms.resolve(f, wctx)
5821 r = ms.resolve(f, wctx)
5868 if r:
5822 if r:
5869 ret = 1
5823 ret = 1
5870 finally:
5824 finally:
5871 ui.setconfig('ui', 'forcemerge', '', 'resolve')
5825 ui.setconfig('ui', 'forcemerge', '', 'resolve')
5872 ms.commit()
5826 ms.commit()
5873
5827
5874 # replace filemerge's .orig file with our resolve file
5828 # replace filemerge's .orig file with our resolve file
5875 a = repo.wjoin(f)
5829 a = repo.wjoin(f)
5876 try:
5830 try:
5877 util.rename(a + ".resolve", scmutil.origpath(ui, repo, a))
5831 util.rename(a + ".resolve", scmutil.origpath(ui, repo, a))
5878 except OSError as inst:
5832 except OSError as inst:
5879 if inst.errno != errno.ENOENT:
5833 if inst.errno != errno.ENOENT:
5880 raise
5834 raise
5881
5835
5882 ms.commit()
5836 ms.commit()
5883 ms.recordactions()
5837 ms.recordactions()
5884
5838
5885 if not didwork and pats:
5839 if not didwork and pats:
5886 hint = None
5840 hint = None
5887 if not any([p for p in pats if p.find(':') >= 0]):
5841 if not any([p for p in pats if p.find(':') >= 0]):
5888 pats = ['path:%s' % p for p in pats]
5842 pats = ['path:%s' % p for p in pats]
5889 m = scmutil.match(wctx, pats, opts)
5843 m = scmutil.match(wctx, pats, opts)
5890 for f in ms:
5844 for f in ms:
5891 if not m(f):
5845 if not m(f):
5892 continue
5846 continue
5893 flags = ''.join(['-%s ' % o[0] for o in flaglist
5847 flags = ''.join(['-%s ' % o[0] for o in flaglist
5894 if opts.get(o)])
5848 if opts.get(o)])
5895 hint = _("(try: hg resolve %s%s)\n") % (
5849 hint = _("(try: hg resolve %s%s)\n") % (
5896 flags,
5850 flags,
5897 ' '.join(pats))
5851 ' '.join(pats))
5898 break
5852 break
5899 ui.warn(_("arguments do not match paths that need resolving\n"))
5853 ui.warn(_("arguments do not match paths that need resolving\n"))
5900 if hint:
5854 if hint:
5901 ui.warn(hint)
5855 ui.warn(hint)
5902 elif ms.mergedriver and ms.mdstate() != 's':
5856 elif ms.mergedriver and ms.mdstate() != 's':
5903 # run conclude step when either a driver-resolved file is requested
5857 # run conclude step when either a driver-resolved file is requested
5904 # or there are no driver-resolved files
5858 # or there are no driver-resolved files
5905 # we can't use 'ret' to determine whether any files are unresolved
5859 # we can't use 'ret' to determine whether any files are unresolved
5906 # because we might not have tried to resolve some
5860 # because we might not have tried to resolve some
5907 if ((runconclude or not list(ms.driverresolved()))
5861 if ((runconclude or not list(ms.driverresolved()))
5908 and not list(ms.unresolved())):
5862 and not list(ms.unresolved())):
5909 proceed = mergemod.driverconclude(repo, ms, wctx)
5863 proceed = mergemod.driverconclude(repo, ms, wctx)
5910 ms.commit()
5864 ms.commit()
5911 if not proceed:
5865 if not proceed:
5912 return 1
5866 return 1
5913
5867
5914 # Nudge users into finishing an unfinished operation
5868 # Nudge users into finishing an unfinished operation
5915 unresolvedf = list(ms.unresolved())
5869 unresolvedf = list(ms.unresolved())
5916 driverresolvedf = list(ms.driverresolved())
5870 driverresolvedf = list(ms.driverresolved())
5917 if not unresolvedf and not driverresolvedf:
5871 if not unresolvedf and not driverresolvedf:
5918 ui.status(_('(no more unresolved files)\n'))
5872 ui.status(_('(no more unresolved files)\n'))
5919 cmdutil.checkafterresolved(repo)
5873 cmdutil.checkafterresolved(repo)
5920 elif not unresolvedf:
5874 elif not unresolvedf:
5921 ui.status(_('(no more unresolved files -- '
5875 ui.status(_('(no more unresolved files -- '
5922 'run "hg resolve --all" to conclude)\n'))
5876 'run "hg resolve --all" to conclude)\n'))
5923
5877
5924 return ret
5878 return ret
5925
5879
5926 @command('revert',
5880 @command('revert',
5927 [('a', 'all', None, _('revert all changes when no arguments given')),
5881 [('a', 'all', None, _('revert all changes when no arguments given')),
5928 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5882 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5929 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5883 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5930 ('C', 'no-backup', None, _('do not save backup copies of files')),
5884 ('C', 'no-backup', None, _('do not save backup copies of files')),
5931 ('i', 'interactive', None,
5885 ('i', 'interactive', None,
5932 _('interactively select the changes (EXPERIMENTAL)')),
5886 _('interactively select the changes (EXPERIMENTAL)')),
5933 ] + walkopts + dryrunopts,
5887 ] + walkopts + dryrunopts,
5934 _('[OPTION]... [-r REV] [NAME]...'))
5888 _('[OPTION]... [-r REV] [NAME]...'))
5935 def revert(ui, repo, *pats, **opts):
5889 def revert(ui, repo, *pats, **opts):
5936 """restore files to their checkout state
5890 """restore files to their checkout state
5937
5891
5938 .. note::
5892 .. note::
5939
5893
5940 To check out earlier revisions, you should use :hg:`update REV`.
5894 To check out earlier revisions, you should use :hg:`update REV`.
5941 To cancel an uncommitted merge (and lose your changes),
5895 To cancel an uncommitted merge (and lose your changes),
5942 use :hg:`update --clean .`.
5896 use :hg:`update --clean .`.
5943
5897
5944 With no revision specified, revert the specified files or directories
5898 With no revision specified, revert the specified files or directories
5945 to the contents they had in the parent of the working directory.
5899 to the contents they had in the parent of the working directory.
5946 This restores the contents of files to an unmodified
5900 This restores the contents of files to an unmodified
5947 state and unschedules adds, removes, copies, and renames. If the
5901 state and unschedules adds, removes, copies, and renames. If the
5948 working directory has two parents, you must explicitly specify a
5902 working directory has two parents, you must explicitly specify a
5949 revision.
5903 revision.
5950
5904
5951 Using the -r/--rev or -d/--date options, revert the given files or
5905 Using the -r/--rev or -d/--date options, revert the given files or
5952 directories to their states as of a specific revision. Because
5906 directories to their states as of a specific revision. Because
5953 revert does not change the working directory parents, this will
5907 revert does not change the working directory parents, this will
5954 cause these files to appear modified. This can be helpful to "back
5908 cause these files to appear modified. This can be helpful to "back
5955 out" some or all of an earlier change. See :hg:`backout` for a
5909 out" some or all of an earlier change. See :hg:`backout` for a
5956 related method.
5910 related method.
5957
5911
5958 Modified files are saved with a .orig suffix before reverting.
5912 Modified files are saved with a .orig suffix before reverting.
5959 To disable these backups, use --no-backup. It is possible to store
5913 To disable these backups, use --no-backup. It is possible to store
5960 the backup files in a custom directory relative to the root of the
5914 the backup files in a custom directory relative to the root of the
5961 repository by setting the ``ui.origbackuppath`` configuration
5915 repository by setting the ``ui.origbackuppath`` configuration
5962 option.
5916 option.
5963
5917
5964 See :hg:`help dates` for a list of formats valid for -d/--date.
5918 See :hg:`help dates` for a list of formats valid for -d/--date.
5965
5919
5966 See :hg:`help backout` for a way to reverse the effect of an
5920 See :hg:`help backout` for a way to reverse the effect of an
5967 earlier changeset.
5921 earlier changeset.
5968
5922
5969 Returns 0 on success.
5923 Returns 0 on success.
5970 """
5924 """
5971
5925
5972 if opts.get("date"):
5926 if opts.get("date"):
5973 if opts.get("rev"):
5927 if opts.get("rev"):
5974 raise error.Abort(_("you can't specify a revision and a date"))
5928 raise error.Abort(_("you can't specify a revision and a date"))
5975 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5929 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5976
5930
5977 parent, p2 = repo.dirstate.parents()
5931 parent, p2 = repo.dirstate.parents()
5978 if not opts.get('rev') and p2 != nullid:
5932 if not opts.get('rev') and p2 != nullid:
5979 # revert after merge is a trap for new users (issue2915)
5933 # revert after merge is a trap for new users (issue2915)
5980 raise error.Abort(_('uncommitted merge with no revision specified'),
5934 raise error.Abort(_('uncommitted merge with no revision specified'),
5981 hint=_("use 'hg update' or see 'hg help revert'"))
5935 hint=_("use 'hg update' or see 'hg help revert'"))
5982
5936
5983 ctx = scmutil.revsingle(repo, opts.get('rev'))
5937 ctx = scmutil.revsingle(repo, opts.get('rev'))
5984
5938
5985 if (not (pats or opts.get('include') or opts.get('exclude') or
5939 if (not (pats or opts.get('include') or opts.get('exclude') or
5986 opts.get('all') or opts.get('interactive'))):
5940 opts.get('all') or opts.get('interactive'))):
5987 msg = _("no files or directories specified")
5941 msg = _("no files or directories specified")
5988 if p2 != nullid:
5942 if p2 != nullid:
5989 hint = _("uncommitted merge, use --all to discard all changes,"
5943 hint = _("uncommitted merge, use --all to discard all changes,"
5990 " or 'hg update -C .' to abort the merge")
5944 " or 'hg update -C .' to abort the merge")
5991 raise error.Abort(msg, hint=hint)
5945 raise error.Abort(msg, hint=hint)
5992 dirty = any(repo.status())
5946 dirty = any(repo.status())
5993 node = ctx.node()
5947 node = ctx.node()
5994 if node != parent:
5948 if node != parent:
5995 if dirty:
5949 if dirty:
5996 hint = _("uncommitted changes, use --all to discard all"
5950 hint = _("uncommitted changes, use --all to discard all"
5997 " changes, or 'hg update %s' to update") % ctx.rev()
5951 " changes, or 'hg update %s' to update") % ctx.rev()
5998 else:
5952 else:
5999 hint = _("use --all to revert all files,"
5953 hint = _("use --all to revert all files,"
6000 " or 'hg update %s' to update") % ctx.rev()
5954 " or 'hg update %s' to update") % ctx.rev()
6001 elif dirty:
5955 elif dirty:
6002 hint = _("uncommitted changes, use --all to discard all changes")
5956 hint = _("uncommitted changes, use --all to discard all changes")
6003 else:
5957 else:
6004 hint = _("use --all to revert all files")
5958 hint = _("use --all to revert all files")
6005 raise error.Abort(msg, hint=hint)
5959 raise error.Abort(msg, hint=hint)
6006
5960
6007 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5961 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
6008
5962
6009 @command('rollback', dryrunopts +
5963 @command('rollback', dryrunopts +
6010 [('f', 'force', False, _('ignore safety measures'))])
5964 [('f', 'force', False, _('ignore safety measures'))])
6011 def rollback(ui, repo, **opts):
5965 def rollback(ui, repo, **opts):
6012 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5966 """roll back the last transaction (DANGEROUS) (DEPRECATED)
6013
5967
6014 Please use :hg:`commit --amend` instead of rollback to correct
5968 Please use :hg:`commit --amend` instead of rollback to correct
6015 mistakes in the last commit.
5969 mistakes in the last commit.
6016
5970
6017 This command should be used with care. There is only one level of
5971 This command should be used with care. There is only one level of
6018 rollback, and there is no way to undo a rollback. It will also
5972 rollback, and there is no way to undo a rollback. It will also
6019 restore the dirstate at the time of the last transaction, losing
5973 restore the dirstate at the time of the last transaction, losing
6020 any dirstate changes since that time. This command does not alter
5974 any dirstate changes since that time. This command does not alter
6021 the working directory.
5975 the working directory.
6022
5976
6023 Transactions are used to encapsulate the effects of all commands
5977 Transactions are used to encapsulate the effects of all commands
6024 that create new changesets or propagate existing changesets into a
5978 that create new changesets or propagate existing changesets into a
6025 repository.
5979 repository.
6026
5980
6027 .. container:: verbose
5981 .. container:: verbose
6028
5982
6029 For example, the following commands are transactional, and their
5983 For example, the following commands are transactional, and their
6030 effects can be rolled back:
5984 effects can be rolled back:
6031
5985
6032 - commit
5986 - commit
6033 - import
5987 - import
6034 - pull
5988 - pull
6035 - push (with this repository as the destination)
5989 - push (with this repository as the destination)
6036 - unbundle
5990 - unbundle
6037
5991
6038 To avoid permanent data loss, rollback will refuse to rollback a
5992 To avoid permanent data loss, rollback will refuse to rollback a
6039 commit transaction if it isn't checked out. Use --force to
5993 commit transaction if it isn't checked out. Use --force to
6040 override this protection.
5994 override this protection.
6041
5995
6042 The rollback command can be entirely disabled by setting the
5996 The rollback command can be entirely disabled by setting the
6043 ``ui.rollback`` configuration setting to false. If you're here
5997 ``ui.rollback`` configuration setting to false. If you're here
6044 because you want to use rollback and it's disabled, you can
5998 because you want to use rollback and it's disabled, you can
6045 re-enable the command by setting ``ui.rollback`` to true.
5999 re-enable the command by setting ``ui.rollback`` to true.
6046
6000
6047 This command is not intended for use on public repositories. Once
6001 This command is not intended for use on public repositories. Once
6048 changes are visible for pull by other users, rolling a transaction
6002 changes are visible for pull by other users, rolling a transaction
6049 back locally is ineffective (someone else may already have pulled
6003 back locally is ineffective (someone else may already have pulled
6050 the changes). Furthermore, a race is possible with readers of the
6004 the changes). Furthermore, a race is possible with readers of the
6051 repository; for example an in-progress pull from the repository
6005 repository; for example an in-progress pull from the repository
6052 may fail if a rollback is performed.
6006 may fail if a rollback is performed.
6053
6007
6054 Returns 0 on success, 1 if no rollback data is available.
6008 Returns 0 on success, 1 if no rollback data is available.
6055 """
6009 """
6056 if not ui.configbool('ui', 'rollback', True):
6010 if not ui.configbool('ui', 'rollback', True):
6057 raise error.Abort(_('rollback is disabled because it is unsafe'),
6011 raise error.Abort(_('rollback is disabled because it is unsafe'),
6058 hint=('see `hg help -v rollback` for information'))
6012 hint=('see `hg help -v rollback` for information'))
6059 return repo.rollback(dryrun=opts.get('dry_run'),
6013 return repo.rollback(dryrun=opts.get('dry_run'),
6060 force=opts.get('force'))
6014 force=opts.get('force'))
6061
6015
6062 @command('root', [])
6016 @command('root', [])
6063 def root(ui, repo):
6017 def root(ui, repo):
6064 """print the root (top) of the current working directory
6018 """print the root (top) of the current working directory
6065
6019
6066 Print the root directory of the current repository.
6020 Print the root directory of the current repository.
6067
6021
6068 Returns 0 on success.
6022 Returns 0 on success.
6069 """
6023 """
6070 ui.write(repo.root + "\n")
6024 ui.write(repo.root + "\n")
6071
6025
6072 @command('^serve',
6026 @command('^serve',
6073 [('A', 'accesslog', '', _('name of access log file to write to'),
6027 [('A', 'accesslog', '', _('name of access log file to write to'),
6074 _('FILE')),
6028 _('FILE')),
6075 ('d', 'daemon', None, _('run server in background')),
6029 ('d', 'daemon', None, _('run server in background')),
6076 ('', 'daemon-postexec', [], _('used internally by daemon mode')),
6030 ('', 'daemon-postexec', [], _('used internally by daemon mode')),
6077 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
6031 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
6078 # use string type, then we can check if something was passed
6032 # use string type, then we can check if something was passed
6079 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
6033 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
6080 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
6034 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
6081 _('ADDR')),
6035 _('ADDR')),
6082 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
6036 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
6083 _('PREFIX')),
6037 _('PREFIX')),
6084 ('n', 'name', '',
6038 ('n', 'name', '',
6085 _('name to show in web pages (default: working directory)'), _('NAME')),
6039 _('name to show in web pages (default: working directory)'), _('NAME')),
6086 ('', 'web-conf', '',
6040 ('', 'web-conf', '',
6087 _("name of the hgweb config file (see 'hg help hgweb')"), _('FILE')),
6041 _("name of the hgweb config file (see 'hg help hgweb')"), _('FILE')),
6088 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
6042 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
6089 _('FILE')),
6043 _('FILE')),
6090 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
6044 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
6091 ('', 'stdio', None, _('for remote clients')),
6045 ('', 'stdio', None, _('for remote clients')),
6092 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
6046 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
6093 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
6047 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
6094 ('', 'style', '', _('template style to use'), _('STYLE')),
6048 ('', 'style', '', _('template style to use'), _('STYLE')),
6095 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
6049 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
6096 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
6050 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
6097 _('[OPTION]...'),
6051 _('[OPTION]...'),
6098 optionalrepo=True)
6052 optionalrepo=True)
6099 def serve(ui, repo, **opts):
6053 def serve(ui, repo, **opts):
6100 """start stand-alone webserver
6054 """start stand-alone webserver
6101
6055
6102 Start a local HTTP repository browser and pull server. You can use
6056 Start a local HTTP repository browser and pull server. You can use
6103 this for ad-hoc sharing and browsing of repositories. It is
6057 this for ad-hoc sharing and browsing of repositories. It is
6104 recommended to use a real web server to serve a repository for
6058 recommended to use a real web server to serve a repository for
6105 longer periods of time.
6059 longer periods of time.
6106
6060
6107 Please note that the server does not implement access control.
6061 Please note that the server does not implement access control.
6108 This means that, by default, anybody can read from the server and
6062 This means that, by default, anybody can read from the server and
6109 nobody can write to it by default. Set the ``web.allow_push``
6063 nobody can write to it by default. Set the ``web.allow_push``
6110 option to ``*`` to allow everybody to push to the server. You
6064 option to ``*`` to allow everybody to push to the server. You
6111 should use a real web server if you need to authenticate users.
6065 should use a real web server if you need to authenticate users.
6112
6066
6113 By default, the server logs accesses to stdout and errors to
6067 By default, the server logs accesses to stdout and errors to
6114 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
6068 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
6115 files.
6069 files.
6116
6070
6117 To have the server choose a free port number to listen on, specify
6071 To have the server choose a free port number to listen on, specify
6118 a port number of 0; in this case, the server will print the port
6072 a port number of 0; in this case, the server will print the port
6119 number it uses.
6073 number it uses.
6120
6074
6121 Returns 0 on success.
6075 Returns 0 on success.
6122 """
6076 """
6123
6077
6124 if opts["stdio"] and opts["cmdserver"]:
6078 if opts["stdio"] and opts["cmdserver"]:
6125 raise error.Abort(_("cannot use --stdio with --cmdserver"))
6079 raise error.Abort(_("cannot use --stdio with --cmdserver"))
6126
6080
6127 if opts["stdio"]:
6081 if opts["stdio"]:
6128 if repo is None:
6082 if repo is None:
6129 raise error.RepoError(_("there is no Mercurial repository here"
6083 raise error.RepoError(_("there is no Mercurial repository here"
6130 " (.hg not found)"))
6084 " (.hg not found)"))
6131 s = sshserver.sshserver(ui, repo)
6085 s = sshserver.sshserver(ui, repo)
6132 s.serve_forever()
6086 s.serve_forever()
6133
6087
6134 service = server.createservice(ui, repo, opts)
6088 service = server.createservice(ui, repo, opts)
6135 return server.runservice(opts, initfn=service.init, runfn=service.run)
6089 return server.runservice(opts, initfn=service.init, runfn=service.run)
6136
6090
6137 @command('^status|st',
6091 @command('^status|st',
6138 [('A', 'all', None, _('show status of all files')),
6092 [('A', 'all', None, _('show status of all files')),
6139 ('m', 'modified', None, _('show only modified files')),
6093 ('m', 'modified', None, _('show only modified files')),
6140 ('a', 'added', None, _('show only added files')),
6094 ('a', 'added', None, _('show only added files')),
6141 ('r', 'removed', None, _('show only removed files')),
6095 ('r', 'removed', None, _('show only removed files')),
6142 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
6096 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
6143 ('c', 'clean', None, _('show only files without changes')),
6097 ('c', 'clean', None, _('show only files without changes')),
6144 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
6098 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
6145 ('i', 'ignored', None, _('show only ignored files')),
6099 ('i', 'ignored', None, _('show only ignored files')),
6146 ('n', 'no-status', None, _('hide status prefix')),
6100 ('n', 'no-status', None, _('hide status prefix')),
6147 ('C', 'copies', None, _('show source of copied files')),
6101 ('C', 'copies', None, _('show source of copied files')),
6148 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
6102 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
6149 ('', 'rev', [], _('show difference from revision'), _('REV')),
6103 ('', 'rev', [], _('show difference from revision'), _('REV')),
6150 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
6104 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
6151 ] + walkopts + subrepoopts + formatteropts,
6105 ] + walkopts + subrepoopts + formatteropts,
6152 _('[OPTION]... [FILE]...'),
6106 _('[OPTION]... [FILE]...'),
6153 inferrepo=True)
6107 inferrepo=True)
6154 def status(ui, repo, *pats, **opts):
6108 def status(ui, repo, *pats, **opts):
6155 """show changed files in the working directory
6109 """show changed files in the working directory
6156
6110
6157 Show status of files in the repository. If names are given, only
6111 Show status of files in the repository. If names are given, only
6158 files that match are shown. Files that are clean or ignored or
6112 files that match are shown. Files that are clean or ignored or
6159 the source of a copy/move operation, are not listed unless
6113 the source of a copy/move operation, are not listed unless
6160 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
6114 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
6161 Unless options described with "show only ..." are given, the
6115 Unless options described with "show only ..." are given, the
6162 options -mardu are used.
6116 options -mardu are used.
6163
6117
6164 Option -q/--quiet hides untracked (unknown and ignored) files
6118 Option -q/--quiet hides untracked (unknown and ignored) files
6165 unless explicitly requested with -u/--unknown or -i/--ignored.
6119 unless explicitly requested with -u/--unknown or -i/--ignored.
6166
6120
6167 .. note::
6121 .. note::
6168
6122
6169 :hg:`status` may appear to disagree with diff if permissions have
6123 :hg:`status` may appear to disagree with diff if permissions have
6170 changed or a merge has occurred. The standard diff format does
6124 changed or a merge has occurred. The standard diff format does
6171 not report permission changes and diff only reports changes
6125 not report permission changes and diff only reports changes
6172 relative to one merge parent.
6126 relative to one merge parent.
6173
6127
6174 If one revision is given, it is used as the base revision.
6128 If one revision is given, it is used as the base revision.
6175 If two revisions are given, the differences between them are
6129 If two revisions are given, the differences between them are
6176 shown. The --change option can also be used as a shortcut to list
6130 shown. The --change option can also be used as a shortcut to list
6177 the changed files of a revision from its first parent.
6131 the changed files of a revision from its first parent.
6178
6132
6179 The codes used to show the status of files are::
6133 The codes used to show the status of files are::
6180
6134
6181 M = modified
6135 M = modified
6182 A = added
6136 A = added
6183 R = removed
6137 R = removed
6184 C = clean
6138 C = clean
6185 ! = missing (deleted by non-hg command, but still tracked)
6139 ! = missing (deleted by non-hg command, but still tracked)
6186 ? = not tracked
6140 ? = not tracked
6187 I = ignored
6141 I = ignored
6188 = origin of the previous file (with --copies)
6142 = origin of the previous file (with --copies)
6189
6143
6190 .. container:: verbose
6144 .. container:: verbose
6191
6145
6192 Examples:
6146 Examples:
6193
6147
6194 - show changes in the working directory relative to a
6148 - show changes in the working directory relative to a
6195 changeset::
6149 changeset::
6196
6150
6197 hg status --rev 9353
6151 hg status --rev 9353
6198
6152
6199 - show changes in the working directory relative to the
6153 - show changes in the working directory relative to the
6200 current directory (see :hg:`help patterns` for more information)::
6154 current directory (see :hg:`help patterns` for more information)::
6201
6155
6202 hg status re:
6156 hg status re:
6203
6157
6204 - show all changes including copies in an existing changeset::
6158 - show all changes including copies in an existing changeset::
6205
6159
6206 hg status --copies --change 9353
6160 hg status --copies --change 9353
6207
6161
6208 - get a NUL separated list of added files, suitable for xargs::
6162 - get a NUL separated list of added files, suitable for xargs::
6209
6163
6210 hg status -an0
6164 hg status -an0
6211
6165
6212 Returns 0 on success.
6166 Returns 0 on success.
6213 """
6167 """
6214
6168
6215 revs = opts.get('rev')
6169 revs = opts.get('rev')
6216 change = opts.get('change')
6170 change = opts.get('change')
6217
6171
6218 if revs and change:
6172 if revs and change:
6219 msg = _('cannot specify --rev and --change at the same time')
6173 msg = _('cannot specify --rev and --change at the same time')
6220 raise error.Abort(msg)
6174 raise error.Abort(msg)
6221 elif change:
6175 elif change:
6222 node2 = scmutil.revsingle(repo, change, None).node()
6176 node2 = scmutil.revsingle(repo, change, None).node()
6223 node1 = repo[node2].p1().node()
6177 node1 = repo[node2].p1().node()
6224 else:
6178 else:
6225 node1, node2 = scmutil.revpair(repo, revs)
6179 node1, node2 = scmutil.revpair(repo, revs)
6226
6180
6227 if pats:
6181 if pats:
6228 cwd = repo.getcwd()
6182 cwd = repo.getcwd()
6229 else:
6183 else:
6230 cwd = ''
6184 cwd = ''
6231
6185
6232 if opts.get('print0'):
6186 if opts.get('print0'):
6233 end = '\0'
6187 end = '\0'
6234 else:
6188 else:
6235 end = '\n'
6189 end = '\n'
6236 copy = {}
6190 copy = {}
6237 states = 'modified added removed deleted unknown ignored clean'.split()
6191 states = 'modified added removed deleted unknown ignored clean'.split()
6238 show = [k for k in states if opts.get(k)]
6192 show = [k for k in states if opts.get(k)]
6239 if opts.get('all'):
6193 if opts.get('all'):
6240 show += ui.quiet and (states[:4] + ['clean']) or states
6194 show += ui.quiet and (states[:4] + ['clean']) or states
6241 if not show:
6195 if not show:
6242 if ui.quiet:
6196 if ui.quiet:
6243 show = states[:4]
6197 show = states[:4]
6244 else:
6198 else:
6245 show = states[:5]
6199 show = states[:5]
6246
6200
6247 m = scmutil.match(repo[node2], pats, opts)
6201 m = scmutil.match(repo[node2], pats, opts)
6248 stat = repo.status(node1, node2, m,
6202 stat = repo.status(node1, node2, m,
6249 'ignored' in show, 'clean' in show, 'unknown' in show,
6203 'ignored' in show, 'clean' in show, 'unknown' in show,
6250 opts.get('subrepos'))
6204 opts.get('subrepos'))
6251 changestates = zip(states, 'MAR!?IC', stat)
6205 changestates = zip(states, 'MAR!?IC', stat)
6252
6206
6253 if (opts.get('all') or opts.get('copies')
6207 if (opts.get('all') or opts.get('copies')
6254 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
6208 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
6255 copy = copies.pathcopies(repo[node1], repo[node2], m)
6209 copy = copies.pathcopies(repo[node1], repo[node2], m)
6256
6210
6257 fm = ui.formatter('status', opts)
6211 fm = ui.formatter('status', opts)
6258 fmt = '%s' + end
6212 fmt = '%s' + end
6259 showchar = not opts.get('no_status')
6213 showchar = not opts.get('no_status')
6260
6214
6261 for state, char, files in changestates:
6215 for state, char, files in changestates:
6262 if state in show:
6216 if state in show:
6263 label = 'status.' + state
6217 label = 'status.' + state
6264 for f in files:
6218 for f in files:
6265 fm.startitem()
6219 fm.startitem()
6266 fm.condwrite(showchar, 'status', '%s ', char, label=label)
6220 fm.condwrite(showchar, 'status', '%s ', char, label=label)
6267 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
6221 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
6268 if f in copy:
6222 if f in copy:
6269 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
6223 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
6270 label='status.copied')
6224 label='status.copied')
6271 fm.end()
6225 fm.end()
6272
6226
6273 @command('^summary|sum',
6227 @command('^summary|sum',
6274 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
6228 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
6275 def summary(ui, repo, **opts):
6229 def summary(ui, repo, **opts):
6276 """summarize working directory state
6230 """summarize working directory state
6277
6231
6278 This generates a brief summary of the working directory state,
6232 This generates a brief summary of the working directory state,
6279 including parents, branch, commit status, phase and available updates.
6233 including parents, branch, commit status, phase and available updates.
6280
6234
6281 With the --remote option, this will check the default paths for
6235 With the --remote option, this will check the default paths for
6282 incoming and outgoing changes. This can be time-consuming.
6236 incoming and outgoing changes. This can be time-consuming.
6283
6237
6284 Returns 0 on success.
6238 Returns 0 on success.
6285 """
6239 """
6286
6240
6287 ctx = repo[None]
6241 ctx = repo[None]
6288 parents = ctx.parents()
6242 parents = ctx.parents()
6289 pnode = parents[0].node()
6243 pnode = parents[0].node()
6290 marks = []
6244 marks = []
6291
6245
6292 ms = None
6246 ms = None
6293 try:
6247 try:
6294 ms = mergemod.mergestate.read(repo)
6248 ms = mergemod.mergestate.read(repo)
6295 except error.UnsupportedMergeRecords as e:
6249 except error.UnsupportedMergeRecords as e:
6296 s = ' '.join(e.recordtypes)
6250 s = ' '.join(e.recordtypes)
6297 ui.warn(
6251 ui.warn(
6298 _('warning: merge state has unsupported record types: %s\n') % s)
6252 _('warning: merge state has unsupported record types: %s\n') % s)
6299 unresolved = 0
6253 unresolved = 0
6300 else:
6254 else:
6301 unresolved = [f for f in ms if ms[f] == 'u']
6255 unresolved = [f for f in ms if ms[f] == 'u']
6302
6256
6303 for p in parents:
6257 for p in parents:
6304 # label with log.changeset (instead of log.parent) since this
6258 # label with log.changeset (instead of log.parent) since this
6305 # shows a working directory parent *changeset*:
6259 # shows a working directory parent *changeset*:
6306 # i18n: column positioning for "hg summary"
6260 # i18n: column positioning for "hg summary"
6307 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
6261 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
6308 label='log.changeset changeset.%s' % p.phasestr())
6262 label='log.changeset changeset.%s' % p.phasestr())
6309 ui.write(' '.join(p.tags()), label='log.tag')
6263 ui.write(' '.join(p.tags()), label='log.tag')
6310 if p.bookmarks():
6264 if p.bookmarks():
6311 marks.extend(p.bookmarks())
6265 marks.extend(p.bookmarks())
6312 if p.rev() == -1:
6266 if p.rev() == -1:
6313 if not len(repo):
6267 if not len(repo):
6314 ui.write(_(' (empty repository)'))
6268 ui.write(_(' (empty repository)'))
6315 else:
6269 else:
6316 ui.write(_(' (no revision checked out)'))
6270 ui.write(_(' (no revision checked out)'))
6317 ui.write('\n')
6271 ui.write('\n')
6318 if p.description():
6272 if p.description():
6319 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
6273 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
6320 label='log.summary')
6274 label='log.summary')
6321
6275
6322 branch = ctx.branch()
6276 branch = ctx.branch()
6323 bheads = repo.branchheads(branch)
6277 bheads = repo.branchheads(branch)
6324 # i18n: column positioning for "hg summary"
6278 # i18n: column positioning for "hg summary"
6325 m = _('branch: %s\n') % branch
6279 m = _('branch: %s\n') % branch
6326 if branch != 'default':
6280 if branch != 'default':
6327 ui.write(m, label='log.branch')
6281 ui.write(m, label='log.branch')
6328 else:
6282 else:
6329 ui.status(m, label='log.branch')
6283 ui.status(m, label='log.branch')
6330
6284
6331 if marks:
6285 if marks:
6332 active = repo._activebookmark
6286 active = repo._activebookmark
6333 # i18n: column positioning for "hg summary"
6287 # i18n: column positioning for "hg summary"
6334 ui.write(_('bookmarks:'), label='log.bookmark')
6288 ui.write(_('bookmarks:'), label='log.bookmark')
6335 if active is not None:
6289 if active is not None:
6336 if active in marks:
6290 if active in marks:
6337 ui.write(' *' + active, label=activebookmarklabel)
6291 ui.write(' *' + active, label=activebookmarklabel)
6338 marks.remove(active)
6292 marks.remove(active)
6339 else:
6293 else:
6340 ui.write(' [%s]' % active, label=activebookmarklabel)
6294 ui.write(' [%s]' % active, label=activebookmarklabel)
6341 for m in marks:
6295 for m in marks:
6342 ui.write(' ' + m, label='log.bookmark')
6296 ui.write(' ' + m, label='log.bookmark')
6343 ui.write('\n', label='log.bookmark')
6297 ui.write('\n', label='log.bookmark')
6344
6298
6345 status = repo.status(unknown=True)
6299 status = repo.status(unknown=True)
6346
6300
6347 c = repo.dirstate.copies()
6301 c = repo.dirstate.copies()
6348 copied, renamed = [], []
6302 copied, renamed = [], []
6349 for d, s in c.iteritems():
6303 for d, s in c.iteritems():
6350 if s in status.removed:
6304 if s in status.removed:
6351 status.removed.remove(s)
6305 status.removed.remove(s)
6352 renamed.append(d)
6306 renamed.append(d)
6353 else:
6307 else:
6354 copied.append(d)
6308 copied.append(d)
6355 if d in status.added:
6309 if d in status.added:
6356 status.added.remove(d)
6310 status.added.remove(d)
6357
6311
6358 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
6312 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
6359
6313
6360 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
6314 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
6361 (ui.label(_('%d added'), 'status.added'), status.added),
6315 (ui.label(_('%d added'), 'status.added'), status.added),
6362 (ui.label(_('%d removed'), 'status.removed'), status.removed),
6316 (ui.label(_('%d removed'), 'status.removed'), status.removed),
6363 (ui.label(_('%d renamed'), 'status.copied'), renamed),
6317 (ui.label(_('%d renamed'), 'status.copied'), renamed),
6364 (ui.label(_('%d copied'), 'status.copied'), copied),
6318 (ui.label(_('%d copied'), 'status.copied'), copied),
6365 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
6319 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
6366 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
6320 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
6367 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
6321 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
6368 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
6322 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
6369 t = []
6323 t = []
6370 for l, s in labels:
6324 for l, s in labels:
6371 if s:
6325 if s:
6372 t.append(l % len(s))
6326 t.append(l % len(s))
6373
6327
6374 t = ', '.join(t)
6328 t = ', '.join(t)
6375 cleanworkdir = False
6329 cleanworkdir = False
6376
6330
6377 if repo.vfs.exists('graftstate'):
6331 if repo.vfs.exists('graftstate'):
6378 t += _(' (graft in progress)')
6332 t += _(' (graft in progress)')
6379 if repo.vfs.exists('updatestate'):
6333 if repo.vfs.exists('updatestate'):
6380 t += _(' (interrupted update)')
6334 t += _(' (interrupted update)')
6381 elif len(parents) > 1:
6335 elif len(parents) > 1:
6382 t += _(' (merge)')
6336 t += _(' (merge)')
6383 elif branch != parents[0].branch():
6337 elif branch != parents[0].branch():
6384 t += _(' (new branch)')
6338 t += _(' (new branch)')
6385 elif (parents[0].closesbranch() and
6339 elif (parents[0].closesbranch() and
6386 pnode in repo.branchheads(branch, closed=True)):
6340 pnode in repo.branchheads(branch, closed=True)):
6387 t += _(' (head closed)')
6341 t += _(' (head closed)')
6388 elif not (status.modified or status.added or status.removed or renamed or
6342 elif not (status.modified or status.added or status.removed or renamed or
6389 copied or subs):
6343 copied or subs):
6390 t += _(' (clean)')
6344 t += _(' (clean)')
6391 cleanworkdir = True
6345 cleanworkdir = True
6392 elif pnode not in bheads:
6346 elif pnode not in bheads:
6393 t += _(' (new branch head)')
6347 t += _(' (new branch head)')
6394
6348
6395 if parents:
6349 if parents:
6396 pendingphase = max(p.phase() for p in parents)
6350 pendingphase = max(p.phase() for p in parents)
6397 else:
6351 else:
6398 pendingphase = phases.public
6352 pendingphase = phases.public
6399
6353
6400 if pendingphase > phases.newcommitphase(ui):
6354 if pendingphase > phases.newcommitphase(ui):
6401 t += ' (%s)' % phases.phasenames[pendingphase]
6355 t += ' (%s)' % phases.phasenames[pendingphase]
6402
6356
6403 if cleanworkdir:
6357 if cleanworkdir:
6404 # i18n: column positioning for "hg summary"
6358 # i18n: column positioning for "hg summary"
6405 ui.status(_('commit: %s\n') % t.strip())
6359 ui.status(_('commit: %s\n') % t.strip())
6406 else:
6360 else:
6407 # i18n: column positioning for "hg summary"
6361 # i18n: column positioning for "hg summary"
6408 ui.write(_('commit: %s\n') % t.strip())
6362 ui.write(_('commit: %s\n') % t.strip())
6409
6363
6410 # all ancestors of branch heads - all ancestors of parent = new csets
6364 # all ancestors of branch heads - all ancestors of parent = new csets
6411 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
6365 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
6412 bheads))
6366 bheads))
6413
6367
6414 if new == 0:
6368 if new == 0:
6415 # i18n: column positioning for "hg summary"
6369 # i18n: column positioning for "hg summary"
6416 ui.status(_('update: (current)\n'))
6370 ui.status(_('update: (current)\n'))
6417 elif pnode not in bheads:
6371 elif pnode not in bheads:
6418 # i18n: column positioning for "hg summary"
6372 # i18n: column positioning for "hg summary"
6419 ui.write(_('update: %d new changesets (update)\n') % new)
6373 ui.write(_('update: %d new changesets (update)\n') % new)
6420 else:
6374 else:
6421 # i18n: column positioning for "hg summary"
6375 # i18n: column positioning for "hg summary"
6422 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
6376 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
6423 (new, len(bheads)))
6377 (new, len(bheads)))
6424
6378
6425 t = []
6379 t = []
6426 draft = len(repo.revs('draft()'))
6380 draft = len(repo.revs('draft()'))
6427 if draft:
6381 if draft:
6428 t.append(_('%d draft') % draft)
6382 t.append(_('%d draft') % draft)
6429 secret = len(repo.revs('secret()'))
6383 secret = len(repo.revs('secret()'))
6430 if secret:
6384 if secret:
6431 t.append(_('%d secret') % secret)
6385 t.append(_('%d secret') % secret)
6432
6386
6433 if draft or secret:
6387 if draft or secret:
6434 ui.status(_('phases: %s\n') % ', '.join(t))
6388 ui.status(_('phases: %s\n') % ', '.join(t))
6435
6389
6436 if obsolete.isenabled(repo, obsolete.createmarkersopt):
6390 if obsolete.isenabled(repo, obsolete.createmarkersopt):
6437 for trouble in ("unstable", "divergent", "bumped"):
6391 for trouble in ("unstable", "divergent", "bumped"):
6438 numtrouble = len(repo.revs(trouble + "()"))
6392 numtrouble = len(repo.revs(trouble + "()"))
6439 # We write all the possibilities to ease translation
6393 # We write all the possibilities to ease translation
6440 troublemsg = {
6394 troublemsg = {
6441 "unstable": _("unstable: %d changesets"),
6395 "unstable": _("unstable: %d changesets"),
6442 "divergent": _("divergent: %d changesets"),
6396 "divergent": _("divergent: %d changesets"),
6443 "bumped": _("bumped: %d changesets"),
6397 "bumped": _("bumped: %d changesets"),
6444 }
6398 }
6445 if numtrouble > 0:
6399 if numtrouble > 0:
6446 ui.status(troublemsg[trouble] % numtrouble + "\n")
6400 ui.status(troublemsg[trouble] % numtrouble + "\n")
6447
6401
6448 cmdutil.summaryhooks(ui, repo)
6402 cmdutil.summaryhooks(ui, repo)
6449
6403
6450 if opts.get('remote'):
6404 if opts.get('remote'):
6451 needsincoming, needsoutgoing = True, True
6405 needsincoming, needsoutgoing = True, True
6452 else:
6406 else:
6453 needsincoming, needsoutgoing = False, False
6407 needsincoming, needsoutgoing = False, False
6454 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
6408 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
6455 if i:
6409 if i:
6456 needsincoming = True
6410 needsincoming = True
6457 if o:
6411 if o:
6458 needsoutgoing = True
6412 needsoutgoing = True
6459 if not needsincoming and not needsoutgoing:
6413 if not needsincoming and not needsoutgoing:
6460 return
6414 return
6461
6415
6462 def getincoming():
6416 def getincoming():
6463 source, branches = hg.parseurl(ui.expandpath('default'))
6417 source, branches = hg.parseurl(ui.expandpath('default'))
6464 sbranch = branches[0]
6418 sbranch = branches[0]
6465 try:
6419 try:
6466 other = hg.peer(repo, {}, source)
6420 other = hg.peer(repo, {}, source)
6467 except error.RepoError:
6421 except error.RepoError:
6468 if opts.get('remote'):
6422 if opts.get('remote'):
6469 raise
6423 raise
6470 return source, sbranch, None, None, None
6424 return source, sbranch, None, None, None
6471 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
6425 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
6472 if revs:
6426 if revs:
6473 revs = [other.lookup(rev) for rev in revs]
6427 revs = [other.lookup(rev) for rev in revs]
6474 ui.debug('comparing with %s\n' % util.hidepassword(source))
6428 ui.debug('comparing with %s\n' % util.hidepassword(source))
6475 repo.ui.pushbuffer()
6429 repo.ui.pushbuffer()
6476 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
6430 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
6477 repo.ui.popbuffer()
6431 repo.ui.popbuffer()
6478 return source, sbranch, other, commoninc, commoninc[1]
6432 return source, sbranch, other, commoninc, commoninc[1]
6479
6433
6480 if needsincoming:
6434 if needsincoming:
6481 source, sbranch, sother, commoninc, incoming = getincoming()
6435 source, sbranch, sother, commoninc, incoming = getincoming()
6482 else:
6436 else:
6483 source = sbranch = sother = commoninc = incoming = None
6437 source = sbranch = sother = commoninc = incoming = None
6484
6438
6485 def getoutgoing():
6439 def getoutgoing():
6486 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
6440 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
6487 dbranch = branches[0]
6441 dbranch = branches[0]
6488 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
6442 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
6489 if source != dest:
6443 if source != dest:
6490 try:
6444 try:
6491 dother = hg.peer(repo, {}, dest)
6445 dother = hg.peer(repo, {}, dest)
6492 except error.RepoError:
6446 except error.RepoError:
6493 if opts.get('remote'):
6447 if opts.get('remote'):
6494 raise
6448 raise
6495 return dest, dbranch, None, None
6449 return dest, dbranch, None, None
6496 ui.debug('comparing with %s\n' % util.hidepassword(dest))
6450 ui.debug('comparing with %s\n' % util.hidepassword(dest))
6497 elif sother is None:
6451 elif sother is None:
6498 # there is no explicit destination peer, but source one is invalid
6452 # there is no explicit destination peer, but source one is invalid
6499 return dest, dbranch, None, None
6453 return dest, dbranch, None, None
6500 else:
6454 else:
6501 dother = sother
6455 dother = sother
6502 if (source != dest or (sbranch is not None and sbranch != dbranch)):
6456 if (source != dest or (sbranch is not None and sbranch != dbranch)):
6503 common = None
6457 common = None
6504 else:
6458 else:
6505 common = commoninc
6459 common = commoninc
6506 if revs:
6460 if revs:
6507 revs = [repo.lookup(rev) for rev in revs]
6461 revs = [repo.lookup(rev) for rev in revs]
6508 repo.ui.pushbuffer()
6462 repo.ui.pushbuffer()
6509 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
6463 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
6510 commoninc=common)
6464 commoninc=common)
6511 repo.ui.popbuffer()
6465 repo.ui.popbuffer()
6512 return dest, dbranch, dother, outgoing
6466 return dest, dbranch, dother, outgoing
6513
6467
6514 if needsoutgoing:
6468 if needsoutgoing:
6515 dest, dbranch, dother, outgoing = getoutgoing()
6469 dest, dbranch, dother, outgoing = getoutgoing()
6516 else:
6470 else:
6517 dest = dbranch = dother = outgoing = None
6471 dest = dbranch = dother = outgoing = None
6518
6472
6519 if opts.get('remote'):
6473 if opts.get('remote'):
6520 t = []
6474 t = []
6521 if incoming:
6475 if incoming:
6522 t.append(_('1 or more incoming'))
6476 t.append(_('1 or more incoming'))
6523 o = outgoing.missing
6477 o = outgoing.missing
6524 if o:
6478 if o:
6525 t.append(_('%d outgoing') % len(o))
6479 t.append(_('%d outgoing') % len(o))
6526 other = dother or sother
6480 other = dother or sother
6527 if 'bookmarks' in other.listkeys('namespaces'):
6481 if 'bookmarks' in other.listkeys('namespaces'):
6528 counts = bookmarks.summary(repo, other)
6482 counts = bookmarks.summary(repo, other)
6529 if counts[0] > 0:
6483 if counts[0] > 0:
6530 t.append(_('%d incoming bookmarks') % counts[0])
6484 t.append(_('%d incoming bookmarks') % counts[0])
6531 if counts[1] > 0:
6485 if counts[1] > 0:
6532 t.append(_('%d outgoing bookmarks') % counts[1])
6486 t.append(_('%d outgoing bookmarks') % counts[1])
6533
6487
6534 if t:
6488 if t:
6535 # i18n: column positioning for "hg summary"
6489 # i18n: column positioning for "hg summary"
6536 ui.write(_('remote: %s\n') % (', '.join(t)))
6490 ui.write(_('remote: %s\n') % (', '.join(t)))
6537 else:
6491 else:
6538 # i18n: column positioning for "hg summary"
6492 # i18n: column positioning for "hg summary"
6539 ui.status(_('remote: (synced)\n'))
6493 ui.status(_('remote: (synced)\n'))
6540
6494
6541 cmdutil.summaryremotehooks(ui, repo, opts,
6495 cmdutil.summaryremotehooks(ui, repo, opts,
6542 ((source, sbranch, sother, commoninc),
6496 ((source, sbranch, sother, commoninc),
6543 (dest, dbranch, dother, outgoing)))
6497 (dest, dbranch, dother, outgoing)))
6544
6498
6545 @command('tag',
6499 @command('tag',
6546 [('f', 'force', None, _('force tag')),
6500 [('f', 'force', None, _('force tag')),
6547 ('l', 'local', None, _('make the tag local')),
6501 ('l', 'local', None, _('make the tag local')),
6548 ('r', 'rev', '', _('revision to tag'), _('REV')),
6502 ('r', 'rev', '', _('revision to tag'), _('REV')),
6549 ('', 'remove', None, _('remove a tag')),
6503 ('', 'remove', None, _('remove a tag')),
6550 # -l/--local is already there, commitopts cannot be used
6504 # -l/--local is already there, commitopts cannot be used
6551 ('e', 'edit', None, _('invoke editor on commit messages')),
6505 ('e', 'edit', None, _('invoke editor on commit messages')),
6552 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
6506 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
6553 ] + commitopts2,
6507 ] + commitopts2,
6554 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
6508 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
6555 def tag(ui, repo, name1, *names, **opts):
6509 def tag(ui, repo, name1, *names, **opts):
6556 """add one or more tags for the current or given revision
6510 """add one or more tags for the current or given revision
6557
6511
6558 Name a particular revision using <name>.
6512 Name a particular revision using <name>.
6559
6513
6560 Tags are used to name particular revisions of the repository and are
6514 Tags are used to name particular revisions of the repository and are
6561 very useful to compare different revisions, to go back to significant
6515 very useful to compare different revisions, to go back to significant
6562 earlier versions or to mark branch points as releases, etc. Changing
6516 earlier versions or to mark branch points as releases, etc. Changing
6563 an existing tag is normally disallowed; use -f/--force to override.
6517 an existing tag is normally disallowed; use -f/--force to override.
6564
6518
6565 If no revision is given, the parent of the working directory is
6519 If no revision is given, the parent of the working directory is
6566 used.
6520 used.
6567
6521
6568 To facilitate version control, distribution, and merging of tags,
6522 To facilitate version control, distribution, and merging of tags,
6569 they are stored as a file named ".hgtags" which is managed similarly
6523 they are stored as a file named ".hgtags" which is managed similarly
6570 to other project files and can be hand-edited if necessary. This
6524 to other project files and can be hand-edited if necessary. This
6571 also means that tagging creates a new commit. The file
6525 also means that tagging creates a new commit. The file
6572 ".hg/localtags" is used for local tags (not shared among
6526 ".hg/localtags" is used for local tags (not shared among
6573 repositories).
6527 repositories).
6574
6528
6575 Tag commits are usually made at the head of a branch. If the parent
6529 Tag commits are usually made at the head of a branch. If the parent
6576 of the working directory is not a branch head, :hg:`tag` aborts; use
6530 of the working directory is not a branch head, :hg:`tag` aborts; use
6577 -f/--force to force the tag commit to be based on a non-head
6531 -f/--force to force the tag commit to be based on a non-head
6578 changeset.
6532 changeset.
6579
6533
6580 See :hg:`help dates` for a list of formats valid for -d/--date.
6534 See :hg:`help dates` for a list of formats valid for -d/--date.
6581
6535
6582 Since tag names have priority over branch names during revision
6536 Since tag names have priority over branch names during revision
6583 lookup, using an existing branch name as a tag name is discouraged.
6537 lookup, using an existing branch name as a tag name is discouraged.
6584
6538
6585 Returns 0 on success.
6539 Returns 0 on success.
6586 """
6540 """
6587 wlock = lock = None
6541 wlock = lock = None
6588 try:
6542 try:
6589 wlock = repo.wlock()
6543 wlock = repo.wlock()
6590 lock = repo.lock()
6544 lock = repo.lock()
6591 rev_ = "."
6545 rev_ = "."
6592 names = [t.strip() for t in (name1,) + names]
6546 names = [t.strip() for t in (name1,) + names]
6593 if len(names) != len(set(names)):
6547 if len(names) != len(set(names)):
6594 raise error.Abort(_('tag names must be unique'))
6548 raise error.Abort(_('tag names must be unique'))
6595 for n in names:
6549 for n in names:
6596 scmutil.checknewlabel(repo, n, 'tag')
6550 scmutil.checknewlabel(repo, n, 'tag')
6597 if not n:
6551 if not n:
6598 raise error.Abort(_('tag names cannot consist entirely of '
6552 raise error.Abort(_('tag names cannot consist entirely of '
6599 'whitespace'))
6553 'whitespace'))
6600 if opts.get('rev') and opts.get('remove'):
6554 if opts.get('rev') and opts.get('remove'):
6601 raise error.Abort(_("--rev and --remove are incompatible"))
6555 raise error.Abort(_("--rev and --remove are incompatible"))
6602 if opts.get('rev'):
6556 if opts.get('rev'):
6603 rev_ = opts['rev']
6557 rev_ = opts['rev']
6604 message = opts.get('message')
6558 message = opts.get('message')
6605 if opts.get('remove'):
6559 if opts.get('remove'):
6606 if opts.get('local'):
6560 if opts.get('local'):
6607 expectedtype = 'local'
6561 expectedtype = 'local'
6608 else:
6562 else:
6609 expectedtype = 'global'
6563 expectedtype = 'global'
6610
6564
6611 for n in names:
6565 for n in names:
6612 if not repo.tagtype(n):
6566 if not repo.tagtype(n):
6613 raise error.Abort(_("tag '%s' does not exist") % n)
6567 raise error.Abort(_("tag '%s' does not exist") % n)
6614 if repo.tagtype(n) != expectedtype:
6568 if repo.tagtype(n) != expectedtype:
6615 if expectedtype == 'global':
6569 if expectedtype == 'global':
6616 raise error.Abort(_("tag '%s' is not a global tag") % n)
6570 raise error.Abort(_("tag '%s' is not a global tag") % n)
6617 else:
6571 else:
6618 raise error.Abort(_("tag '%s' is not a local tag") % n)
6572 raise error.Abort(_("tag '%s' is not a local tag") % n)
6619 rev_ = 'null'
6573 rev_ = 'null'
6620 if not message:
6574 if not message:
6621 # we don't translate commit messages
6575 # we don't translate commit messages
6622 message = 'Removed tag %s' % ', '.join(names)
6576 message = 'Removed tag %s' % ', '.join(names)
6623 elif not opts.get('force'):
6577 elif not opts.get('force'):
6624 for n in names:
6578 for n in names:
6625 if n in repo.tags():
6579 if n in repo.tags():
6626 raise error.Abort(_("tag '%s' already exists "
6580 raise error.Abort(_("tag '%s' already exists "
6627 "(use -f to force)") % n)
6581 "(use -f to force)") % n)
6628 if not opts.get('local'):
6582 if not opts.get('local'):
6629 p1, p2 = repo.dirstate.parents()
6583 p1, p2 = repo.dirstate.parents()
6630 if p2 != nullid:
6584 if p2 != nullid:
6631 raise error.Abort(_('uncommitted merge'))
6585 raise error.Abort(_('uncommitted merge'))
6632 bheads = repo.branchheads()
6586 bheads = repo.branchheads()
6633 if not opts.get('force') and bheads and p1 not in bheads:
6587 if not opts.get('force') and bheads and p1 not in bheads:
6634 raise error.Abort(_('working directory is not at a branch head '
6588 raise error.Abort(_('working directory is not at a branch head '
6635 '(use -f to force)'))
6589 '(use -f to force)'))
6636 r = scmutil.revsingle(repo, rev_).node()
6590 r = scmutil.revsingle(repo, rev_).node()
6637
6591
6638 if not message:
6592 if not message:
6639 # we don't translate commit messages
6593 # we don't translate commit messages
6640 message = ('Added tag %s for changeset %s' %
6594 message = ('Added tag %s for changeset %s' %
6641 (', '.join(names), short(r)))
6595 (', '.join(names), short(r)))
6642
6596
6643 date = opts.get('date')
6597 date = opts.get('date')
6644 if date:
6598 if date:
6645 date = util.parsedate(date)
6599 date = util.parsedate(date)
6646
6600
6647 if opts.get('remove'):
6601 if opts.get('remove'):
6648 editform = 'tag.remove'
6602 editform = 'tag.remove'
6649 else:
6603 else:
6650 editform = 'tag.add'
6604 editform = 'tag.add'
6651 editor = cmdutil.getcommiteditor(editform=editform, **opts)
6605 editor = cmdutil.getcommiteditor(editform=editform, **opts)
6652
6606
6653 # don't allow tagging the null rev
6607 # don't allow tagging the null rev
6654 if (not opts.get('remove') and
6608 if (not opts.get('remove') and
6655 scmutil.revsingle(repo, rev_).rev() == nullrev):
6609 scmutil.revsingle(repo, rev_).rev() == nullrev):
6656 raise error.Abort(_("cannot tag null revision"))
6610 raise error.Abort(_("cannot tag null revision"))
6657
6611
6658 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date,
6612 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date,
6659 editor=editor)
6613 editor=editor)
6660 finally:
6614 finally:
6661 release(lock, wlock)
6615 release(lock, wlock)
6662
6616
6663 @command('tags', formatteropts, '')
6617 @command('tags', formatteropts, '')
6664 def tags(ui, repo, **opts):
6618 def tags(ui, repo, **opts):
6665 """list repository tags
6619 """list repository tags
6666
6620
6667 This lists both regular and local tags. When the -v/--verbose
6621 This lists both regular and local tags. When the -v/--verbose
6668 switch is used, a third column "local" is printed for local tags.
6622 switch is used, a third column "local" is printed for local tags.
6669 When the -q/--quiet switch is used, only the tag name is printed.
6623 When the -q/--quiet switch is used, only the tag name is printed.
6670
6624
6671 Returns 0 on success.
6625 Returns 0 on success.
6672 """
6626 """
6673
6627
6674 fm = ui.formatter('tags', opts)
6628 fm = ui.formatter('tags', opts)
6675 hexfunc = fm.hexfunc
6629 hexfunc = fm.hexfunc
6676 tagtype = ""
6630 tagtype = ""
6677
6631
6678 for t, n in reversed(repo.tagslist()):
6632 for t, n in reversed(repo.tagslist()):
6679 hn = hexfunc(n)
6633 hn = hexfunc(n)
6680 label = 'tags.normal'
6634 label = 'tags.normal'
6681 tagtype = ''
6635 tagtype = ''
6682 if repo.tagtype(t) == 'local':
6636 if repo.tagtype(t) == 'local':
6683 label = 'tags.local'
6637 label = 'tags.local'
6684 tagtype = 'local'
6638 tagtype = 'local'
6685
6639
6686 fm.startitem()
6640 fm.startitem()
6687 fm.write('tag', '%s', t, label=label)
6641 fm.write('tag', '%s', t, label=label)
6688 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
6642 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
6689 fm.condwrite(not ui.quiet, 'rev node', fmt,
6643 fm.condwrite(not ui.quiet, 'rev node', fmt,
6690 repo.changelog.rev(n), hn, label=label)
6644 repo.changelog.rev(n), hn, label=label)
6691 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
6645 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
6692 tagtype, label=label)
6646 tagtype, label=label)
6693 fm.plain('\n')
6647 fm.plain('\n')
6694 fm.end()
6648 fm.end()
6695
6649
6696 @command('tip',
6650 @command('tip',
6697 [('p', 'patch', None, _('show patch')),
6651 [('p', 'patch', None, _('show patch')),
6698 ('g', 'git', None, _('use git extended diff format')),
6652 ('g', 'git', None, _('use git extended diff format')),
6699 ] + templateopts,
6653 ] + templateopts,
6700 _('[-p] [-g]'))
6654 _('[-p] [-g]'))
6701 def tip(ui, repo, **opts):
6655 def tip(ui, repo, **opts):
6702 """show the tip revision (DEPRECATED)
6656 """show the tip revision (DEPRECATED)
6703
6657
6704 The tip revision (usually just called the tip) is the changeset
6658 The tip revision (usually just called the tip) is the changeset
6705 most recently added to the repository (and therefore the most
6659 most recently added to the repository (and therefore the most
6706 recently changed head).
6660 recently changed head).
6707
6661
6708 If you have just made a commit, that commit will be the tip. If
6662 If you have just made a commit, that commit will be the tip. If
6709 you have just pulled changes from another repository, the tip of
6663 you have just pulled changes from another repository, the tip of
6710 that repository becomes the current tip. The "tip" tag is special
6664 that repository becomes the current tip. The "tip" tag is special
6711 and cannot be renamed or assigned to a different changeset.
6665 and cannot be renamed or assigned to a different changeset.
6712
6666
6713 This command is deprecated, please use :hg:`heads` instead.
6667 This command is deprecated, please use :hg:`heads` instead.
6714
6668
6715 Returns 0 on success.
6669 Returns 0 on success.
6716 """
6670 """
6717 displayer = cmdutil.show_changeset(ui, repo, opts)
6671 displayer = cmdutil.show_changeset(ui, repo, opts)
6718 displayer.show(repo['tip'])
6672 displayer.show(repo['tip'])
6719 displayer.close()
6673 displayer.close()
6720
6674
6721 @command('unbundle',
6675 @command('unbundle',
6722 [('u', 'update', None,
6676 [('u', 'update', None,
6723 _('update to new branch head if changesets were unbundled'))],
6677 _('update to new branch head if changesets were unbundled'))],
6724 _('[-u] FILE...'))
6678 _('[-u] FILE...'))
6725 def unbundle(ui, repo, fname1, *fnames, **opts):
6679 def unbundle(ui, repo, fname1, *fnames, **opts):
6726 """apply one or more changegroup files
6680 """apply one or more changegroup files
6727
6681
6728 Apply one or more compressed changegroup files generated by the
6682 Apply one or more compressed changegroup files generated by the
6729 bundle command.
6683 bundle command.
6730
6684
6731 Returns 0 on success, 1 if an update has unresolved files.
6685 Returns 0 on success, 1 if an update has unresolved files.
6732 """
6686 """
6733 fnames = (fname1,) + fnames
6687 fnames = (fname1,) + fnames
6734
6688
6735 with repo.lock():
6689 with repo.lock():
6736 for fname in fnames:
6690 for fname in fnames:
6737 f = hg.openpath(ui, fname)
6691 f = hg.openpath(ui, fname)
6738 gen = exchange.readbundle(ui, f, fname)
6692 gen = exchange.readbundle(ui, f, fname)
6739 if isinstance(gen, bundle2.unbundle20):
6693 if isinstance(gen, bundle2.unbundle20):
6740 tr = repo.transaction('unbundle')
6694 tr = repo.transaction('unbundle')
6741 try:
6695 try:
6742 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
6696 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
6743 url='bundle:' + fname)
6697 url='bundle:' + fname)
6744 tr.close()
6698 tr.close()
6745 except error.BundleUnknownFeatureError as exc:
6699 except error.BundleUnknownFeatureError as exc:
6746 raise error.Abort(_('%s: unknown bundle feature, %s')
6700 raise error.Abort(_('%s: unknown bundle feature, %s')
6747 % (fname, exc),
6701 % (fname, exc),
6748 hint=_("see https://mercurial-scm.org/"
6702 hint=_("see https://mercurial-scm.org/"
6749 "wiki/BundleFeature for more "
6703 "wiki/BundleFeature for more "
6750 "information"))
6704 "information"))
6751 finally:
6705 finally:
6752 if tr:
6706 if tr:
6753 tr.release()
6707 tr.release()
6754 changes = [r.get('return', 0)
6708 changes = [r.get('return', 0)
6755 for r in op.records['changegroup']]
6709 for r in op.records['changegroup']]
6756 modheads = changegroup.combineresults(changes)
6710 modheads = changegroup.combineresults(changes)
6757 elif isinstance(gen, streamclone.streamcloneapplier):
6711 elif isinstance(gen, streamclone.streamcloneapplier):
6758 raise error.Abort(
6712 raise error.Abort(
6759 _('packed bundles cannot be applied with '
6713 _('packed bundles cannot be applied with '
6760 '"hg unbundle"'),
6714 '"hg unbundle"'),
6761 hint=_('use "hg debugapplystreamclonebundle"'))
6715 hint=_('use "hg debugapplystreamclonebundle"'))
6762 else:
6716 else:
6763 modheads = gen.apply(repo, 'unbundle', 'bundle:' + fname)
6717 modheads = gen.apply(repo, 'unbundle', 'bundle:' + fname)
6764
6718
6765 return postincoming(ui, repo, modheads, opts.get('update'), None, None)
6719 return postincoming(ui, repo, modheads, opts.get('update'), None, None)
6766
6720
6767 @command('^update|up|checkout|co',
6721 @command('^update|up|checkout|co',
6768 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
6722 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
6769 ('c', 'check', None, _('require clean working directory')),
6723 ('c', 'check', None, _('require clean working directory')),
6770 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
6724 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
6771 ('r', 'rev', '', _('revision'), _('REV'))
6725 ('r', 'rev', '', _('revision'), _('REV'))
6772 ] + mergetoolopts,
6726 ] + mergetoolopts,
6773 _('[-c] [-C] [-d DATE] [[-r] REV]'))
6727 _('[-c] [-C] [-d DATE] [[-r] REV]'))
6774 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
6728 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
6775 tool=None):
6729 tool=None):
6776 """update working directory (or switch revisions)
6730 """update working directory (or switch revisions)
6777
6731
6778 Update the repository's working directory to the specified
6732 Update the repository's working directory to the specified
6779 changeset. If no changeset is specified, update to the tip of the
6733 changeset. If no changeset is specified, update to the tip of the
6780 current named branch and move the active bookmark (see :hg:`help
6734 current named branch and move the active bookmark (see :hg:`help
6781 bookmarks`).
6735 bookmarks`).
6782
6736
6783 Update sets the working directory's parent revision to the specified
6737 Update sets the working directory's parent revision to the specified
6784 changeset (see :hg:`help parents`).
6738 changeset (see :hg:`help parents`).
6785
6739
6786 If the changeset is not a descendant or ancestor of the working
6740 If the changeset is not a descendant or ancestor of the working
6787 directory's parent, the update is aborted. With the -c/--check
6741 directory's parent, the update is aborted. With the -c/--check
6788 option, the working directory is checked for uncommitted changes; if
6742 option, the working directory is checked for uncommitted changes; if
6789 none are found, the working directory is updated to the specified
6743 none are found, the working directory is updated to the specified
6790 changeset.
6744 changeset.
6791
6745
6792 .. container:: verbose
6746 .. container:: verbose
6793
6747
6794 The following rules apply when the working directory contains
6748 The following rules apply when the working directory contains
6795 uncommitted changes:
6749 uncommitted changes:
6796
6750
6797 1. If neither -c/--check nor -C/--clean is specified, and if
6751 1. If neither -c/--check nor -C/--clean is specified, and if
6798 the requested changeset is an ancestor or descendant of
6752 the requested changeset is an ancestor or descendant of
6799 the working directory's parent, the uncommitted changes
6753 the working directory's parent, the uncommitted changes
6800 are merged into the requested changeset and the merged
6754 are merged into the requested changeset and the merged
6801 result is left uncommitted. If the requested changeset is
6755 result is left uncommitted. If the requested changeset is
6802 not an ancestor or descendant (that is, it is on another
6756 not an ancestor or descendant (that is, it is on another
6803 branch), the update is aborted and the uncommitted changes
6757 branch), the update is aborted and the uncommitted changes
6804 are preserved.
6758 are preserved.
6805
6759
6806 2. With the -c/--check option, the update is aborted and the
6760 2. With the -c/--check option, the update is aborted and the
6807 uncommitted changes are preserved.
6761 uncommitted changes are preserved.
6808
6762
6809 3. With the -C/--clean option, uncommitted changes are discarded and
6763 3. With the -C/--clean option, uncommitted changes are discarded and
6810 the working directory is updated to the requested changeset.
6764 the working directory is updated to the requested changeset.
6811
6765
6812 To cancel an uncommitted merge (and lose your changes), use
6766 To cancel an uncommitted merge (and lose your changes), use
6813 :hg:`update --clean .`.
6767 :hg:`update --clean .`.
6814
6768
6815 Use null as the changeset to remove the working directory (like
6769 Use null as the changeset to remove the working directory (like
6816 :hg:`clone -U`).
6770 :hg:`clone -U`).
6817
6771
6818 If you want to revert just one file to an older revision, use
6772 If you want to revert just one file to an older revision, use
6819 :hg:`revert [-r REV] NAME`.
6773 :hg:`revert [-r REV] NAME`.
6820
6774
6821 See :hg:`help dates` for a list of formats valid for -d/--date.
6775 See :hg:`help dates` for a list of formats valid for -d/--date.
6822
6776
6823 Returns 0 on success, 1 if there are unresolved files.
6777 Returns 0 on success, 1 if there are unresolved files.
6824 """
6778 """
6825 if rev and node:
6779 if rev and node:
6826 raise error.Abort(_("please specify just one revision"))
6780 raise error.Abort(_("please specify just one revision"))
6827
6781
6828 if rev is None or rev == '':
6782 if rev is None or rev == '':
6829 rev = node
6783 rev = node
6830
6784
6831 if date and rev is not None:
6785 if date and rev is not None:
6832 raise error.Abort(_("you can't specify a revision and a date"))
6786 raise error.Abort(_("you can't specify a revision and a date"))
6833
6787
6834 if check and clean:
6788 if check and clean:
6835 raise error.Abort(_("cannot specify both -c/--check and -C/--clean"))
6789 raise error.Abort(_("cannot specify both -c/--check and -C/--clean"))
6836
6790
6837 with repo.wlock():
6791 with repo.wlock():
6838 cmdutil.clearunfinished(repo)
6792 cmdutil.clearunfinished(repo)
6839
6793
6840 if date:
6794 if date:
6841 rev = cmdutil.finddate(ui, repo, date)
6795 rev = cmdutil.finddate(ui, repo, date)
6842
6796
6843 # if we defined a bookmark, we have to remember the original name
6797 # if we defined a bookmark, we have to remember the original name
6844 brev = rev
6798 brev = rev
6845 rev = scmutil.revsingle(repo, rev, rev).rev()
6799 rev = scmutil.revsingle(repo, rev, rev).rev()
6846
6800
6847 if check:
6801 if check:
6848 cmdutil.bailifchanged(repo, merge=False)
6802 cmdutil.bailifchanged(repo, merge=False)
6849
6803
6850 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
6804 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
6851
6805
6852 return hg.updatetotally(ui, repo, rev, brev, clean=clean, check=check)
6806 return hg.updatetotally(ui, repo, rev, brev, clean=clean, check=check)
6853
6807
6854 @command('verify', [])
6808 @command('verify', [])
6855 def verify(ui, repo):
6809 def verify(ui, repo):
6856 """verify the integrity of the repository
6810 """verify the integrity of the repository
6857
6811
6858 Verify the integrity of the current repository.
6812 Verify the integrity of the current repository.
6859
6813
6860 This will perform an extensive check of the repository's
6814 This will perform an extensive check of the repository's
6861 integrity, validating the hashes and checksums of each entry in
6815 integrity, validating the hashes and checksums of each entry in
6862 the changelog, manifest, and tracked files, as well as the
6816 the changelog, manifest, and tracked files, as well as the
6863 integrity of their crosslinks and indices.
6817 integrity of their crosslinks and indices.
6864
6818
6865 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
6819 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
6866 for more information about recovery from corruption of the
6820 for more information about recovery from corruption of the
6867 repository.
6821 repository.
6868
6822
6869 Returns 0 on success, 1 if errors are encountered.
6823 Returns 0 on success, 1 if errors are encountered.
6870 """
6824 """
6871 return hg.verify(repo)
6825 return hg.verify(repo)
6872
6826
6873 @command('version', [] + formatteropts, norepo=True)
6827 @command('version', [] + formatteropts, norepo=True)
6874 def version_(ui, **opts):
6828 def version_(ui, **opts):
6875 """output version and copyright information"""
6829 """output version and copyright information"""
6876 fm = ui.formatter("version", opts)
6830 fm = ui.formatter("version", opts)
6877 fm.startitem()
6831 fm.startitem()
6878 fm.write("ver", _("Mercurial Distributed SCM (version %s)\n"),
6832 fm.write("ver", _("Mercurial Distributed SCM (version %s)\n"),
6879 util.version())
6833 util.version())
6880 license = _(
6834 license = _(
6881 "(see https://mercurial-scm.org for more information)\n"
6835 "(see https://mercurial-scm.org for more information)\n"
6882 "\nCopyright (C) 2005-2016 Matt Mackall and others\n"
6836 "\nCopyright (C) 2005-2016 Matt Mackall and others\n"
6883 "This is free software; see the source for copying conditions. "
6837 "This is free software; see the source for copying conditions. "
6884 "There is NO\nwarranty; "
6838 "There is NO\nwarranty; "
6885 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
6839 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
6886 )
6840 )
6887 if not ui.quiet:
6841 if not ui.quiet:
6888 fm.plain(license)
6842 fm.plain(license)
6889
6843
6890 if ui.verbose:
6844 if ui.verbose:
6891 fm.plain(_("\nEnabled extensions:\n\n"))
6845 fm.plain(_("\nEnabled extensions:\n\n"))
6892 # format names and versions into columns
6846 # format names and versions into columns
6893 names = []
6847 names = []
6894 vers = []
6848 vers = []
6895 isinternals = []
6849 isinternals = []
6896 for name, module in extensions.extensions():
6850 for name, module in extensions.extensions():
6897 names.append(name)
6851 names.append(name)
6898 vers.append(extensions.moduleversion(module) or None)
6852 vers.append(extensions.moduleversion(module) or None)
6899 isinternals.append(extensions.ismoduleinternal(module))
6853 isinternals.append(extensions.ismoduleinternal(module))
6900 fn = fm.nested("extensions")
6854 fn = fm.nested("extensions")
6901 if names:
6855 if names:
6902 namefmt = " %%-%ds " % max(len(n) for n in names)
6856 namefmt = " %%-%ds " % max(len(n) for n in names)
6903 places = [_("external"), _("internal")]
6857 places = [_("external"), _("internal")]
6904 for n, v, p in zip(names, vers, isinternals):
6858 for n, v, p in zip(names, vers, isinternals):
6905 fn.startitem()
6859 fn.startitem()
6906 fn.condwrite(ui.verbose, "name", namefmt, n)
6860 fn.condwrite(ui.verbose, "name", namefmt, n)
6907 if ui.verbose:
6861 if ui.verbose:
6908 fn.plain("%s " % places[p])
6862 fn.plain("%s " % places[p])
6909 fn.data(bundled=p)
6863 fn.data(bundled=p)
6910 fn.condwrite(ui.verbose and v, "ver", "%s", v)
6864 fn.condwrite(ui.verbose and v, "ver", "%s", v)
6911 if ui.verbose:
6865 if ui.verbose:
6912 fn.plain("\n")
6866 fn.plain("\n")
6913 fn.end()
6867 fn.end()
6914 fm.end()
6868 fm.end()
6915
6869
6916 def loadcmdtable(ui, name, cmdtable):
6870 def loadcmdtable(ui, name, cmdtable):
6917 """Load command functions from specified cmdtable
6871 """Load command functions from specified cmdtable
6918 """
6872 """
6919 overrides = [cmd for cmd in cmdtable if cmd in table]
6873 overrides = [cmd for cmd in cmdtable if cmd in table]
6920 if overrides:
6874 if overrides:
6921 ui.warn(_("extension '%s' overrides commands: %s\n")
6875 ui.warn(_("extension '%s' overrides commands: %s\n")
6922 % (name, " ".join(overrides)))
6876 % (name, " ".join(overrides)))
6923 table.update(cmdtable)
6877 table.update(cmdtable)
@@ -1,525 +1,572 b''
1 # debugcommands.py - command processing for debug* commands
1 # debugcommands.py - command processing for debug* commands
2 #
2 #
3 # Copyright 2005-2016 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2016 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import operator
10 import os
11 import os
11 import random
12 import random
12
13
13 from .i18n import _
14 from .i18n import _
14 from .node import (
15 from .node import (
15 hex,
16 hex,
16 short,
17 short,
17 )
18 )
18 from . import (
19 from . import (
19 bundle2,
20 bundle2,
20 changegroup,
21 changegroup,
21 cmdutil,
22 cmdutil,
22 commands,
23 commands,
23 context,
24 context,
24 dagparser,
25 dagparser,
25 dagutil,
26 dagutil,
26 error,
27 error,
27 exchange,
28 exchange,
29 extensions,
28 hg,
30 hg,
29 localrepo,
31 localrepo,
30 lock as lockmod,
32 lock as lockmod,
31 revlog,
33 revlog,
32 scmutil,
34 scmutil,
33 setdiscovery,
35 setdiscovery,
34 simplemerge,
36 simplemerge,
35 streamclone,
37 streamclone,
36 treediscovery,
38 treediscovery,
37 util,
39 util,
38 )
40 )
39
41
40 release = lockmod.release
42 release = lockmod.release
41
43
42 # We reuse the command table from commands because it is easier than
44 # We reuse the command table from commands because it is easier than
43 # teaching dispatch about multiple tables.
45 # teaching dispatch about multiple tables.
44 command = cmdutil.command(commands.table)
46 command = cmdutil.command(commands.table)
45
47
46 @command('debugancestor', [], _('[INDEX] REV1 REV2'), optionalrepo=True)
48 @command('debugancestor', [], _('[INDEX] REV1 REV2'), optionalrepo=True)
47 def debugancestor(ui, repo, *args):
49 def debugancestor(ui, repo, *args):
48 """find the ancestor revision of two revisions in a given index"""
50 """find the ancestor revision of two revisions in a given index"""
49 if len(args) == 3:
51 if len(args) == 3:
50 index, rev1, rev2 = args
52 index, rev1, rev2 = args
51 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
53 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
52 lookup = r.lookup
54 lookup = r.lookup
53 elif len(args) == 2:
55 elif len(args) == 2:
54 if not repo:
56 if not repo:
55 raise error.Abort(_('there is no Mercurial repository here '
57 raise error.Abort(_('there is no Mercurial repository here '
56 '(.hg not found)'))
58 '(.hg not found)'))
57 rev1, rev2 = args
59 rev1, rev2 = args
58 r = repo.changelog
60 r = repo.changelog
59 lookup = repo.lookup
61 lookup = repo.lookup
60 else:
62 else:
61 raise error.Abort(_('either two or three arguments required'))
63 raise error.Abort(_('either two or three arguments required'))
62 a = r.ancestor(lookup(rev1), lookup(rev2))
64 a = r.ancestor(lookup(rev1), lookup(rev2))
63 ui.write('%d:%s\n' % (r.rev(a), hex(a)))
65 ui.write('%d:%s\n' % (r.rev(a), hex(a)))
64
66
65 @command('debugbuilddag',
67 @command('debugbuilddag',
66 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
68 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
67 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
69 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
68 ('n', 'new-file', None, _('add new file at each rev'))],
70 ('n', 'new-file', None, _('add new file at each rev'))],
69 _('[OPTION]... [TEXT]'))
71 _('[OPTION]... [TEXT]'))
70 def debugbuilddag(ui, repo, text=None,
72 def debugbuilddag(ui, repo, text=None,
71 mergeable_file=False,
73 mergeable_file=False,
72 overwritten_file=False,
74 overwritten_file=False,
73 new_file=False):
75 new_file=False):
74 """builds a repo with a given DAG from scratch in the current empty repo
76 """builds a repo with a given DAG from scratch in the current empty repo
75
77
76 The description of the DAG is read from stdin if not given on the
78 The description of the DAG is read from stdin if not given on the
77 command line.
79 command line.
78
80
79 Elements:
81 Elements:
80
82
81 - "+n" is a linear run of n nodes based on the current default parent
83 - "+n" is a linear run of n nodes based on the current default parent
82 - "." is a single node based on the current default parent
84 - "." is a single node based on the current default parent
83 - "$" resets the default parent to null (implied at the start);
85 - "$" resets the default parent to null (implied at the start);
84 otherwise the default parent is always the last node created
86 otherwise the default parent is always the last node created
85 - "<p" sets the default parent to the backref p
87 - "<p" sets the default parent to the backref p
86 - "*p" is a fork at parent p, which is a backref
88 - "*p" is a fork at parent p, which is a backref
87 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
89 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
88 - "/p2" is a merge of the preceding node and p2
90 - "/p2" is a merge of the preceding node and p2
89 - ":tag" defines a local tag for the preceding node
91 - ":tag" defines a local tag for the preceding node
90 - "@branch" sets the named branch for subsequent nodes
92 - "@branch" sets the named branch for subsequent nodes
91 - "#...\\n" is a comment up to the end of the line
93 - "#...\\n" is a comment up to the end of the line
92
94
93 Whitespace between the above elements is ignored.
95 Whitespace between the above elements is ignored.
94
96
95 A backref is either
97 A backref is either
96
98
97 - a number n, which references the node curr-n, where curr is the current
99 - a number n, which references the node curr-n, where curr is the current
98 node, or
100 node, or
99 - the name of a local tag you placed earlier using ":tag", or
101 - the name of a local tag you placed earlier using ":tag", or
100 - empty to denote the default parent.
102 - empty to denote the default parent.
101
103
102 All string valued-elements are either strictly alphanumeric, or must
104 All string valued-elements are either strictly alphanumeric, or must
103 be enclosed in double quotes ("..."), with "\\" as escape character.
105 be enclosed in double quotes ("..."), with "\\" as escape character.
104 """
106 """
105
107
106 if text is None:
108 if text is None:
107 ui.status(_("reading DAG from stdin\n"))
109 ui.status(_("reading DAG from stdin\n"))
108 text = ui.fin.read()
110 text = ui.fin.read()
109
111
110 cl = repo.changelog
112 cl = repo.changelog
111 if len(cl) > 0:
113 if len(cl) > 0:
112 raise error.Abort(_('repository is not empty'))
114 raise error.Abort(_('repository is not empty'))
113
115
114 # determine number of revs in DAG
116 # determine number of revs in DAG
115 total = 0
117 total = 0
116 for type, data in dagparser.parsedag(text):
118 for type, data in dagparser.parsedag(text):
117 if type == 'n':
119 if type == 'n':
118 total += 1
120 total += 1
119
121
120 if mergeable_file:
122 if mergeable_file:
121 linesperrev = 2
123 linesperrev = 2
122 # make a file with k lines per rev
124 # make a file with k lines per rev
123 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
125 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
124 initialmergedlines.append("")
126 initialmergedlines.append("")
125
127
126 tags = []
128 tags = []
127
129
128 wlock = lock = tr = None
130 wlock = lock = tr = None
129 try:
131 try:
130 wlock = repo.wlock()
132 wlock = repo.wlock()
131 lock = repo.lock()
133 lock = repo.lock()
132 tr = repo.transaction("builddag")
134 tr = repo.transaction("builddag")
133
135
134 at = -1
136 at = -1
135 atbranch = 'default'
137 atbranch = 'default'
136 nodeids = []
138 nodeids = []
137 id = 0
139 id = 0
138 ui.progress(_('building'), id, unit=_('revisions'), total=total)
140 ui.progress(_('building'), id, unit=_('revisions'), total=total)
139 for type, data in dagparser.parsedag(text):
141 for type, data in dagparser.parsedag(text):
140 if type == 'n':
142 if type == 'n':
141 ui.note(('node %s\n' % str(data)))
143 ui.note(('node %s\n' % str(data)))
142 id, ps = data
144 id, ps = data
143
145
144 files = []
146 files = []
145 fctxs = {}
147 fctxs = {}
146
148
147 p2 = None
149 p2 = None
148 if mergeable_file:
150 if mergeable_file:
149 fn = "mf"
151 fn = "mf"
150 p1 = repo[ps[0]]
152 p1 = repo[ps[0]]
151 if len(ps) > 1:
153 if len(ps) > 1:
152 p2 = repo[ps[1]]
154 p2 = repo[ps[1]]
153 pa = p1.ancestor(p2)
155 pa = p1.ancestor(p2)
154 base, local, other = [x[fn].data() for x in (pa, p1,
156 base, local, other = [x[fn].data() for x in (pa, p1,
155 p2)]
157 p2)]
156 m3 = simplemerge.Merge3Text(base, local, other)
158 m3 = simplemerge.Merge3Text(base, local, other)
157 ml = [l.strip() for l in m3.merge_lines()]
159 ml = [l.strip() for l in m3.merge_lines()]
158 ml.append("")
160 ml.append("")
159 elif at > 0:
161 elif at > 0:
160 ml = p1[fn].data().split("\n")
162 ml = p1[fn].data().split("\n")
161 else:
163 else:
162 ml = initialmergedlines
164 ml = initialmergedlines
163 ml[id * linesperrev] += " r%i" % id
165 ml[id * linesperrev] += " r%i" % id
164 mergedtext = "\n".join(ml)
166 mergedtext = "\n".join(ml)
165 files.append(fn)
167 files.append(fn)
166 fctxs[fn] = context.memfilectx(repo, fn, mergedtext)
168 fctxs[fn] = context.memfilectx(repo, fn, mergedtext)
167
169
168 if overwritten_file:
170 if overwritten_file:
169 fn = "of"
171 fn = "of"
170 files.append(fn)
172 files.append(fn)
171 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
173 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
172
174
173 if new_file:
175 if new_file:
174 fn = "nf%i" % id
176 fn = "nf%i" % id
175 files.append(fn)
177 files.append(fn)
176 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
178 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
177 if len(ps) > 1:
179 if len(ps) > 1:
178 if not p2:
180 if not p2:
179 p2 = repo[ps[1]]
181 p2 = repo[ps[1]]
180 for fn in p2:
182 for fn in p2:
181 if fn.startswith("nf"):
183 if fn.startswith("nf"):
182 files.append(fn)
184 files.append(fn)
183 fctxs[fn] = p2[fn]
185 fctxs[fn] = p2[fn]
184
186
185 def fctxfn(repo, cx, path):
187 def fctxfn(repo, cx, path):
186 return fctxs.get(path)
188 return fctxs.get(path)
187
189
188 if len(ps) == 0 or ps[0] < 0:
190 if len(ps) == 0 or ps[0] < 0:
189 pars = [None, None]
191 pars = [None, None]
190 elif len(ps) == 1:
192 elif len(ps) == 1:
191 pars = [nodeids[ps[0]], None]
193 pars = [nodeids[ps[0]], None]
192 else:
194 else:
193 pars = [nodeids[p] for p in ps]
195 pars = [nodeids[p] for p in ps]
194 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
196 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
195 date=(id, 0),
197 date=(id, 0),
196 user="debugbuilddag",
198 user="debugbuilddag",
197 extra={'branch': atbranch})
199 extra={'branch': atbranch})
198 nodeid = repo.commitctx(cx)
200 nodeid = repo.commitctx(cx)
199 nodeids.append(nodeid)
201 nodeids.append(nodeid)
200 at = id
202 at = id
201 elif type == 'l':
203 elif type == 'l':
202 id, name = data
204 id, name = data
203 ui.note(('tag %s\n' % name))
205 ui.note(('tag %s\n' % name))
204 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
206 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
205 elif type == 'a':
207 elif type == 'a':
206 ui.note(('branch %s\n' % data))
208 ui.note(('branch %s\n' % data))
207 atbranch = data
209 atbranch = data
208 ui.progress(_('building'), id, unit=_('revisions'), total=total)
210 ui.progress(_('building'), id, unit=_('revisions'), total=total)
209 tr.close()
211 tr.close()
210
212
211 if tags:
213 if tags:
212 repo.vfs.write("localtags", "".join(tags))
214 repo.vfs.write("localtags", "".join(tags))
213 finally:
215 finally:
214 ui.progress(_('building'), None)
216 ui.progress(_('building'), None)
215 release(tr, lock, wlock)
217 release(tr, lock, wlock)
216
218
217 @command('debugbundle',
219 @command('debugbundle',
218 [('a', 'all', None, _('show all details')),
220 [('a', 'all', None, _('show all details')),
219 ('', 'spec', None, _('print the bundlespec of the bundle'))],
221 ('', 'spec', None, _('print the bundlespec of the bundle'))],
220 _('FILE'),
222 _('FILE'),
221 norepo=True)
223 norepo=True)
222 def debugbundle(ui, bundlepath, all=None, spec=None, **opts):
224 def debugbundle(ui, bundlepath, all=None, spec=None, **opts):
223 """lists the contents of a bundle"""
225 """lists the contents of a bundle"""
224 with hg.openpath(ui, bundlepath) as f:
226 with hg.openpath(ui, bundlepath) as f:
225 if spec:
227 if spec:
226 spec = exchange.getbundlespec(ui, f)
228 spec = exchange.getbundlespec(ui, f)
227 ui.write('%s\n' % spec)
229 ui.write('%s\n' % spec)
228 return
230 return
229
231
230 gen = exchange.readbundle(ui, f, bundlepath)
232 gen = exchange.readbundle(ui, f, bundlepath)
231 if isinstance(gen, bundle2.unbundle20):
233 if isinstance(gen, bundle2.unbundle20):
232 return _debugbundle2(ui, gen, all=all, **opts)
234 return _debugbundle2(ui, gen, all=all, **opts)
233 _debugchangegroup(ui, gen, all=all, **opts)
235 _debugchangegroup(ui, gen, all=all, **opts)
234
236
235 def _debugchangegroup(ui, gen, all=None, indent=0, **opts):
237 def _debugchangegroup(ui, gen, all=None, indent=0, **opts):
236 indent_string = ' ' * indent
238 indent_string = ' ' * indent
237 if all:
239 if all:
238 ui.write(("%sformat: id, p1, p2, cset, delta base, len(delta)\n")
240 ui.write(("%sformat: id, p1, p2, cset, delta base, len(delta)\n")
239 % indent_string)
241 % indent_string)
240
242
241 def showchunks(named):
243 def showchunks(named):
242 ui.write("\n%s%s\n" % (indent_string, named))
244 ui.write("\n%s%s\n" % (indent_string, named))
243 chain = None
245 chain = None
244 for chunkdata in iter(lambda: gen.deltachunk(chain), {}):
246 for chunkdata in iter(lambda: gen.deltachunk(chain), {}):
245 node = chunkdata['node']
247 node = chunkdata['node']
246 p1 = chunkdata['p1']
248 p1 = chunkdata['p1']
247 p2 = chunkdata['p2']
249 p2 = chunkdata['p2']
248 cs = chunkdata['cs']
250 cs = chunkdata['cs']
249 deltabase = chunkdata['deltabase']
251 deltabase = chunkdata['deltabase']
250 delta = chunkdata['delta']
252 delta = chunkdata['delta']
251 ui.write("%s%s %s %s %s %s %s\n" %
253 ui.write("%s%s %s %s %s %s %s\n" %
252 (indent_string, hex(node), hex(p1), hex(p2),
254 (indent_string, hex(node), hex(p1), hex(p2),
253 hex(cs), hex(deltabase), len(delta)))
255 hex(cs), hex(deltabase), len(delta)))
254 chain = node
256 chain = node
255
257
256 chunkdata = gen.changelogheader()
258 chunkdata = gen.changelogheader()
257 showchunks("changelog")
259 showchunks("changelog")
258 chunkdata = gen.manifestheader()
260 chunkdata = gen.manifestheader()
259 showchunks("manifest")
261 showchunks("manifest")
260 for chunkdata in iter(gen.filelogheader, {}):
262 for chunkdata in iter(gen.filelogheader, {}):
261 fname = chunkdata['filename']
263 fname = chunkdata['filename']
262 showchunks(fname)
264 showchunks(fname)
263 else:
265 else:
264 if isinstance(gen, bundle2.unbundle20):
266 if isinstance(gen, bundle2.unbundle20):
265 raise error.Abort(_('use debugbundle2 for this file'))
267 raise error.Abort(_('use debugbundle2 for this file'))
266 chunkdata = gen.changelogheader()
268 chunkdata = gen.changelogheader()
267 chain = None
269 chain = None
268 for chunkdata in iter(lambda: gen.deltachunk(chain), {}):
270 for chunkdata in iter(lambda: gen.deltachunk(chain), {}):
269 node = chunkdata['node']
271 node = chunkdata['node']
270 ui.write("%s%s\n" % (indent_string, hex(node)))
272 ui.write("%s%s\n" % (indent_string, hex(node)))
271 chain = node
273 chain = node
272
274
273 def _debugbundle2(ui, gen, all=None, **opts):
275 def _debugbundle2(ui, gen, all=None, **opts):
274 """lists the contents of a bundle2"""
276 """lists the contents of a bundle2"""
275 if not isinstance(gen, bundle2.unbundle20):
277 if not isinstance(gen, bundle2.unbundle20):
276 raise error.Abort(_('not a bundle2 file'))
278 raise error.Abort(_('not a bundle2 file'))
277 ui.write(('Stream params: %s\n' % repr(gen.params)))
279 ui.write(('Stream params: %s\n' % repr(gen.params)))
278 for part in gen.iterparts():
280 for part in gen.iterparts():
279 ui.write('%s -- %r\n' % (part.type, repr(part.params)))
281 ui.write('%s -- %r\n' % (part.type, repr(part.params)))
280 if part.type == 'changegroup':
282 if part.type == 'changegroup':
281 version = part.params.get('version', '01')
283 version = part.params.get('version', '01')
282 cg = changegroup.getunbundler(version, part, 'UN')
284 cg = changegroup.getunbundler(version, part, 'UN')
283 _debugchangegroup(ui, cg, all=all, indent=4, **opts)
285 _debugchangegroup(ui, cg, all=all, indent=4, **opts)
284
286
285 @command('debugcreatestreamclonebundle', [], 'FILE')
287 @command('debugcreatestreamclonebundle', [], 'FILE')
286 def debugcreatestreamclonebundle(ui, repo, fname):
288 def debugcreatestreamclonebundle(ui, repo, fname):
287 """create a stream clone bundle file
289 """create a stream clone bundle file
288
290
289 Stream bundles are special bundles that are essentially archives of
291 Stream bundles are special bundles that are essentially archives of
290 revlog files. They are commonly used for cloning very quickly.
292 revlog files. They are commonly used for cloning very quickly.
291 """
293 """
292 requirements, gen = streamclone.generatebundlev1(repo)
294 requirements, gen = streamclone.generatebundlev1(repo)
293 changegroup.writechunks(ui, gen, fname)
295 changegroup.writechunks(ui, gen, fname)
294
296
295 ui.write(_('bundle requirements: %s\n') % ', '.join(sorted(requirements)))
297 ui.write(_('bundle requirements: %s\n') % ', '.join(sorted(requirements)))
296
298
297 @command('debugapplystreamclonebundle', [], 'FILE')
299 @command('debugapplystreamclonebundle', [], 'FILE')
298 def debugapplystreamclonebundle(ui, repo, fname):
300 def debugapplystreamclonebundle(ui, repo, fname):
299 """apply a stream clone bundle file"""
301 """apply a stream clone bundle file"""
300 f = hg.openpath(ui, fname)
302 f = hg.openpath(ui, fname)
301 gen = exchange.readbundle(ui, f, fname)
303 gen = exchange.readbundle(ui, f, fname)
302 gen.apply(repo)
304 gen.apply(repo)
303
305
304 @command('debugcheckstate', [], '')
306 @command('debugcheckstate', [], '')
305 def debugcheckstate(ui, repo):
307 def debugcheckstate(ui, repo):
306 """validate the correctness of the current dirstate"""
308 """validate the correctness of the current dirstate"""
307 parent1, parent2 = repo.dirstate.parents()
309 parent1, parent2 = repo.dirstate.parents()
308 m1 = repo[parent1].manifest()
310 m1 = repo[parent1].manifest()
309 m2 = repo[parent2].manifest()
311 m2 = repo[parent2].manifest()
310 errors = 0
312 errors = 0
311 for f in repo.dirstate:
313 for f in repo.dirstate:
312 state = repo.dirstate[f]
314 state = repo.dirstate[f]
313 if state in "nr" and f not in m1:
315 if state in "nr" and f not in m1:
314 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
316 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
315 errors += 1
317 errors += 1
316 if state in "a" and f in m1:
318 if state in "a" and f in m1:
317 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
319 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
318 errors += 1
320 errors += 1
319 if state in "m" and f not in m1 and f not in m2:
321 if state in "m" and f not in m1 and f not in m2:
320 ui.warn(_("%s in state %s, but not in either manifest\n") %
322 ui.warn(_("%s in state %s, but not in either manifest\n") %
321 (f, state))
323 (f, state))
322 errors += 1
324 errors += 1
323 for f in m1:
325 for f in m1:
324 state = repo.dirstate[f]
326 state = repo.dirstate[f]
325 if state not in "nrm":
327 if state not in "nrm":
326 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
328 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
327 errors += 1
329 errors += 1
328 if errors:
330 if errors:
329 error = _(".hg/dirstate inconsistent with current parent's manifest")
331 error = _(".hg/dirstate inconsistent with current parent's manifest")
330 raise error.Abort(error)
332 raise error.Abort(error)
331
333
332 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
334 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
333 def debugcommands(ui, cmd='', *args):
335 def debugcommands(ui, cmd='', *args):
334 """list all available commands and options"""
336 """list all available commands and options"""
335 for cmd, vals in sorted(commands.table.iteritems()):
337 for cmd, vals in sorted(commands.table.iteritems()):
336 cmd = cmd.split('|')[0].strip('^')
338 cmd = cmd.split('|')[0].strip('^')
337 opts = ', '.join([i[1] for i in vals[1]])
339 opts = ', '.join([i[1] for i in vals[1]])
338 ui.write('%s: %s\n' % (cmd, opts))
340 ui.write('%s: %s\n' % (cmd, opts))
339
341
340 @command('debugcomplete',
342 @command('debugcomplete',
341 [('o', 'options', None, _('show the command options'))],
343 [('o', 'options', None, _('show the command options'))],
342 _('[-o] CMD'),
344 _('[-o] CMD'),
343 norepo=True)
345 norepo=True)
344 def debugcomplete(ui, cmd='', **opts):
346 def debugcomplete(ui, cmd='', **opts):
345 """returns the completion list associated with the given command"""
347 """returns the completion list associated with the given command"""
346
348
347 if opts.get('options'):
349 if opts.get('options'):
348 options = []
350 options = []
349 otables = [commands.globalopts]
351 otables = [commands.globalopts]
350 if cmd:
352 if cmd:
351 aliases, entry = cmdutil.findcmd(cmd, commands.table, False)
353 aliases, entry = cmdutil.findcmd(cmd, commands.table, False)
352 otables.append(entry[1])
354 otables.append(entry[1])
353 for t in otables:
355 for t in otables:
354 for o in t:
356 for o in t:
355 if "(DEPRECATED)" in o[3]:
357 if "(DEPRECATED)" in o[3]:
356 continue
358 continue
357 if o[0]:
359 if o[0]:
358 options.append('-%s' % o[0])
360 options.append('-%s' % o[0])
359 options.append('--%s' % o[1])
361 options.append('--%s' % o[1])
360 ui.write("%s\n" % "\n".join(options))
362 ui.write("%s\n" % "\n".join(options))
361 return
363 return
362
364
363 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, commands.table)
365 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, commands.table)
364 if ui.verbose:
366 if ui.verbose:
365 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
367 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
366 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
368 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
367
369
368 @command('debugdag',
370 @command('debugdag',
369 [('t', 'tags', None, _('use tags as labels')),
371 [('t', 'tags', None, _('use tags as labels')),
370 ('b', 'branches', None, _('annotate with branch names')),
372 ('b', 'branches', None, _('annotate with branch names')),
371 ('', 'dots', None, _('use dots for runs')),
373 ('', 'dots', None, _('use dots for runs')),
372 ('s', 'spaces', None, _('separate elements by spaces'))],
374 ('s', 'spaces', None, _('separate elements by spaces'))],
373 _('[OPTION]... [FILE [REV]...]'),
375 _('[OPTION]... [FILE [REV]...]'),
374 optionalrepo=True)
376 optionalrepo=True)
375 def debugdag(ui, repo, file_=None, *revs, **opts):
377 def debugdag(ui, repo, file_=None, *revs, **opts):
376 """format the changelog or an index DAG as a concise textual description
378 """format the changelog or an index DAG as a concise textual description
377
379
378 If you pass a revlog index, the revlog's DAG is emitted. If you list
380 If you pass a revlog index, the revlog's DAG is emitted. If you list
379 revision numbers, they get labeled in the output as rN.
381 revision numbers, they get labeled in the output as rN.
380
382
381 Otherwise, the changelog DAG of the current repo is emitted.
383 Otherwise, the changelog DAG of the current repo is emitted.
382 """
384 """
383 spaces = opts.get('spaces')
385 spaces = opts.get('spaces')
384 dots = opts.get('dots')
386 dots = opts.get('dots')
385 if file_:
387 if file_:
386 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
388 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
387 revs = set((int(r) for r in revs))
389 revs = set((int(r) for r in revs))
388 def events():
390 def events():
389 for r in rlog:
391 for r in rlog:
390 yield 'n', (r, list(p for p in rlog.parentrevs(r)
392 yield 'n', (r, list(p for p in rlog.parentrevs(r)
391 if p != -1))
393 if p != -1))
392 if r in revs:
394 if r in revs:
393 yield 'l', (r, "r%i" % r)
395 yield 'l', (r, "r%i" % r)
394 elif repo:
396 elif repo:
395 cl = repo.changelog
397 cl = repo.changelog
396 tags = opts.get('tags')
398 tags = opts.get('tags')
397 branches = opts.get('branches')
399 branches = opts.get('branches')
398 if tags:
400 if tags:
399 labels = {}
401 labels = {}
400 for l, n in repo.tags().items():
402 for l, n in repo.tags().items():
401 labels.setdefault(cl.rev(n), []).append(l)
403 labels.setdefault(cl.rev(n), []).append(l)
402 def events():
404 def events():
403 b = "default"
405 b = "default"
404 for r in cl:
406 for r in cl:
405 if branches:
407 if branches:
406 newb = cl.read(cl.node(r))[5]['branch']
408 newb = cl.read(cl.node(r))[5]['branch']
407 if newb != b:
409 if newb != b:
408 yield 'a', newb
410 yield 'a', newb
409 b = newb
411 b = newb
410 yield 'n', (r, list(p for p in cl.parentrevs(r)
412 yield 'n', (r, list(p for p in cl.parentrevs(r)
411 if p != -1))
413 if p != -1))
412 if tags:
414 if tags:
413 ls = labels.get(r)
415 ls = labels.get(r)
414 if ls:
416 if ls:
415 for l in ls:
417 for l in ls:
416 yield 'l', (r, l)
418 yield 'l', (r, l)
417 else:
419 else:
418 raise error.Abort(_('need repo for changelog dag'))
420 raise error.Abort(_('need repo for changelog dag'))
419
421
420 for line in dagparser.dagtextlines(events(),
422 for line in dagparser.dagtextlines(events(),
421 addspaces=spaces,
423 addspaces=spaces,
422 wraplabels=True,
424 wraplabels=True,
423 wrapannotations=True,
425 wrapannotations=True,
424 wrapnonlinear=dots,
426 wrapnonlinear=dots,
425 usedots=dots,
427 usedots=dots,
426 maxlinewidth=70):
428 maxlinewidth=70):
427 ui.write(line)
429 ui.write(line)
428 ui.write("\n")
430 ui.write("\n")
429
431
430 @command('debugdata', commands.debugrevlogopts, _('-c|-m|FILE REV'))
432 @command('debugdata', commands.debugrevlogopts, _('-c|-m|FILE REV'))
431 def debugdata(ui, repo, file_, rev=None, **opts):
433 def debugdata(ui, repo, file_, rev=None, **opts):
432 """dump the contents of a data file revision"""
434 """dump the contents of a data file revision"""
433 if opts.get('changelog') or opts.get('manifest') or opts.get('dir'):
435 if opts.get('changelog') or opts.get('manifest') or opts.get('dir'):
434 if rev is not None:
436 if rev is not None:
435 raise error.CommandError('debugdata', _('invalid arguments'))
437 raise error.CommandError('debugdata', _('invalid arguments'))
436 file_, rev = None, file_
438 file_, rev = None, file_
437 elif rev is None:
439 elif rev is None:
438 raise error.CommandError('debugdata', _('invalid arguments'))
440 raise error.CommandError('debugdata', _('invalid arguments'))
439 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
441 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
440 try:
442 try:
441 ui.write(r.revision(r.lookup(rev)))
443 ui.write(r.revision(r.lookup(rev)))
442 except KeyError:
444 except KeyError:
443 raise error.Abort(_('invalid revision identifier %s') % rev)
445 raise error.Abort(_('invalid revision identifier %s') % rev)
444
446
445 @command('debugdate',
447 @command('debugdate',
446 [('e', 'extended', None, _('try extended date formats'))],
448 [('e', 'extended', None, _('try extended date formats'))],
447 _('[-e] DATE [RANGE]'),
449 _('[-e] DATE [RANGE]'),
448 norepo=True, optionalrepo=True)
450 norepo=True, optionalrepo=True)
449 def debugdate(ui, date, range=None, **opts):
451 def debugdate(ui, date, range=None, **opts):
450 """parse and display a date"""
452 """parse and display a date"""
451 if opts["extended"]:
453 if opts["extended"]:
452 d = util.parsedate(date, util.extendeddateformats)
454 d = util.parsedate(date, util.extendeddateformats)
453 else:
455 else:
454 d = util.parsedate(date)
456 d = util.parsedate(date)
455 ui.write(("internal: %s %s\n") % d)
457 ui.write(("internal: %s %s\n") % d)
456 ui.write(("standard: %s\n") % util.datestr(d))
458 ui.write(("standard: %s\n") % util.datestr(d))
457 if range:
459 if range:
458 m = util.matchdate(range)
460 m = util.matchdate(range)
459 ui.write(("match: %s\n") % m(d[0]))
461 ui.write(("match: %s\n") % m(d[0]))
460
462
461 @command('debugdiscovery',
463 @command('debugdiscovery',
462 [('', 'old', None, _('use old-style discovery')),
464 [('', 'old', None, _('use old-style discovery')),
463 ('', 'nonheads', None,
465 ('', 'nonheads', None,
464 _('use old-style discovery with non-heads included')),
466 _('use old-style discovery with non-heads included')),
465 ] + commands.remoteopts,
467 ] + commands.remoteopts,
466 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
468 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
467 def debugdiscovery(ui, repo, remoteurl="default", **opts):
469 def debugdiscovery(ui, repo, remoteurl="default", **opts):
468 """runs the changeset discovery protocol in isolation"""
470 """runs the changeset discovery protocol in isolation"""
469 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
471 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
470 opts.get('branch'))
472 opts.get('branch'))
471 remote = hg.peer(repo, opts, remoteurl)
473 remote = hg.peer(repo, opts, remoteurl)
472 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
474 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
473
475
474 # make sure tests are repeatable
476 # make sure tests are repeatable
475 random.seed(12323)
477 random.seed(12323)
476
478
477 def doit(localheads, remoteheads, remote=remote):
479 def doit(localheads, remoteheads, remote=remote):
478 if opts.get('old'):
480 if opts.get('old'):
479 if localheads:
481 if localheads:
480 raise error.Abort('cannot use localheads with old style '
482 raise error.Abort('cannot use localheads with old style '
481 'discovery')
483 'discovery')
482 if not util.safehasattr(remote, 'branches'):
484 if not util.safehasattr(remote, 'branches'):
483 # enable in-client legacy support
485 # enable in-client legacy support
484 remote = localrepo.locallegacypeer(remote.local())
486 remote = localrepo.locallegacypeer(remote.local())
485 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
487 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
486 force=True)
488 force=True)
487 common = set(common)
489 common = set(common)
488 if not opts.get('nonheads'):
490 if not opts.get('nonheads'):
489 ui.write(("unpruned common: %s\n") %
491 ui.write(("unpruned common: %s\n") %
490 " ".join(sorted(short(n) for n in common)))
492 " ".join(sorted(short(n) for n in common)))
491 dag = dagutil.revlogdag(repo.changelog)
493 dag = dagutil.revlogdag(repo.changelog)
492 all = dag.ancestorset(dag.internalizeall(common))
494 all = dag.ancestorset(dag.internalizeall(common))
493 common = dag.externalizeall(dag.headsetofconnecteds(all))
495 common = dag.externalizeall(dag.headsetofconnecteds(all))
494 else:
496 else:
495 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
497 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
496 common = set(common)
498 common = set(common)
497 rheads = set(hds)
499 rheads = set(hds)
498 lheads = set(repo.heads())
500 lheads = set(repo.heads())
499 ui.write(("common heads: %s\n") %
501 ui.write(("common heads: %s\n") %
500 " ".join(sorted(short(n) for n in common)))
502 " ".join(sorted(short(n) for n in common)))
501 if lheads <= common:
503 if lheads <= common:
502 ui.write(("local is subset\n"))
504 ui.write(("local is subset\n"))
503 elif rheads <= common:
505 elif rheads <= common:
504 ui.write(("remote is subset\n"))
506 ui.write(("remote is subset\n"))
505
507
506 serverlogs = opts.get('serverlog')
508 serverlogs = opts.get('serverlog')
507 if serverlogs:
509 if serverlogs:
508 for filename in serverlogs:
510 for filename in serverlogs:
509 with open(filename, 'r') as logfile:
511 with open(filename, 'r') as logfile:
510 line = logfile.readline()
512 line = logfile.readline()
511 while line:
513 while line:
512 parts = line.strip().split(';')
514 parts = line.strip().split(';')
513 op = parts[1]
515 op = parts[1]
514 if op == 'cg':
516 if op == 'cg':
515 pass
517 pass
516 elif op == 'cgss':
518 elif op == 'cgss':
517 doit(parts[2].split(' '), parts[3].split(' '))
519 doit(parts[2].split(' '), parts[3].split(' '))
518 elif op == 'unb':
520 elif op == 'unb':
519 doit(parts[3].split(' '), parts[2].split(' '))
521 doit(parts[3].split(' '), parts[2].split(' '))
520 line = logfile.readline()
522 line = logfile.readline()
521 else:
523 else:
522 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
524 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
523 opts.get('remote_head'))
525 opts.get('remote_head'))
524 localrevs = opts.get('local_head')
526 localrevs = opts.get('local_head')
525 doit(localrevs, remoterevs)
527 doit(localrevs, remoterevs)
528
529 @command('debugextensions', commands.formatteropts, [], norepo=True)
530 def debugextensions(ui, **opts):
531 '''show information about active extensions'''
532 exts = extensions.extensions(ui)
533 hgver = util.version()
534 fm = ui.formatter('debugextensions', opts)
535 for extname, extmod in sorted(exts, key=operator.itemgetter(0)):
536 isinternal = extensions.ismoduleinternal(extmod)
537 extsource = extmod.__file__
538 if isinternal:
539 exttestedwith = [] # never expose magic string to users
540 else:
541 exttestedwith = getattr(extmod, 'testedwith', '').split()
542 extbuglink = getattr(extmod, 'buglink', None)
543
544 fm.startitem()
545
546 if ui.quiet or ui.verbose:
547 fm.write('name', '%s\n', extname)
548 else:
549 fm.write('name', '%s', extname)
550 if isinternal or hgver in exttestedwith:
551 fm.plain('\n')
552 elif not exttestedwith:
553 fm.plain(_(' (untested!)\n'))
554 else:
555 lasttestedversion = exttestedwith[-1]
556 fm.plain(' (%s!)\n' % lasttestedversion)
557
558 fm.condwrite(ui.verbose and extsource, 'source',
559 _(' location: %s\n'), extsource or "")
560
561 if ui.verbose:
562 fm.plain(_(' bundled: %s\n') % ['no', 'yes'][isinternal])
563 fm.data(bundled=isinternal)
564
565 fm.condwrite(ui.verbose and exttestedwith, 'testedwith',
566 _(' tested with: %s\n'),
567 fm.formatlist(exttestedwith, name='ver'))
568
569 fm.condwrite(ui.verbose and extbuglink, 'buglink',
570 _(' bug reporting: %s\n'), extbuglink or "")
571
572 fm.end()
General Comments 0
You need to be logged in to leave comments. Login now