##// END OF EJS Templates
httpservice: move sys.exit() out of serve_forever()...
Martin von Zweigbergk -
r46422:b7b8a153 default
parent child Browse files
Show More
@@ -1,7677 +1,7678 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 errno
10 import errno
11 import os
11 import os
12 import re
12 import re
13 import sys
13 import sys
14
14
15 from .i18n import _
15 from .i18n import _
16 from .node import (
16 from .node import (
17 hex,
17 hex,
18 nullid,
18 nullid,
19 nullrev,
19 nullrev,
20 short,
20 short,
21 wdirhex,
21 wdirhex,
22 wdirrev,
22 wdirrev,
23 )
23 )
24 from .pycompat import open
24 from .pycompat import open
25 from . import (
25 from . import (
26 archival,
26 archival,
27 bookmarks,
27 bookmarks,
28 bundle2,
28 bundle2,
29 bundlecaches,
29 bundlecaches,
30 changegroup,
30 changegroup,
31 cmdutil,
31 cmdutil,
32 copies,
32 copies,
33 debugcommands as debugcommandsmod,
33 debugcommands as debugcommandsmod,
34 destutil,
34 destutil,
35 dirstateguard,
35 dirstateguard,
36 discovery,
36 discovery,
37 encoding,
37 encoding,
38 error,
38 error,
39 exchange,
39 exchange,
40 extensions,
40 extensions,
41 filemerge,
41 filemerge,
42 formatter,
42 formatter,
43 graphmod,
43 graphmod,
44 grep as grepmod,
44 grep as grepmod,
45 hbisect,
45 hbisect,
46 help,
46 help,
47 hg,
47 hg,
48 logcmdutil,
48 logcmdutil,
49 merge as mergemod,
49 merge as mergemod,
50 mergestate as mergestatemod,
50 mergestate as mergestatemod,
51 narrowspec,
51 narrowspec,
52 obsolete,
52 obsolete,
53 obsutil,
53 obsutil,
54 patch,
54 patch,
55 phases,
55 phases,
56 pycompat,
56 pycompat,
57 rcutil,
57 rcutil,
58 registrar,
58 registrar,
59 requirements,
59 requirements,
60 revsetlang,
60 revsetlang,
61 rewriteutil,
61 rewriteutil,
62 scmutil,
62 scmutil,
63 server,
63 server,
64 shelve as shelvemod,
64 shelve as shelvemod,
65 state as statemod,
65 state as statemod,
66 streamclone,
66 streamclone,
67 tags as tagsmod,
67 tags as tagsmod,
68 ui as uimod,
68 ui as uimod,
69 util,
69 util,
70 verify as verifymod,
70 verify as verifymod,
71 vfs as vfsmod,
71 vfs as vfsmod,
72 wireprotoserver,
72 wireprotoserver,
73 )
73 )
74 from .utils import (
74 from .utils import (
75 dateutil,
75 dateutil,
76 stringutil,
76 stringutil,
77 )
77 )
78
78
79 table = {}
79 table = {}
80 table.update(debugcommandsmod.command._table)
80 table.update(debugcommandsmod.command._table)
81
81
82 command = registrar.command(table)
82 command = registrar.command(table)
83 INTENT_READONLY = registrar.INTENT_READONLY
83 INTENT_READONLY = registrar.INTENT_READONLY
84
84
85 # common command options
85 # common command options
86
86
87 globalopts = [
87 globalopts = [
88 (
88 (
89 b'R',
89 b'R',
90 b'repository',
90 b'repository',
91 b'',
91 b'',
92 _(b'repository root directory or name of overlay bundle file'),
92 _(b'repository root directory or name of overlay bundle file'),
93 _(b'REPO'),
93 _(b'REPO'),
94 ),
94 ),
95 (b'', b'cwd', b'', _(b'change working directory'), _(b'DIR')),
95 (b'', b'cwd', b'', _(b'change working directory'), _(b'DIR')),
96 (
96 (
97 b'y',
97 b'y',
98 b'noninteractive',
98 b'noninteractive',
99 None,
99 None,
100 _(
100 _(
101 b'do not prompt, automatically pick the first choice for all prompts'
101 b'do not prompt, automatically pick the first choice for all prompts'
102 ),
102 ),
103 ),
103 ),
104 (b'q', b'quiet', None, _(b'suppress output')),
104 (b'q', b'quiet', None, _(b'suppress output')),
105 (b'v', b'verbose', None, _(b'enable additional output')),
105 (b'v', b'verbose', None, _(b'enable additional output')),
106 (
106 (
107 b'',
107 b'',
108 b'color',
108 b'color',
109 b'',
109 b'',
110 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
110 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
111 # and should not be translated
111 # and should not be translated
112 _(b"when to colorize (boolean, always, auto, never, or debug)"),
112 _(b"when to colorize (boolean, always, auto, never, or debug)"),
113 _(b'TYPE'),
113 _(b'TYPE'),
114 ),
114 ),
115 (
115 (
116 b'',
116 b'',
117 b'config',
117 b'config',
118 [],
118 [],
119 _(b'set/override config option (use \'section.name=value\')'),
119 _(b'set/override config option (use \'section.name=value\')'),
120 _(b'CONFIG'),
120 _(b'CONFIG'),
121 ),
121 ),
122 (b'', b'debug', None, _(b'enable debugging output')),
122 (b'', b'debug', None, _(b'enable debugging output')),
123 (b'', b'debugger', None, _(b'start debugger')),
123 (b'', b'debugger', None, _(b'start debugger')),
124 (
124 (
125 b'',
125 b'',
126 b'encoding',
126 b'encoding',
127 encoding.encoding,
127 encoding.encoding,
128 _(b'set the charset encoding'),
128 _(b'set the charset encoding'),
129 _(b'ENCODE'),
129 _(b'ENCODE'),
130 ),
130 ),
131 (
131 (
132 b'',
132 b'',
133 b'encodingmode',
133 b'encodingmode',
134 encoding.encodingmode,
134 encoding.encodingmode,
135 _(b'set the charset encoding mode'),
135 _(b'set the charset encoding mode'),
136 _(b'MODE'),
136 _(b'MODE'),
137 ),
137 ),
138 (b'', b'traceback', None, _(b'always print a traceback on exception')),
138 (b'', b'traceback', None, _(b'always print a traceback on exception')),
139 (b'', b'time', None, _(b'time how long the command takes')),
139 (b'', b'time', None, _(b'time how long the command takes')),
140 (b'', b'profile', None, _(b'print command execution profile')),
140 (b'', b'profile', None, _(b'print command execution profile')),
141 (b'', b'version', None, _(b'output version information and exit')),
141 (b'', b'version', None, _(b'output version information and exit')),
142 (b'h', b'help', None, _(b'display help and exit')),
142 (b'h', b'help', None, _(b'display help and exit')),
143 (b'', b'hidden', False, _(b'consider hidden changesets')),
143 (b'', b'hidden', False, _(b'consider hidden changesets')),
144 (
144 (
145 b'',
145 b'',
146 b'pager',
146 b'pager',
147 b'auto',
147 b'auto',
148 _(b"when to paginate (boolean, always, auto, or never)"),
148 _(b"when to paginate (boolean, always, auto, or never)"),
149 _(b'TYPE'),
149 _(b'TYPE'),
150 ),
150 ),
151 ]
151 ]
152
152
153 dryrunopts = cmdutil.dryrunopts
153 dryrunopts = cmdutil.dryrunopts
154 remoteopts = cmdutil.remoteopts
154 remoteopts = cmdutil.remoteopts
155 walkopts = cmdutil.walkopts
155 walkopts = cmdutil.walkopts
156 commitopts = cmdutil.commitopts
156 commitopts = cmdutil.commitopts
157 commitopts2 = cmdutil.commitopts2
157 commitopts2 = cmdutil.commitopts2
158 commitopts3 = cmdutil.commitopts3
158 commitopts3 = cmdutil.commitopts3
159 formatteropts = cmdutil.formatteropts
159 formatteropts = cmdutil.formatteropts
160 templateopts = cmdutil.templateopts
160 templateopts = cmdutil.templateopts
161 logopts = cmdutil.logopts
161 logopts = cmdutil.logopts
162 diffopts = cmdutil.diffopts
162 diffopts = cmdutil.diffopts
163 diffwsopts = cmdutil.diffwsopts
163 diffwsopts = cmdutil.diffwsopts
164 diffopts2 = cmdutil.diffopts2
164 diffopts2 = cmdutil.diffopts2
165 mergetoolopts = cmdutil.mergetoolopts
165 mergetoolopts = cmdutil.mergetoolopts
166 similarityopts = cmdutil.similarityopts
166 similarityopts = cmdutil.similarityopts
167 subrepoopts = cmdutil.subrepoopts
167 subrepoopts = cmdutil.subrepoopts
168 debugrevlogopts = cmdutil.debugrevlogopts
168 debugrevlogopts = cmdutil.debugrevlogopts
169
169
170 # Commands start here, listed alphabetically
170 # Commands start here, listed alphabetically
171
171
172
172
173 @command(
173 @command(
174 b'abort',
174 b'abort',
175 dryrunopts,
175 dryrunopts,
176 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
176 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
177 helpbasic=True,
177 helpbasic=True,
178 )
178 )
179 def abort(ui, repo, **opts):
179 def abort(ui, repo, **opts):
180 """abort an unfinished operation (EXPERIMENTAL)
180 """abort an unfinished operation (EXPERIMENTAL)
181
181
182 Aborts a multistep operation like graft, histedit, rebase, merge,
182 Aborts a multistep operation like graft, histedit, rebase, merge,
183 and unshelve if they are in an unfinished state.
183 and unshelve if they are in an unfinished state.
184
184
185 use --dry-run/-n to dry run the command.
185 use --dry-run/-n to dry run the command.
186 """
186 """
187 dryrun = opts.get('dry_run')
187 dryrun = opts.get('dry_run')
188 abortstate = cmdutil.getunfinishedstate(repo)
188 abortstate = cmdutil.getunfinishedstate(repo)
189 if not abortstate:
189 if not abortstate:
190 raise error.Abort(_(b'no operation in progress'))
190 raise error.Abort(_(b'no operation in progress'))
191 if not abortstate.abortfunc:
191 if not abortstate.abortfunc:
192 raise error.Abort(
192 raise error.Abort(
193 (
193 (
194 _(b"%s in progress but does not support 'hg abort'")
194 _(b"%s in progress but does not support 'hg abort'")
195 % (abortstate._opname)
195 % (abortstate._opname)
196 ),
196 ),
197 hint=abortstate.hint(),
197 hint=abortstate.hint(),
198 )
198 )
199 if dryrun:
199 if dryrun:
200 ui.status(
200 ui.status(
201 _(b'%s in progress, will be aborted\n') % (abortstate._opname)
201 _(b'%s in progress, will be aborted\n') % (abortstate._opname)
202 )
202 )
203 return
203 return
204 return abortstate.abortfunc(ui, repo)
204 return abortstate.abortfunc(ui, repo)
205
205
206
206
207 @command(
207 @command(
208 b'add',
208 b'add',
209 walkopts + subrepoopts + dryrunopts,
209 walkopts + subrepoopts + dryrunopts,
210 _(b'[OPTION]... [FILE]...'),
210 _(b'[OPTION]... [FILE]...'),
211 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
211 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
212 helpbasic=True,
212 helpbasic=True,
213 inferrepo=True,
213 inferrepo=True,
214 )
214 )
215 def add(ui, repo, *pats, **opts):
215 def add(ui, repo, *pats, **opts):
216 """add the specified files on the next commit
216 """add the specified files on the next commit
217
217
218 Schedule files to be version controlled and added to the
218 Schedule files to be version controlled and added to the
219 repository.
219 repository.
220
220
221 The files will be added to the repository at the next commit. To
221 The files will be added to the repository at the next commit. To
222 undo an add before that, see :hg:`forget`.
222 undo an add before that, see :hg:`forget`.
223
223
224 If no names are given, add all files to the repository (except
224 If no names are given, add all files to the repository (except
225 files matching ``.hgignore``).
225 files matching ``.hgignore``).
226
226
227 .. container:: verbose
227 .. container:: verbose
228
228
229 Examples:
229 Examples:
230
230
231 - New (unknown) files are added
231 - New (unknown) files are added
232 automatically by :hg:`add`::
232 automatically by :hg:`add`::
233
233
234 $ ls
234 $ ls
235 foo.c
235 foo.c
236 $ hg status
236 $ hg status
237 ? foo.c
237 ? foo.c
238 $ hg add
238 $ hg add
239 adding foo.c
239 adding foo.c
240 $ hg status
240 $ hg status
241 A foo.c
241 A foo.c
242
242
243 - Specific files to be added can be specified::
243 - Specific files to be added can be specified::
244
244
245 $ ls
245 $ ls
246 bar.c foo.c
246 bar.c foo.c
247 $ hg status
247 $ hg status
248 ? bar.c
248 ? bar.c
249 ? foo.c
249 ? foo.c
250 $ hg add bar.c
250 $ hg add bar.c
251 $ hg status
251 $ hg status
252 A bar.c
252 A bar.c
253 ? foo.c
253 ? foo.c
254
254
255 Returns 0 if all files are successfully added.
255 Returns 0 if all files are successfully added.
256 """
256 """
257
257
258 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
258 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
259 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
259 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
260 rejected = cmdutil.add(ui, repo, m, b"", uipathfn, False, **opts)
260 rejected = cmdutil.add(ui, repo, m, b"", uipathfn, False, **opts)
261 return rejected and 1 or 0
261 return rejected and 1 or 0
262
262
263
263
264 @command(
264 @command(
265 b'addremove',
265 b'addremove',
266 similarityopts + subrepoopts + walkopts + dryrunopts,
266 similarityopts + subrepoopts + walkopts + dryrunopts,
267 _(b'[OPTION]... [FILE]...'),
267 _(b'[OPTION]... [FILE]...'),
268 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
268 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
269 inferrepo=True,
269 inferrepo=True,
270 )
270 )
271 def addremove(ui, repo, *pats, **opts):
271 def addremove(ui, repo, *pats, **opts):
272 """add all new files, delete all missing files
272 """add all new files, delete all missing files
273
273
274 Add all new files and remove all missing files from the
274 Add all new files and remove all missing files from the
275 repository.
275 repository.
276
276
277 Unless names are given, new files are ignored if they match any of
277 Unless names are given, new files are ignored if they match any of
278 the patterns in ``.hgignore``. As with add, these changes take
278 the patterns in ``.hgignore``. As with add, these changes take
279 effect at the next commit.
279 effect at the next commit.
280
280
281 Use the -s/--similarity option to detect renamed files. This
281 Use the -s/--similarity option to detect renamed files. This
282 option takes a percentage between 0 (disabled) and 100 (files must
282 option takes a percentage between 0 (disabled) and 100 (files must
283 be identical) as its parameter. With a parameter greater than 0,
283 be identical) as its parameter. With a parameter greater than 0,
284 this compares every removed file with every added file and records
284 this compares every removed file with every added file and records
285 those similar enough as renames. Detecting renamed files this way
285 those similar enough as renames. Detecting renamed files this way
286 can be expensive. After using this option, :hg:`status -C` can be
286 can be expensive. After using this option, :hg:`status -C` can be
287 used to check which files were identified as moved or renamed. If
287 used to check which files were identified as moved or renamed. If
288 not specified, -s/--similarity defaults to 100 and only renames of
288 not specified, -s/--similarity defaults to 100 and only renames of
289 identical files are detected.
289 identical files are detected.
290
290
291 .. container:: verbose
291 .. container:: verbose
292
292
293 Examples:
293 Examples:
294
294
295 - A number of files (bar.c and foo.c) are new,
295 - A number of files (bar.c and foo.c) are new,
296 while foobar.c has been removed (without using :hg:`remove`)
296 while foobar.c has been removed (without using :hg:`remove`)
297 from the repository::
297 from the repository::
298
298
299 $ ls
299 $ ls
300 bar.c foo.c
300 bar.c foo.c
301 $ hg status
301 $ hg status
302 ! foobar.c
302 ! foobar.c
303 ? bar.c
303 ? bar.c
304 ? foo.c
304 ? foo.c
305 $ hg addremove
305 $ hg addremove
306 adding bar.c
306 adding bar.c
307 adding foo.c
307 adding foo.c
308 removing foobar.c
308 removing foobar.c
309 $ hg status
309 $ hg status
310 A bar.c
310 A bar.c
311 A foo.c
311 A foo.c
312 R foobar.c
312 R foobar.c
313
313
314 - A file foobar.c was moved to foo.c without using :hg:`rename`.
314 - A file foobar.c was moved to foo.c without using :hg:`rename`.
315 Afterwards, it was edited slightly::
315 Afterwards, it was edited slightly::
316
316
317 $ ls
317 $ ls
318 foo.c
318 foo.c
319 $ hg status
319 $ hg status
320 ! foobar.c
320 ! foobar.c
321 ? foo.c
321 ? foo.c
322 $ hg addremove --similarity 90
322 $ hg addremove --similarity 90
323 removing foobar.c
323 removing foobar.c
324 adding foo.c
324 adding foo.c
325 recording removal of foobar.c as rename to foo.c (94% similar)
325 recording removal of foobar.c as rename to foo.c (94% similar)
326 $ hg status -C
326 $ hg status -C
327 A foo.c
327 A foo.c
328 foobar.c
328 foobar.c
329 R foobar.c
329 R foobar.c
330
330
331 Returns 0 if all files are successfully added.
331 Returns 0 if all files are successfully added.
332 """
332 """
333 opts = pycompat.byteskwargs(opts)
333 opts = pycompat.byteskwargs(opts)
334 if not opts.get(b'similarity'):
334 if not opts.get(b'similarity'):
335 opts[b'similarity'] = b'100'
335 opts[b'similarity'] = b'100'
336 matcher = scmutil.match(repo[None], pats, opts)
336 matcher = scmutil.match(repo[None], pats, opts)
337 relative = scmutil.anypats(pats, opts)
337 relative = scmutil.anypats(pats, opts)
338 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
338 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
339 return scmutil.addremove(repo, matcher, b"", uipathfn, opts)
339 return scmutil.addremove(repo, matcher, b"", uipathfn, opts)
340
340
341
341
342 @command(
342 @command(
343 b'annotate|blame',
343 b'annotate|blame',
344 [
344 [
345 (b'r', b'rev', b'', _(b'annotate the specified revision'), _(b'REV')),
345 (b'r', b'rev', b'', _(b'annotate the specified revision'), _(b'REV')),
346 (
346 (
347 b'',
347 b'',
348 b'follow',
348 b'follow',
349 None,
349 None,
350 _(b'follow copies/renames and list the filename (DEPRECATED)'),
350 _(b'follow copies/renames and list the filename (DEPRECATED)'),
351 ),
351 ),
352 (b'', b'no-follow', None, _(b"don't follow copies and renames")),
352 (b'', b'no-follow', None, _(b"don't follow copies and renames")),
353 (b'a', b'text', None, _(b'treat all files as text')),
353 (b'a', b'text', None, _(b'treat all files as text')),
354 (b'u', b'user', None, _(b'list the author (long with -v)')),
354 (b'u', b'user', None, _(b'list the author (long with -v)')),
355 (b'f', b'file', None, _(b'list the filename')),
355 (b'f', b'file', None, _(b'list the filename')),
356 (b'd', b'date', None, _(b'list the date (short with -q)')),
356 (b'd', b'date', None, _(b'list the date (short with -q)')),
357 (b'n', b'number', None, _(b'list the revision number (default)')),
357 (b'n', b'number', None, _(b'list the revision number (default)')),
358 (b'c', b'changeset', None, _(b'list the changeset')),
358 (b'c', b'changeset', None, _(b'list the changeset')),
359 (
359 (
360 b'l',
360 b'l',
361 b'line-number',
361 b'line-number',
362 None,
362 None,
363 _(b'show line number at the first appearance'),
363 _(b'show line number at the first appearance'),
364 ),
364 ),
365 (
365 (
366 b'',
366 b'',
367 b'skip',
367 b'skip',
368 [],
368 [],
369 _(b'revset to not display (EXPERIMENTAL)'),
369 _(b'revset to not display (EXPERIMENTAL)'),
370 _(b'REV'),
370 _(b'REV'),
371 ),
371 ),
372 ]
372 ]
373 + diffwsopts
373 + diffwsopts
374 + walkopts
374 + walkopts
375 + formatteropts,
375 + formatteropts,
376 _(b'[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
376 _(b'[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
377 helpcategory=command.CATEGORY_FILE_CONTENTS,
377 helpcategory=command.CATEGORY_FILE_CONTENTS,
378 helpbasic=True,
378 helpbasic=True,
379 inferrepo=True,
379 inferrepo=True,
380 )
380 )
381 def annotate(ui, repo, *pats, **opts):
381 def annotate(ui, repo, *pats, **opts):
382 """show changeset information by line for each file
382 """show changeset information by line for each file
383
383
384 List changes in files, showing the revision id responsible for
384 List changes in files, showing the revision id responsible for
385 each line.
385 each line.
386
386
387 This command is useful for discovering when a change was made and
387 This command is useful for discovering when a change was made and
388 by whom.
388 by whom.
389
389
390 If you include --file, --user, or --date, the revision number is
390 If you include --file, --user, or --date, the revision number is
391 suppressed unless you also include --number.
391 suppressed unless you also include --number.
392
392
393 Without the -a/--text option, annotate will avoid processing files
393 Without the -a/--text option, annotate will avoid processing files
394 it detects as binary. With -a, annotate will annotate the file
394 it detects as binary. With -a, annotate will annotate the file
395 anyway, although the results will probably be neither useful
395 anyway, although the results will probably be neither useful
396 nor desirable.
396 nor desirable.
397
397
398 .. container:: verbose
398 .. container:: verbose
399
399
400 Template:
400 Template:
401
401
402 The following keywords are supported in addition to the common template
402 The following keywords are supported in addition to the common template
403 keywords and functions. See also :hg:`help templates`.
403 keywords and functions. See also :hg:`help templates`.
404
404
405 :lines: List of lines with annotation data.
405 :lines: List of lines with annotation data.
406 :path: String. Repository-absolute path of the specified file.
406 :path: String. Repository-absolute path of the specified file.
407
407
408 And each entry of ``{lines}`` provides the following sub-keywords in
408 And each entry of ``{lines}`` provides the following sub-keywords in
409 addition to ``{date}``, ``{node}``, ``{rev}``, ``{user}``, etc.
409 addition to ``{date}``, ``{node}``, ``{rev}``, ``{user}``, etc.
410
410
411 :line: String. Line content.
411 :line: String. Line content.
412 :lineno: Integer. Line number at that revision.
412 :lineno: Integer. Line number at that revision.
413 :path: String. Repository-absolute path of the file at that revision.
413 :path: String. Repository-absolute path of the file at that revision.
414
414
415 See :hg:`help templates.operators` for the list expansion syntax.
415 See :hg:`help templates.operators` for the list expansion syntax.
416
416
417 Returns 0 on success.
417 Returns 0 on success.
418 """
418 """
419 opts = pycompat.byteskwargs(opts)
419 opts = pycompat.byteskwargs(opts)
420 if not pats:
420 if not pats:
421 raise error.Abort(_(b'at least one filename or pattern is required'))
421 raise error.Abort(_(b'at least one filename or pattern is required'))
422
422
423 if opts.get(b'follow'):
423 if opts.get(b'follow'):
424 # --follow is deprecated and now just an alias for -f/--file
424 # --follow is deprecated and now just an alias for -f/--file
425 # to mimic the behavior of Mercurial before version 1.5
425 # to mimic the behavior of Mercurial before version 1.5
426 opts[b'file'] = True
426 opts[b'file'] = True
427
427
428 if (
428 if (
429 not opts.get(b'user')
429 not opts.get(b'user')
430 and not opts.get(b'changeset')
430 and not opts.get(b'changeset')
431 and not opts.get(b'date')
431 and not opts.get(b'date')
432 and not opts.get(b'file')
432 and not opts.get(b'file')
433 ):
433 ):
434 opts[b'number'] = True
434 opts[b'number'] = True
435
435
436 linenumber = opts.get(b'line_number') is not None
436 linenumber = opts.get(b'line_number') is not None
437 if (
437 if (
438 linenumber
438 linenumber
439 and (not opts.get(b'changeset'))
439 and (not opts.get(b'changeset'))
440 and (not opts.get(b'number'))
440 and (not opts.get(b'number'))
441 ):
441 ):
442 raise error.Abort(_(b'at least one of -n/-c is required for -l'))
442 raise error.Abort(_(b'at least one of -n/-c is required for -l'))
443
443
444 rev = opts.get(b'rev')
444 rev = opts.get(b'rev')
445 if rev:
445 if rev:
446 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
446 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
447 ctx = scmutil.revsingle(repo, rev)
447 ctx = scmutil.revsingle(repo, rev)
448
448
449 ui.pager(b'annotate')
449 ui.pager(b'annotate')
450 rootfm = ui.formatter(b'annotate', opts)
450 rootfm = ui.formatter(b'annotate', opts)
451 if ui.debugflag:
451 if ui.debugflag:
452 shorthex = pycompat.identity
452 shorthex = pycompat.identity
453 else:
453 else:
454
454
455 def shorthex(h):
455 def shorthex(h):
456 return h[:12]
456 return h[:12]
457
457
458 if ui.quiet:
458 if ui.quiet:
459 datefunc = dateutil.shortdate
459 datefunc = dateutil.shortdate
460 else:
460 else:
461 datefunc = dateutil.datestr
461 datefunc = dateutil.datestr
462 if ctx.rev() is None:
462 if ctx.rev() is None:
463 if opts.get(b'changeset'):
463 if opts.get(b'changeset'):
464 # omit "+" suffix which is appended to node hex
464 # omit "+" suffix which is appended to node hex
465 def formatrev(rev):
465 def formatrev(rev):
466 if rev == wdirrev:
466 if rev == wdirrev:
467 return b'%d' % ctx.p1().rev()
467 return b'%d' % ctx.p1().rev()
468 else:
468 else:
469 return b'%d' % rev
469 return b'%d' % rev
470
470
471 else:
471 else:
472
472
473 def formatrev(rev):
473 def formatrev(rev):
474 if rev == wdirrev:
474 if rev == wdirrev:
475 return b'%d+' % ctx.p1().rev()
475 return b'%d+' % ctx.p1().rev()
476 else:
476 else:
477 return b'%d ' % rev
477 return b'%d ' % rev
478
478
479 def formathex(h):
479 def formathex(h):
480 if h == wdirhex:
480 if h == wdirhex:
481 return b'%s+' % shorthex(hex(ctx.p1().node()))
481 return b'%s+' % shorthex(hex(ctx.p1().node()))
482 else:
482 else:
483 return b'%s ' % shorthex(h)
483 return b'%s ' % shorthex(h)
484
484
485 else:
485 else:
486 formatrev = b'%d'.__mod__
486 formatrev = b'%d'.__mod__
487 formathex = shorthex
487 formathex = shorthex
488
488
489 opmap = [
489 opmap = [
490 (b'user', b' ', lambda x: x.fctx.user(), ui.shortuser),
490 (b'user', b' ', lambda x: x.fctx.user(), ui.shortuser),
491 (b'rev', b' ', lambda x: scmutil.intrev(x.fctx), formatrev),
491 (b'rev', b' ', lambda x: scmutil.intrev(x.fctx), formatrev),
492 (b'node', b' ', lambda x: hex(scmutil.binnode(x.fctx)), formathex),
492 (b'node', b' ', lambda x: hex(scmutil.binnode(x.fctx)), formathex),
493 (b'date', b' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
493 (b'date', b' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
494 (b'path', b' ', lambda x: x.fctx.path(), pycompat.bytestr),
494 (b'path', b' ', lambda x: x.fctx.path(), pycompat.bytestr),
495 (b'lineno', b':', lambda x: x.lineno, pycompat.bytestr),
495 (b'lineno', b':', lambda x: x.lineno, pycompat.bytestr),
496 ]
496 ]
497 opnamemap = {
497 opnamemap = {
498 b'rev': b'number',
498 b'rev': b'number',
499 b'node': b'changeset',
499 b'node': b'changeset',
500 b'path': b'file',
500 b'path': b'file',
501 b'lineno': b'line_number',
501 b'lineno': b'line_number',
502 }
502 }
503
503
504 if rootfm.isplain():
504 if rootfm.isplain():
505
505
506 def makefunc(get, fmt):
506 def makefunc(get, fmt):
507 return lambda x: fmt(get(x))
507 return lambda x: fmt(get(x))
508
508
509 else:
509 else:
510
510
511 def makefunc(get, fmt):
511 def makefunc(get, fmt):
512 return get
512 return get
513
513
514 datahint = rootfm.datahint()
514 datahint = rootfm.datahint()
515 funcmap = [
515 funcmap = [
516 (makefunc(get, fmt), sep)
516 (makefunc(get, fmt), sep)
517 for fn, sep, get, fmt in opmap
517 for fn, sep, get, fmt in opmap
518 if opts.get(opnamemap.get(fn, fn)) or fn in datahint
518 if opts.get(opnamemap.get(fn, fn)) or fn in datahint
519 ]
519 ]
520 funcmap[0] = (funcmap[0][0], b'') # no separator in front of first column
520 funcmap[0] = (funcmap[0][0], b'') # no separator in front of first column
521 fields = b' '.join(
521 fields = b' '.join(
522 fn
522 fn
523 for fn, sep, get, fmt in opmap
523 for fn, sep, get, fmt in opmap
524 if opts.get(opnamemap.get(fn, fn)) or fn in datahint
524 if opts.get(opnamemap.get(fn, fn)) or fn in datahint
525 )
525 )
526
526
527 def bad(x, y):
527 def bad(x, y):
528 raise error.Abort(b"%s: %s" % (x, y))
528 raise error.Abort(b"%s: %s" % (x, y))
529
529
530 m = scmutil.match(ctx, pats, opts, badfn=bad)
530 m = scmutil.match(ctx, pats, opts, badfn=bad)
531
531
532 follow = not opts.get(b'no_follow')
532 follow = not opts.get(b'no_follow')
533 diffopts = patch.difffeatureopts(
533 diffopts = patch.difffeatureopts(
534 ui, opts, section=b'annotate', whitespace=True
534 ui, opts, section=b'annotate', whitespace=True
535 )
535 )
536 skiprevs = opts.get(b'skip')
536 skiprevs = opts.get(b'skip')
537 if skiprevs:
537 if skiprevs:
538 skiprevs = scmutil.revrange(repo, skiprevs)
538 skiprevs = scmutil.revrange(repo, skiprevs)
539
539
540 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
540 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
541 for abs in ctx.walk(m):
541 for abs in ctx.walk(m):
542 fctx = ctx[abs]
542 fctx = ctx[abs]
543 rootfm.startitem()
543 rootfm.startitem()
544 rootfm.data(path=abs)
544 rootfm.data(path=abs)
545 if not opts.get(b'text') and fctx.isbinary():
545 if not opts.get(b'text') and fctx.isbinary():
546 rootfm.plain(_(b"%s: binary file\n") % uipathfn(abs))
546 rootfm.plain(_(b"%s: binary file\n") % uipathfn(abs))
547 continue
547 continue
548
548
549 fm = rootfm.nested(b'lines', tmpl=b'{rev}: {line}')
549 fm = rootfm.nested(b'lines', tmpl=b'{rev}: {line}')
550 lines = fctx.annotate(
550 lines = fctx.annotate(
551 follow=follow, skiprevs=skiprevs, diffopts=diffopts
551 follow=follow, skiprevs=skiprevs, diffopts=diffopts
552 )
552 )
553 if not lines:
553 if not lines:
554 fm.end()
554 fm.end()
555 continue
555 continue
556 formats = []
556 formats = []
557 pieces = []
557 pieces = []
558
558
559 for f, sep in funcmap:
559 for f, sep in funcmap:
560 l = [f(n) for n in lines]
560 l = [f(n) for n in lines]
561 if fm.isplain():
561 if fm.isplain():
562 sizes = [encoding.colwidth(x) for x in l]
562 sizes = [encoding.colwidth(x) for x in l]
563 ml = max(sizes)
563 ml = max(sizes)
564 formats.append([sep + b' ' * (ml - w) + b'%s' for w in sizes])
564 formats.append([sep + b' ' * (ml - w) + b'%s' for w in sizes])
565 else:
565 else:
566 formats.append([b'%s'] * len(l))
566 formats.append([b'%s'] * len(l))
567 pieces.append(l)
567 pieces.append(l)
568
568
569 for f, p, n in zip(zip(*formats), zip(*pieces), lines):
569 for f, p, n in zip(zip(*formats), zip(*pieces), lines):
570 fm.startitem()
570 fm.startitem()
571 fm.context(fctx=n.fctx)
571 fm.context(fctx=n.fctx)
572 fm.write(fields, b"".join(f), *p)
572 fm.write(fields, b"".join(f), *p)
573 if n.skip:
573 if n.skip:
574 fmt = b"* %s"
574 fmt = b"* %s"
575 else:
575 else:
576 fmt = b": %s"
576 fmt = b": %s"
577 fm.write(b'line', fmt, n.text)
577 fm.write(b'line', fmt, n.text)
578
578
579 if not lines[-1].text.endswith(b'\n'):
579 if not lines[-1].text.endswith(b'\n'):
580 fm.plain(b'\n')
580 fm.plain(b'\n')
581 fm.end()
581 fm.end()
582
582
583 rootfm.end()
583 rootfm.end()
584
584
585
585
586 @command(
586 @command(
587 b'archive',
587 b'archive',
588 [
588 [
589 (b'', b'no-decode', None, _(b'do not pass files through decoders')),
589 (b'', b'no-decode', None, _(b'do not pass files through decoders')),
590 (
590 (
591 b'p',
591 b'p',
592 b'prefix',
592 b'prefix',
593 b'',
593 b'',
594 _(b'directory prefix for files in archive'),
594 _(b'directory prefix for files in archive'),
595 _(b'PREFIX'),
595 _(b'PREFIX'),
596 ),
596 ),
597 (b'r', b'rev', b'', _(b'revision to distribute'), _(b'REV')),
597 (b'r', b'rev', b'', _(b'revision to distribute'), _(b'REV')),
598 (b't', b'type', b'', _(b'type of distribution to create'), _(b'TYPE')),
598 (b't', b'type', b'', _(b'type of distribution to create'), _(b'TYPE')),
599 ]
599 ]
600 + subrepoopts
600 + subrepoopts
601 + walkopts,
601 + walkopts,
602 _(b'[OPTION]... DEST'),
602 _(b'[OPTION]... DEST'),
603 helpcategory=command.CATEGORY_IMPORT_EXPORT,
603 helpcategory=command.CATEGORY_IMPORT_EXPORT,
604 )
604 )
605 def archive(ui, repo, dest, **opts):
605 def archive(ui, repo, dest, **opts):
606 '''create an unversioned archive of a repository revision
606 '''create an unversioned archive of a repository revision
607
607
608 By default, the revision used is the parent of the working
608 By default, the revision used is the parent of the working
609 directory; use -r/--rev to specify a different revision.
609 directory; use -r/--rev to specify a different revision.
610
610
611 The archive type is automatically detected based on file
611 The archive type is automatically detected based on file
612 extension (to override, use -t/--type).
612 extension (to override, use -t/--type).
613
613
614 .. container:: verbose
614 .. container:: verbose
615
615
616 Examples:
616 Examples:
617
617
618 - create a zip file containing the 1.0 release::
618 - create a zip file containing the 1.0 release::
619
619
620 hg archive -r 1.0 project-1.0.zip
620 hg archive -r 1.0 project-1.0.zip
621
621
622 - create a tarball excluding .hg files::
622 - create a tarball excluding .hg files::
623
623
624 hg archive project.tar.gz -X ".hg*"
624 hg archive project.tar.gz -X ".hg*"
625
625
626 Valid types are:
626 Valid types are:
627
627
628 :``files``: a directory full of files (default)
628 :``files``: a directory full of files (default)
629 :``tar``: tar archive, uncompressed
629 :``tar``: tar archive, uncompressed
630 :``tbz2``: tar archive, compressed using bzip2
630 :``tbz2``: tar archive, compressed using bzip2
631 :``tgz``: tar archive, compressed using gzip
631 :``tgz``: tar archive, compressed using gzip
632 :``txz``: tar archive, compressed using lzma (only in Python 3)
632 :``txz``: tar archive, compressed using lzma (only in Python 3)
633 :``uzip``: zip archive, uncompressed
633 :``uzip``: zip archive, uncompressed
634 :``zip``: zip archive, compressed using deflate
634 :``zip``: zip archive, compressed using deflate
635
635
636 The exact name of the destination archive or directory is given
636 The exact name of the destination archive or directory is given
637 using a format string; see :hg:`help export` for details.
637 using a format string; see :hg:`help export` for details.
638
638
639 Each member added to an archive file has a directory prefix
639 Each member added to an archive file has a directory prefix
640 prepended. Use -p/--prefix to specify a format string for the
640 prepended. Use -p/--prefix to specify a format string for the
641 prefix. The default is the basename of the archive, with suffixes
641 prefix. The default is the basename of the archive, with suffixes
642 removed.
642 removed.
643
643
644 Returns 0 on success.
644 Returns 0 on success.
645 '''
645 '''
646
646
647 opts = pycompat.byteskwargs(opts)
647 opts = pycompat.byteskwargs(opts)
648 rev = opts.get(b'rev')
648 rev = opts.get(b'rev')
649 if rev:
649 if rev:
650 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
650 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
651 ctx = scmutil.revsingle(repo, rev)
651 ctx = scmutil.revsingle(repo, rev)
652 if not ctx:
652 if not ctx:
653 raise error.Abort(_(b'no working directory: please specify a revision'))
653 raise error.Abort(_(b'no working directory: please specify a revision'))
654 node = ctx.node()
654 node = ctx.node()
655 dest = cmdutil.makefilename(ctx, dest)
655 dest = cmdutil.makefilename(ctx, dest)
656 if os.path.realpath(dest) == repo.root:
656 if os.path.realpath(dest) == repo.root:
657 raise error.Abort(_(b'repository root cannot be destination'))
657 raise error.Abort(_(b'repository root cannot be destination'))
658
658
659 kind = opts.get(b'type') or archival.guesskind(dest) or b'files'
659 kind = opts.get(b'type') or archival.guesskind(dest) or b'files'
660 prefix = opts.get(b'prefix')
660 prefix = opts.get(b'prefix')
661
661
662 if dest == b'-':
662 if dest == b'-':
663 if kind == b'files':
663 if kind == b'files':
664 raise error.Abort(_(b'cannot archive plain files to stdout'))
664 raise error.Abort(_(b'cannot archive plain files to stdout'))
665 dest = cmdutil.makefileobj(ctx, dest)
665 dest = cmdutil.makefileobj(ctx, dest)
666 if not prefix:
666 if not prefix:
667 prefix = os.path.basename(repo.root) + b'-%h'
667 prefix = os.path.basename(repo.root) + b'-%h'
668
668
669 prefix = cmdutil.makefilename(ctx, prefix)
669 prefix = cmdutil.makefilename(ctx, prefix)
670 match = scmutil.match(ctx, [], opts)
670 match = scmutil.match(ctx, [], opts)
671 archival.archive(
671 archival.archive(
672 repo,
672 repo,
673 dest,
673 dest,
674 node,
674 node,
675 kind,
675 kind,
676 not opts.get(b'no_decode'),
676 not opts.get(b'no_decode'),
677 match,
677 match,
678 prefix,
678 prefix,
679 subrepos=opts.get(b'subrepos'),
679 subrepos=opts.get(b'subrepos'),
680 )
680 )
681
681
682
682
683 @command(
683 @command(
684 b'backout',
684 b'backout',
685 [
685 [
686 (
686 (
687 b'',
687 b'',
688 b'merge',
688 b'merge',
689 None,
689 None,
690 _(b'merge with old dirstate parent after backout'),
690 _(b'merge with old dirstate parent after backout'),
691 ),
691 ),
692 (
692 (
693 b'',
693 b'',
694 b'commit',
694 b'commit',
695 None,
695 None,
696 _(b'commit if no conflicts were encountered (DEPRECATED)'),
696 _(b'commit if no conflicts were encountered (DEPRECATED)'),
697 ),
697 ),
698 (b'', b'no-commit', None, _(b'do not commit')),
698 (b'', b'no-commit', None, _(b'do not commit')),
699 (
699 (
700 b'',
700 b'',
701 b'parent',
701 b'parent',
702 b'',
702 b'',
703 _(b'parent to choose when backing out merge (DEPRECATED)'),
703 _(b'parent to choose when backing out merge (DEPRECATED)'),
704 _(b'REV'),
704 _(b'REV'),
705 ),
705 ),
706 (b'r', b'rev', b'', _(b'revision to backout'), _(b'REV')),
706 (b'r', b'rev', b'', _(b'revision to backout'), _(b'REV')),
707 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
707 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
708 ]
708 ]
709 + mergetoolopts
709 + mergetoolopts
710 + walkopts
710 + walkopts
711 + commitopts
711 + commitopts
712 + commitopts2,
712 + commitopts2,
713 _(b'[OPTION]... [-r] REV'),
713 _(b'[OPTION]... [-r] REV'),
714 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
714 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
715 )
715 )
716 def backout(ui, repo, node=None, rev=None, **opts):
716 def backout(ui, repo, node=None, rev=None, **opts):
717 '''reverse effect of earlier changeset
717 '''reverse effect of earlier changeset
718
718
719 Prepare a new changeset with the effect of REV undone in the
719 Prepare a new changeset with the effect of REV undone in the
720 current working directory. If no conflicts were encountered,
720 current working directory. If no conflicts were encountered,
721 it will be committed immediately.
721 it will be committed immediately.
722
722
723 If REV is the parent of the working directory, then this new changeset
723 If REV is the parent of the working directory, then this new changeset
724 is committed automatically (unless --no-commit is specified).
724 is committed automatically (unless --no-commit is specified).
725
725
726 .. note::
726 .. note::
727
727
728 :hg:`backout` cannot be used to fix either an unwanted or
728 :hg:`backout` cannot be used to fix either an unwanted or
729 incorrect merge.
729 incorrect merge.
730
730
731 .. container:: verbose
731 .. container:: verbose
732
732
733 Examples:
733 Examples:
734
734
735 - Reverse the effect of the parent of the working directory.
735 - Reverse the effect of the parent of the working directory.
736 This backout will be committed immediately::
736 This backout will be committed immediately::
737
737
738 hg backout -r .
738 hg backout -r .
739
739
740 - Reverse the effect of previous bad revision 23::
740 - Reverse the effect of previous bad revision 23::
741
741
742 hg backout -r 23
742 hg backout -r 23
743
743
744 - Reverse the effect of previous bad revision 23 and
744 - Reverse the effect of previous bad revision 23 and
745 leave changes uncommitted::
745 leave changes uncommitted::
746
746
747 hg backout -r 23 --no-commit
747 hg backout -r 23 --no-commit
748 hg commit -m "Backout revision 23"
748 hg commit -m "Backout revision 23"
749
749
750 By default, the pending changeset will have one parent,
750 By default, the pending changeset will have one parent,
751 maintaining a linear history. With --merge, the pending
751 maintaining a linear history. With --merge, the pending
752 changeset will instead have two parents: the old parent of the
752 changeset will instead have two parents: the old parent of the
753 working directory and a new child of REV that simply undoes REV.
753 working directory and a new child of REV that simply undoes REV.
754
754
755 Before version 1.7, the behavior without --merge was equivalent
755 Before version 1.7, the behavior without --merge was equivalent
756 to specifying --merge followed by :hg:`update --clean .` to
756 to specifying --merge followed by :hg:`update --clean .` to
757 cancel the merge and leave the child of REV as a head to be
757 cancel the merge and leave the child of REV as a head to be
758 merged separately.
758 merged separately.
759
759
760 See :hg:`help dates` for a list of formats valid for -d/--date.
760 See :hg:`help dates` for a list of formats valid for -d/--date.
761
761
762 See :hg:`help revert` for a way to restore files to the state
762 See :hg:`help revert` for a way to restore files to the state
763 of another revision.
763 of another revision.
764
764
765 Returns 0 on success, 1 if nothing to backout or there are unresolved
765 Returns 0 on success, 1 if nothing to backout or there are unresolved
766 files.
766 files.
767 '''
767 '''
768 with repo.wlock(), repo.lock():
768 with repo.wlock(), repo.lock():
769 return _dobackout(ui, repo, node, rev, **opts)
769 return _dobackout(ui, repo, node, rev, **opts)
770
770
771
771
772 def _dobackout(ui, repo, node=None, rev=None, **opts):
772 def _dobackout(ui, repo, node=None, rev=None, **opts):
773 cmdutil.check_incompatible_arguments(opts, 'no_commit', ['commit', 'merge'])
773 cmdutil.check_incompatible_arguments(opts, 'no_commit', ['commit', 'merge'])
774 opts = pycompat.byteskwargs(opts)
774 opts = pycompat.byteskwargs(opts)
775
775
776 if rev and node:
776 if rev and node:
777 raise error.Abort(_(b"please specify just one revision"))
777 raise error.Abort(_(b"please specify just one revision"))
778
778
779 if not rev:
779 if not rev:
780 rev = node
780 rev = node
781
781
782 if not rev:
782 if not rev:
783 raise error.Abort(_(b"please specify a revision to backout"))
783 raise error.Abort(_(b"please specify a revision to backout"))
784
784
785 date = opts.get(b'date')
785 date = opts.get(b'date')
786 if date:
786 if date:
787 opts[b'date'] = dateutil.parsedate(date)
787 opts[b'date'] = dateutil.parsedate(date)
788
788
789 cmdutil.checkunfinished(repo)
789 cmdutil.checkunfinished(repo)
790 cmdutil.bailifchanged(repo)
790 cmdutil.bailifchanged(repo)
791 ctx = scmutil.revsingle(repo, rev)
791 ctx = scmutil.revsingle(repo, rev)
792 node = ctx.node()
792 node = ctx.node()
793
793
794 op1, op2 = repo.dirstate.parents()
794 op1, op2 = repo.dirstate.parents()
795 if not repo.changelog.isancestor(node, op1):
795 if not repo.changelog.isancestor(node, op1):
796 raise error.Abort(_(b'cannot backout change that is not an ancestor'))
796 raise error.Abort(_(b'cannot backout change that is not an ancestor'))
797
797
798 p1, p2 = repo.changelog.parents(node)
798 p1, p2 = repo.changelog.parents(node)
799 if p1 == nullid:
799 if p1 == nullid:
800 raise error.Abort(_(b'cannot backout a change with no parents'))
800 raise error.Abort(_(b'cannot backout a change with no parents'))
801 if p2 != nullid:
801 if p2 != nullid:
802 if not opts.get(b'parent'):
802 if not opts.get(b'parent'):
803 raise error.Abort(_(b'cannot backout a merge changeset'))
803 raise error.Abort(_(b'cannot backout a merge changeset'))
804 p = repo.lookup(opts[b'parent'])
804 p = repo.lookup(opts[b'parent'])
805 if p not in (p1, p2):
805 if p not in (p1, p2):
806 raise error.Abort(
806 raise error.Abort(
807 _(b'%s is not a parent of %s') % (short(p), short(node))
807 _(b'%s is not a parent of %s') % (short(p), short(node))
808 )
808 )
809 parent = p
809 parent = p
810 else:
810 else:
811 if opts.get(b'parent'):
811 if opts.get(b'parent'):
812 raise error.Abort(_(b'cannot use --parent on non-merge changeset'))
812 raise error.Abort(_(b'cannot use --parent on non-merge changeset'))
813 parent = p1
813 parent = p1
814
814
815 # the backout should appear on the same branch
815 # the backout should appear on the same branch
816 branch = repo.dirstate.branch()
816 branch = repo.dirstate.branch()
817 bheads = repo.branchheads(branch)
817 bheads = repo.branchheads(branch)
818 rctx = scmutil.revsingle(repo, hex(parent))
818 rctx = scmutil.revsingle(repo, hex(parent))
819 if not opts.get(b'merge') and op1 != node:
819 if not opts.get(b'merge') and op1 != node:
820 with dirstateguard.dirstateguard(repo, b'backout'):
820 with dirstateguard.dirstateguard(repo, b'backout'):
821 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
821 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
822 with ui.configoverride(overrides, b'backout'):
822 with ui.configoverride(overrides, b'backout'):
823 stats = mergemod.back_out(ctx, parent=repo[parent])
823 stats = mergemod.back_out(ctx, parent=repo[parent])
824 repo.setparents(op1, op2)
824 repo.setparents(op1, op2)
825 hg._showstats(repo, stats)
825 hg._showstats(repo, stats)
826 if stats.unresolvedcount:
826 if stats.unresolvedcount:
827 repo.ui.status(
827 repo.ui.status(
828 _(b"use 'hg resolve' to retry unresolved file merges\n")
828 _(b"use 'hg resolve' to retry unresolved file merges\n")
829 )
829 )
830 return 1
830 return 1
831 else:
831 else:
832 hg.clean(repo, node, show_stats=False)
832 hg.clean(repo, node, show_stats=False)
833 repo.dirstate.setbranch(branch)
833 repo.dirstate.setbranch(branch)
834 cmdutil.revert(ui, repo, rctx)
834 cmdutil.revert(ui, repo, rctx)
835
835
836 if opts.get(b'no_commit'):
836 if opts.get(b'no_commit'):
837 msg = _(b"changeset %s backed out, don't forget to commit.\n")
837 msg = _(b"changeset %s backed out, don't forget to commit.\n")
838 ui.status(msg % short(node))
838 ui.status(msg % short(node))
839 return 0
839 return 0
840
840
841 def commitfunc(ui, repo, message, match, opts):
841 def commitfunc(ui, repo, message, match, opts):
842 editform = b'backout'
842 editform = b'backout'
843 e = cmdutil.getcommiteditor(
843 e = cmdutil.getcommiteditor(
844 editform=editform, **pycompat.strkwargs(opts)
844 editform=editform, **pycompat.strkwargs(opts)
845 )
845 )
846 if not message:
846 if not message:
847 # we don't translate commit messages
847 # we don't translate commit messages
848 message = b"Backed out changeset %s" % short(node)
848 message = b"Backed out changeset %s" % short(node)
849 e = cmdutil.getcommiteditor(edit=True, editform=editform)
849 e = cmdutil.getcommiteditor(edit=True, editform=editform)
850 return repo.commit(
850 return repo.commit(
851 message, opts.get(b'user'), opts.get(b'date'), match, editor=e
851 message, opts.get(b'user'), opts.get(b'date'), match, editor=e
852 )
852 )
853
853
854 # save to detect changes
854 # save to detect changes
855 tip = repo.changelog.tip()
855 tip = repo.changelog.tip()
856
856
857 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
857 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
858 if not newnode:
858 if not newnode:
859 ui.status(_(b"nothing changed\n"))
859 ui.status(_(b"nothing changed\n"))
860 return 1
860 return 1
861 cmdutil.commitstatus(repo, newnode, branch, bheads, tip)
861 cmdutil.commitstatus(repo, newnode, branch, bheads, tip)
862
862
863 def nice(node):
863 def nice(node):
864 return b'%d:%s' % (repo.changelog.rev(node), short(node))
864 return b'%d:%s' % (repo.changelog.rev(node), short(node))
865
865
866 ui.status(
866 ui.status(
867 _(b'changeset %s backs out changeset %s\n')
867 _(b'changeset %s backs out changeset %s\n')
868 % (nice(newnode), nice(node))
868 % (nice(newnode), nice(node))
869 )
869 )
870 if opts.get(b'merge') and op1 != node:
870 if opts.get(b'merge') and op1 != node:
871 hg.clean(repo, op1, show_stats=False)
871 hg.clean(repo, op1, show_stats=False)
872 ui.status(_(b'merging with changeset %s\n') % nice(newnode))
872 ui.status(_(b'merging with changeset %s\n') % nice(newnode))
873 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
873 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
874 with ui.configoverride(overrides, b'backout'):
874 with ui.configoverride(overrides, b'backout'):
875 return hg.merge(repo[b'tip'])
875 return hg.merge(repo[b'tip'])
876 return 0
876 return 0
877
877
878
878
879 @command(
879 @command(
880 b'bisect',
880 b'bisect',
881 [
881 [
882 (b'r', b'reset', False, _(b'reset bisect state')),
882 (b'r', b'reset', False, _(b'reset bisect state')),
883 (b'g', b'good', False, _(b'mark changeset good')),
883 (b'g', b'good', False, _(b'mark changeset good')),
884 (b'b', b'bad', False, _(b'mark changeset bad')),
884 (b'b', b'bad', False, _(b'mark changeset bad')),
885 (b's', b'skip', False, _(b'skip testing changeset')),
885 (b's', b'skip', False, _(b'skip testing changeset')),
886 (b'e', b'extend', False, _(b'extend the bisect range')),
886 (b'e', b'extend', False, _(b'extend the bisect range')),
887 (
887 (
888 b'c',
888 b'c',
889 b'command',
889 b'command',
890 b'',
890 b'',
891 _(b'use command to check changeset state'),
891 _(b'use command to check changeset state'),
892 _(b'CMD'),
892 _(b'CMD'),
893 ),
893 ),
894 (b'U', b'noupdate', False, _(b'do not update to target')),
894 (b'U', b'noupdate', False, _(b'do not update to target')),
895 ],
895 ],
896 _(b"[-gbsr] [-U] [-c CMD] [REV]"),
896 _(b"[-gbsr] [-U] [-c CMD] [REV]"),
897 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
897 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
898 )
898 )
899 def bisect(
899 def bisect(
900 ui,
900 ui,
901 repo,
901 repo,
902 rev=None,
902 rev=None,
903 extra=None,
903 extra=None,
904 command=None,
904 command=None,
905 reset=None,
905 reset=None,
906 good=None,
906 good=None,
907 bad=None,
907 bad=None,
908 skip=None,
908 skip=None,
909 extend=None,
909 extend=None,
910 noupdate=None,
910 noupdate=None,
911 ):
911 ):
912 """subdivision search of changesets
912 """subdivision search of changesets
913
913
914 This command helps to find changesets which introduce problems. To
914 This command helps to find changesets which introduce problems. To
915 use, mark the earliest changeset you know exhibits the problem as
915 use, mark the earliest changeset you know exhibits the problem as
916 bad, then mark the latest changeset which is free from the problem
916 bad, then mark the latest changeset which is free from the problem
917 as good. Bisect will update your working directory to a revision
917 as good. Bisect will update your working directory to a revision
918 for testing (unless the -U/--noupdate option is specified). Once
918 for testing (unless the -U/--noupdate option is specified). Once
919 you have performed tests, mark the working directory as good or
919 you have performed tests, mark the working directory as good or
920 bad, and bisect will either update to another candidate changeset
920 bad, and bisect will either update to another candidate changeset
921 or announce that it has found the bad revision.
921 or announce that it has found the bad revision.
922
922
923 As a shortcut, you can also use the revision argument to mark a
923 As a shortcut, you can also use the revision argument to mark a
924 revision as good or bad without checking it out first.
924 revision as good or bad without checking it out first.
925
925
926 If you supply a command, it will be used for automatic bisection.
926 If you supply a command, it will be used for automatic bisection.
927 The environment variable HG_NODE will contain the ID of the
927 The environment variable HG_NODE will contain the ID of the
928 changeset being tested. The exit status of the command will be
928 changeset being tested. The exit status of the command will be
929 used to mark revisions as good or bad: status 0 means good, 125
929 used to mark revisions as good or bad: status 0 means good, 125
930 means to skip the revision, 127 (command not found) will abort the
930 means to skip the revision, 127 (command not found) will abort the
931 bisection, and any other non-zero exit status means the revision
931 bisection, and any other non-zero exit status means the revision
932 is bad.
932 is bad.
933
933
934 .. container:: verbose
934 .. container:: verbose
935
935
936 Some examples:
936 Some examples:
937
937
938 - start a bisection with known bad revision 34, and good revision 12::
938 - start a bisection with known bad revision 34, and good revision 12::
939
939
940 hg bisect --bad 34
940 hg bisect --bad 34
941 hg bisect --good 12
941 hg bisect --good 12
942
942
943 - advance the current bisection by marking current revision as good or
943 - advance the current bisection by marking current revision as good or
944 bad::
944 bad::
945
945
946 hg bisect --good
946 hg bisect --good
947 hg bisect --bad
947 hg bisect --bad
948
948
949 - mark the current revision, or a known revision, to be skipped (e.g. if
949 - mark the current revision, or a known revision, to be skipped (e.g. if
950 that revision is not usable because of another issue)::
950 that revision is not usable because of another issue)::
951
951
952 hg bisect --skip
952 hg bisect --skip
953 hg bisect --skip 23
953 hg bisect --skip 23
954
954
955 - skip all revisions that do not touch directories ``foo`` or ``bar``::
955 - skip all revisions that do not touch directories ``foo`` or ``bar``::
956
956
957 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
957 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
958
958
959 - forget the current bisection::
959 - forget the current bisection::
960
960
961 hg bisect --reset
961 hg bisect --reset
962
962
963 - use 'make && make tests' to automatically find the first broken
963 - use 'make && make tests' to automatically find the first broken
964 revision::
964 revision::
965
965
966 hg bisect --reset
966 hg bisect --reset
967 hg bisect --bad 34
967 hg bisect --bad 34
968 hg bisect --good 12
968 hg bisect --good 12
969 hg bisect --command "make && make tests"
969 hg bisect --command "make && make tests"
970
970
971 - see all changesets whose states are already known in the current
971 - see all changesets whose states are already known in the current
972 bisection::
972 bisection::
973
973
974 hg log -r "bisect(pruned)"
974 hg log -r "bisect(pruned)"
975
975
976 - see the changeset currently being bisected (especially useful
976 - see the changeset currently being bisected (especially useful
977 if running with -U/--noupdate)::
977 if running with -U/--noupdate)::
978
978
979 hg log -r "bisect(current)"
979 hg log -r "bisect(current)"
980
980
981 - see all changesets that took part in the current bisection::
981 - see all changesets that took part in the current bisection::
982
982
983 hg log -r "bisect(range)"
983 hg log -r "bisect(range)"
984
984
985 - you can even get a nice graph::
985 - you can even get a nice graph::
986
986
987 hg log --graph -r "bisect(range)"
987 hg log --graph -r "bisect(range)"
988
988
989 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
989 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
990
990
991 Returns 0 on success.
991 Returns 0 on success.
992 """
992 """
993 # backward compatibility
993 # backward compatibility
994 if rev in b"good bad reset init".split():
994 if rev in b"good bad reset init".split():
995 ui.warn(_(b"(use of 'hg bisect <cmd>' is deprecated)\n"))
995 ui.warn(_(b"(use of 'hg bisect <cmd>' is deprecated)\n"))
996 cmd, rev, extra = rev, extra, None
996 cmd, rev, extra = rev, extra, None
997 if cmd == b"good":
997 if cmd == b"good":
998 good = True
998 good = True
999 elif cmd == b"bad":
999 elif cmd == b"bad":
1000 bad = True
1000 bad = True
1001 else:
1001 else:
1002 reset = True
1002 reset = True
1003 elif extra:
1003 elif extra:
1004 raise error.Abort(_(b'incompatible arguments'))
1004 raise error.Abort(_(b'incompatible arguments'))
1005
1005
1006 incompatibles = {
1006 incompatibles = {
1007 b'--bad': bad,
1007 b'--bad': bad,
1008 b'--command': bool(command),
1008 b'--command': bool(command),
1009 b'--extend': extend,
1009 b'--extend': extend,
1010 b'--good': good,
1010 b'--good': good,
1011 b'--reset': reset,
1011 b'--reset': reset,
1012 b'--skip': skip,
1012 b'--skip': skip,
1013 }
1013 }
1014
1014
1015 enabled = [x for x in incompatibles if incompatibles[x]]
1015 enabled = [x for x in incompatibles if incompatibles[x]]
1016
1016
1017 if len(enabled) > 1:
1017 if len(enabled) > 1:
1018 raise error.Abort(
1018 raise error.Abort(
1019 _(b'%s and %s are incompatible') % tuple(sorted(enabled)[0:2])
1019 _(b'%s and %s are incompatible') % tuple(sorted(enabled)[0:2])
1020 )
1020 )
1021
1021
1022 if reset:
1022 if reset:
1023 hbisect.resetstate(repo)
1023 hbisect.resetstate(repo)
1024 return
1024 return
1025
1025
1026 state = hbisect.load_state(repo)
1026 state = hbisect.load_state(repo)
1027
1027
1028 # update state
1028 # update state
1029 if good or bad or skip:
1029 if good or bad or skip:
1030 if rev:
1030 if rev:
1031 nodes = [repo[i].node() for i in scmutil.revrange(repo, [rev])]
1031 nodes = [repo[i].node() for i in scmutil.revrange(repo, [rev])]
1032 else:
1032 else:
1033 nodes = [repo.lookup(b'.')]
1033 nodes = [repo.lookup(b'.')]
1034 if good:
1034 if good:
1035 state[b'good'] += nodes
1035 state[b'good'] += nodes
1036 elif bad:
1036 elif bad:
1037 state[b'bad'] += nodes
1037 state[b'bad'] += nodes
1038 elif skip:
1038 elif skip:
1039 state[b'skip'] += nodes
1039 state[b'skip'] += nodes
1040 hbisect.save_state(repo, state)
1040 hbisect.save_state(repo, state)
1041 if not (state[b'good'] and state[b'bad']):
1041 if not (state[b'good'] and state[b'bad']):
1042 return
1042 return
1043
1043
1044 def mayupdate(repo, node, show_stats=True):
1044 def mayupdate(repo, node, show_stats=True):
1045 """common used update sequence"""
1045 """common used update sequence"""
1046 if noupdate:
1046 if noupdate:
1047 return
1047 return
1048 cmdutil.checkunfinished(repo)
1048 cmdutil.checkunfinished(repo)
1049 cmdutil.bailifchanged(repo)
1049 cmdutil.bailifchanged(repo)
1050 return hg.clean(repo, node, show_stats=show_stats)
1050 return hg.clean(repo, node, show_stats=show_stats)
1051
1051
1052 displayer = logcmdutil.changesetdisplayer(ui, repo, {})
1052 displayer = logcmdutil.changesetdisplayer(ui, repo, {})
1053
1053
1054 if command:
1054 if command:
1055 changesets = 1
1055 changesets = 1
1056 if noupdate:
1056 if noupdate:
1057 try:
1057 try:
1058 node = state[b'current'][0]
1058 node = state[b'current'][0]
1059 except LookupError:
1059 except LookupError:
1060 raise error.Abort(
1060 raise error.Abort(
1061 _(
1061 _(
1062 b'current bisect revision is unknown - '
1062 b'current bisect revision is unknown - '
1063 b'start a new bisect to fix'
1063 b'start a new bisect to fix'
1064 )
1064 )
1065 )
1065 )
1066 else:
1066 else:
1067 node, p2 = repo.dirstate.parents()
1067 node, p2 = repo.dirstate.parents()
1068 if p2 != nullid:
1068 if p2 != nullid:
1069 raise error.Abort(_(b'current bisect revision is a merge'))
1069 raise error.Abort(_(b'current bisect revision is a merge'))
1070 if rev:
1070 if rev:
1071 node = repo[scmutil.revsingle(repo, rev, node)].node()
1071 node = repo[scmutil.revsingle(repo, rev, node)].node()
1072 with hbisect.restore_state(repo, state, node):
1072 with hbisect.restore_state(repo, state, node):
1073 while changesets:
1073 while changesets:
1074 # update state
1074 # update state
1075 state[b'current'] = [node]
1075 state[b'current'] = [node]
1076 hbisect.save_state(repo, state)
1076 hbisect.save_state(repo, state)
1077 status = ui.system(
1077 status = ui.system(
1078 command,
1078 command,
1079 environ={b'HG_NODE': hex(node)},
1079 environ={b'HG_NODE': hex(node)},
1080 blockedtag=b'bisect_check',
1080 blockedtag=b'bisect_check',
1081 )
1081 )
1082 if status == 125:
1082 if status == 125:
1083 transition = b"skip"
1083 transition = b"skip"
1084 elif status == 0:
1084 elif status == 0:
1085 transition = b"good"
1085 transition = b"good"
1086 # status < 0 means process was killed
1086 # status < 0 means process was killed
1087 elif status == 127:
1087 elif status == 127:
1088 raise error.Abort(_(b"failed to execute %s") % command)
1088 raise error.Abort(_(b"failed to execute %s") % command)
1089 elif status < 0:
1089 elif status < 0:
1090 raise error.Abort(_(b"%s killed") % command)
1090 raise error.Abort(_(b"%s killed") % command)
1091 else:
1091 else:
1092 transition = b"bad"
1092 transition = b"bad"
1093 state[transition].append(node)
1093 state[transition].append(node)
1094 ctx = repo[node]
1094 ctx = repo[node]
1095 ui.status(
1095 ui.status(
1096 _(b'changeset %d:%s: %s\n') % (ctx.rev(), ctx, transition)
1096 _(b'changeset %d:%s: %s\n') % (ctx.rev(), ctx, transition)
1097 )
1097 )
1098 hbisect.checkstate(state)
1098 hbisect.checkstate(state)
1099 # bisect
1099 # bisect
1100 nodes, changesets, bgood = hbisect.bisect(repo, state)
1100 nodes, changesets, bgood = hbisect.bisect(repo, state)
1101 # update to next check
1101 # update to next check
1102 node = nodes[0]
1102 node = nodes[0]
1103 mayupdate(repo, node, show_stats=False)
1103 mayupdate(repo, node, show_stats=False)
1104 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
1104 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
1105 return
1105 return
1106
1106
1107 hbisect.checkstate(state)
1107 hbisect.checkstate(state)
1108
1108
1109 # actually bisect
1109 # actually bisect
1110 nodes, changesets, good = hbisect.bisect(repo, state)
1110 nodes, changesets, good = hbisect.bisect(repo, state)
1111 if extend:
1111 if extend:
1112 if not changesets:
1112 if not changesets:
1113 extendnode = hbisect.extendrange(repo, state, nodes, good)
1113 extendnode = hbisect.extendrange(repo, state, nodes, good)
1114 if extendnode is not None:
1114 if extendnode is not None:
1115 ui.write(
1115 ui.write(
1116 _(b"Extending search to changeset %d:%s\n")
1116 _(b"Extending search to changeset %d:%s\n")
1117 % (extendnode.rev(), extendnode)
1117 % (extendnode.rev(), extendnode)
1118 )
1118 )
1119 state[b'current'] = [extendnode.node()]
1119 state[b'current'] = [extendnode.node()]
1120 hbisect.save_state(repo, state)
1120 hbisect.save_state(repo, state)
1121 return mayupdate(repo, extendnode.node())
1121 return mayupdate(repo, extendnode.node())
1122 raise error.Abort(_(b"nothing to extend"))
1122 raise error.Abort(_(b"nothing to extend"))
1123
1123
1124 if changesets == 0:
1124 if changesets == 0:
1125 hbisect.printresult(ui, repo, state, displayer, nodes, good)
1125 hbisect.printresult(ui, repo, state, displayer, nodes, good)
1126 else:
1126 else:
1127 assert len(nodes) == 1 # only a single node can be tested next
1127 assert len(nodes) == 1 # only a single node can be tested next
1128 node = nodes[0]
1128 node = nodes[0]
1129 # compute the approximate number of remaining tests
1129 # compute the approximate number of remaining tests
1130 tests, size = 0, 2
1130 tests, size = 0, 2
1131 while size <= changesets:
1131 while size <= changesets:
1132 tests, size = tests + 1, size * 2
1132 tests, size = tests + 1, size * 2
1133 rev = repo.changelog.rev(node)
1133 rev = repo.changelog.rev(node)
1134 ui.write(
1134 ui.write(
1135 _(
1135 _(
1136 b"Testing changeset %d:%s "
1136 b"Testing changeset %d:%s "
1137 b"(%d changesets remaining, ~%d tests)\n"
1137 b"(%d changesets remaining, ~%d tests)\n"
1138 )
1138 )
1139 % (rev, short(node), changesets, tests)
1139 % (rev, short(node), changesets, tests)
1140 )
1140 )
1141 state[b'current'] = [node]
1141 state[b'current'] = [node]
1142 hbisect.save_state(repo, state)
1142 hbisect.save_state(repo, state)
1143 return mayupdate(repo, node)
1143 return mayupdate(repo, node)
1144
1144
1145
1145
1146 @command(
1146 @command(
1147 b'bookmarks|bookmark',
1147 b'bookmarks|bookmark',
1148 [
1148 [
1149 (b'f', b'force', False, _(b'force')),
1149 (b'f', b'force', False, _(b'force')),
1150 (b'r', b'rev', b'', _(b'revision for bookmark action'), _(b'REV')),
1150 (b'r', b'rev', b'', _(b'revision for bookmark action'), _(b'REV')),
1151 (b'd', b'delete', False, _(b'delete a given bookmark')),
1151 (b'd', b'delete', False, _(b'delete a given bookmark')),
1152 (b'm', b'rename', b'', _(b'rename a given bookmark'), _(b'OLD')),
1152 (b'm', b'rename', b'', _(b'rename a given bookmark'), _(b'OLD')),
1153 (b'i', b'inactive', False, _(b'mark a bookmark inactive')),
1153 (b'i', b'inactive', False, _(b'mark a bookmark inactive')),
1154 (b'l', b'list', False, _(b'list existing bookmarks')),
1154 (b'l', b'list', False, _(b'list existing bookmarks')),
1155 ]
1155 ]
1156 + formatteropts,
1156 + formatteropts,
1157 _(b'hg bookmarks [OPTIONS]... [NAME]...'),
1157 _(b'hg bookmarks [OPTIONS]... [NAME]...'),
1158 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1158 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1159 )
1159 )
1160 def bookmark(ui, repo, *names, **opts):
1160 def bookmark(ui, repo, *names, **opts):
1161 '''create a new bookmark or list existing bookmarks
1161 '''create a new bookmark or list existing bookmarks
1162
1162
1163 Bookmarks are labels on changesets to help track lines of development.
1163 Bookmarks are labels on changesets to help track lines of development.
1164 Bookmarks are unversioned and can be moved, renamed and deleted.
1164 Bookmarks are unversioned and can be moved, renamed and deleted.
1165 Deleting or moving a bookmark has no effect on the associated changesets.
1165 Deleting or moving a bookmark has no effect on the associated changesets.
1166
1166
1167 Creating or updating to a bookmark causes it to be marked as 'active'.
1167 Creating or updating to a bookmark causes it to be marked as 'active'.
1168 The active bookmark is indicated with a '*'.
1168 The active bookmark is indicated with a '*'.
1169 When a commit is made, the active bookmark will advance to the new commit.
1169 When a commit is made, the active bookmark will advance to the new commit.
1170 A plain :hg:`update` will also advance an active bookmark, if possible.
1170 A plain :hg:`update` will also advance an active bookmark, if possible.
1171 Updating away from a bookmark will cause it to be deactivated.
1171 Updating away from a bookmark will cause it to be deactivated.
1172
1172
1173 Bookmarks can be pushed and pulled between repositories (see
1173 Bookmarks can be pushed and pulled between repositories (see
1174 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
1174 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
1175 diverged, a new 'divergent bookmark' of the form 'name@path' will
1175 diverged, a new 'divergent bookmark' of the form 'name@path' will
1176 be created. Using :hg:`merge` will resolve the divergence.
1176 be created. Using :hg:`merge` will resolve the divergence.
1177
1177
1178 Specifying bookmark as '.' to -m/-d/-l options is equivalent to specifying
1178 Specifying bookmark as '.' to -m/-d/-l options is equivalent to specifying
1179 the active bookmark's name.
1179 the active bookmark's name.
1180
1180
1181 A bookmark named '@' has the special property that :hg:`clone` will
1181 A bookmark named '@' has the special property that :hg:`clone` will
1182 check it out by default if it exists.
1182 check it out by default if it exists.
1183
1183
1184 .. container:: verbose
1184 .. container:: verbose
1185
1185
1186 Template:
1186 Template:
1187
1187
1188 The following keywords are supported in addition to the common template
1188 The following keywords are supported in addition to the common template
1189 keywords and functions such as ``{bookmark}``. See also
1189 keywords and functions such as ``{bookmark}``. See also
1190 :hg:`help templates`.
1190 :hg:`help templates`.
1191
1191
1192 :active: Boolean. True if the bookmark is active.
1192 :active: Boolean. True if the bookmark is active.
1193
1193
1194 Examples:
1194 Examples:
1195
1195
1196 - create an active bookmark for a new line of development::
1196 - create an active bookmark for a new line of development::
1197
1197
1198 hg book new-feature
1198 hg book new-feature
1199
1199
1200 - create an inactive bookmark as a place marker::
1200 - create an inactive bookmark as a place marker::
1201
1201
1202 hg book -i reviewed
1202 hg book -i reviewed
1203
1203
1204 - create an inactive bookmark on another changeset::
1204 - create an inactive bookmark on another changeset::
1205
1205
1206 hg book -r .^ tested
1206 hg book -r .^ tested
1207
1207
1208 - rename bookmark turkey to dinner::
1208 - rename bookmark turkey to dinner::
1209
1209
1210 hg book -m turkey dinner
1210 hg book -m turkey dinner
1211
1211
1212 - move the '@' bookmark from another branch::
1212 - move the '@' bookmark from another branch::
1213
1213
1214 hg book -f @
1214 hg book -f @
1215
1215
1216 - print only the active bookmark name::
1216 - print only the active bookmark name::
1217
1217
1218 hg book -ql .
1218 hg book -ql .
1219 '''
1219 '''
1220 opts = pycompat.byteskwargs(opts)
1220 opts = pycompat.byteskwargs(opts)
1221 force = opts.get(b'force')
1221 force = opts.get(b'force')
1222 rev = opts.get(b'rev')
1222 rev = opts.get(b'rev')
1223 inactive = opts.get(b'inactive') # meaning add/rename to inactive bookmark
1223 inactive = opts.get(b'inactive') # meaning add/rename to inactive bookmark
1224
1224
1225 action = cmdutil.check_at_most_one_arg(opts, b'delete', b'rename', b'list')
1225 action = cmdutil.check_at_most_one_arg(opts, b'delete', b'rename', b'list')
1226 if action:
1226 if action:
1227 cmdutil.check_incompatible_arguments(opts, action, [b'rev'])
1227 cmdutil.check_incompatible_arguments(opts, action, [b'rev'])
1228 elif names or rev:
1228 elif names or rev:
1229 action = b'add'
1229 action = b'add'
1230 elif inactive:
1230 elif inactive:
1231 action = b'inactive' # meaning deactivate
1231 action = b'inactive' # meaning deactivate
1232 else:
1232 else:
1233 action = b'list'
1233 action = b'list'
1234
1234
1235 cmdutil.check_incompatible_arguments(
1235 cmdutil.check_incompatible_arguments(
1236 opts, b'inactive', [b'delete', b'list']
1236 opts, b'inactive', [b'delete', b'list']
1237 )
1237 )
1238 if not names and action in {b'add', b'delete'}:
1238 if not names and action in {b'add', b'delete'}:
1239 raise error.Abort(_(b"bookmark name required"))
1239 raise error.Abort(_(b"bookmark name required"))
1240
1240
1241 if action in {b'add', b'delete', b'rename', b'inactive'}:
1241 if action in {b'add', b'delete', b'rename', b'inactive'}:
1242 with repo.wlock(), repo.lock(), repo.transaction(b'bookmark') as tr:
1242 with repo.wlock(), repo.lock(), repo.transaction(b'bookmark') as tr:
1243 if action == b'delete':
1243 if action == b'delete':
1244 names = pycompat.maplist(repo._bookmarks.expandname, names)
1244 names = pycompat.maplist(repo._bookmarks.expandname, names)
1245 bookmarks.delete(repo, tr, names)
1245 bookmarks.delete(repo, tr, names)
1246 elif action == b'rename':
1246 elif action == b'rename':
1247 if not names:
1247 if not names:
1248 raise error.Abort(_(b"new bookmark name required"))
1248 raise error.Abort(_(b"new bookmark name required"))
1249 elif len(names) > 1:
1249 elif len(names) > 1:
1250 raise error.Abort(_(b"only one new bookmark name allowed"))
1250 raise error.Abort(_(b"only one new bookmark name allowed"))
1251 oldname = repo._bookmarks.expandname(opts[b'rename'])
1251 oldname = repo._bookmarks.expandname(opts[b'rename'])
1252 bookmarks.rename(repo, tr, oldname, names[0], force, inactive)
1252 bookmarks.rename(repo, tr, oldname, names[0], force, inactive)
1253 elif action == b'add':
1253 elif action == b'add':
1254 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
1254 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
1255 elif action == b'inactive':
1255 elif action == b'inactive':
1256 if len(repo._bookmarks) == 0:
1256 if len(repo._bookmarks) == 0:
1257 ui.status(_(b"no bookmarks set\n"))
1257 ui.status(_(b"no bookmarks set\n"))
1258 elif not repo._activebookmark:
1258 elif not repo._activebookmark:
1259 ui.status(_(b"no active bookmark\n"))
1259 ui.status(_(b"no active bookmark\n"))
1260 else:
1260 else:
1261 bookmarks.deactivate(repo)
1261 bookmarks.deactivate(repo)
1262 elif action == b'list':
1262 elif action == b'list':
1263 names = pycompat.maplist(repo._bookmarks.expandname, names)
1263 names = pycompat.maplist(repo._bookmarks.expandname, names)
1264 with ui.formatter(b'bookmarks', opts) as fm:
1264 with ui.formatter(b'bookmarks', opts) as fm:
1265 bookmarks.printbookmarks(ui, repo, fm, names)
1265 bookmarks.printbookmarks(ui, repo, fm, names)
1266 else:
1266 else:
1267 raise error.ProgrammingError(b'invalid action: %s' % action)
1267 raise error.ProgrammingError(b'invalid action: %s' % action)
1268
1268
1269
1269
1270 @command(
1270 @command(
1271 b'branch',
1271 b'branch',
1272 [
1272 [
1273 (
1273 (
1274 b'f',
1274 b'f',
1275 b'force',
1275 b'force',
1276 None,
1276 None,
1277 _(b'set branch name even if it shadows an existing branch'),
1277 _(b'set branch name even if it shadows an existing branch'),
1278 ),
1278 ),
1279 (b'C', b'clean', None, _(b'reset branch name to parent branch name')),
1279 (b'C', b'clean', None, _(b'reset branch name to parent branch name')),
1280 (
1280 (
1281 b'r',
1281 b'r',
1282 b'rev',
1282 b'rev',
1283 [],
1283 [],
1284 _(b'change branches of the given revs (EXPERIMENTAL)'),
1284 _(b'change branches of the given revs (EXPERIMENTAL)'),
1285 ),
1285 ),
1286 ],
1286 ],
1287 _(b'[-fC] [NAME]'),
1287 _(b'[-fC] [NAME]'),
1288 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1288 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1289 )
1289 )
1290 def branch(ui, repo, label=None, **opts):
1290 def branch(ui, repo, label=None, **opts):
1291 """set or show the current branch name
1291 """set or show the current branch name
1292
1292
1293 .. note::
1293 .. note::
1294
1294
1295 Branch names are permanent and global. Use :hg:`bookmark` to create a
1295 Branch names are permanent and global. Use :hg:`bookmark` to create a
1296 light-weight bookmark instead. See :hg:`help glossary` for more
1296 light-weight bookmark instead. See :hg:`help glossary` for more
1297 information about named branches and bookmarks.
1297 information about named branches and bookmarks.
1298
1298
1299 With no argument, show the current branch name. With one argument,
1299 With no argument, show the current branch name. With one argument,
1300 set the working directory branch name (the branch will not exist
1300 set the working directory branch name (the branch will not exist
1301 in the repository until the next commit). Standard practice
1301 in the repository until the next commit). Standard practice
1302 recommends that primary development take place on the 'default'
1302 recommends that primary development take place on the 'default'
1303 branch.
1303 branch.
1304
1304
1305 Unless -f/--force is specified, branch will not let you set a
1305 Unless -f/--force is specified, branch will not let you set a
1306 branch name that already exists.
1306 branch name that already exists.
1307
1307
1308 Use -C/--clean to reset the working directory branch to that of
1308 Use -C/--clean to reset the working directory branch to that of
1309 the parent of the working directory, negating a previous branch
1309 the parent of the working directory, negating a previous branch
1310 change.
1310 change.
1311
1311
1312 Use the command :hg:`update` to switch to an existing branch. Use
1312 Use the command :hg:`update` to switch to an existing branch. Use
1313 :hg:`commit --close-branch` to mark this branch head as closed.
1313 :hg:`commit --close-branch` to mark this branch head as closed.
1314 When all heads of a branch are closed, the branch will be
1314 When all heads of a branch are closed, the branch will be
1315 considered closed.
1315 considered closed.
1316
1316
1317 Returns 0 on success.
1317 Returns 0 on success.
1318 """
1318 """
1319 opts = pycompat.byteskwargs(opts)
1319 opts = pycompat.byteskwargs(opts)
1320 revs = opts.get(b'rev')
1320 revs = opts.get(b'rev')
1321 if label:
1321 if label:
1322 label = label.strip()
1322 label = label.strip()
1323
1323
1324 if not opts.get(b'clean') and not label:
1324 if not opts.get(b'clean') and not label:
1325 if revs:
1325 if revs:
1326 raise error.Abort(_(b"no branch name specified for the revisions"))
1326 raise error.Abort(_(b"no branch name specified for the revisions"))
1327 ui.write(b"%s\n" % repo.dirstate.branch())
1327 ui.write(b"%s\n" % repo.dirstate.branch())
1328 return
1328 return
1329
1329
1330 with repo.wlock():
1330 with repo.wlock():
1331 if opts.get(b'clean'):
1331 if opts.get(b'clean'):
1332 label = repo[b'.'].branch()
1332 label = repo[b'.'].branch()
1333 repo.dirstate.setbranch(label)
1333 repo.dirstate.setbranch(label)
1334 ui.status(_(b'reset working directory to branch %s\n') % label)
1334 ui.status(_(b'reset working directory to branch %s\n') % label)
1335 elif label:
1335 elif label:
1336
1336
1337 scmutil.checknewlabel(repo, label, b'branch')
1337 scmutil.checknewlabel(repo, label, b'branch')
1338 if revs:
1338 if revs:
1339 return cmdutil.changebranch(ui, repo, revs, label, opts)
1339 return cmdutil.changebranch(ui, repo, revs, label, opts)
1340
1340
1341 if not opts.get(b'force') and label in repo.branchmap():
1341 if not opts.get(b'force') and label in repo.branchmap():
1342 if label not in [p.branch() for p in repo[None].parents()]:
1342 if label not in [p.branch() for p in repo[None].parents()]:
1343 raise error.Abort(
1343 raise error.Abort(
1344 _(b'a branch of the same name already exists'),
1344 _(b'a branch of the same name already exists'),
1345 # i18n: "it" refers to an existing branch
1345 # i18n: "it" refers to an existing branch
1346 hint=_(b"use 'hg update' to switch to it"),
1346 hint=_(b"use 'hg update' to switch to it"),
1347 )
1347 )
1348
1348
1349 repo.dirstate.setbranch(label)
1349 repo.dirstate.setbranch(label)
1350 ui.status(_(b'marked working directory as branch %s\n') % label)
1350 ui.status(_(b'marked working directory as branch %s\n') % label)
1351
1351
1352 # find any open named branches aside from default
1352 # find any open named branches aside from default
1353 for n, h, t, c in repo.branchmap().iterbranches():
1353 for n, h, t, c in repo.branchmap().iterbranches():
1354 if n != b"default" and not c:
1354 if n != b"default" and not c:
1355 return 0
1355 return 0
1356 ui.status(
1356 ui.status(
1357 _(
1357 _(
1358 b'(branches are permanent and global, '
1358 b'(branches are permanent and global, '
1359 b'did you want a bookmark?)\n'
1359 b'did you want a bookmark?)\n'
1360 )
1360 )
1361 )
1361 )
1362
1362
1363
1363
1364 @command(
1364 @command(
1365 b'branches',
1365 b'branches',
1366 [
1366 [
1367 (
1367 (
1368 b'a',
1368 b'a',
1369 b'active',
1369 b'active',
1370 False,
1370 False,
1371 _(b'show only branches that have unmerged heads (DEPRECATED)'),
1371 _(b'show only branches that have unmerged heads (DEPRECATED)'),
1372 ),
1372 ),
1373 (b'c', b'closed', False, _(b'show normal and closed branches')),
1373 (b'c', b'closed', False, _(b'show normal and closed branches')),
1374 (b'r', b'rev', [], _(b'show branch name(s) of the given rev')),
1374 (b'r', b'rev', [], _(b'show branch name(s) of the given rev')),
1375 ]
1375 ]
1376 + formatteropts,
1376 + formatteropts,
1377 _(b'[-c]'),
1377 _(b'[-c]'),
1378 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1378 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1379 intents={INTENT_READONLY},
1379 intents={INTENT_READONLY},
1380 )
1380 )
1381 def branches(ui, repo, active=False, closed=False, **opts):
1381 def branches(ui, repo, active=False, closed=False, **opts):
1382 """list repository named branches
1382 """list repository named branches
1383
1383
1384 List the repository's named branches, indicating which ones are
1384 List the repository's named branches, indicating which ones are
1385 inactive. If -c/--closed is specified, also list branches which have
1385 inactive. If -c/--closed is specified, also list branches which have
1386 been marked closed (see :hg:`commit --close-branch`).
1386 been marked closed (see :hg:`commit --close-branch`).
1387
1387
1388 Use the command :hg:`update` to switch to an existing branch.
1388 Use the command :hg:`update` to switch to an existing branch.
1389
1389
1390 .. container:: verbose
1390 .. container:: verbose
1391
1391
1392 Template:
1392 Template:
1393
1393
1394 The following keywords are supported in addition to the common template
1394 The following keywords are supported in addition to the common template
1395 keywords and functions such as ``{branch}``. See also
1395 keywords and functions such as ``{branch}``. See also
1396 :hg:`help templates`.
1396 :hg:`help templates`.
1397
1397
1398 :active: Boolean. True if the branch is active.
1398 :active: Boolean. True if the branch is active.
1399 :closed: Boolean. True if the branch is closed.
1399 :closed: Boolean. True if the branch is closed.
1400 :current: Boolean. True if it is the current branch.
1400 :current: Boolean. True if it is the current branch.
1401
1401
1402 Returns 0.
1402 Returns 0.
1403 """
1403 """
1404
1404
1405 opts = pycompat.byteskwargs(opts)
1405 opts = pycompat.byteskwargs(opts)
1406 revs = opts.get(b'rev')
1406 revs = opts.get(b'rev')
1407 selectedbranches = None
1407 selectedbranches = None
1408 if revs:
1408 if revs:
1409 revs = scmutil.revrange(repo, revs)
1409 revs = scmutil.revrange(repo, revs)
1410 getbi = repo.revbranchcache().branchinfo
1410 getbi = repo.revbranchcache().branchinfo
1411 selectedbranches = {getbi(r)[0] for r in revs}
1411 selectedbranches = {getbi(r)[0] for r in revs}
1412
1412
1413 ui.pager(b'branches')
1413 ui.pager(b'branches')
1414 fm = ui.formatter(b'branches', opts)
1414 fm = ui.formatter(b'branches', opts)
1415 hexfunc = fm.hexfunc
1415 hexfunc = fm.hexfunc
1416
1416
1417 allheads = set(repo.heads())
1417 allheads = set(repo.heads())
1418 branches = []
1418 branches = []
1419 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1419 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1420 if selectedbranches is not None and tag not in selectedbranches:
1420 if selectedbranches is not None and tag not in selectedbranches:
1421 continue
1421 continue
1422 isactive = False
1422 isactive = False
1423 if not isclosed:
1423 if not isclosed:
1424 openheads = set(repo.branchmap().iteropen(heads))
1424 openheads = set(repo.branchmap().iteropen(heads))
1425 isactive = bool(openheads & allheads)
1425 isactive = bool(openheads & allheads)
1426 branches.append((tag, repo[tip], isactive, not isclosed))
1426 branches.append((tag, repo[tip], isactive, not isclosed))
1427 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]), reverse=True)
1427 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]), reverse=True)
1428
1428
1429 for tag, ctx, isactive, isopen in branches:
1429 for tag, ctx, isactive, isopen in branches:
1430 if active and not isactive:
1430 if active and not isactive:
1431 continue
1431 continue
1432 if isactive:
1432 if isactive:
1433 label = b'branches.active'
1433 label = b'branches.active'
1434 notice = b''
1434 notice = b''
1435 elif not isopen:
1435 elif not isopen:
1436 if not closed:
1436 if not closed:
1437 continue
1437 continue
1438 label = b'branches.closed'
1438 label = b'branches.closed'
1439 notice = _(b' (closed)')
1439 notice = _(b' (closed)')
1440 else:
1440 else:
1441 label = b'branches.inactive'
1441 label = b'branches.inactive'
1442 notice = _(b' (inactive)')
1442 notice = _(b' (inactive)')
1443 current = tag == repo.dirstate.branch()
1443 current = tag == repo.dirstate.branch()
1444 if current:
1444 if current:
1445 label = b'branches.current'
1445 label = b'branches.current'
1446
1446
1447 fm.startitem()
1447 fm.startitem()
1448 fm.write(b'branch', b'%s', tag, label=label)
1448 fm.write(b'branch', b'%s', tag, label=label)
1449 rev = ctx.rev()
1449 rev = ctx.rev()
1450 padsize = max(31 - len(b"%d" % rev) - encoding.colwidth(tag), 0)
1450 padsize = max(31 - len(b"%d" % rev) - encoding.colwidth(tag), 0)
1451 fmt = b' ' * padsize + b' %d:%s'
1451 fmt = b' ' * padsize + b' %d:%s'
1452 fm.condwrite(
1452 fm.condwrite(
1453 not ui.quiet,
1453 not ui.quiet,
1454 b'rev node',
1454 b'rev node',
1455 fmt,
1455 fmt,
1456 rev,
1456 rev,
1457 hexfunc(ctx.node()),
1457 hexfunc(ctx.node()),
1458 label=b'log.changeset changeset.%s' % ctx.phasestr(),
1458 label=b'log.changeset changeset.%s' % ctx.phasestr(),
1459 )
1459 )
1460 fm.context(ctx=ctx)
1460 fm.context(ctx=ctx)
1461 fm.data(active=isactive, closed=not isopen, current=current)
1461 fm.data(active=isactive, closed=not isopen, current=current)
1462 if not ui.quiet:
1462 if not ui.quiet:
1463 fm.plain(notice)
1463 fm.plain(notice)
1464 fm.plain(b'\n')
1464 fm.plain(b'\n')
1465 fm.end()
1465 fm.end()
1466
1466
1467
1467
1468 @command(
1468 @command(
1469 b'bundle',
1469 b'bundle',
1470 [
1470 [
1471 (
1471 (
1472 b'f',
1472 b'f',
1473 b'force',
1473 b'force',
1474 None,
1474 None,
1475 _(b'run even when the destination is unrelated'),
1475 _(b'run even when the destination is unrelated'),
1476 ),
1476 ),
1477 (
1477 (
1478 b'r',
1478 b'r',
1479 b'rev',
1479 b'rev',
1480 [],
1480 [],
1481 _(b'a changeset intended to be added to the destination'),
1481 _(b'a changeset intended to be added to the destination'),
1482 _(b'REV'),
1482 _(b'REV'),
1483 ),
1483 ),
1484 (
1484 (
1485 b'b',
1485 b'b',
1486 b'branch',
1486 b'branch',
1487 [],
1487 [],
1488 _(b'a specific branch you would like to bundle'),
1488 _(b'a specific branch you would like to bundle'),
1489 _(b'BRANCH'),
1489 _(b'BRANCH'),
1490 ),
1490 ),
1491 (
1491 (
1492 b'',
1492 b'',
1493 b'base',
1493 b'base',
1494 [],
1494 [],
1495 _(b'a base changeset assumed to be available at the destination'),
1495 _(b'a base changeset assumed to be available at the destination'),
1496 _(b'REV'),
1496 _(b'REV'),
1497 ),
1497 ),
1498 (b'a', b'all', None, _(b'bundle all changesets in the repository')),
1498 (b'a', b'all', None, _(b'bundle all changesets in the repository')),
1499 (
1499 (
1500 b't',
1500 b't',
1501 b'type',
1501 b'type',
1502 b'bzip2',
1502 b'bzip2',
1503 _(b'bundle compression type to use'),
1503 _(b'bundle compression type to use'),
1504 _(b'TYPE'),
1504 _(b'TYPE'),
1505 ),
1505 ),
1506 ]
1506 ]
1507 + remoteopts,
1507 + remoteopts,
1508 _(b'[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'),
1508 _(b'[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'),
1509 helpcategory=command.CATEGORY_IMPORT_EXPORT,
1509 helpcategory=command.CATEGORY_IMPORT_EXPORT,
1510 )
1510 )
1511 def bundle(ui, repo, fname, dest=None, **opts):
1511 def bundle(ui, repo, fname, dest=None, **opts):
1512 """create a bundle file
1512 """create a bundle file
1513
1513
1514 Generate a bundle file containing data to be transferred to another
1514 Generate a bundle file containing data to be transferred to another
1515 repository.
1515 repository.
1516
1516
1517 To create a bundle containing all changesets, use -a/--all
1517 To create a bundle containing all changesets, use -a/--all
1518 (or --base null). Otherwise, hg assumes the destination will have
1518 (or --base null). Otherwise, hg assumes the destination will have
1519 all the nodes you specify with --base parameters. Otherwise, hg
1519 all the nodes you specify with --base parameters. Otherwise, hg
1520 will assume the repository has all the nodes in destination, or
1520 will assume the repository has all the nodes in destination, or
1521 default-push/default if no destination is specified, where destination
1521 default-push/default if no destination is specified, where destination
1522 is the repository you provide through DEST option.
1522 is the repository you provide through DEST option.
1523
1523
1524 You can change bundle format with the -t/--type option. See
1524 You can change bundle format with the -t/--type option. See
1525 :hg:`help bundlespec` for documentation on this format. By default,
1525 :hg:`help bundlespec` for documentation on this format. By default,
1526 the most appropriate format is used and compression defaults to
1526 the most appropriate format is used and compression defaults to
1527 bzip2.
1527 bzip2.
1528
1528
1529 The bundle file can then be transferred using conventional means
1529 The bundle file can then be transferred using conventional means
1530 and applied to another repository with the unbundle or pull
1530 and applied to another repository with the unbundle or pull
1531 command. This is useful when direct push and pull are not
1531 command. This is useful when direct push and pull are not
1532 available or when exporting an entire repository is undesirable.
1532 available or when exporting an entire repository is undesirable.
1533
1533
1534 Applying bundles preserves all changeset contents including
1534 Applying bundles preserves all changeset contents including
1535 permissions, copy/rename information, and revision history.
1535 permissions, copy/rename information, and revision history.
1536
1536
1537 Returns 0 on success, 1 if no changes found.
1537 Returns 0 on success, 1 if no changes found.
1538 """
1538 """
1539 opts = pycompat.byteskwargs(opts)
1539 opts = pycompat.byteskwargs(opts)
1540 revs = None
1540 revs = None
1541 if b'rev' in opts:
1541 if b'rev' in opts:
1542 revstrings = opts[b'rev']
1542 revstrings = opts[b'rev']
1543 revs = scmutil.revrange(repo, revstrings)
1543 revs = scmutil.revrange(repo, revstrings)
1544 if revstrings and not revs:
1544 if revstrings and not revs:
1545 raise error.Abort(_(b'no commits to bundle'))
1545 raise error.Abort(_(b'no commits to bundle'))
1546
1546
1547 bundletype = opts.get(b'type', b'bzip2').lower()
1547 bundletype = opts.get(b'type', b'bzip2').lower()
1548 try:
1548 try:
1549 bundlespec = bundlecaches.parsebundlespec(
1549 bundlespec = bundlecaches.parsebundlespec(
1550 repo, bundletype, strict=False
1550 repo, bundletype, strict=False
1551 )
1551 )
1552 except error.UnsupportedBundleSpecification as e:
1552 except error.UnsupportedBundleSpecification as e:
1553 raise error.Abort(
1553 raise error.Abort(
1554 pycompat.bytestr(e),
1554 pycompat.bytestr(e),
1555 hint=_(b"see 'hg help bundlespec' for supported values for --type"),
1555 hint=_(b"see 'hg help bundlespec' for supported values for --type"),
1556 )
1556 )
1557 cgversion = bundlespec.contentopts[b"cg.version"]
1557 cgversion = bundlespec.contentopts[b"cg.version"]
1558
1558
1559 # Packed bundles are a pseudo bundle format for now.
1559 # Packed bundles are a pseudo bundle format for now.
1560 if cgversion == b's1':
1560 if cgversion == b's1':
1561 raise error.Abort(
1561 raise error.Abort(
1562 _(b'packed bundles cannot be produced by "hg bundle"'),
1562 _(b'packed bundles cannot be produced by "hg bundle"'),
1563 hint=_(b"use 'hg debugcreatestreamclonebundle'"),
1563 hint=_(b"use 'hg debugcreatestreamclonebundle'"),
1564 )
1564 )
1565
1565
1566 if opts.get(b'all'):
1566 if opts.get(b'all'):
1567 if dest:
1567 if dest:
1568 raise error.Abort(
1568 raise error.Abort(
1569 _(b"--all is incompatible with specifying a destination")
1569 _(b"--all is incompatible with specifying a destination")
1570 )
1570 )
1571 if opts.get(b'base'):
1571 if opts.get(b'base'):
1572 ui.warn(_(b"ignoring --base because --all was specified\n"))
1572 ui.warn(_(b"ignoring --base because --all was specified\n"))
1573 base = [nullrev]
1573 base = [nullrev]
1574 else:
1574 else:
1575 base = scmutil.revrange(repo, opts.get(b'base'))
1575 base = scmutil.revrange(repo, opts.get(b'base'))
1576 if cgversion not in changegroup.supportedoutgoingversions(repo):
1576 if cgversion not in changegroup.supportedoutgoingversions(repo):
1577 raise error.Abort(
1577 raise error.Abort(
1578 _(b"repository does not support bundle version %s") % cgversion
1578 _(b"repository does not support bundle version %s") % cgversion
1579 )
1579 )
1580
1580
1581 if base:
1581 if base:
1582 if dest:
1582 if dest:
1583 raise error.Abort(
1583 raise error.Abort(
1584 _(b"--base is incompatible with specifying a destination")
1584 _(b"--base is incompatible with specifying a destination")
1585 )
1585 )
1586 common = [repo[rev].node() for rev in base]
1586 common = [repo[rev].node() for rev in base]
1587 heads = [repo[r].node() for r in revs] if revs else None
1587 heads = [repo[r].node() for r in revs] if revs else None
1588 outgoing = discovery.outgoing(repo, common, heads)
1588 outgoing = discovery.outgoing(repo, common, heads)
1589 else:
1589 else:
1590 dest = ui.expandpath(dest or b'default-push', dest or b'default')
1590 dest = ui.expandpath(dest or b'default-push', dest or b'default')
1591 dest, branches = hg.parseurl(dest, opts.get(b'branch'))
1591 dest, branches = hg.parseurl(dest, opts.get(b'branch'))
1592 other = hg.peer(repo, opts, dest)
1592 other = hg.peer(repo, opts, dest)
1593 revs = [repo[r].hex() for r in revs]
1593 revs = [repo[r].hex() for r in revs]
1594 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1594 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1595 heads = revs and pycompat.maplist(repo.lookup, revs) or revs
1595 heads = revs and pycompat.maplist(repo.lookup, revs) or revs
1596 outgoing = discovery.findcommonoutgoing(
1596 outgoing = discovery.findcommonoutgoing(
1597 repo,
1597 repo,
1598 other,
1598 other,
1599 onlyheads=heads,
1599 onlyheads=heads,
1600 force=opts.get(b'force'),
1600 force=opts.get(b'force'),
1601 portable=True,
1601 portable=True,
1602 )
1602 )
1603
1603
1604 if not outgoing.missing:
1604 if not outgoing.missing:
1605 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1605 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1606 return 1
1606 return 1
1607
1607
1608 if cgversion == b'01': # bundle1
1608 if cgversion == b'01': # bundle1
1609 bversion = b'HG10' + bundlespec.wirecompression
1609 bversion = b'HG10' + bundlespec.wirecompression
1610 bcompression = None
1610 bcompression = None
1611 elif cgversion in (b'02', b'03'):
1611 elif cgversion in (b'02', b'03'):
1612 bversion = b'HG20'
1612 bversion = b'HG20'
1613 bcompression = bundlespec.wirecompression
1613 bcompression = bundlespec.wirecompression
1614 else:
1614 else:
1615 raise error.ProgrammingError(
1615 raise error.ProgrammingError(
1616 b'bundle: unexpected changegroup version %s' % cgversion
1616 b'bundle: unexpected changegroup version %s' % cgversion
1617 )
1617 )
1618
1618
1619 # TODO compression options should be derived from bundlespec parsing.
1619 # TODO compression options should be derived from bundlespec parsing.
1620 # This is a temporary hack to allow adjusting bundle compression
1620 # This is a temporary hack to allow adjusting bundle compression
1621 # level without a) formalizing the bundlespec changes to declare it
1621 # level without a) formalizing the bundlespec changes to declare it
1622 # b) introducing a command flag.
1622 # b) introducing a command flag.
1623 compopts = {}
1623 compopts = {}
1624 complevel = ui.configint(
1624 complevel = ui.configint(
1625 b'experimental', b'bundlecomplevel.' + bundlespec.compression
1625 b'experimental', b'bundlecomplevel.' + bundlespec.compression
1626 )
1626 )
1627 if complevel is None:
1627 if complevel is None:
1628 complevel = ui.configint(b'experimental', b'bundlecomplevel')
1628 complevel = ui.configint(b'experimental', b'bundlecomplevel')
1629 if complevel is not None:
1629 if complevel is not None:
1630 compopts[b'level'] = complevel
1630 compopts[b'level'] = complevel
1631
1631
1632 # Allow overriding the bundling of obsmarker in phases through
1632 # Allow overriding the bundling of obsmarker in phases through
1633 # configuration while we don't have a bundle version that include them
1633 # configuration while we don't have a bundle version that include them
1634 if repo.ui.configbool(b'experimental', b'evolution.bundle-obsmarker'):
1634 if repo.ui.configbool(b'experimental', b'evolution.bundle-obsmarker'):
1635 bundlespec.contentopts[b'obsolescence'] = True
1635 bundlespec.contentopts[b'obsolescence'] = True
1636 if repo.ui.configbool(b'experimental', b'bundle-phases'):
1636 if repo.ui.configbool(b'experimental', b'bundle-phases'):
1637 bundlespec.contentopts[b'phases'] = True
1637 bundlespec.contentopts[b'phases'] = True
1638
1638
1639 bundle2.writenewbundle(
1639 bundle2.writenewbundle(
1640 ui,
1640 ui,
1641 repo,
1641 repo,
1642 b'bundle',
1642 b'bundle',
1643 fname,
1643 fname,
1644 bversion,
1644 bversion,
1645 outgoing,
1645 outgoing,
1646 bundlespec.contentopts,
1646 bundlespec.contentopts,
1647 compression=bcompression,
1647 compression=bcompression,
1648 compopts=compopts,
1648 compopts=compopts,
1649 )
1649 )
1650
1650
1651
1651
1652 @command(
1652 @command(
1653 b'cat',
1653 b'cat',
1654 [
1654 [
1655 (
1655 (
1656 b'o',
1656 b'o',
1657 b'output',
1657 b'output',
1658 b'',
1658 b'',
1659 _(b'print output to file with formatted name'),
1659 _(b'print output to file with formatted name'),
1660 _(b'FORMAT'),
1660 _(b'FORMAT'),
1661 ),
1661 ),
1662 (b'r', b'rev', b'', _(b'print the given revision'), _(b'REV')),
1662 (b'r', b'rev', b'', _(b'print the given revision'), _(b'REV')),
1663 (b'', b'decode', None, _(b'apply any matching decode filter')),
1663 (b'', b'decode', None, _(b'apply any matching decode filter')),
1664 ]
1664 ]
1665 + walkopts
1665 + walkopts
1666 + formatteropts,
1666 + formatteropts,
1667 _(b'[OPTION]... FILE...'),
1667 _(b'[OPTION]... FILE...'),
1668 helpcategory=command.CATEGORY_FILE_CONTENTS,
1668 helpcategory=command.CATEGORY_FILE_CONTENTS,
1669 inferrepo=True,
1669 inferrepo=True,
1670 intents={INTENT_READONLY},
1670 intents={INTENT_READONLY},
1671 )
1671 )
1672 def cat(ui, repo, file1, *pats, **opts):
1672 def cat(ui, repo, file1, *pats, **opts):
1673 """output the current or given revision of files
1673 """output the current or given revision of files
1674
1674
1675 Print the specified files as they were at the given revision. If
1675 Print the specified files as they were at the given revision. If
1676 no revision is given, the parent of the working directory is used.
1676 no revision is given, the parent of the working directory is used.
1677
1677
1678 Output may be to a file, in which case the name of the file is
1678 Output may be to a file, in which case the name of the file is
1679 given using a template string. See :hg:`help templates`. In addition
1679 given using a template string. See :hg:`help templates`. In addition
1680 to the common template keywords, the following formatting rules are
1680 to the common template keywords, the following formatting rules are
1681 supported:
1681 supported:
1682
1682
1683 :``%%``: literal "%" character
1683 :``%%``: literal "%" character
1684 :``%s``: basename of file being printed
1684 :``%s``: basename of file being printed
1685 :``%d``: dirname of file being printed, or '.' if in repository root
1685 :``%d``: dirname of file being printed, or '.' if in repository root
1686 :``%p``: root-relative path name of file being printed
1686 :``%p``: root-relative path name of file being printed
1687 :``%H``: changeset hash (40 hexadecimal digits)
1687 :``%H``: changeset hash (40 hexadecimal digits)
1688 :``%R``: changeset revision number
1688 :``%R``: changeset revision number
1689 :``%h``: short-form changeset hash (12 hexadecimal digits)
1689 :``%h``: short-form changeset hash (12 hexadecimal digits)
1690 :``%r``: zero-padded changeset revision number
1690 :``%r``: zero-padded changeset revision number
1691 :``%b``: basename of the exporting repository
1691 :``%b``: basename of the exporting repository
1692 :``\\``: literal "\\" character
1692 :``\\``: literal "\\" character
1693
1693
1694 .. container:: verbose
1694 .. container:: verbose
1695
1695
1696 Template:
1696 Template:
1697
1697
1698 The following keywords are supported in addition to the common template
1698 The following keywords are supported in addition to the common template
1699 keywords and functions. See also :hg:`help templates`.
1699 keywords and functions. See also :hg:`help templates`.
1700
1700
1701 :data: String. File content.
1701 :data: String. File content.
1702 :path: String. Repository-absolute path of the file.
1702 :path: String. Repository-absolute path of the file.
1703
1703
1704 Returns 0 on success.
1704 Returns 0 on success.
1705 """
1705 """
1706 opts = pycompat.byteskwargs(opts)
1706 opts = pycompat.byteskwargs(opts)
1707 rev = opts.get(b'rev')
1707 rev = opts.get(b'rev')
1708 if rev:
1708 if rev:
1709 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
1709 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
1710 ctx = scmutil.revsingle(repo, rev)
1710 ctx = scmutil.revsingle(repo, rev)
1711 m = scmutil.match(ctx, (file1,) + pats, opts)
1711 m = scmutil.match(ctx, (file1,) + pats, opts)
1712 fntemplate = opts.pop(b'output', b'')
1712 fntemplate = opts.pop(b'output', b'')
1713 if cmdutil.isstdiofilename(fntemplate):
1713 if cmdutil.isstdiofilename(fntemplate):
1714 fntemplate = b''
1714 fntemplate = b''
1715
1715
1716 if fntemplate:
1716 if fntemplate:
1717 fm = formatter.nullformatter(ui, b'cat', opts)
1717 fm = formatter.nullformatter(ui, b'cat', opts)
1718 else:
1718 else:
1719 ui.pager(b'cat')
1719 ui.pager(b'cat')
1720 fm = ui.formatter(b'cat', opts)
1720 fm = ui.formatter(b'cat', opts)
1721 with fm:
1721 with fm:
1722 return cmdutil.cat(
1722 return cmdutil.cat(
1723 ui, repo, ctx, m, fm, fntemplate, b'', **pycompat.strkwargs(opts)
1723 ui, repo, ctx, m, fm, fntemplate, b'', **pycompat.strkwargs(opts)
1724 )
1724 )
1725
1725
1726
1726
1727 @command(
1727 @command(
1728 b'clone',
1728 b'clone',
1729 [
1729 [
1730 (
1730 (
1731 b'U',
1731 b'U',
1732 b'noupdate',
1732 b'noupdate',
1733 None,
1733 None,
1734 _(
1734 _(
1735 b'the clone will include an empty working '
1735 b'the clone will include an empty working '
1736 b'directory (only a repository)'
1736 b'directory (only a repository)'
1737 ),
1737 ),
1738 ),
1738 ),
1739 (
1739 (
1740 b'u',
1740 b'u',
1741 b'updaterev',
1741 b'updaterev',
1742 b'',
1742 b'',
1743 _(b'revision, tag, or branch to check out'),
1743 _(b'revision, tag, or branch to check out'),
1744 _(b'REV'),
1744 _(b'REV'),
1745 ),
1745 ),
1746 (
1746 (
1747 b'r',
1747 b'r',
1748 b'rev',
1748 b'rev',
1749 [],
1749 [],
1750 _(
1750 _(
1751 b'do not clone everything, but include this changeset'
1751 b'do not clone everything, but include this changeset'
1752 b' and its ancestors'
1752 b' and its ancestors'
1753 ),
1753 ),
1754 _(b'REV'),
1754 _(b'REV'),
1755 ),
1755 ),
1756 (
1756 (
1757 b'b',
1757 b'b',
1758 b'branch',
1758 b'branch',
1759 [],
1759 [],
1760 _(
1760 _(
1761 b'do not clone everything, but include this branch\'s'
1761 b'do not clone everything, but include this branch\'s'
1762 b' changesets and their ancestors'
1762 b' changesets and their ancestors'
1763 ),
1763 ),
1764 _(b'BRANCH'),
1764 _(b'BRANCH'),
1765 ),
1765 ),
1766 (b'', b'pull', None, _(b'use pull protocol to copy metadata')),
1766 (b'', b'pull', None, _(b'use pull protocol to copy metadata')),
1767 (b'', b'uncompressed', None, _(b'an alias to --stream (DEPRECATED)')),
1767 (b'', b'uncompressed', None, _(b'an alias to --stream (DEPRECATED)')),
1768 (b'', b'stream', None, _(b'clone with minimal data processing')),
1768 (b'', b'stream', None, _(b'clone with minimal data processing')),
1769 ]
1769 ]
1770 + remoteopts,
1770 + remoteopts,
1771 _(b'[OPTION]... SOURCE [DEST]'),
1771 _(b'[OPTION]... SOURCE [DEST]'),
1772 helpcategory=command.CATEGORY_REPO_CREATION,
1772 helpcategory=command.CATEGORY_REPO_CREATION,
1773 helpbasic=True,
1773 helpbasic=True,
1774 norepo=True,
1774 norepo=True,
1775 )
1775 )
1776 def clone(ui, source, dest=None, **opts):
1776 def clone(ui, source, dest=None, **opts):
1777 """make a copy of an existing repository
1777 """make a copy of an existing repository
1778
1778
1779 Create a copy of an existing repository in a new directory.
1779 Create a copy of an existing repository in a new directory.
1780
1780
1781 If no destination directory name is specified, it defaults to the
1781 If no destination directory name is specified, it defaults to the
1782 basename of the source.
1782 basename of the source.
1783
1783
1784 The location of the source is added to the new repository's
1784 The location of the source is added to the new repository's
1785 ``.hg/hgrc`` file, as the default to be used for future pulls.
1785 ``.hg/hgrc`` file, as the default to be used for future pulls.
1786
1786
1787 Only local paths and ``ssh://`` URLs are supported as
1787 Only local paths and ``ssh://`` URLs are supported as
1788 destinations. For ``ssh://`` destinations, no working directory or
1788 destinations. For ``ssh://`` destinations, no working directory or
1789 ``.hg/hgrc`` will be created on the remote side.
1789 ``.hg/hgrc`` will be created on the remote side.
1790
1790
1791 If the source repository has a bookmark called '@' set, that
1791 If the source repository has a bookmark called '@' set, that
1792 revision will be checked out in the new repository by default.
1792 revision will be checked out in the new repository by default.
1793
1793
1794 To check out a particular version, use -u/--update, or
1794 To check out a particular version, use -u/--update, or
1795 -U/--noupdate to create a clone with no working directory.
1795 -U/--noupdate to create a clone with no working directory.
1796
1796
1797 To pull only a subset of changesets, specify one or more revisions
1797 To pull only a subset of changesets, specify one or more revisions
1798 identifiers with -r/--rev or branches with -b/--branch. The
1798 identifiers with -r/--rev or branches with -b/--branch. The
1799 resulting clone will contain only the specified changesets and
1799 resulting clone will contain only the specified changesets and
1800 their ancestors. These options (or 'clone src#rev dest') imply
1800 their ancestors. These options (or 'clone src#rev dest') imply
1801 --pull, even for local source repositories.
1801 --pull, even for local source repositories.
1802
1802
1803 In normal clone mode, the remote normalizes repository data into a common
1803 In normal clone mode, the remote normalizes repository data into a common
1804 exchange format and the receiving end translates this data into its local
1804 exchange format and the receiving end translates this data into its local
1805 storage format. --stream activates a different clone mode that essentially
1805 storage format. --stream activates a different clone mode that essentially
1806 copies repository files from the remote with minimal data processing. This
1806 copies repository files from the remote with minimal data processing. This
1807 significantly reduces the CPU cost of a clone both remotely and locally.
1807 significantly reduces the CPU cost of a clone both remotely and locally.
1808 However, it often increases the transferred data size by 30-40%. This can
1808 However, it often increases the transferred data size by 30-40%. This can
1809 result in substantially faster clones where I/O throughput is plentiful,
1809 result in substantially faster clones where I/O throughput is plentiful,
1810 especially for larger repositories. A side-effect of --stream clones is
1810 especially for larger repositories. A side-effect of --stream clones is
1811 that storage settings and requirements on the remote are applied locally:
1811 that storage settings and requirements on the remote are applied locally:
1812 a modern client may inherit legacy or inefficient storage used by the
1812 a modern client may inherit legacy or inefficient storage used by the
1813 remote or a legacy Mercurial client may not be able to clone from a
1813 remote or a legacy Mercurial client may not be able to clone from a
1814 modern Mercurial remote.
1814 modern Mercurial remote.
1815
1815
1816 .. note::
1816 .. note::
1817
1817
1818 Specifying a tag will include the tagged changeset but not the
1818 Specifying a tag will include the tagged changeset but not the
1819 changeset containing the tag.
1819 changeset containing the tag.
1820
1820
1821 .. container:: verbose
1821 .. container:: verbose
1822
1822
1823 For efficiency, hardlinks are used for cloning whenever the
1823 For efficiency, hardlinks are used for cloning whenever the
1824 source and destination are on the same filesystem (note this
1824 source and destination are on the same filesystem (note this
1825 applies only to the repository data, not to the working
1825 applies only to the repository data, not to the working
1826 directory). Some filesystems, such as AFS, implement hardlinking
1826 directory). Some filesystems, such as AFS, implement hardlinking
1827 incorrectly, but do not report errors. In these cases, use the
1827 incorrectly, but do not report errors. In these cases, use the
1828 --pull option to avoid hardlinking.
1828 --pull option to avoid hardlinking.
1829
1829
1830 Mercurial will update the working directory to the first applicable
1830 Mercurial will update the working directory to the first applicable
1831 revision from this list:
1831 revision from this list:
1832
1832
1833 a) null if -U or the source repository has no changesets
1833 a) null if -U or the source repository has no changesets
1834 b) if -u . and the source repository is local, the first parent of
1834 b) if -u . and the source repository is local, the first parent of
1835 the source repository's working directory
1835 the source repository's working directory
1836 c) the changeset specified with -u (if a branch name, this means the
1836 c) the changeset specified with -u (if a branch name, this means the
1837 latest head of that branch)
1837 latest head of that branch)
1838 d) the changeset specified with -r
1838 d) the changeset specified with -r
1839 e) the tipmost head specified with -b
1839 e) the tipmost head specified with -b
1840 f) the tipmost head specified with the url#branch source syntax
1840 f) the tipmost head specified with the url#branch source syntax
1841 g) the revision marked with the '@' bookmark, if present
1841 g) the revision marked with the '@' bookmark, if present
1842 h) the tipmost head of the default branch
1842 h) the tipmost head of the default branch
1843 i) tip
1843 i) tip
1844
1844
1845 When cloning from servers that support it, Mercurial may fetch
1845 When cloning from servers that support it, Mercurial may fetch
1846 pre-generated data from a server-advertised URL or inline from the
1846 pre-generated data from a server-advertised URL or inline from the
1847 same stream. When this is done, hooks operating on incoming changesets
1847 same stream. When this is done, hooks operating on incoming changesets
1848 and changegroups may fire more than once, once for each pre-generated
1848 and changegroups may fire more than once, once for each pre-generated
1849 bundle and as well as for any additional remaining data. In addition,
1849 bundle and as well as for any additional remaining data. In addition,
1850 if an error occurs, the repository may be rolled back to a partial
1850 if an error occurs, the repository may be rolled back to a partial
1851 clone. This behavior may change in future releases.
1851 clone. This behavior may change in future releases.
1852 See :hg:`help -e clonebundles` for more.
1852 See :hg:`help -e clonebundles` for more.
1853
1853
1854 Examples:
1854 Examples:
1855
1855
1856 - clone a remote repository to a new directory named hg/::
1856 - clone a remote repository to a new directory named hg/::
1857
1857
1858 hg clone https://www.mercurial-scm.org/repo/hg/
1858 hg clone https://www.mercurial-scm.org/repo/hg/
1859
1859
1860 - create a lightweight local clone::
1860 - create a lightweight local clone::
1861
1861
1862 hg clone project/ project-feature/
1862 hg clone project/ project-feature/
1863
1863
1864 - clone from an absolute path on an ssh server (note double-slash)::
1864 - clone from an absolute path on an ssh server (note double-slash)::
1865
1865
1866 hg clone ssh://user@server//home/projects/alpha/
1866 hg clone ssh://user@server//home/projects/alpha/
1867
1867
1868 - do a streaming clone while checking out a specified version::
1868 - do a streaming clone while checking out a specified version::
1869
1869
1870 hg clone --stream http://server/repo -u 1.5
1870 hg clone --stream http://server/repo -u 1.5
1871
1871
1872 - create a repository without changesets after a particular revision::
1872 - create a repository without changesets after a particular revision::
1873
1873
1874 hg clone -r 04e544 experimental/ good/
1874 hg clone -r 04e544 experimental/ good/
1875
1875
1876 - clone (and track) a particular named branch::
1876 - clone (and track) a particular named branch::
1877
1877
1878 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1878 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1879
1879
1880 See :hg:`help urls` for details on specifying URLs.
1880 See :hg:`help urls` for details on specifying URLs.
1881
1881
1882 Returns 0 on success.
1882 Returns 0 on success.
1883 """
1883 """
1884 opts = pycompat.byteskwargs(opts)
1884 opts = pycompat.byteskwargs(opts)
1885 cmdutil.check_at_most_one_arg(opts, b'noupdate', b'updaterev')
1885 cmdutil.check_at_most_one_arg(opts, b'noupdate', b'updaterev')
1886
1886
1887 # --include/--exclude can come from narrow or sparse.
1887 # --include/--exclude can come from narrow or sparse.
1888 includepats, excludepats = None, None
1888 includepats, excludepats = None, None
1889
1889
1890 # hg.clone() differentiates between None and an empty set. So make sure
1890 # hg.clone() differentiates between None and an empty set. So make sure
1891 # patterns are sets if narrow is requested without patterns.
1891 # patterns are sets if narrow is requested without patterns.
1892 if opts.get(b'narrow'):
1892 if opts.get(b'narrow'):
1893 includepats = set()
1893 includepats = set()
1894 excludepats = set()
1894 excludepats = set()
1895
1895
1896 if opts.get(b'include'):
1896 if opts.get(b'include'):
1897 includepats = narrowspec.parsepatterns(opts.get(b'include'))
1897 includepats = narrowspec.parsepatterns(opts.get(b'include'))
1898 if opts.get(b'exclude'):
1898 if opts.get(b'exclude'):
1899 excludepats = narrowspec.parsepatterns(opts.get(b'exclude'))
1899 excludepats = narrowspec.parsepatterns(opts.get(b'exclude'))
1900
1900
1901 r = hg.clone(
1901 r = hg.clone(
1902 ui,
1902 ui,
1903 opts,
1903 opts,
1904 source,
1904 source,
1905 dest,
1905 dest,
1906 pull=opts.get(b'pull'),
1906 pull=opts.get(b'pull'),
1907 stream=opts.get(b'stream') or opts.get(b'uncompressed'),
1907 stream=opts.get(b'stream') or opts.get(b'uncompressed'),
1908 revs=opts.get(b'rev'),
1908 revs=opts.get(b'rev'),
1909 update=opts.get(b'updaterev') or not opts.get(b'noupdate'),
1909 update=opts.get(b'updaterev') or not opts.get(b'noupdate'),
1910 branch=opts.get(b'branch'),
1910 branch=opts.get(b'branch'),
1911 shareopts=opts.get(b'shareopts'),
1911 shareopts=opts.get(b'shareopts'),
1912 storeincludepats=includepats,
1912 storeincludepats=includepats,
1913 storeexcludepats=excludepats,
1913 storeexcludepats=excludepats,
1914 depth=opts.get(b'depth') or None,
1914 depth=opts.get(b'depth') or None,
1915 )
1915 )
1916
1916
1917 return r is None
1917 return r is None
1918
1918
1919
1919
1920 @command(
1920 @command(
1921 b'commit|ci',
1921 b'commit|ci',
1922 [
1922 [
1923 (
1923 (
1924 b'A',
1924 b'A',
1925 b'addremove',
1925 b'addremove',
1926 None,
1926 None,
1927 _(b'mark new/missing files as added/removed before committing'),
1927 _(b'mark new/missing files as added/removed before committing'),
1928 ),
1928 ),
1929 (b'', b'close-branch', None, _(b'mark a branch head as closed')),
1929 (b'', b'close-branch', None, _(b'mark a branch head as closed')),
1930 (b'', b'amend', None, _(b'amend the parent of the working directory')),
1930 (b'', b'amend', None, _(b'amend the parent of the working directory')),
1931 (b's', b'secret', None, _(b'use the secret phase for committing')),
1931 (b's', b'secret', None, _(b'use the secret phase for committing')),
1932 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
1932 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
1933 (
1933 (
1934 b'',
1934 b'',
1935 b'force-close-branch',
1935 b'force-close-branch',
1936 None,
1936 None,
1937 _(b'forcibly close branch from a non-head changeset (ADVANCED)'),
1937 _(b'forcibly close branch from a non-head changeset (ADVANCED)'),
1938 ),
1938 ),
1939 (b'i', b'interactive', None, _(b'use interactive mode')),
1939 (b'i', b'interactive', None, _(b'use interactive mode')),
1940 ]
1940 ]
1941 + walkopts
1941 + walkopts
1942 + commitopts
1942 + commitopts
1943 + commitopts2
1943 + commitopts2
1944 + subrepoopts,
1944 + subrepoopts,
1945 _(b'[OPTION]... [FILE]...'),
1945 _(b'[OPTION]... [FILE]...'),
1946 helpcategory=command.CATEGORY_COMMITTING,
1946 helpcategory=command.CATEGORY_COMMITTING,
1947 helpbasic=True,
1947 helpbasic=True,
1948 inferrepo=True,
1948 inferrepo=True,
1949 )
1949 )
1950 def commit(ui, repo, *pats, **opts):
1950 def commit(ui, repo, *pats, **opts):
1951 """commit the specified files or all outstanding changes
1951 """commit the specified files or all outstanding changes
1952
1952
1953 Commit changes to the given files into the repository. Unlike a
1953 Commit changes to the given files into the repository. Unlike a
1954 centralized SCM, this operation is a local operation. See
1954 centralized SCM, this operation is a local operation. See
1955 :hg:`push` for a way to actively distribute your changes.
1955 :hg:`push` for a way to actively distribute your changes.
1956
1956
1957 If a list of files is omitted, all changes reported by :hg:`status`
1957 If a list of files is omitted, all changes reported by :hg:`status`
1958 will be committed.
1958 will be committed.
1959
1959
1960 If you are committing the result of a merge, do not provide any
1960 If you are committing the result of a merge, do not provide any
1961 filenames or -I/-X filters.
1961 filenames or -I/-X filters.
1962
1962
1963 If no commit message is specified, Mercurial starts your
1963 If no commit message is specified, Mercurial starts your
1964 configured editor where you can enter a message. In case your
1964 configured editor where you can enter a message. In case your
1965 commit fails, you will find a backup of your message in
1965 commit fails, you will find a backup of your message in
1966 ``.hg/last-message.txt``.
1966 ``.hg/last-message.txt``.
1967
1967
1968 The --close-branch flag can be used to mark the current branch
1968 The --close-branch flag can be used to mark the current branch
1969 head closed. When all heads of a branch are closed, the branch
1969 head closed. When all heads of a branch are closed, the branch
1970 will be considered closed and no longer listed.
1970 will be considered closed and no longer listed.
1971
1971
1972 The --amend flag can be used to amend the parent of the
1972 The --amend flag can be used to amend the parent of the
1973 working directory with a new commit that contains the changes
1973 working directory with a new commit that contains the changes
1974 in the parent in addition to those currently reported by :hg:`status`,
1974 in the parent in addition to those currently reported by :hg:`status`,
1975 if there are any. The old commit is stored in a backup bundle in
1975 if there are any. The old commit is stored in a backup bundle in
1976 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1976 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1977 on how to restore it).
1977 on how to restore it).
1978
1978
1979 Message, user and date are taken from the amended commit unless
1979 Message, user and date are taken from the amended commit unless
1980 specified. When a message isn't specified on the command line,
1980 specified. When a message isn't specified on the command line,
1981 the editor will open with the message of the amended commit.
1981 the editor will open with the message of the amended commit.
1982
1982
1983 It is not possible to amend public changesets (see :hg:`help phases`)
1983 It is not possible to amend public changesets (see :hg:`help phases`)
1984 or changesets that have children.
1984 or changesets that have children.
1985
1985
1986 See :hg:`help dates` for a list of formats valid for -d/--date.
1986 See :hg:`help dates` for a list of formats valid for -d/--date.
1987
1987
1988 Returns 0 on success, 1 if nothing changed.
1988 Returns 0 on success, 1 if nothing changed.
1989
1989
1990 .. container:: verbose
1990 .. container:: verbose
1991
1991
1992 Examples:
1992 Examples:
1993
1993
1994 - commit all files ending in .py::
1994 - commit all files ending in .py::
1995
1995
1996 hg commit --include "set:**.py"
1996 hg commit --include "set:**.py"
1997
1997
1998 - commit all non-binary files::
1998 - commit all non-binary files::
1999
1999
2000 hg commit --exclude "set:binary()"
2000 hg commit --exclude "set:binary()"
2001
2001
2002 - amend the current commit and set the date to now::
2002 - amend the current commit and set the date to now::
2003
2003
2004 hg commit --amend --date now
2004 hg commit --amend --date now
2005 """
2005 """
2006 with repo.wlock(), repo.lock():
2006 with repo.wlock(), repo.lock():
2007 return _docommit(ui, repo, *pats, **opts)
2007 return _docommit(ui, repo, *pats, **opts)
2008
2008
2009
2009
2010 def _docommit(ui, repo, *pats, **opts):
2010 def _docommit(ui, repo, *pats, **opts):
2011 if opts.get('interactive'):
2011 if opts.get('interactive'):
2012 opts.pop('interactive')
2012 opts.pop('interactive')
2013 ret = cmdutil.dorecord(
2013 ret = cmdutil.dorecord(
2014 ui, repo, commit, None, False, cmdutil.recordfilter, *pats, **opts
2014 ui, repo, commit, None, False, cmdutil.recordfilter, *pats, **opts
2015 )
2015 )
2016 # ret can be 0 (no changes to record) or the value returned by
2016 # ret can be 0 (no changes to record) or the value returned by
2017 # commit(), 1 if nothing changed or None on success.
2017 # commit(), 1 if nothing changed or None on success.
2018 return 1 if ret == 0 else ret
2018 return 1 if ret == 0 else ret
2019
2019
2020 opts = pycompat.byteskwargs(opts)
2020 opts = pycompat.byteskwargs(opts)
2021 if opts.get(b'subrepos'):
2021 if opts.get(b'subrepos'):
2022 cmdutil.check_incompatible_arguments(opts, b'subrepos', [b'amend'])
2022 cmdutil.check_incompatible_arguments(opts, b'subrepos', [b'amend'])
2023 # Let --subrepos on the command line override config setting.
2023 # Let --subrepos on the command line override config setting.
2024 ui.setconfig(b'ui', b'commitsubrepos', True, b'commit')
2024 ui.setconfig(b'ui', b'commitsubrepos', True, b'commit')
2025
2025
2026 cmdutil.checkunfinished(repo, commit=True)
2026 cmdutil.checkunfinished(repo, commit=True)
2027
2027
2028 branch = repo[None].branch()
2028 branch = repo[None].branch()
2029 bheads = repo.branchheads(branch)
2029 bheads = repo.branchheads(branch)
2030 tip = repo.changelog.tip()
2030 tip = repo.changelog.tip()
2031
2031
2032 extra = {}
2032 extra = {}
2033 if opts.get(b'close_branch') or opts.get(b'force_close_branch'):
2033 if opts.get(b'close_branch') or opts.get(b'force_close_branch'):
2034 extra[b'close'] = b'1'
2034 extra[b'close'] = b'1'
2035
2035
2036 if repo[b'.'].closesbranch():
2036 if repo[b'.'].closesbranch():
2037 raise error.Abort(
2037 raise error.Abort(
2038 _(b'current revision is already a branch closing head')
2038 _(b'current revision is already a branch closing head')
2039 )
2039 )
2040 elif not bheads:
2040 elif not bheads:
2041 raise error.Abort(_(b'branch "%s" has no heads to close') % branch)
2041 raise error.Abort(_(b'branch "%s" has no heads to close') % branch)
2042 elif (
2042 elif (
2043 branch == repo[b'.'].branch()
2043 branch == repo[b'.'].branch()
2044 and repo[b'.'].node() not in bheads
2044 and repo[b'.'].node() not in bheads
2045 and not opts.get(b'force_close_branch')
2045 and not opts.get(b'force_close_branch')
2046 ):
2046 ):
2047 hint = _(
2047 hint = _(
2048 b'use --force-close-branch to close branch from a non-head'
2048 b'use --force-close-branch to close branch from a non-head'
2049 b' changeset'
2049 b' changeset'
2050 )
2050 )
2051 raise error.Abort(_(b'can only close branch heads'), hint=hint)
2051 raise error.Abort(_(b'can only close branch heads'), hint=hint)
2052 elif opts.get(b'amend'):
2052 elif opts.get(b'amend'):
2053 if (
2053 if (
2054 repo[b'.'].p1().branch() != branch
2054 repo[b'.'].p1().branch() != branch
2055 and repo[b'.'].p2().branch() != branch
2055 and repo[b'.'].p2().branch() != branch
2056 ):
2056 ):
2057 raise error.Abort(_(b'can only close branch heads'))
2057 raise error.Abort(_(b'can only close branch heads'))
2058
2058
2059 if opts.get(b'amend'):
2059 if opts.get(b'amend'):
2060 if ui.configbool(b'ui', b'commitsubrepos'):
2060 if ui.configbool(b'ui', b'commitsubrepos'):
2061 raise error.Abort(_(b'cannot amend with ui.commitsubrepos enabled'))
2061 raise error.Abort(_(b'cannot amend with ui.commitsubrepos enabled'))
2062
2062
2063 old = repo[b'.']
2063 old = repo[b'.']
2064 rewriteutil.precheck(repo, [old.rev()], b'amend')
2064 rewriteutil.precheck(repo, [old.rev()], b'amend')
2065
2065
2066 # Currently histedit gets confused if an amend happens while histedit
2066 # Currently histedit gets confused if an amend happens while histedit
2067 # is in progress. Since we have a checkunfinished command, we are
2067 # is in progress. Since we have a checkunfinished command, we are
2068 # temporarily honoring it.
2068 # temporarily honoring it.
2069 #
2069 #
2070 # Note: eventually this guard will be removed. Please do not expect
2070 # Note: eventually this guard will be removed. Please do not expect
2071 # this behavior to remain.
2071 # this behavior to remain.
2072 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
2072 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
2073 cmdutil.checkunfinished(repo)
2073 cmdutil.checkunfinished(repo)
2074
2074
2075 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
2075 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
2076 if node == old.node():
2076 if node == old.node():
2077 ui.status(_(b"nothing changed\n"))
2077 ui.status(_(b"nothing changed\n"))
2078 return 1
2078 return 1
2079 else:
2079 else:
2080
2080
2081 def commitfunc(ui, repo, message, match, opts):
2081 def commitfunc(ui, repo, message, match, opts):
2082 overrides = {}
2082 overrides = {}
2083 if opts.get(b'secret'):
2083 if opts.get(b'secret'):
2084 overrides[(b'phases', b'new-commit')] = b'secret'
2084 overrides[(b'phases', b'new-commit')] = b'secret'
2085
2085
2086 baseui = repo.baseui
2086 baseui = repo.baseui
2087 with baseui.configoverride(overrides, b'commit'):
2087 with baseui.configoverride(overrides, b'commit'):
2088 with ui.configoverride(overrides, b'commit'):
2088 with ui.configoverride(overrides, b'commit'):
2089 editform = cmdutil.mergeeditform(
2089 editform = cmdutil.mergeeditform(
2090 repo[None], b'commit.normal'
2090 repo[None], b'commit.normal'
2091 )
2091 )
2092 editor = cmdutil.getcommiteditor(
2092 editor = cmdutil.getcommiteditor(
2093 editform=editform, **pycompat.strkwargs(opts)
2093 editform=editform, **pycompat.strkwargs(opts)
2094 )
2094 )
2095 return repo.commit(
2095 return repo.commit(
2096 message,
2096 message,
2097 opts.get(b'user'),
2097 opts.get(b'user'),
2098 opts.get(b'date'),
2098 opts.get(b'date'),
2099 match,
2099 match,
2100 editor=editor,
2100 editor=editor,
2101 extra=extra,
2101 extra=extra,
2102 )
2102 )
2103
2103
2104 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
2104 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
2105
2105
2106 if not node:
2106 if not node:
2107 stat = cmdutil.postcommitstatus(repo, pats, opts)
2107 stat = cmdutil.postcommitstatus(repo, pats, opts)
2108 if stat.deleted:
2108 if stat.deleted:
2109 ui.status(
2109 ui.status(
2110 _(
2110 _(
2111 b"nothing changed (%d missing files, see "
2111 b"nothing changed (%d missing files, see "
2112 b"'hg status')\n"
2112 b"'hg status')\n"
2113 )
2113 )
2114 % len(stat.deleted)
2114 % len(stat.deleted)
2115 )
2115 )
2116 else:
2116 else:
2117 ui.status(_(b"nothing changed\n"))
2117 ui.status(_(b"nothing changed\n"))
2118 return 1
2118 return 1
2119
2119
2120 cmdutil.commitstatus(repo, node, branch, bheads, tip, opts)
2120 cmdutil.commitstatus(repo, node, branch, bheads, tip, opts)
2121
2121
2122 if not ui.quiet and ui.configbool(b'commands', b'commit.post-status'):
2122 if not ui.quiet and ui.configbool(b'commands', b'commit.post-status'):
2123 status(
2123 status(
2124 ui,
2124 ui,
2125 repo,
2125 repo,
2126 modified=True,
2126 modified=True,
2127 added=True,
2127 added=True,
2128 removed=True,
2128 removed=True,
2129 deleted=True,
2129 deleted=True,
2130 unknown=True,
2130 unknown=True,
2131 subrepos=opts.get(b'subrepos'),
2131 subrepos=opts.get(b'subrepos'),
2132 )
2132 )
2133
2133
2134
2134
2135 @command(
2135 @command(
2136 b'config|showconfig|debugconfig',
2136 b'config|showconfig|debugconfig',
2137 [
2137 [
2138 (b'u', b'untrusted', None, _(b'show untrusted configuration options')),
2138 (b'u', b'untrusted', None, _(b'show untrusted configuration options')),
2139 (b'e', b'edit', None, _(b'edit user config')),
2139 (b'e', b'edit', None, _(b'edit user config')),
2140 (b'l', b'local', None, _(b'edit repository config')),
2140 (b'l', b'local', None, _(b'edit repository config')),
2141 (
2141 (
2142 b'',
2142 b'',
2143 b'shared',
2143 b'shared',
2144 None,
2144 None,
2145 _(b'edit shared source repository config (EXPERIMENTAL)'),
2145 _(b'edit shared source repository config (EXPERIMENTAL)'),
2146 ),
2146 ),
2147 (b'', b'non-shared', None, _(b'edit non shared config (EXPERIMENTAL)')),
2147 (b'', b'non-shared', None, _(b'edit non shared config (EXPERIMENTAL)')),
2148 (b'g', b'global', None, _(b'edit global config')),
2148 (b'g', b'global', None, _(b'edit global config')),
2149 ]
2149 ]
2150 + formatteropts,
2150 + formatteropts,
2151 _(b'[-u] [NAME]...'),
2151 _(b'[-u] [NAME]...'),
2152 helpcategory=command.CATEGORY_HELP,
2152 helpcategory=command.CATEGORY_HELP,
2153 optionalrepo=True,
2153 optionalrepo=True,
2154 intents={INTENT_READONLY},
2154 intents={INTENT_READONLY},
2155 )
2155 )
2156 def config(ui, repo, *values, **opts):
2156 def config(ui, repo, *values, **opts):
2157 """show combined config settings from all hgrc files
2157 """show combined config settings from all hgrc files
2158
2158
2159 With no arguments, print names and values of all config items.
2159 With no arguments, print names and values of all config items.
2160
2160
2161 With one argument of the form section.name, print just the value
2161 With one argument of the form section.name, print just the value
2162 of that config item.
2162 of that config item.
2163
2163
2164 With multiple arguments, print names and values of all config
2164 With multiple arguments, print names and values of all config
2165 items with matching section names or section.names.
2165 items with matching section names or section.names.
2166
2166
2167 With --edit, start an editor on the user-level config file. With
2167 With --edit, start an editor on the user-level config file. With
2168 --global, edit the system-wide config file. With --local, edit the
2168 --global, edit the system-wide config file. With --local, edit the
2169 repository-level config file.
2169 repository-level config file.
2170
2170
2171 With --debug, the source (filename and line number) is printed
2171 With --debug, the source (filename and line number) is printed
2172 for each config item.
2172 for each config item.
2173
2173
2174 See :hg:`help config` for more information about config files.
2174 See :hg:`help config` for more information about config files.
2175
2175
2176 .. container:: verbose
2176 .. container:: verbose
2177
2177
2178 --non-shared flag is used to edit `.hg/hgrc-not-shared` config file.
2178 --non-shared flag is used to edit `.hg/hgrc-not-shared` config file.
2179 This file is not shared across shares when in share-safe mode.
2179 This file is not shared across shares when in share-safe mode.
2180
2180
2181 Template:
2181 Template:
2182
2182
2183 The following keywords are supported. See also :hg:`help templates`.
2183 The following keywords are supported. See also :hg:`help templates`.
2184
2184
2185 :name: String. Config name.
2185 :name: String. Config name.
2186 :source: String. Filename and line number where the item is defined.
2186 :source: String. Filename and line number where the item is defined.
2187 :value: String. Config value.
2187 :value: String. Config value.
2188
2188
2189 The --shared flag can be used to edit the config file of shared source
2189 The --shared flag can be used to edit the config file of shared source
2190 repository. It only works when you have shared using the experimental
2190 repository. It only works when you have shared using the experimental
2191 share safe feature.
2191 share safe feature.
2192
2192
2193 Returns 0 on success, 1 if NAME does not exist.
2193 Returns 0 on success, 1 if NAME does not exist.
2194
2194
2195 """
2195 """
2196
2196
2197 opts = pycompat.byteskwargs(opts)
2197 opts = pycompat.byteskwargs(opts)
2198 editopts = (b'edit', b'local', b'global', b'shared', b'non_shared')
2198 editopts = (b'edit', b'local', b'global', b'shared', b'non_shared')
2199 if any(opts.get(o) for o in editopts):
2199 if any(opts.get(o) for o in editopts):
2200 cmdutil.check_at_most_one_arg(opts, *editopts[1:])
2200 cmdutil.check_at_most_one_arg(opts, *editopts[1:])
2201 if opts.get(b'local'):
2201 if opts.get(b'local'):
2202 if not repo:
2202 if not repo:
2203 raise error.Abort(_(b"can't use --local outside a repository"))
2203 raise error.Abort(_(b"can't use --local outside a repository"))
2204 paths = [repo.vfs.join(b'hgrc')]
2204 paths = [repo.vfs.join(b'hgrc')]
2205 elif opts.get(b'global'):
2205 elif opts.get(b'global'):
2206 paths = rcutil.systemrcpath()
2206 paths = rcutil.systemrcpath()
2207 elif opts.get(b'shared'):
2207 elif opts.get(b'shared'):
2208 if not repo.shared():
2208 if not repo.shared():
2209 raise error.Abort(
2209 raise error.Abort(
2210 _(b"repository is not shared; can't use --shared")
2210 _(b"repository is not shared; can't use --shared")
2211 )
2211 )
2212 if requirements.SHARESAFE_REQUIREMENT not in repo.requirements:
2212 if requirements.SHARESAFE_REQUIREMENT not in repo.requirements:
2213 raise error.Abort(
2213 raise error.Abort(
2214 _(
2214 _(
2215 b"share safe feature not unabled; "
2215 b"share safe feature not unabled; "
2216 b"unable to edit shared source repository config"
2216 b"unable to edit shared source repository config"
2217 )
2217 )
2218 )
2218 )
2219 paths = [vfsmod.vfs(repo.sharedpath).join(b'hgrc')]
2219 paths = [vfsmod.vfs(repo.sharedpath).join(b'hgrc')]
2220 elif opts.get(b'non_shared'):
2220 elif opts.get(b'non_shared'):
2221 paths = [repo.vfs.join(b'hgrc-not-shared')]
2221 paths = [repo.vfs.join(b'hgrc-not-shared')]
2222 else:
2222 else:
2223 paths = rcutil.userrcpath()
2223 paths = rcutil.userrcpath()
2224
2224
2225 for f in paths:
2225 for f in paths:
2226 if os.path.exists(f):
2226 if os.path.exists(f):
2227 break
2227 break
2228 else:
2228 else:
2229 if opts.get(b'global'):
2229 if opts.get(b'global'):
2230 samplehgrc = uimod.samplehgrcs[b'global']
2230 samplehgrc = uimod.samplehgrcs[b'global']
2231 elif opts.get(b'local'):
2231 elif opts.get(b'local'):
2232 samplehgrc = uimod.samplehgrcs[b'local']
2232 samplehgrc = uimod.samplehgrcs[b'local']
2233 else:
2233 else:
2234 samplehgrc = uimod.samplehgrcs[b'user']
2234 samplehgrc = uimod.samplehgrcs[b'user']
2235
2235
2236 f = paths[0]
2236 f = paths[0]
2237 fp = open(f, b"wb")
2237 fp = open(f, b"wb")
2238 fp.write(util.tonativeeol(samplehgrc))
2238 fp.write(util.tonativeeol(samplehgrc))
2239 fp.close()
2239 fp.close()
2240
2240
2241 editor = ui.geteditor()
2241 editor = ui.geteditor()
2242 ui.system(
2242 ui.system(
2243 b"%s \"%s\"" % (editor, f),
2243 b"%s \"%s\"" % (editor, f),
2244 onerr=error.Abort,
2244 onerr=error.Abort,
2245 errprefix=_(b"edit failed"),
2245 errprefix=_(b"edit failed"),
2246 blockedtag=b'config_edit',
2246 blockedtag=b'config_edit',
2247 )
2247 )
2248 return
2248 return
2249 ui.pager(b'config')
2249 ui.pager(b'config')
2250 fm = ui.formatter(b'config', opts)
2250 fm = ui.formatter(b'config', opts)
2251 for t, f in rcutil.rccomponents():
2251 for t, f in rcutil.rccomponents():
2252 if t == b'path':
2252 if t == b'path':
2253 ui.debug(b'read config from: %s\n' % f)
2253 ui.debug(b'read config from: %s\n' % f)
2254 elif t == b'resource':
2254 elif t == b'resource':
2255 ui.debug(b'read config from: resource:%s.%s\n' % (f[0], f[1]))
2255 ui.debug(b'read config from: resource:%s.%s\n' % (f[0], f[1]))
2256 elif t == b'items':
2256 elif t == b'items':
2257 # Don't print anything for 'items'.
2257 # Don't print anything for 'items'.
2258 pass
2258 pass
2259 else:
2259 else:
2260 raise error.ProgrammingError(b'unknown rctype: %s' % t)
2260 raise error.ProgrammingError(b'unknown rctype: %s' % t)
2261 untrusted = bool(opts.get(b'untrusted'))
2261 untrusted = bool(opts.get(b'untrusted'))
2262
2262
2263 selsections = selentries = []
2263 selsections = selentries = []
2264 if values:
2264 if values:
2265 selsections = [v for v in values if b'.' not in v]
2265 selsections = [v for v in values if b'.' not in v]
2266 selentries = [v for v in values if b'.' in v]
2266 selentries = [v for v in values if b'.' in v]
2267 uniquesel = len(selentries) == 1 and not selsections
2267 uniquesel = len(selentries) == 1 and not selsections
2268 selsections = set(selsections)
2268 selsections = set(selsections)
2269 selentries = set(selentries)
2269 selentries = set(selentries)
2270
2270
2271 matched = False
2271 matched = False
2272 for section, name, value in ui.walkconfig(untrusted=untrusted):
2272 for section, name, value in ui.walkconfig(untrusted=untrusted):
2273 source = ui.configsource(section, name, untrusted)
2273 source = ui.configsource(section, name, untrusted)
2274 value = pycompat.bytestr(value)
2274 value = pycompat.bytestr(value)
2275 defaultvalue = ui.configdefault(section, name)
2275 defaultvalue = ui.configdefault(section, name)
2276 if fm.isplain():
2276 if fm.isplain():
2277 source = source or b'none'
2277 source = source or b'none'
2278 value = value.replace(b'\n', b'\\n')
2278 value = value.replace(b'\n', b'\\n')
2279 entryname = section + b'.' + name
2279 entryname = section + b'.' + name
2280 if values and not (section in selsections or entryname in selentries):
2280 if values and not (section in selsections or entryname in selentries):
2281 continue
2281 continue
2282 fm.startitem()
2282 fm.startitem()
2283 fm.condwrite(ui.debugflag, b'source', b'%s: ', source)
2283 fm.condwrite(ui.debugflag, b'source', b'%s: ', source)
2284 if uniquesel:
2284 if uniquesel:
2285 fm.data(name=entryname)
2285 fm.data(name=entryname)
2286 fm.write(b'value', b'%s\n', value)
2286 fm.write(b'value', b'%s\n', value)
2287 else:
2287 else:
2288 fm.write(b'name value', b'%s=%s\n', entryname, value)
2288 fm.write(b'name value', b'%s=%s\n', entryname, value)
2289 if formatter.isprintable(defaultvalue):
2289 if formatter.isprintable(defaultvalue):
2290 fm.data(defaultvalue=defaultvalue)
2290 fm.data(defaultvalue=defaultvalue)
2291 elif isinstance(defaultvalue, list) and all(
2291 elif isinstance(defaultvalue, list) and all(
2292 formatter.isprintable(e) for e in defaultvalue
2292 formatter.isprintable(e) for e in defaultvalue
2293 ):
2293 ):
2294 fm.data(defaultvalue=fm.formatlist(defaultvalue, name=b'value'))
2294 fm.data(defaultvalue=fm.formatlist(defaultvalue, name=b'value'))
2295 # TODO: no idea how to process unsupported defaultvalue types
2295 # TODO: no idea how to process unsupported defaultvalue types
2296 matched = True
2296 matched = True
2297 fm.end()
2297 fm.end()
2298 if matched:
2298 if matched:
2299 return 0
2299 return 0
2300 return 1
2300 return 1
2301
2301
2302
2302
2303 @command(
2303 @command(
2304 b'continue',
2304 b'continue',
2305 dryrunopts,
2305 dryrunopts,
2306 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
2306 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
2307 helpbasic=True,
2307 helpbasic=True,
2308 )
2308 )
2309 def continuecmd(ui, repo, **opts):
2309 def continuecmd(ui, repo, **opts):
2310 """resumes an interrupted operation (EXPERIMENTAL)
2310 """resumes an interrupted operation (EXPERIMENTAL)
2311
2311
2312 Finishes a multistep operation like graft, histedit, rebase, merge,
2312 Finishes a multistep operation like graft, histedit, rebase, merge,
2313 and unshelve if they are in an interrupted state.
2313 and unshelve if they are in an interrupted state.
2314
2314
2315 use --dry-run/-n to dry run the command.
2315 use --dry-run/-n to dry run the command.
2316 """
2316 """
2317 dryrun = opts.get('dry_run')
2317 dryrun = opts.get('dry_run')
2318 contstate = cmdutil.getunfinishedstate(repo)
2318 contstate = cmdutil.getunfinishedstate(repo)
2319 if not contstate:
2319 if not contstate:
2320 raise error.Abort(_(b'no operation in progress'))
2320 raise error.Abort(_(b'no operation in progress'))
2321 if not contstate.continuefunc:
2321 if not contstate.continuefunc:
2322 raise error.Abort(
2322 raise error.Abort(
2323 (
2323 (
2324 _(b"%s in progress but does not support 'hg continue'")
2324 _(b"%s in progress but does not support 'hg continue'")
2325 % (contstate._opname)
2325 % (contstate._opname)
2326 ),
2326 ),
2327 hint=contstate.continuemsg(),
2327 hint=contstate.continuemsg(),
2328 )
2328 )
2329 if dryrun:
2329 if dryrun:
2330 ui.status(_(b'%s in progress, will be resumed\n') % (contstate._opname))
2330 ui.status(_(b'%s in progress, will be resumed\n') % (contstate._opname))
2331 return
2331 return
2332 return contstate.continuefunc(ui, repo)
2332 return contstate.continuefunc(ui, repo)
2333
2333
2334
2334
2335 @command(
2335 @command(
2336 b'copy|cp',
2336 b'copy|cp',
2337 [
2337 [
2338 (b'', b'forget', None, _(b'unmark a destination file as copied')),
2338 (b'', b'forget', None, _(b'unmark a destination file as copied')),
2339 (b'A', b'after', None, _(b'record a copy that has already occurred')),
2339 (b'A', b'after', None, _(b'record a copy that has already occurred')),
2340 (
2340 (
2341 b'',
2341 b'',
2342 b'at-rev',
2342 b'at-rev',
2343 b'',
2343 b'',
2344 _(b'(un)mark copies in the given revision (EXPERIMENTAL)'),
2344 _(b'(un)mark copies in the given revision (EXPERIMENTAL)'),
2345 _(b'REV'),
2345 _(b'REV'),
2346 ),
2346 ),
2347 (
2347 (
2348 b'f',
2348 b'f',
2349 b'force',
2349 b'force',
2350 None,
2350 None,
2351 _(b'forcibly copy over an existing managed file'),
2351 _(b'forcibly copy over an existing managed file'),
2352 ),
2352 ),
2353 ]
2353 ]
2354 + walkopts
2354 + walkopts
2355 + dryrunopts,
2355 + dryrunopts,
2356 _(b'[OPTION]... (SOURCE... DEST | --forget DEST...)'),
2356 _(b'[OPTION]... (SOURCE... DEST | --forget DEST...)'),
2357 helpcategory=command.CATEGORY_FILE_CONTENTS,
2357 helpcategory=command.CATEGORY_FILE_CONTENTS,
2358 )
2358 )
2359 def copy(ui, repo, *pats, **opts):
2359 def copy(ui, repo, *pats, **opts):
2360 """mark files as copied for the next commit
2360 """mark files as copied for the next commit
2361
2361
2362 Mark dest as having copies of source files. If dest is a
2362 Mark dest as having copies of source files. If dest is a
2363 directory, copies are put in that directory. If dest is a file,
2363 directory, copies are put in that directory. If dest is a file,
2364 the source must be a single file.
2364 the source must be a single file.
2365
2365
2366 By default, this command copies the contents of files as they
2366 By default, this command copies the contents of files as they
2367 exist in the working directory. If invoked with -A/--after, the
2367 exist in the working directory. If invoked with -A/--after, the
2368 operation is recorded, but no copying is performed.
2368 operation is recorded, but no copying is performed.
2369
2369
2370 To undo marking a destination file as copied, use --forget. With that
2370 To undo marking a destination file as copied, use --forget. With that
2371 option, all given (positional) arguments are unmarked as copies. The
2371 option, all given (positional) arguments are unmarked as copies. The
2372 destination file(s) will be left in place (still tracked).
2372 destination file(s) will be left in place (still tracked).
2373
2373
2374 This command takes effect with the next commit by default.
2374 This command takes effect with the next commit by default.
2375
2375
2376 Returns 0 on success, 1 if errors are encountered.
2376 Returns 0 on success, 1 if errors are encountered.
2377 """
2377 """
2378 opts = pycompat.byteskwargs(opts)
2378 opts = pycompat.byteskwargs(opts)
2379 with repo.wlock():
2379 with repo.wlock():
2380 return cmdutil.copy(ui, repo, pats, opts)
2380 return cmdutil.copy(ui, repo, pats, opts)
2381
2381
2382
2382
2383 @command(
2383 @command(
2384 b'debugcommands',
2384 b'debugcommands',
2385 [],
2385 [],
2386 _(b'[COMMAND]'),
2386 _(b'[COMMAND]'),
2387 helpcategory=command.CATEGORY_HELP,
2387 helpcategory=command.CATEGORY_HELP,
2388 norepo=True,
2388 norepo=True,
2389 )
2389 )
2390 def debugcommands(ui, cmd=b'', *args):
2390 def debugcommands(ui, cmd=b'', *args):
2391 """list all available commands and options"""
2391 """list all available commands and options"""
2392 for cmd, vals in sorted(pycompat.iteritems(table)):
2392 for cmd, vals in sorted(pycompat.iteritems(table)):
2393 cmd = cmd.split(b'|')[0]
2393 cmd = cmd.split(b'|')[0]
2394 opts = b', '.join([i[1] for i in vals[1]])
2394 opts = b', '.join([i[1] for i in vals[1]])
2395 ui.write(b'%s: %s\n' % (cmd, opts))
2395 ui.write(b'%s: %s\n' % (cmd, opts))
2396
2396
2397
2397
2398 @command(
2398 @command(
2399 b'debugcomplete',
2399 b'debugcomplete',
2400 [(b'o', b'options', None, _(b'show the command options'))],
2400 [(b'o', b'options', None, _(b'show the command options'))],
2401 _(b'[-o] CMD'),
2401 _(b'[-o] CMD'),
2402 helpcategory=command.CATEGORY_HELP,
2402 helpcategory=command.CATEGORY_HELP,
2403 norepo=True,
2403 norepo=True,
2404 )
2404 )
2405 def debugcomplete(ui, cmd=b'', **opts):
2405 def debugcomplete(ui, cmd=b'', **opts):
2406 """returns the completion list associated with the given command"""
2406 """returns the completion list associated with the given command"""
2407
2407
2408 if opts.get('options'):
2408 if opts.get('options'):
2409 options = []
2409 options = []
2410 otables = [globalopts]
2410 otables = [globalopts]
2411 if cmd:
2411 if cmd:
2412 aliases, entry = cmdutil.findcmd(cmd, table, False)
2412 aliases, entry = cmdutil.findcmd(cmd, table, False)
2413 otables.append(entry[1])
2413 otables.append(entry[1])
2414 for t in otables:
2414 for t in otables:
2415 for o in t:
2415 for o in t:
2416 if b"(DEPRECATED)" in o[3]:
2416 if b"(DEPRECATED)" in o[3]:
2417 continue
2417 continue
2418 if o[0]:
2418 if o[0]:
2419 options.append(b'-%s' % o[0])
2419 options.append(b'-%s' % o[0])
2420 options.append(b'--%s' % o[1])
2420 options.append(b'--%s' % o[1])
2421 ui.write(b"%s\n" % b"\n".join(options))
2421 ui.write(b"%s\n" % b"\n".join(options))
2422 return
2422 return
2423
2423
2424 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
2424 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
2425 if ui.verbose:
2425 if ui.verbose:
2426 cmdlist = [b' '.join(c[0]) for c in cmdlist.values()]
2426 cmdlist = [b' '.join(c[0]) for c in cmdlist.values()]
2427 ui.write(b"%s\n" % b"\n".join(sorted(cmdlist)))
2427 ui.write(b"%s\n" % b"\n".join(sorted(cmdlist)))
2428
2428
2429
2429
2430 @command(
2430 @command(
2431 b'diff',
2431 b'diff',
2432 [
2432 [
2433 (b'r', b'rev', [], _(b'revision'), _(b'REV')),
2433 (b'r', b'rev', [], _(b'revision'), _(b'REV')),
2434 (b'c', b'change', b'', _(b'change made by revision'), _(b'REV')),
2434 (b'c', b'change', b'', _(b'change made by revision'), _(b'REV')),
2435 ]
2435 ]
2436 + diffopts
2436 + diffopts
2437 + diffopts2
2437 + diffopts2
2438 + walkopts
2438 + walkopts
2439 + subrepoopts,
2439 + subrepoopts,
2440 _(b'[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
2440 _(b'[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
2441 helpcategory=command.CATEGORY_FILE_CONTENTS,
2441 helpcategory=command.CATEGORY_FILE_CONTENTS,
2442 helpbasic=True,
2442 helpbasic=True,
2443 inferrepo=True,
2443 inferrepo=True,
2444 intents={INTENT_READONLY},
2444 intents={INTENT_READONLY},
2445 )
2445 )
2446 def diff(ui, repo, *pats, **opts):
2446 def diff(ui, repo, *pats, **opts):
2447 """diff repository (or selected files)
2447 """diff repository (or selected files)
2448
2448
2449 Show differences between revisions for the specified files.
2449 Show differences between revisions for the specified files.
2450
2450
2451 Differences between files are shown using the unified diff format.
2451 Differences between files are shown using the unified diff format.
2452
2452
2453 .. note::
2453 .. note::
2454
2454
2455 :hg:`diff` may generate unexpected results for merges, as it will
2455 :hg:`diff` may generate unexpected results for merges, as it will
2456 default to comparing against the working directory's first
2456 default to comparing against the working directory's first
2457 parent changeset if no revisions are specified.
2457 parent changeset if no revisions are specified.
2458
2458
2459 When two revision arguments are given, then changes are shown
2459 When two revision arguments are given, then changes are shown
2460 between those revisions. If only one revision is specified then
2460 between those revisions. If only one revision is specified then
2461 that revision is compared to the working directory, and, when no
2461 that revision is compared to the working directory, and, when no
2462 revisions are specified, the working directory files are compared
2462 revisions are specified, the working directory files are compared
2463 to its first parent.
2463 to its first parent.
2464
2464
2465 Alternatively you can specify -c/--change with a revision to see
2465 Alternatively you can specify -c/--change with a revision to see
2466 the changes in that changeset relative to its first parent.
2466 the changes in that changeset relative to its first parent.
2467
2467
2468 Without the -a/--text option, diff will avoid generating diffs of
2468 Without the -a/--text option, diff will avoid generating diffs of
2469 files it detects as binary. With -a, diff will generate a diff
2469 files it detects as binary. With -a, diff will generate a diff
2470 anyway, probably with undesirable results.
2470 anyway, probably with undesirable results.
2471
2471
2472 Use the -g/--git option to generate diffs in the git extended diff
2472 Use the -g/--git option to generate diffs in the git extended diff
2473 format. For more information, read :hg:`help diffs`.
2473 format. For more information, read :hg:`help diffs`.
2474
2474
2475 .. container:: verbose
2475 .. container:: verbose
2476
2476
2477 Examples:
2477 Examples:
2478
2478
2479 - compare a file in the current working directory to its parent::
2479 - compare a file in the current working directory to its parent::
2480
2480
2481 hg diff foo.c
2481 hg diff foo.c
2482
2482
2483 - compare two historical versions of a directory, with rename info::
2483 - compare two historical versions of a directory, with rename info::
2484
2484
2485 hg diff --git -r 1.0:1.2 lib/
2485 hg diff --git -r 1.0:1.2 lib/
2486
2486
2487 - get change stats relative to the last change on some date::
2487 - get change stats relative to the last change on some date::
2488
2488
2489 hg diff --stat -r "date('may 2')"
2489 hg diff --stat -r "date('may 2')"
2490
2490
2491 - diff all newly-added files that contain a keyword::
2491 - diff all newly-added files that contain a keyword::
2492
2492
2493 hg diff "set:added() and grep(GNU)"
2493 hg diff "set:added() and grep(GNU)"
2494
2494
2495 - compare a revision and its parents::
2495 - compare a revision and its parents::
2496
2496
2497 hg diff -c 9353 # compare against first parent
2497 hg diff -c 9353 # compare against first parent
2498 hg diff -r 9353^:9353 # same using revset syntax
2498 hg diff -r 9353^:9353 # same using revset syntax
2499 hg diff -r 9353^2:9353 # compare against the second parent
2499 hg diff -r 9353^2:9353 # compare against the second parent
2500
2500
2501 Returns 0 on success.
2501 Returns 0 on success.
2502 """
2502 """
2503
2503
2504 cmdutil.check_at_most_one_arg(opts, 'rev', 'change')
2504 cmdutil.check_at_most_one_arg(opts, 'rev', 'change')
2505 opts = pycompat.byteskwargs(opts)
2505 opts = pycompat.byteskwargs(opts)
2506 revs = opts.get(b'rev')
2506 revs = opts.get(b'rev')
2507 change = opts.get(b'change')
2507 change = opts.get(b'change')
2508 stat = opts.get(b'stat')
2508 stat = opts.get(b'stat')
2509 reverse = opts.get(b'reverse')
2509 reverse = opts.get(b'reverse')
2510
2510
2511 if change:
2511 if change:
2512 repo = scmutil.unhidehashlikerevs(repo, [change], b'nowarn')
2512 repo = scmutil.unhidehashlikerevs(repo, [change], b'nowarn')
2513 ctx2 = scmutil.revsingle(repo, change, None)
2513 ctx2 = scmutil.revsingle(repo, change, None)
2514 ctx1 = ctx2.p1()
2514 ctx1 = ctx2.p1()
2515 else:
2515 else:
2516 repo = scmutil.unhidehashlikerevs(repo, revs, b'nowarn')
2516 repo = scmutil.unhidehashlikerevs(repo, revs, b'nowarn')
2517 ctx1, ctx2 = scmutil.revpair(repo, revs)
2517 ctx1, ctx2 = scmutil.revpair(repo, revs)
2518
2518
2519 if reverse:
2519 if reverse:
2520 ctxleft = ctx2
2520 ctxleft = ctx2
2521 ctxright = ctx1
2521 ctxright = ctx1
2522 else:
2522 else:
2523 ctxleft = ctx1
2523 ctxleft = ctx1
2524 ctxright = ctx2
2524 ctxright = ctx2
2525
2525
2526 diffopts = patch.diffallopts(ui, opts)
2526 diffopts = patch.diffallopts(ui, opts)
2527 m = scmutil.match(ctx2, pats, opts)
2527 m = scmutil.match(ctx2, pats, opts)
2528 m = repo.narrowmatch(m)
2528 m = repo.narrowmatch(m)
2529 ui.pager(b'diff')
2529 ui.pager(b'diff')
2530 logcmdutil.diffordiffstat(
2530 logcmdutil.diffordiffstat(
2531 ui,
2531 ui,
2532 repo,
2532 repo,
2533 diffopts,
2533 diffopts,
2534 ctxleft,
2534 ctxleft,
2535 ctxright,
2535 ctxright,
2536 m,
2536 m,
2537 stat=stat,
2537 stat=stat,
2538 listsubrepos=opts.get(b'subrepos'),
2538 listsubrepos=opts.get(b'subrepos'),
2539 root=opts.get(b'root'),
2539 root=opts.get(b'root'),
2540 )
2540 )
2541
2541
2542
2542
2543 @command(
2543 @command(
2544 b'export',
2544 b'export',
2545 [
2545 [
2546 (
2546 (
2547 b'B',
2547 b'B',
2548 b'bookmark',
2548 b'bookmark',
2549 b'',
2549 b'',
2550 _(b'export changes only reachable by given bookmark'),
2550 _(b'export changes only reachable by given bookmark'),
2551 _(b'BOOKMARK'),
2551 _(b'BOOKMARK'),
2552 ),
2552 ),
2553 (
2553 (
2554 b'o',
2554 b'o',
2555 b'output',
2555 b'output',
2556 b'',
2556 b'',
2557 _(b'print output to file with formatted name'),
2557 _(b'print output to file with formatted name'),
2558 _(b'FORMAT'),
2558 _(b'FORMAT'),
2559 ),
2559 ),
2560 (b'', b'switch-parent', None, _(b'diff against the second parent')),
2560 (b'', b'switch-parent', None, _(b'diff against the second parent')),
2561 (b'r', b'rev', [], _(b'revisions to export'), _(b'REV')),
2561 (b'r', b'rev', [], _(b'revisions to export'), _(b'REV')),
2562 ]
2562 ]
2563 + diffopts
2563 + diffopts
2564 + formatteropts,
2564 + formatteropts,
2565 _(b'[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'),
2565 _(b'[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'),
2566 helpcategory=command.CATEGORY_IMPORT_EXPORT,
2566 helpcategory=command.CATEGORY_IMPORT_EXPORT,
2567 helpbasic=True,
2567 helpbasic=True,
2568 intents={INTENT_READONLY},
2568 intents={INTENT_READONLY},
2569 )
2569 )
2570 def export(ui, repo, *changesets, **opts):
2570 def export(ui, repo, *changesets, **opts):
2571 """dump the header and diffs for one or more changesets
2571 """dump the header and diffs for one or more changesets
2572
2572
2573 Print the changeset header and diffs for one or more revisions.
2573 Print the changeset header and diffs for one or more revisions.
2574 If no revision is given, the parent of the working directory is used.
2574 If no revision is given, the parent of the working directory is used.
2575
2575
2576 The information shown in the changeset header is: author, date,
2576 The information shown in the changeset header is: author, date,
2577 branch name (if non-default), changeset hash, parent(s) and commit
2577 branch name (if non-default), changeset hash, parent(s) and commit
2578 comment.
2578 comment.
2579
2579
2580 .. note::
2580 .. note::
2581
2581
2582 :hg:`export` may generate unexpected diff output for merge
2582 :hg:`export` may generate unexpected diff output for merge
2583 changesets, as it will compare the merge changeset against its
2583 changesets, as it will compare the merge changeset against its
2584 first parent only.
2584 first parent only.
2585
2585
2586 Output may be to a file, in which case the name of the file is
2586 Output may be to a file, in which case the name of the file is
2587 given using a template string. See :hg:`help templates`. In addition
2587 given using a template string. See :hg:`help templates`. In addition
2588 to the common template keywords, the following formatting rules are
2588 to the common template keywords, the following formatting rules are
2589 supported:
2589 supported:
2590
2590
2591 :``%%``: literal "%" character
2591 :``%%``: literal "%" character
2592 :``%H``: changeset hash (40 hexadecimal digits)
2592 :``%H``: changeset hash (40 hexadecimal digits)
2593 :``%N``: number of patches being generated
2593 :``%N``: number of patches being generated
2594 :``%R``: changeset revision number
2594 :``%R``: changeset revision number
2595 :``%b``: basename of the exporting repository
2595 :``%b``: basename of the exporting repository
2596 :``%h``: short-form changeset hash (12 hexadecimal digits)
2596 :``%h``: short-form changeset hash (12 hexadecimal digits)
2597 :``%m``: first line of the commit message (only alphanumeric characters)
2597 :``%m``: first line of the commit message (only alphanumeric characters)
2598 :``%n``: zero-padded sequence number, starting at 1
2598 :``%n``: zero-padded sequence number, starting at 1
2599 :``%r``: zero-padded changeset revision number
2599 :``%r``: zero-padded changeset revision number
2600 :``\\``: literal "\\" character
2600 :``\\``: literal "\\" character
2601
2601
2602 Without the -a/--text option, export will avoid generating diffs
2602 Without the -a/--text option, export will avoid generating diffs
2603 of files it detects as binary. With -a, export will generate a
2603 of files it detects as binary. With -a, export will generate a
2604 diff anyway, probably with undesirable results.
2604 diff anyway, probably with undesirable results.
2605
2605
2606 With -B/--bookmark changesets reachable by the given bookmark are
2606 With -B/--bookmark changesets reachable by the given bookmark are
2607 selected.
2607 selected.
2608
2608
2609 Use the -g/--git option to generate diffs in the git extended diff
2609 Use the -g/--git option to generate diffs in the git extended diff
2610 format. See :hg:`help diffs` for more information.
2610 format. See :hg:`help diffs` for more information.
2611
2611
2612 With the --switch-parent option, the diff will be against the
2612 With the --switch-parent option, the diff will be against the
2613 second parent. It can be useful to review a merge.
2613 second parent. It can be useful to review a merge.
2614
2614
2615 .. container:: verbose
2615 .. container:: verbose
2616
2616
2617 Template:
2617 Template:
2618
2618
2619 The following keywords are supported in addition to the common template
2619 The following keywords are supported in addition to the common template
2620 keywords and functions. See also :hg:`help templates`.
2620 keywords and functions. See also :hg:`help templates`.
2621
2621
2622 :diff: String. Diff content.
2622 :diff: String. Diff content.
2623 :parents: List of strings. Parent nodes of the changeset.
2623 :parents: List of strings. Parent nodes of the changeset.
2624
2624
2625 Examples:
2625 Examples:
2626
2626
2627 - use export and import to transplant a bugfix to the current
2627 - use export and import to transplant a bugfix to the current
2628 branch::
2628 branch::
2629
2629
2630 hg export -r 9353 | hg import -
2630 hg export -r 9353 | hg import -
2631
2631
2632 - export all the changesets between two revisions to a file with
2632 - export all the changesets between two revisions to a file with
2633 rename information::
2633 rename information::
2634
2634
2635 hg export --git -r 123:150 > changes.txt
2635 hg export --git -r 123:150 > changes.txt
2636
2636
2637 - split outgoing changes into a series of patches with
2637 - split outgoing changes into a series of patches with
2638 descriptive names::
2638 descriptive names::
2639
2639
2640 hg export -r "outgoing()" -o "%n-%m.patch"
2640 hg export -r "outgoing()" -o "%n-%m.patch"
2641
2641
2642 Returns 0 on success.
2642 Returns 0 on success.
2643 """
2643 """
2644 opts = pycompat.byteskwargs(opts)
2644 opts = pycompat.byteskwargs(opts)
2645 bookmark = opts.get(b'bookmark')
2645 bookmark = opts.get(b'bookmark')
2646 changesets += tuple(opts.get(b'rev', []))
2646 changesets += tuple(opts.get(b'rev', []))
2647
2647
2648 cmdutil.check_at_most_one_arg(opts, b'rev', b'bookmark')
2648 cmdutil.check_at_most_one_arg(opts, b'rev', b'bookmark')
2649
2649
2650 if bookmark:
2650 if bookmark:
2651 if bookmark not in repo._bookmarks:
2651 if bookmark not in repo._bookmarks:
2652 raise error.Abort(_(b"bookmark '%s' not found") % bookmark)
2652 raise error.Abort(_(b"bookmark '%s' not found") % bookmark)
2653
2653
2654 revs = scmutil.bookmarkrevs(repo, bookmark)
2654 revs = scmutil.bookmarkrevs(repo, bookmark)
2655 else:
2655 else:
2656 if not changesets:
2656 if not changesets:
2657 changesets = [b'.']
2657 changesets = [b'.']
2658
2658
2659 repo = scmutil.unhidehashlikerevs(repo, changesets, b'nowarn')
2659 repo = scmutil.unhidehashlikerevs(repo, changesets, b'nowarn')
2660 revs = scmutil.revrange(repo, changesets)
2660 revs = scmutil.revrange(repo, changesets)
2661
2661
2662 if not revs:
2662 if not revs:
2663 raise error.Abort(_(b"export requires at least one changeset"))
2663 raise error.Abort(_(b"export requires at least one changeset"))
2664 if len(revs) > 1:
2664 if len(revs) > 1:
2665 ui.note(_(b'exporting patches:\n'))
2665 ui.note(_(b'exporting patches:\n'))
2666 else:
2666 else:
2667 ui.note(_(b'exporting patch:\n'))
2667 ui.note(_(b'exporting patch:\n'))
2668
2668
2669 fntemplate = opts.get(b'output')
2669 fntemplate = opts.get(b'output')
2670 if cmdutil.isstdiofilename(fntemplate):
2670 if cmdutil.isstdiofilename(fntemplate):
2671 fntemplate = b''
2671 fntemplate = b''
2672
2672
2673 if fntemplate:
2673 if fntemplate:
2674 fm = formatter.nullformatter(ui, b'export', opts)
2674 fm = formatter.nullformatter(ui, b'export', opts)
2675 else:
2675 else:
2676 ui.pager(b'export')
2676 ui.pager(b'export')
2677 fm = ui.formatter(b'export', opts)
2677 fm = ui.formatter(b'export', opts)
2678 with fm:
2678 with fm:
2679 cmdutil.export(
2679 cmdutil.export(
2680 repo,
2680 repo,
2681 revs,
2681 revs,
2682 fm,
2682 fm,
2683 fntemplate=fntemplate,
2683 fntemplate=fntemplate,
2684 switch_parent=opts.get(b'switch_parent'),
2684 switch_parent=opts.get(b'switch_parent'),
2685 opts=patch.diffallopts(ui, opts),
2685 opts=patch.diffallopts(ui, opts),
2686 )
2686 )
2687
2687
2688
2688
2689 @command(
2689 @command(
2690 b'files',
2690 b'files',
2691 [
2691 [
2692 (
2692 (
2693 b'r',
2693 b'r',
2694 b'rev',
2694 b'rev',
2695 b'',
2695 b'',
2696 _(b'search the repository as it is in REV'),
2696 _(b'search the repository as it is in REV'),
2697 _(b'REV'),
2697 _(b'REV'),
2698 ),
2698 ),
2699 (
2699 (
2700 b'0',
2700 b'0',
2701 b'print0',
2701 b'print0',
2702 None,
2702 None,
2703 _(b'end filenames with NUL, for use with xargs'),
2703 _(b'end filenames with NUL, for use with xargs'),
2704 ),
2704 ),
2705 ]
2705 ]
2706 + walkopts
2706 + walkopts
2707 + formatteropts
2707 + formatteropts
2708 + subrepoopts,
2708 + subrepoopts,
2709 _(b'[OPTION]... [FILE]...'),
2709 _(b'[OPTION]... [FILE]...'),
2710 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2710 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2711 intents={INTENT_READONLY},
2711 intents={INTENT_READONLY},
2712 )
2712 )
2713 def files(ui, repo, *pats, **opts):
2713 def files(ui, repo, *pats, **opts):
2714 """list tracked files
2714 """list tracked files
2715
2715
2716 Print files under Mercurial control in the working directory or
2716 Print files under Mercurial control in the working directory or
2717 specified revision for given files (excluding removed files).
2717 specified revision for given files (excluding removed files).
2718 Files can be specified as filenames or filesets.
2718 Files can be specified as filenames or filesets.
2719
2719
2720 If no files are given to match, this command prints the names
2720 If no files are given to match, this command prints the names
2721 of all files under Mercurial control.
2721 of all files under Mercurial control.
2722
2722
2723 .. container:: verbose
2723 .. container:: verbose
2724
2724
2725 Template:
2725 Template:
2726
2726
2727 The following keywords are supported in addition to the common template
2727 The following keywords are supported in addition to the common template
2728 keywords and functions. See also :hg:`help templates`.
2728 keywords and functions. See also :hg:`help templates`.
2729
2729
2730 :flags: String. Character denoting file's symlink and executable bits.
2730 :flags: String. Character denoting file's symlink and executable bits.
2731 :path: String. Repository-absolute path of the file.
2731 :path: String. Repository-absolute path of the file.
2732 :size: Integer. Size of the file in bytes.
2732 :size: Integer. Size of the file in bytes.
2733
2733
2734 Examples:
2734 Examples:
2735
2735
2736 - list all files under the current directory::
2736 - list all files under the current directory::
2737
2737
2738 hg files .
2738 hg files .
2739
2739
2740 - shows sizes and flags for current revision::
2740 - shows sizes and flags for current revision::
2741
2741
2742 hg files -vr .
2742 hg files -vr .
2743
2743
2744 - list all files named README::
2744 - list all files named README::
2745
2745
2746 hg files -I "**/README"
2746 hg files -I "**/README"
2747
2747
2748 - list all binary files::
2748 - list all binary files::
2749
2749
2750 hg files "set:binary()"
2750 hg files "set:binary()"
2751
2751
2752 - find files containing a regular expression::
2752 - find files containing a regular expression::
2753
2753
2754 hg files "set:grep('bob')"
2754 hg files "set:grep('bob')"
2755
2755
2756 - search tracked file contents with xargs and grep::
2756 - search tracked file contents with xargs and grep::
2757
2757
2758 hg files -0 | xargs -0 grep foo
2758 hg files -0 | xargs -0 grep foo
2759
2759
2760 See :hg:`help patterns` and :hg:`help filesets` for more information
2760 See :hg:`help patterns` and :hg:`help filesets` for more information
2761 on specifying file patterns.
2761 on specifying file patterns.
2762
2762
2763 Returns 0 if a match is found, 1 otherwise.
2763 Returns 0 if a match is found, 1 otherwise.
2764
2764
2765 """
2765 """
2766
2766
2767 opts = pycompat.byteskwargs(opts)
2767 opts = pycompat.byteskwargs(opts)
2768 rev = opts.get(b'rev')
2768 rev = opts.get(b'rev')
2769 if rev:
2769 if rev:
2770 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
2770 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
2771 ctx = scmutil.revsingle(repo, rev, None)
2771 ctx = scmutil.revsingle(repo, rev, None)
2772
2772
2773 end = b'\n'
2773 end = b'\n'
2774 if opts.get(b'print0'):
2774 if opts.get(b'print0'):
2775 end = b'\0'
2775 end = b'\0'
2776 fmt = b'%s' + end
2776 fmt = b'%s' + end
2777
2777
2778 m = scmutil.match(ctx, pats, opts)
2778 m = scmutil.match(ctx, pats, opts)
2779 ui.pager(b'files')
2779 ui.pager(b'files')
2780 uipathfn = scmutil.getuipathfn(ctx.repo(), legacyrelativevalue=True)
2780 uipathfn = scmutil.getuipathfn(ctx.repo(), legacyrelativevalue=True)
2781 with ui.formatter(b'files', opts) as fm:
2781 with ui.formatter(b'files', opts) as fm:
2782 return cmdutil.files(
2782 return cmdutil.files(
2783 ui, ctx, m, uipathfn, fm, fmt, opts.get(b'subrepos')
2783 ui, ctx, m, uipathfn, fm, fmt, opts.get(b'subrepos')
2784 )
2784 )
2785
2785
2786
2786
2787 @command(
2787 @command(
2788 b'forget',
2788 b'forget',
2789 [(b'i', b'interactive', None, _(b'use interactive mode')),]
2789 [(b'i', b'interactive', None, _(b'use interactive mode')),]
2790 + walkopts
2790 + walkopts
2791 + dryrunopts,
2791 + dryrunopts,
2792 _(b'[OPTION]... FILE...'),
2792 _(b'[OPTION]... FILE...'),
2793 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2793 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2794 helpbasic=True,
2794 helpbasic=True,
2795 inferrepo=True,
2795 inferrepo=True,
2796 )
2796 )
2797 def forget(ui, repo, *pats, **opts):
2797 def forget(ui, repo, *pats, **opts):
2798 """forget the specified files on the next commit
2798 """forget the specified files on the next commit
2799
2799
2800 Mark the specified files so they will no longer be tracked
2800 Mark the specified files so they will no longer be tracked
2801 after the next commit.
2801 after the next commit.
2802
2802
2803 This only removes files from the current branch, not from the
2803 This only removes files from the current branch, not from the
2804 entire project history, and it does not delete them from the
2804 entire project history, and it does not delete them from the
2805 working directory.
2805 working directory.
2806
2806
2807 To delete the file from the working directory, see :hg:`remove`.
2807 To delete the file from the working directory, see :hg:`remove`.
2808
2808
2809 To undo a forget before the next commit, see :hg:`add`.
2809 To undo a forget before the next commit, see :hg:`add`.
2810
2810
2811 .. container:: verbose
2811 .. container:: verbose
2812
2812
2813 Examples:
2813 Examples:
2814
2814
2815 - forget newly-added binary files::
2815 - forget newly-added binary files::
2816
2816
2817 hg forget "set:added() and binary()"
2817 hg forget "set:added() and binary()"
2818
2818
2819 - forget files that would be excluded by .hgignore::
2819 - forget files that would be excluded by .hgignore::
2820
2820
2821 hg forget "set:hgignore()"
2821 hg forget "set:hgignore()"
2822
2822
2823 Returns 0 on success.
2823 Returns 0 on success.
2824 """
2824 """
2825
2825
2826 opts = pycompat.byteskwargs(opts)
2826 opts = pycompat.byteskwargs(opts)
2827 if not pats:
2827 if not pats:
2828 raise error.Abort(_(b'no files specified'))
2828 raise error.Abort(_(b'no files specified'))
2829
2829
2830 m = scmutil.match(repo[None], pats, opts)
2830 m = scmutil.match(repo[None], pats, opts)
2831 dryrun, interactive = opts.get(b'dry_run'), opts.get(b'interactive')
2831 dryrun, interactive = opts.get(b'dry_run'), opts.get(b'interactive')
2832 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
2832 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
2833 rejected = cmdutil.forget(
2833 rejected = cmdutil.forget(
2834 ui,
2834 ui,
2835 repo,
2835 repo,
2836 m,
2836 m,
2837 prefix=b"",
2837 prefix=b"",
2838 uipathfn=uipathfn,
2838 uipathfn=uipathfn,
2839 explicitonly=False,
2839 explicitonly=False,
2840 dryrun=dryrun,
2840 dryrun=dryrun,
2841 interactive=interactive,
2841 interactive=interactive,
2842 )[0]
2842 )[0]
2843 return rejected and 1 or 0
2843 return rejected and 1 or 0
2844
2844
2845
2845
2846 @command(
2846 @command(
2847 b'graft',
2847 b'graft',
2848 [
2848 [
2849 (b'r', b'rev', [], _(b'revisions to graft'), _(b'REV')),
2849 (b'r', b'rev', [], _(b'revisions to graft'), _(b'REV')),
2850 (
2850 (
2851 b'',
2851 b'',
2852 b'base',
2852 b'base',
2853 b'',
2853 b'',
2854 _(b'base revision when doing the graft merge (ADVANCED)'),
2854 _(b'base revision when doing the graft merge (ADVANCED)'),
2855 _(b'REV'),
2855 _(b'REV'),
2856 ),
2856 ),
2857 (b'c', b'continue', False, _(b'resume interrupted graft')),
2857 (b'c', b'continue', False, _(b'resume interrupted graft')),
2858 (b'', b'stop', False, _(b'stop interrupted graft')),
2858 (b'', b'stop', False, _(b'stop interrupted graft')),
2859 (b'', b'abort', False, _(b'abort interrupted graft')),
2859 (b'', b'abort', False, _(b'abort interrupted graft')),
2860 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
2860 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
2861 (b'', b'log', None, _(b'append graft info to log message')),
2861 (b'', b'log', None, _(b'append graft info to log message')),
2862 (
2862 (
2863 b'',
2863 b'',
2864 b'no-commit',
2864 b'no-commit',
2865 None,
2865 None,
2866 _(b"don't commit, just apply the changes in working directory"),
2866 _(b"don't commit, just apply the changes in working directory"),
2867 ),
2867 ),
2868 (b'f', b'force', False, _(b'force graft')),
2868 (b'f', b'force', False, _(b'force graft')),
2869 (
2869 (
2870 b'D',
2870 b'D',
2871 b'currentdate',
2871 b'currentdate',
2872 False,
2872 False,
2873 _(b'record the current date as commit date'),
2873 _(b'record the current date as commit date'),
2874 ),
2874 ),
2875 (
2875 (
2876 b'U',
2876 b'U',
2877 b'currentuser',
2877 b'currentuser',
2878 False,
2878 False,
2879 _(b'record the current user as committer'),
2879 _(b'record the current user as committer'),
2880 ),
2880 ),
2881 ]
2881 ]
2882 + commitopts2
2882 + commitopts2
2883 + mergetoolopts
2883 + mergetoolopts
2884 + dryrunopts,
2884 + dryrunopts,
2885 _(b'[OPTION]... [-r REV]... REV...'),
2885 _(b'[OPTION]... [-r REV]... REV...'),
2886 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
2886 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
2887 )
2887 )
2888 def graft(ui, repo, *revs, **opts):
2888 def graft(ui, repo, *revs, **opts):
2889 '''copy changes from other branches onto the current branch
2889 '''copy changes from other branches onto the current branch
2890
2890
2891 This command uses Mercurial's merge logic to copy individual
2891 This command uses Mercurial's merge logic to copy individual
2892 changes from other branches without merging branches in the
2892 changes from other branches without merging branches in the
2893 history graph. This is sometimes known as 'backporting' or
2893 history graph. This is sometimes known as 'backporting' or
2894 'cherry-picking'. By default, graft will copy user, date, and
2894 'cherry-picking'. By default, graft will copy user, date, and
2895 description from the source changesets.
2895 description from the source changesets.
2896
2896
2897 Changesets that are ancestors of the current revision, that have
2897 Changesets that are ancestors of the current revision, that have
2898 already been grafted, or that are merges will be skipped.
2898 already been grafted, or that are merges will be skipped.
2899
2899
2900 If --log is specified, log messages will have a comment appended
2900 If --log is specified, log messages will have a comment appended
2901 of the form::
2901 of the form::
2902
2902
2903 (grafted from CHANGESETHASH)
2903 (grafted from CHANGESETHASH)
2904
2904
2905 If --force is specified, revisions will be grafted even if they
2905 If --force is specified, revisions will be grafted even if they
2906 are already ancestors of, or have been grafted to, the destination.
2906 are already ancestors of, or have been grafted to, the destination.
2907 This is useful when the revisions have since been backed out.
2907 This is useful when the revisions have since been backed out.
2908
2908
2909 If a graft merge results in conflicts, the graft process is
2909 If a graft merge results in conflicts, the graft process is
2910 interrupted so that the current merge can be manually resolved.
2910 interrupted so that the current merge can be manually resolved.
2911 Once all conflicts are addressed, the graft process can be
2911 Once all conflicts are addressed, the graft process can be
2912 continued with the -c/--continue option.
2912 continued with the -c/--continue option.
2913
2913
2914 The -c/--continue option reapplies all the earlier options.
2914 The -c/--continue option reapplies all the earlier options.
2915
2915
2916 .. container:: verbose
2916 .. container:: verbose
2917
2917
2918 The --base option exposes more of how graft internally uses merge with a
2918 The --base option exposes more of how graft internally uses merge with a
2919 custom base revision. --base can be used to specify another ancestor than
2919 custom base revision. --base can be used to specify another ancestor than
2920 the first and only parent.
2920 the first and only parent.
2921
2921
2922 The command::
2922 The command::
2923
2923
2924 hg graft -r 345 --base 234
2924 hg graft -r 345 --base 234
2925
2925
2926 is thus pretty much the same as::
2926 is thus pretty much the same as::
2927
2927
2928 hg diff -r 234 -r 345 | hg import
2928 hg diff -r 234 -r 345 | hg import
2929
2929
2930 but using merge to resolve conflicts and track moved files.
2930 but using merge to resolve conflicts and track moved files.
2931
2931
2932 The result of a merge can thus be backported as a single commit by
2932 The result of a merge can thus be backported as a single commit by
2933 specifying one of the merge parents as base, and thus effectively
2933 specifying one of the merge parents as base, and thus effectively
2934 grafting the changes from the other side.
2934 grafting the changes from the other side.
2935
2935
2936 It is also possible to collapse multiple changesets and clean up history
2936 It is also possible to collapse multiple changesets and clean up history
2937 by specifying another ancestor as base, much like rebase --collapse
2937 by specifying another ancestor as base, much like rebase --collapse
2938 --keep.
2938 --keep.
2939
2939
2940 The commit message can be tweaked after the fact using commit --amend .
2940 The commit message can be tweaked after the fact using commit --amend .
2941
2941
2942 For using non-ancestors as the base to backout changes, see the backout
2942 For using non-ancestors as the base to backout changes, see the backout
2943 command and the hidden --parent option.
2943 command and the hidden --parent option.
2944
2944
2945 .. container:: verbose
2945 .. container:: verbose
2946
2946
2947 Examples:
2947 Examples:
2948
2948
2949 - copy a single change to the stable branch and edit its description::
2949 - copy a single change to the stable branch and edit its description::
2950
2950
2951 hg update stable
2951 hg update stable
2952 hg graft --edit 9393
2952 hg graft --edit 9393
2953
2953
2954 - graft a range of changesets with one exception, updating dates::
2954 - graft a range of changesets with one exception, updating dates::
2955
2955
2956 hg graft -D "2085::2093 and not 2091"
2956 hg graft -D "2085::2093 and not 2091"
2957
2957
2958 - continue a graft after resolving conflicts::
2958 - continue a graft after resolving conflicts::
2959
2959
2960 hg graft -c
2960 hg graft -c
2961
2961
2962 - show the source of a grafted changeset::
2962 - show the source of a grafted changeset::
2963
2963
2964 hg log --debug -r .
2964 hg log --debug -r .
2965
2965
2966 - show revisions sorted by date::
2966 - show revisions sorted by date::
2967
2967
2968 hg log -r "sort(all(), date)"
2968 hg log -r "sort(all(), date)"
2969
2969
2970 - backport the result of a merge as a single commit::
2970 - backport the result of a merge as a single commit::
2971
2971
2972 hg graft -r 123 --base 123^
2972 hg graft -r 123 --base 123^
2973
2973
2974 - land a feature branch as one changeset::
2974 - land a feature branch as one changeset::
2975
2975
2976 hg up -cr default
2976 hg up -cr default
2977 hg graft -r featureX --base "ancestor('featureX', 'default')"
2977 hg graft -r featureX --base "ancestor('featureX', 'default')"
2978
2978
2979 See :hg:`help revisions` for more about specifying revisions.
2979 See :hg:`help revisions` for more about specifying revisions.
2980
2980
2981 Returns 0 on successful completion, 1 if there are unresolved files.
2981 Returns 0 on successful completion, 1 if there are unresolved files.
2982 '''
2982 '''
2983 with repo.wlock():
2983 with repo.wlock():
2984 return _dograft(ui, repo, *revs, **opts)
2984 return _dograft(ui, repo, *revs, **opts)
2985
2985
2986
2986
2987 def _dograft(ui, repo, *revs, **opts):
2987 def _dograft(ui, repo, *revs, **opts):
2988 opts = pycompat.byteskwargs(opts)
2988 opts = pycompat.byteskwargs(opts)
2989 if revs and opts.get(b'rev'):
2989 if revs and opts.get(b'rev'):
2990 ui.warn(
2990 ui.warn(
2991 _(
2991 _(
2992 b'warning: inconsistent use of --rev might give unexpected '
2992 b'warning: inconsistent use of --rev might give unexpected '
2993 b'revision ordering!\n'
2993 b'revision ordering!\n'
2994 )
2994 )
2995 )
2995 )
2996
2996
2997 revs = list(revs)
2997 revs = list(revs)
2998 revs.extend(opts.get(b'rev'))
2998 revs.extend(opts.get(b'rev'))
2999 # a dict of data to be stored in state file
2999 # a dict of data to be stored in state file
3000 statedata = {}
3000 statedata = {}
3001 # list of new nodes created by ongoing graft
3001 # list of new nodes created by ongoing graft
3002 statedata[b'newnodes'] = []
3002 statedata[b'newnodes'] = []
3003
3003
3004 cmdutil.resolvecommitoptions(ui, opts)
3004 cmdutil.resolvecommitoptions(ui, opts)
3005
3005
3006 editor = cmdutil.getcommiteditor(
3006 editor = cmdutil.getcommiteditor(
3007 editform=b'graft', **pycompat.strkwargs(opts)
3007 editform=b'graft', **pycompat.strkwargs(opts)
3008 )
3008 )
3009
3009
3010 cmdutil.check_at_most_one_arg(opts, b'abort', b'stop', b'continue')
3010 cmdutil.check_at_most_one_arg(opts, b'abort', b'stop', b'continue')
3011
3011
3012 cont = False
3012 cont = False
3013 if opts.get(b'no_commit'):
3013 if opts.get(b'no_commit'):
3014 cmdutil.check_incompatible_arguments(
3014 cmdutil.check_incompatible_arguments(
3015 opts,
3015 opts,
3016 b'no_commit',
3016 b'no_commit',
3017 [b'edit', b'currentuser', b'currentdate', b'log'],
3017 [b'edit', b'currentuser', b'currentdate', b'log'],
3018 )
3018 )
3019
3019
3020 graftstate = statemod.cmdstate(repo, b'graftstate')
3020 graftstate = statemod.cmdstate(repo, b'graftstate')
3021
3021
3022 if opts.get(b'stop'):
3022 if opts.get(b'stop'):
3023 cmdutil.check_incompatible_arguments(
3023 cmdutil.check_incompatible_arguments(
3024 opts,
3024 opts,
3025 b'stop',
3025 b'stop',
3026 [
3026 [
3027 b'edit',
3027 b'edit',
3028 b'log',
3028 b'log',
3029 b'user',
3029 b'user',
3030 b'date',
3030 b'date',
3031 b'currentdate',
3031 b'currentdate',
3032 b'currentuser',
3032 b'currentuser',
3033 b'rev',
3033 b'rev',
3034 ],
3034 ],
3035 )
3035 )
3036 return _stopgraft(ui, repo, graftstate)
3036 return _stopgraft(ui, repo, graftstate)
3037 elif opts.get(b'abort'):
3037 elif opts.get(b'abort'):
3038 cmdutil.check_incompatible_arguments(
3038 cmdutil.check_incompatible_arguments(
3039 opts,
3039 opts,
3040 b'abort',
3040 b'abort',
3041 [
3041 [
3042 b'edit',
3042 b'edit',
3043 b'log',
3043 b'log',
3044 b'user',
3044 b'user',
3045 b'date',
3045 b'date',
3046 b'currentdate',
3046 b'currentdate',
3047 b'currentuser',
3047 b'currentuser',
3048 b'rev',
3048 b'rev',
3049 ],
3049 ],
3050 )
3050 )
3051 return cmdutil.abortgraft(ui, repo, graftstate)
3051 return cmdutil.abortgraft(ui, repo, graftstate)
3052 elif opts.get(b'continue'):
3052 elif opts.get(b'continue'):
3053 cont = True
3053 cont = True
3054 if revs:
3054 if revs:
3055 raise error.Abort(_(b"can't specify --continue and revisions"))
3055 raise error.Abort(_(b"can't specify --continue and revisions"))
3056 # read in unfinished revisions
3056 # read in unfinished revisions
3057 if graftstate.exists():
3057 if graftstate.exists():
3058 statedata = cmdutil.readgraftstate(repo, graftstate)
3058 statedata = cmdutil.readgraftstate(repo, graftstate)
3059 if statedata.get(b'date'):
3059 if statedata.get(b'date'):
3060 opts[b'date'] = statedata[b'date']
3060 opts[b'date'] = statedata[b'date']
3061 if statedata.get(b'user'):
3061 if statedata.get(b'user'):
3062 opts[b'user'] = statedata[b'user']
3062 opts[b'user'] = statedata[b'user']
3063 if statedata.get(b'log'):
3063 if statedata.get(b'log'):
3064 opts[b'log'] = True
3064 opts[b'log'] = True
3065 if statedata.get(b'no_commit'):
3065 if statedata.get(b'no_commit'):
3066 opts[b'no_commit'] = statedata.get(b'no_commit')
3066 opts[b'no_commit'] = statedata.get(b'no_commit')
3067 if statedata.get(b'base'):
3067 if statedata.get(b'base'):
3068 opts[b'base'] = statedata.get(b'base')
3068 opts[b'base'] = statedata.get(b'base')
3069 nodes = statedata[b'nodes']
3069 nodes = statedata[b'nodes']
3070 revs = [repo[node].rev() for node in nodes]
3070 revs = [repo[node].rev() for node in nodes]
3071 else:
3071 else:
3072 cmdutil.wrongtooltocontinue(repo, _(b'graft'))
3072 cmdutil.wrongtooltocontinue(repo, _(b'graft'))
3073 else:
3073 else:
3074 if not revs:
3074 if not revs:
3075 raise error.Abort(_(b'no revisions specified'))
3075 raise error.Abort(_(b'no revisions specified'))
3076 cmdutil.checkunfinished(repo)
3076 cmdutil.checkunfinished(repo)
3077 cmdutil.bailifchanged(repo)
3077 cmdutil.bailifchanged(repo)
3078 revs = scmutil.revrange(repo, revs)
3078 revs = scmutil.revrange(repo, revs)
3079
3079
3080 skipped = set()
3080 skipped = set()
3081 basectx = None
3081 basectx = None
3082 if opts.get(b'base'):
3082 if opts.get(b'base'):
3083 basectx = scmutil.revsingle(repo, opts[b'base'], None)
3083 basectx = scmutil.revsingle(repo, opts[b'base'], None)
3084 if basectx is None:
3084 if basectx is None:
3085 # check for merges
3085 # check for merges
3086 for rev in repo.revs(b'%ld and merge()', revs):
3086 for rev in repo.revs(b'%ld and merge()', revs):
3087 ui.warn(_(b'skipping ungraftable merge revision %d\n') % rev)
3087 ui.warn(_(b'skipping ungraftable merge revision %d\n') % rev)
3088 skipped.add(rev)
3088 skipped.add(rev)
3089 revs = [r for r in revs if r not in skipped]
3089 revs = [r for r in revs if r not in skipped]
3090 if not revs:
3090 if not revs:
3091 return -1
3091 return -1
3092 if basectx is not None and len(revs) != 1:
3092 if basectx is not None and len(revs) != 1:
3093 raise error.Abort(_(b'only one revision allowed with --base '))
3093 raise error.Abort(_(b'only one revision allowed with --base '))
3094
3094
3095 # Don't check in the --continue case, in effect retaining --force across
3095 # Don't check in the --continue case, in effect retaining --force across
3096 # --continues. That's because without --force, any revisions we decided to
3096 # --continues. That's because without --force, any revisions we decided to
3097 # skip would have been filtered out here, so they wouldn't have made their
3097 # skip would have been filtered out here, so they wouldn't have made their
3098 # way to the graftstate. With --force, any revisions we would have otherwise
3098 # way to the graftstate. With --force, any revisions we would have otherwise
3099 # skipped would not have been filtered out, and if they hadn't been applied
3099 # skipped would not have been filtered out, and if they hadn't been applied
3100 # already, they'd have been in the graftstate.
3100 # already, they'd have been in the graftstate.
3101 if not (cont or opts.get(b'force')) and basectx is None:
3101 if not (cont or opts.get(b'force')) and basectx is None:
3102 # check for ancestors of dest branch
3102 # check for ancestors of dest branch
3103 ancestors = repo.revs(b'%ld & (::.)', revs)
3103 ancestors = repo.revs(b'%ld & (::.)', revs)
3104 for rev in ancestors:
3104 for rev in ancestors:
3105 ui.warn(_(b'skipping ancestor revision %d:%s\n') % (rev, repo[rev]))
3105 ui.warn(_(b'skipping ancestor revision %d:%s\n') % (rev, repo[rev]))
3106
3106
3107 revs = [r for r in revs if r not in ancestors]
3107 revs = [r for r in revs if r not in ancestors]
3108
3108
3109 if not revs:
3109 if not revs:
3110 return -1
3110 return -1
3111
3111
3112 # analyze revs for earlier grafts
3112 # analyze revs for earlier grafts
3113 ids = {}
3113 ids = {}
3114 for ctx in repo.set(b"%ld", revs):
3114 for ctx in repo.set(b"%ld", revs):
3115 ids[ctx.hex()] = ctx.rev()
3115 ids[ctx.hex()] = ctx.rev()
3116 n = ctx.extra().get(b'source')
3116 n = ctx.extra().get(b'source')
3117 if n:
3117 if n:
3118 ids[n] = ctx.rev()
3118 ids[n] = ctx.rev()
3119
3119
3120 # check ancestors for earlier grafts
3120 # check ancestors for earlier grafts
3121 ui.debug(b'scanning for duplicate grafts\n')
3121 ui.debug(b'scanning for duplicate grafts\n')
3122
3122
3123 # The only changesets we can be sure doesn't contain grafts of any
3123 # The only changesets we can be sure doesn't contain grafts of any
3124 # revs, are the ones that are common ancestors of *all* revs:
3124 # revs, are the ones that are common ancestors of *all* revs:
3125 for rev in repo.revs(b'only(%d,ancestor(%ld))', repo[b'.'].rev(), revs):
3125 for rev in repo.revs(b'only(%d,ancestor(%ld))', repo[b'.'].rev(), revs):
3126 ctx = repo[rev]
3126 ctx = repo[rev]
3127 n = ctx.extra().get(b'source')
3127 n = ctx.extra().get(b'source')
3128 if n in ids:
3128 if n in ids:
3129 try:
3129 try:
3130 r = repo[n].rev()
3130 r = repo[n].rev()
3131 except error.RepoLookupError:
3131 except error.RepoLookupError:
3132 r = None
3132 r = None
3133 if r in revs:
3133 if r in revs:
3134 ui.warn(
3134 ui.warn(
3135 _(
3135 _(
3136 b'skipping revision %d:%s '
3136 b'skipping revision %d:%s '
3137 b'(already grafted to %d:%s)\n'
3137 b'(already grafted to %d:%s)\n'
3138 )
3138 )
3139 % (r, repo[r], rev, ctx)
3139 % (r, repo[r], rev, ctx)
3140 )
3140 )
3141 revs.remove(r)
3141 revs.remove(r)
3142 elif ids[n] in revs:
3142 elif ids[n] in revs:
3143 if r is None:
3143 if r is None:
3144 ui.warn(
3144 ui.warn(
3145 _(
3145 _(
3146 b'skipping already grafted revision %d:%s '
3146 b'skipping already grafted revision %d:%s '
3147 b'(%d:%s also has unknown origin %s)\n'
3147 b'(%d:%s also has unknown origin %s)\n'
3148 )
3148 )
3149 % (ids[n], repo[ids[n]], rev, ctx, n[:12])
3149 % (ids[n], repo[ids[n]], rev, ctx, n[:12])
3150 )
3150 )
3151 else:
3151 else:
3152 ui.warn(
3152 ui.warn(
3153 _(
3153 _(
3154 b'skipping already grafted revision %d:%s '
3154 b'skipping already grafted revision %d:%s '
3155 b'(%d:%s also has origin %d:%s)\n'
3155 b'(%d:%s also has origin %d:%s)\n'
3156 )
3156 )
3157 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12])
3157 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12])
3158 )
3158 )
3159 revs.remove(ids[n])
3159 revs.remove(ids[n])
3160 elif ctx.hex() in ids:
3160 elif ctx.hex() in ids:
3161 r = ids[ctx.hex()]
3161 r = ids[ctx.hex()]
3162 if r in revs:
3162 if r in revs:
3163 ui.warn(
3163 ui.warn(
3164 _(
3164 _(
3165 b'skipping already grafted revision %d:%s '
3165 b'skipping already grafted revision %d:%s '
3166 b'(was grafted from %d:%s)\n'
3166 b'(was grafted from %d:%s)\n'
3167 )
3167 )
3168 % (r, repo[r], rev, ctx)
3168 % (r, repo[r], rev, ctx)
3169 )
3169 )
3170 revs.remove(r)
3170 revs.remove(r)
3171 if not revs:
3171 if not revs:
3172 return -1
3172 return -1
3173
3173
3174 if opts.get(b'no_commit'):
3174 if opts.get(b'no_commit'):
3175 statedata[b'no_commit'] = True
3175 statedata[b'no_commit'] = True
3176 if opts.get(b'base'):
3176 if opts.get(b'base'):
3177 statedata[b'base'] = opts[b'base']
3177 statedata[b'base'] = opts[b'base']
3178 for pos, ctx in enumerate(repo.set(b"%ld", revs)):
3178 for pos, ctx in enumerate(repo.set(b"%ld", revs)):
3179 desc = b'%d:%s "%s"' % (
3179 desc = b'%d:%s "%s"' % (
3180 ctx.rev(),
3180 ctx.rev(),
3181 ctx,
3181 ctx,
3182 ctx.description().split(b'\n', 1)[0],
3182 ctx.description().split(b'\n', 1)[0],
3183 )
3183 )
3184 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
3184 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
3185 if names:
3185 if names:
3186 desc += b' (%s)' % b' '.join(names)
3186 desc += b' (%s)' % b' '.join(names)
3187 ui.status(_(b'grafting %s\n') % desc)
3187 ui.status(_(b'grafting %s\n') % desc)
3188 if opts.get(b'dry_run'):
3188 if opts.get(b'dry_run'):
3189 continue
3189 continue
3190
3190
3191 source = ctx.extra().get(b'source')
3191 source = ctx.extra().get(b'source')
3192 extra = {}
3192 extra = {}
3193 if source:
3193 if source:
3194 extra[b'source'] = source
3194 extra[b'source'] = source
3195 extra[b'intermediate-source'] = ctx.hex()
3195 extra[b'intermediate-source'] = ctx.hex()
3196 else:
3196 else:
3197 extra[b'source'] = ctx.hex()
3197 extra[b'source'] = ctx.hex()
3198 user = ctx.user()
3198 user = ctx.user()
3199 if opts.get(b'user'):
3199 if opts.get(b'user'):
3200 user = opts[b'user']
3200 user = opts[b'user']
3201 statedata[b'user'] = user
3201 statedata[b'user'] = user
3202 date = ctx.date()
3202 date = ctx.date()
3203 if opts.get(b'date'):
3203 if opts.get(b'date'):
3204 date = opts[b'date']
3204 date = opts[b'date']
3205 statedata[b'date'] = date
3205 statedata[b'date'] = date
3206 message = ctx.description()
3206 message = ctx.description()
3207 if opts.get(b'log'):
3207 if opts.get(b'log'):
3208 message += b'\n(grafted from %s)' % ctx.hex()
3208 message += b'\n(grafted from %s)' % ctx.hex()
3209 statedata[b'log'] = True
3209 statedata[b'log'] = True
3210
3210
3211 # we don't merge the first commit when continuing
3211 # we don't merge the first commit when continuing
3212 if not cont:
3212 if not cont:
3213 # perform the graft merge with p1(rev) as 'ancestor'
3213 # perform the graft merge with p1(rev) as 'ancestor'
3214 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
3214 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
3215 base = ctx.p1() if basectx is None else basectx
3215 base = ctx.p1() if basectx is None else basectx
3216 with ui.configoverride(overrides, b'graft'):
3216 with ui.configoverride(overrides, b'graft'):
3217 stats = mergemod.graft(repo, ctx, base, [b'local', b'graft'])
3217 stats = mergemod.graft(repo, ctx, base, [b'local', b'graft'])
3218 # report any conflicts
3218 # report any conflicts
3219 if stats.unresolvedcount > 0:
3219 if stats.unresolvedcount > 0:
3220 # write out state for --continue
3220 # write out state for --continue
3221 nodes = [repo[rev].hex() for rev in revs[pos:]]
3221 nodes = [repo[rev].hex() for rev in revs[pos:]]
3222 statedata[b'nodes'] = nodes
3222 statedata[b'nodes'] = nodes
3223 stateversion = 1
3223 stateversion = 1
3224 graftstate.save(stateversion, statedata)
3224 graftstate.save(stateversion, statedata)
3225 ui.error(_(b"abort: unresolved conflicts, can't continue\n"))
3225 ui.error(_(b"abort: unresolved conflicts, can't continue\n"))
3226 ui.error(_(b"(use 'hg resolve' and 'hg graft --continue')\n"))
3226 ui.error(_(b"(use 'hg resolve' and 'hg graft --continue')\n"))
3227 return 1
3227 return 1
3228 else:
3228 else:
3229 cont = False
3229 cont = False
3230
3230
3231 # commit if --no-commit is false
3231 # commit if --no-commit is false
3232 if not opts.get(b'no_commit'):
3232 if not opts.get(b'no_commit'):
3233 node = repo.commit(
3233 node = repo.commit(
3234 text=message, user=user, date=date, extra=extra, editor=editor
3234 text=message, user=user, date=date, extra=extra, editor=editor
3235 )
3235 )
3236 if node is None:
3236 if node is None:
3237 ui.warn(
3237 ui.warn(
3238 _(b'note: graft of %d:%s created no changes to commit\n')
3238 _(b'note: graft of %d:%s created no changes to commit\n')
3239 % (ctx.rev(), ctx)
3239 % (ctx.rev(), ctx)
3240 )
3240 )
3241 # checking that newnodes exist because old state files won't have it
3241 # checking that newnodes exist because old state files won't have it
3242 elif statedata.get(b'newnodes') is not None:
3242 elif statedata.get(b'newnodes') is not None:
3243 statedata[b'newnodes'].append(node)
3243 statedata[b'newnodes'].append(node)
3244
3244
3245 # remove state when we complete successfully
3245 # remove state when we complete successfully
3246 if not opts.get(b'dry_run'):
3246 if not opts.get(b'dry_run'):
3247 graftstate.delete()
3247 graftstate.delete()
3248
3248
3249 return 0
3249 return 0
3250
3250
3251
3251
3252 def _stopgraft(ui, repo, graftstate):
3252 def _stopgraft(ui, repo, graftstate):
3253 """stop the interrupted graft"""
3253 """stop the interrupted graft"""
3254 if not graftstate.exists():
3254 if not graftstate.exists():
3255 raise error.Abort(_(b"no interrupted graft found"))
3255 raise error.Abort(_(b"no interrupted graft found"))
3256 pctx = repo[b'.']
3256 pctx = repo[b'.']
3257 mergemod.clean_update(pctx)
3257 mergemod.clean_update(pctx)
3258 graftstate.delete()
3258 graftstate.delete()
3259 ui.status(_(b"stopped the interrupted graft\n"))
3259 ui.status(_(b"stopped the interrupted graft\n"))
3260 ui.status(_(b"working directory is now at %s\n") % pctx.hex()[:12])
3260 ui.status(_(b"working directory is now at %s\n") % pctx.hex()[:12])
3261 return 0
3261 return 0
3262
3262
3263
3263
3264 statemod.addunfinished(
3264 statemod.addunfinished(
3265 b'graft',
3265 b'graft',
3266 fname=b'graftstate',
3266 fname=b'graftstate',
3267 clearable=True,
3267 clearable=True,
3268 stopflag=True,
3268 stopflag=True,
3269 continueflag=True,
3269 continueflag=True,
3270 abortfunc=cmdutil.hgabortgraft,
3270 abortfunc=cmdutil.hgabortgraft,
3271 cmdhint=_(b"use 'hg graft --continue' or 'hg graft --stop' to stop"),
3271 cmdhint=_(b"use 'hg graft --continue' or 'hg graft --stop' to stop"),
3272 )
3272 )
3273
3273
3274
3274
3275 @command(
3275 @command(
3276 b'grep',
3276 b'grep',
3277 [
3277 [
3278 (b'0', b'print0', None, _(b'end fields with NUL')),
3278 (b'0', b'print0', None, _(b'end fields with NUL')),
3279 (b'', b'all', None, _(b'an alias to --diff (DEPRECATED)')),
3279 (b'', b'all', None, _(b'an alias to --diff (DEPRECATED)')),
3280 (
3280 (
3281 b'',
3281 b'',
3282 b'diff',
3282 b'diff',
3283 None,
3283 None,
3284 _(
3284 _(
3285 b'search revision differences for when the pattern was added '
3285 b'search revision differences for when the pattern was added '
3286 b'or removed'
3286 b'or removed'
3287 ),
3287 ),
3288 ),
3288 ),
3289 (b'a', b'text', None, _(b'treat all files as text')),
3289 (b'a', b'text', None, _(b'treat all files as text')),
3290 (
3290 (
3291 b'f',
3291 b'f',
3292 b'follow',
3292 b'follow',
3293 None,
3293 None,
3294 _(
3294 _(
3295 b'follow changeset history,'
3295 b'follow changeset history,'
3296 b' or file history across copies and renames'
3296 b' or file history across copies and renames'
3297 ),
3297 ),
3298 ),
3298 ),
3299 (b'i', b'ignore-case', None, _(b'ignore case when matching')),
3299 (b'i', b'ignore-case', None, _(b'ignore case when matching')),
3300 (
3300 (
3301 b'l',
3301 b'l',
3302 b'files-with-matches',
3302 b'files-with-matches',
3303 None,
3303 None,
3304 _(b'print only filenames and revisions that match'),
3304 _(b'print only filenames and revisions that match'),
3305 ),
3305 ),
3306 (b'n', b'line-number', None, _(b'print matching line numbers')),
3306 (b'n', b'line-number', None, _(b'print matching line numbers')),
3307 (
3307 (
3308 b'r',
3308 b'r',
3309 b'rev',
3309 b'rev',
3310 [],
3310 [],
3311 _(b'search files changed within revision range'),
3311 _(b'search files changed within revision range'),
3312 _(b'REV'),
3312 _(b'REV'),
3313 ),
3313 ),
3314 (
3314 (
3315 b'',
3315 b'',
3316 b'all-files',
3316 b'all-files',
3317 None,
3317 None,
3318 _(
3318 _(
3319 b'include all files in the changeset while grepping (DEPRECATED)'
3319 b'include all files in the changeset while grepping (DEPRECATED)'
3320 ),
3320 ),
3321 ),
3321 ),
3322 (b'u', b'user', None, _(b'list the author (long with -v)')),
3322 (b'u', b'user', None, _(b'list the author (long with -v)')),
3323 (b'd', b'date', None, _(b'list the date (short with -q)')),
3323 (b'd', b'date', None, _(b'list the date (short with -q)')),
3324 ]
3324 ]
3325 + formatteropts
3325 + formatteropts
3326 + walkopts,
3326 + walkopts,
3327 _(b'[--diff] [OPTION]... PATTERN [FILE]...'),
3327 _(b'[--diff] [OPTION]... PATTERN [FILE]...'),
3328 helpcategory=command.CATEGORY_FILE_CONTENTS,
3328 helpcategory=command.CATEGORY_FILE_CONTENTS,
3329 inferrepo=True,
3329 inferrepo=True,
3330 intents={INTENT_READONLY},
3330 intents={INTENT_READONLY},
3331 )
3331 )
3332 def grep(ui, repo, pattern, *pats, **opts):
3332 def grep(ui, repo, pattern, *pats, **opts):
3333 """search for a pattern in specified files
3333 """search for a pattern in specified files
3334
3334
3335 Search the working directory or revision history for a regular
3335 Search the working directory or revision history for a regular
3336 expression in the specified files for the entire repository.
3336 expression in the specified files for the entire repository.
3337
3337
3338 By default, grep searches the repository files in the working
3338 By default, grep searches the repository files in the working
3339 directory and prints the files where it finds a match. To specify
3339 directory and prints the files where it finds a match. To specify
3340 historical revisions instead of the working directory, use the
3340 historical revisions instead of the working directory, use the
3341 --rev flag.
3341 --rev flag.
3342
3342
3343 To search instead historical revision differences that contains a
3343 To search instead historical revision differences that contains a
3344 change in match status ("-" for a match that becomes a non-match,
3344 change in match status ("-" for a match that becomes a non-match,
3345 or "+" for a non-match that becomes a match), use the --diff flag.
3345 or "+" for a non-match that becomes a match), use the --diff flag.
3346
3346
3347 PATTERN can be any Python (roughly Perl-compatible) regular
3347 PATTERN can be any Python (roughly Perl-compatible) regular
3348 expression.
3348 expression.
3349
3349
3350 If no FILEs are specified and the --rev flag isn't supplied, all
3350 If no FILEs are specified and the --rev flag isn't supplied, all
3351 files in the working directory are searched. When using the --rev
3351 files in the working directory are searched. When using the --rev
3352 flag and specifying FILEs, use the --follow argument to also
3352 flag and specifying FILEs, use the --follow argument to also
3353 follow the specified FILEs across renames and copies.
3353 follow the specified FILEs across renames and copies.
3354
3354
3355 .. container:: verbose
3355 .. container:: verbose
3356
3356
3357 Template:
3357 Template:
3358
3358
3359 The following keywords are supported in addition to the common template
3359 The following keywords are supported in addition to the common template
3360 keywords and functions. See also :hg:`help templates`.
3360 keywords and functions. See also :hg:`help templates`.
3361
3361
3362 :change: String. Character denoting insertion ``+`` or removal ``-``.
3362 :change: String. Character denoting insertion ``+`` or removal ``-``.
3363 Available if ``--diff`` is specified.
3363 Available if ``--diff`` is specified.
3364 :lineno: Integer. Line number of the match.
3364 :lineno: Integer. Line number of the match.
3365 :path: String. Repository-absolute path of the file.
3365 :path: String. Repository-absolute path of the file.
3366 :texts: List of text chunks.
3366 :texts: List of text chunks.
3367
3367
3368 And each entry of ``{texts}`` provides the following sub-keywords.
3368 And each entry of ``{texts}`` provides the following sub-keywords.
3369
3369
3370 :matched: Boolean. True if the chunk matches the specified pattern.
3370 :matched: Boolean. True if the chunk matches the specified pattern.
3371 :text: String. Chunk content.
3371 :text: String. Chunk content.
3372
3372
3373 See :hg:`help templates.operators` for the list expansion syntax.
3373 See :hg:`help templates.operators` for the list expansion syntax.
3374
3374
3375 Returns 0 if a match is found, 1 otherwise.
3375 Returns 0 if a match is found, 1 otherwise.
3376
3376
3377 """
3377 """
3378 cmdutil.check_incompatible_arguments(opts, 'all_files', ['all', 'diff'])
3378 cmdutil.check_incompatible_arguments(opts, 'all_files', ['all', 'diff'])
3379 opts = pycompat.byteskwargs(opts)
3379 opts = pycompat.byteskwargs(opts)
3380 diff = opts.get(b'all') or opts.get(b'diff')
3380 diff = opts.get(b'all') or opts.get(b'diff')
3381 follow = opts.get(b'follow')
3381 follow = opts.get(b'follow')
3382 if opts.get(b'all_files') is None and not diff:
3382 if opts.get(b'all_files') is None and not diff:
3383 opts[b'all_files'] = True
3383 opts[b'all_files'] = True
3384 plaingrep = (
3384 plaingrep = (
3385 opts.get(b'all_files')
3385 opts.get(b'all_files')
3386 and not opts.get(b'rev')
3386 and not opts.get(b'rev')
3387 and not opts.get(b'follow')
3387 and not opts.get(b'follow')
3388 )
3388 )
3389 all_files = opts.get(b'all_files')
3389 all_files = opts.get(b'all_files')
3390 if plaingrep:
3390 if plaingrep:
3391 opts[b'rev'] = [b'wdir()']
3391 opts[b'rev'] = [b'wdir()']
3392
3392
3393 reflags = re.M
3393 reflags = re.M
3394 if opts.get(b'ignore_case'):
3394 if opts.get(b'ignore_case'):
3395 reflags |= re.I
3395 reflags |= re.I
3396 try:
3396 try:
3397 regexp = util.re.compile(pattern, reflags)
3397 regexp = util.re.compile(pattern, reflags)
3398 except re.error as inst:
3398 except re.error as inst:
3399 ui.warn(
3399 ui.warn(
3400 _(b"grep: invalid match pattern: %s\n") % pycompat.bytestr(inst)
3400 _(b"grep: invalid match pattern: %s\n") % pycompat.bytestr(inst)
3401 )
3401 )
3402 return 1
3402 return 1
3403 sep, eol = b':', b'\n'
3403 sep, eol = b':', b'\n'
3404 if opts.get(b'print0'):
3404 if opts.get(b'print0'):
3405 sep = eol = b'\0'
3405 sep = eol = b'\0'
3406
3406
3407 searcher = grepmod.grepsearcher(
3407 searcher = grepmod.grepsearcher(
3408 ui, repo, regexp, all_files=all_files, diff=diff, follow=follow
3408 ui, repo, regexp, all_files=all_files, diff=diff, follow=follow
3409 )
3409 )
3410
3410
3411 getfile = searcher._getfile
3411 getfile = searcher._getfile
3412
3412
3413 uipathfn = scmutil.getuipathfn(repo)
3413 uipathfn = scmutil.getuipathfn(repo)
3414
3414
3415 def display(fm, fn, ctx, pstates, states):
3415 def display(fm, fn, ctx, pstates, states):
3416 rev = scmutil.intrev(ctx)
3416 rev = scmutil.intrev(ctx)
3417 if fm.isplain():
3417 if fm.isplain():
3418 formatuser = ui.shortuser
3418 formatuser = ui.shortuser
3419 else:
3419 else:
3420 formatuser = pycompat.bytestr
3420 formatuser = pycompat.bytestr
3421 if ui.quiet:
3421 if ui.quiet:
3422 datefmt = b'%Y-%m-%d'
3422 datefmt = b'%Y-%m-%d'
3423 else:
3423 else:
3424 datefmt = b'%a %b %d %H:%M:%S %Y %1%2'
3424 datefmt = b'%a %b %d %H:%M:%S %Y %1%2'
3425 found = False
3425 found = False
3426
3426
3427 @util.cachefunc
3427 @util.cachefunc
3428 def binary():
3428 def binary():
3429 flog = getfile(fn)
3429 flog = getfile(fn)
3430 try:
3430 try:
3431 return stringutil.binary(flog.read(ctx.filenode(fn)))
3431 return stringutil.binary(flog.read(ctx.filenode(fn)))
3432 except error.WdirUnsupported:
3432 except error.WdirUnsupported:
3433 return ctx[fn].isbinary()
3433 return ctx[fn].isbinary()
3434
3434
3435 fieldnamemap = {b'linenumber': b'lineno'}
3435 fieldnamemap = {b'linenumber': b'lineno'}
3436 if diff:
3436 if diff:
3437 iter = grepmod.difflinestates(pstates, states)
3437 iter = grepmod.difflinestates(pstates, states)
3438 else:
3438 else:
3439 iter = [(b'', l) for l in states]
3439 iter = [(b'', l) for l in states]
3440 for change, l in iter:
3440 for change, l in iter:
3441 fm.startitem()
3441 fm.startitem()
3442 fm.context(ctx=ctx)
3442 fm.context(ctx=ctx)
3443 fm.data(node=fm.hexfunc(scmutil.binnode(ctx)), path=fn)
3443 fm.data(node=fm.hexfunc(scmutil.binnode(ctx)), path=fn)
3444 fm.plain(uipathfn(fn), label=b'grep.filename')
3444 fm.plain(uipathfn(fn), label=b'grep.filename')
3445
3445
3446 cols = [
3446 cols = [
3447 (b'rev', b'%d', rev, not plaingrep, b''),
3447 (b'rev', b'%d', rev, not plaingrep, b''),
3448 (
3448 (
3449 b'linenumber',
3449 b'linenumber',
3450 b'%d',
3450 b'%d',
3451 l.linenum,
3451 l.linenum,
3452 opts.get(b'line_number'),
3452 opts.get(b'line_number'),
3453 b'',
3453 b'',
3454 ),
3454 ),
3455 ]
3455 ]
3456 if diff:
3456 if diff:
3457 cols.append(
3457 cols.append(
3458 (
3458 (
3459 b'change',
3459 b'change',
3460 b'%s',
3460 b'%s',
3461 change,
3461 change,
3462 True,
3462 True,
3463 b'grep.inserted '
3463 b'grep.inserted '
3464 if change == b'+'
3464 if change == b'+'
3465 else b'grep.deleted ',
3465 else b'grep.deleted ',
3466 )
3466 )
3467 )
3467 )
3468 cols.extend(
3468 cols.extend(
3469 [
3469 [
3470 (
3470 (
3471 b'user',
3471 b'user',
3472 b'%s',
3472 b'%s',
3473 formatuser(ctx.user()),
3473 formatuser(ctx.user()),
3474 opts.get(b'user'),
3474 opts.get(b'user'),
3475 b'',
3475 b'',
3476 ),
3476 ),
3477 (
3477 (
3478 b'date',
3478 b'date',
3479 b'%s',
3479 b'%s',
3480 fm.formatdate(ctx.date(), datefmt),
3480 fm.formatdate(ctx.date(), datefmt),
3481 opts.get(b'date'),
3481 opts.get(b'date'),
3482 b'',
3482 b'',
3483 ),
3483 ),
3484 ]
3484 ]
3485 )
3485 )
3486 for name, fmt, data, cond, extra_label in cols:
3486 for name, fmt, data, cond, extra_label in cols:
3487 if cond:
3487 if cond:
3488 fm.plain(sep, label=b'grep.sep')
3488 fm.plain(sep, label=b'grep.sep')
3489 field = fieldnamemap.get(name, name)
3489 field = fieldnamemap.get(name, name)
3490 label = extra_label + (b'grep.%s' % name)
3490 label = extra_label + (b'grep.%s' % name)
3491 fm.condwrite(cond, field, fmt, data, label=label)
3491 fm.condwrite(cond, field, fmt, data, label=label)
3492 if not opts.get(b'files_with_matches'):
3492 if not opts.get(b'files_with_matches'):
3493 fm.plain(sep, label=b'grep.sep')
3493 fm.plain(sep, label=b'grep.sep')
3494 if not opts.get(b'text') and binary():
3494 if not opts.get(b'text') and binary():
3495 fm.plain(_(b" Binary file matches"))
3495 fm.plain(_(b" Binary file matches"))
3496 else:
3496 else:
3497 displaymatches(fm.nested(b'texts', tmpl=b'{text}'), l)
3497 displaymatches(fm.nested(b'texts', tmpl=b'{text}'), l)
3498 fm.plain(eol)
3498 fm.plain(eol)
3499 found = True
3499 found = True
3500 if opts.get(b'files_with_matches'):
3500 if opts.get(b'files_with_matches'):
3501 break
3501 break
3502 return found
3502 return found
3503
3503
3504 def displaymatches(fm, l):
3504 def displaymatches(fm, l):
3505 p = 0
3505 p = 0
3506 for s, e in l.findpos(regexp):
3506 for s, e in l.findpos(regexp):
3507 if p < s:
3507 if p < s:
3508 fm.startitem()
3508 fm.startitem()
3509 fm.write(b'text', b'%s', l.line[p:s])
3509 fm.write(b'text', b'%s', l.line[p:s])
3510 fm.data(matched=False)
3510 fm.data(matched=False)
3511 fm.startitem()
3511 fm.startitem()
3512 fm.write(b'text', b'%s', l.line[s:e], label=b'grep.match')
3512 fm.write(b'text', b'%s', l.line[s:e], label=b'grep.match')
3513 fm.data(matched=True)
3513 fm.data(matched=True)
3514 p = e
3514 p = e
3515 if p < len(l.line):
3515 if p < len(l.line):
3516 fm.startitem()
3516 fm.startitem()
3517 fm.write(b'text', b'%s', l.line[p:])
3517 fm.write(b'text', b'%s', l.line[p:])
3518 fm.data(matched=False)
3518 fm.data(matched=False)
3519 fm.end()
3519 fm.end()
3520
3520
3521 found = False
3521 found = False
3522
3522
3523 wopts = logcmdutil.walkopts(
3523 wopts = logcmdutil.walkopts(
3524 pats=pats,
3524 pats=pats,
3525 opts=opts,
3525 opts=opts,
3526 revspec=opts[b'rev'],
3526 revspec=opts[b'rev'],
3527 include_pats=opts[b'include'],
3527 include_pats=opts[b'include'],
3528 exclude_pats=opts[b'exclude'],
3528 exclude_pats=opts[b'exclude'],
3529 follow=follow,
3529 follow=follow,
3530 force_changelog_traversal=all_files,
3530 force_changelog_traversal=all_files,
3531 filter_revisions_by_pats=not all_files,
3531 filter_revisions_by_pats=not all_files,
3532 )
3532 )
3533 revs, makefilematcher = logcmdutil.makewalker(repo, wopts)
3533 revs, makefilematcher = logcmdutil.makewalker(repo, wopts)
3534
3534
3535 ui.pager(b'grep')
3535 ui.pager(b'grep')
3536 fm = ui.formatter(b'grep', opts)
3536 fm = ui.formatter(b'grep', opts)
3537 for fn, ctx, pstates, states in searcher.searchfiles(revs, makefilematcher):
3537 for fn, ctx, pstates, states in searcher.searchfiles(revs, makefilematcher):
3538 r = display(fm, fn, ctx, pstates, states)
3538 r = display(fm, fn, ctx, pstates, states)
3539 found = found or r
3539 found = found or r
3540 if r and not diff and not all_files:
3540 if r and not diff and not all_files:
3541 searcher.skipfile(fn, ctx.rev())
3541 searcher.skipfile(fn, ctx.rev())
3542 fm.end()
3542 fm.end()
3543
3543
3544 return not found
3544 return not found
3545
3545
3546
3546
3547 @command(
3547 @command(
3548 b'heads',
3548 b'heads',
3549 [
3549 [
3550 (
3550 (
3551 b'r',
3551 b'r',
3552 b'rev',
3552 b'rev',
3553 b'',
3553 b'',
3554 _(b'show only heads which are descendants of STARTREV'),
3554 _(b'show only heads which are descendants of STARTREV'),
3555 _(b'STARTREV'),
3555 _(b'STARTREV'),
3556 ),
3556 ),
3557 (b't', b'topo', False, _(b'show topological heads only')),
3557 (b't', b'topo', False, _(b'show topological heads only')),
3558 (
3558 (
3559 b'a',
3559 b'a',
3560 b'active',
3560 b'active',
3561 False,
3561 False,
3562 _(b'show active branchheads only (DEPRECATED)'),
3562 _(b'show active branchheads only (DEPRECATED)'),
3563 ),
3563 ),
3564 (b'c', b'closed', False, _(b'show normal and closed branch heads')),
3564 (b'c', b'closed', False, _(b'show normal and closed branch heads')),
3565 ]
3565 ]
3566 + templateopts,
3566 + templateopts,
3567 _(b'[-ct] [-r STARTREV] [REV]...'),
3567 _(b'[-ct] [-r STARTREV] [REV]...'),
3568 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3568 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3569 intents={INTENT_READONLY},
3569 intents={INTENT_READONLY},
3570 )
3570 )
3571 def heads(ui, repo, *branchrevs, **opts):
3571 def heads(ui, repo, *branchrevs, **opts):
3572 """show branch heads
3572 """show branch heads
3573
3573
3574 With no arguments, show all open branch heads in the repository.
3574 With no arguments, show all open branch heads in the repository.
3575 Branch heads are changesets that have no descendants on the
3575 Branch heads are changesets that have no descendants on the
3576 same branch. They are where development generally takes place and
3576 same branch. They are where development generally takes place and
3577 are the usual targets for update and merge operations.
3577 are the usual targets for update and merge operations.
3578
3578
3579 If one or more REVs are given, only open branch heads on the
3579 If one or more REVs are given, only open branch heads on the
3580 branches associated with the specified changesets are shown. This
3580 branches associated with the specified changesets are shown. This
3581 means that you can use :hg:`heads .` to see the heads on the
3581 means that you can use :hg:`heads .` to see the heads on the
3582 currently checked-out branch.
3582 currently checked-out branch.
3583
3583
3584 If -c/--closed is specified, also show branch heads marked closed
3584 If -c/--closed is specified, also show branch heads marked closed
3585 (see :hg:`commit --close-branch`).
3585 (see :hg:`commit --close-branch`).
3586
3586
3587 If STARTREV is specified, only those heads that are descendants of
3587 If STARTREV is specified, only those heads that are descendants of
3588 STARTREV will be displayed.
3588 STARTREV will be displayed.
3589
3589
3590 If -t/--topo is specified, named branch mechanics will be ignored and only
3590 If -t/--topo is specified, named branch mechanics will be ignored and only
3591 topological heads (changesets with no children) will be shown.
3591 topological heads (changesets with no children) will be shown.
3592
3592
3593 Returns 0 if matching heads are found, 1 if not.
3593 Returns 0 if matching heads are found, 1 if not.
3594 """
3594 """
3595
3595
3596 opts = pycompat.byteskwargs(opts)
3596 opts = pycompat.byteskwargs(opts)
3597 start = None
3597 start = None
3598 rev = opts.get(b'rev')
3598 rev = opts.get(b'rev')
3599 if rev:
3599 if rev:
3600 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
3600 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
3601 start = scmutil.revsingle(repo, rev, None).node()
3601 start = scmutil.revsingle(repo, rev, None).node()
3602
3602
3603 if opts.get(b'topo'):
3603 if opts.get(b'topo'):
3604 heads = [repo[h] for h in repo.heads(start)]
3604 heads = [repo[h] for h in repo.heads(start)]
3605 else:
3605 else:
3606 heads = []
3606 heads = []
3607 for branch in repo.branchmap():
3607 for branch in repo.branchmap():
3608 heads += repo.branchheads(branch, start, opts.get(b'closed'))
3608 heads += repo.branchheads(branch, start, opts.get(b'closed'))
3609 heads = [repo[h] for h in heads]
3609 heads = [repo[h] for h in heads]
3610
3610
3611 if branchrevs:
3611 if branchrevs:
3612 branches = {
3612 branches = {
3613 repo[r].branch() for r in scmutil.revrange(repo, branchrevs)
3613 repo[r].branch() for r in scmutil.revrange(repo, branchrevs)
3614 }
3614 }
3615 heads = [h for h in heads if h.branch() in branches]
3615 heads = [h for h in heads if h.branch() in branches]
3616
3616
3617 if opts.get(b'active') and branchrevs:
3617 if opts.get(b'active') and branchrevs:
3618 dagheads = repo.heads(start)
3618 dagheads = repo.heads(start)
3619 heads = [h for h in heads if h.node() in dagheads]
3619 heads = [h for h in heads if h.node() in dagheads]
3620
3620
3621 if branchrevs:
3621 if branchrevs:
3622 haveheads = {h.branch() for h in heads}
3622 haveheads = {h.branch() for h in heads}
3623 if branches - haveheads:
3623 if branches - haveheads:
3624 headless = b', '.join(b for b in branches - haveheads)
3624 headless = b', '.join(b for b in branches - haveheads)
3625 msg = _(b'no open branch heads found on branches %s')
3625 msg = _(b'no open branch heads found on branches %s')
3626 if opts.get(b'rev'):
3626 if opts.get(b'rev'):
3627 msg += _(b' (started at %s)') % opts[b'rev']
3627 msg += _(b' (started at %s)') % opts[b'rev']
3628 ui.warn((msg + b'\n') % headless)
3628 ui.warn((msg + b'\n') % headless)
3629
3629
3630 if not heads:
3630 if not heads:
3631 return 1
3631 return 1
3632
3632
3633 ui.pager(b'heads')
3633 ui.pager(b'heads')
3634 heads = sorted(heads, key=lambda x: -(x.rev()))
3634 heads = sorted(heads, key=lambda x: -(x.rev()))
3635 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
3635 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
3636 for ctx in heads:
3636 for ctx in heads:
3637 displayer.show(ctx)
3637 displayer.show(ctx)
3638 displayer.close()
3638 displayer.close()
3639
3639
3640
3640
3641 @command(
3641 @command(
3642 b'help',
3642 b'help',
3643 [
3643 [
3644 (b'e', b'extension', None, _(b'show only help for extensions')),
3644 (b'e', b'extension', None, _(b'show only help for extensions')),
3645 (b'c', b'command', None, _(b'show only help for commands')),
3645 (b'c', b'command', None, _(b'show only help for commands')),
3646 (b'k', b'keyword', None, _(b'show topics matching keyword')),
3646 (b'k', b'keyword', None, _(b'show topics matching keyword')),
3647 (
3647 (
3648 b's',
3648 b's',
3649 b'system',
3649 b'system',
3650 [],
3650 [],
3651 _(b'show help for specific platform(s)'),
3651 _(b'show help for specific platform(s)'),
3652 _(b'PLATFORM'),
3652 _(b'PLATFORM'),
3653 ),
3653 ),
3654 ],
3654 ],
3655 _(b'[-eck] [-s PLATFORM] [TOPIC]'),
3655 _(b'[-eck] [-s PLATFORM] [TOPIC]'),
3656 helpcategory=command.CATEGORY_HELP,
3656 helpcategory=command.CATEGORY_HELP,
3657 norepo=True,
3657 norepo=True,
3658 intents={INTENT_READONLY},
3658 intents={INTENT_READONLY},
3659 )
3659 )
3660 def help_(ui, name=None, **opts):
3660 def help_(ui, name=None, **opts):
3661 """show help for a given topic or a help overview
3661 """show help for a given topic or a help overview
3662
3662
3663 With no arguments, print a list of commands with short help messages.
3663 With no arguments, print a list of commands with short help messages.
3664
3664
3665 Given a topic, extension, or command name, print help for that
3665 Given a topic, extension, or command name, print help for that
3666 topic.
3666 topic.
3667
3667
3668 Returns 0 if successful.
3668 Returns 0 if successful.
3669 """
3669 """
3670
3670
3671 keep = opts.get('system') or []
3671 keep = opts.get('system') or []
3672 if len(keep) == 0:
3672 if len(keep) == 0:
3673 if pycompat.sysplatform.startswith(b'win'):
3673 if pycompat.sysplatform.startswith(b'win'):
3674 keep.append(b'windows')
3674 keep.append(b'windows')
3675 elif pycompat.sysplatform == b'OpenVMS':
3675 elif pycompat.sysplatform == b'OpenVMS':
3676 keep.append(b'vms')
3676 keep.append(b'vms')
3677 elif pycompat.sysplatform == b'plan9':
3677 elif pycompat.sysplatform == b'plan9':
3678 keep.append(b'plan9')
3678 keep.append(b'plan9')
3679 else:
3679 else:
3680 keep.append(b'unix')
3680 keep.append(b'unix')
3681 keep.append(pycompat.sysplatform.lower())
3681 keep.append(pycompat.sysplatform.lower())
3682 if ui.verbose:
3682 if ui.verbose:
3683 keep.append(b'verbose')
3683 keep.append(b'verbose')
3684
3684
3685 commands = sys.modules[__name__]
3685 commands = sys.modules[__name__]
3686 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
3686 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
3687 ui.pager(b'help')
3687 ui.pager(b'help')
3688 ui.write(formatted)
3688 ui.write(formatted)
3689
3689
3690
3690
3691 @command(
3691 @command(
3692 b'identify|id',
3692 b'identify|id',
3693 [
3693 [
3694 (b'r', b'rev', b'', _(b'identify the specified revision'), _(b'REV')),
3694 (b'r', b'rev', b'', _(b'identify the specified revision'), _(b'REV')),
3695 (b'n', b'num', None, _(b'show local revision number')),
3695 (b'n', b'num', None, _(b'show local revision number')),
3696 (b'i', b'id', None, _(b'show global revision id')),
3696 (b'i', b'id', None, _(b'show global revision id')),
3697 (b'b', b'branch', None, _(b'show branch')),
3697 (b'b', b'branch', None, _(b'show branch')),
3698 (b't', b'tags', None, _(b'show tags')),
3698 (b't', b'tags', None, _(b'show tags')),
3699 (b'B', b'bookmarks', None, _(b'show bookmarks')),
3699 (b'B', b'bookmarks', None, _(b'show bookmarks')),
3700 ]
3700 ]
3701 + remoteopts
3701 + remoteopts
3702 + formatteropts,
3702 + formatteropts,
3703 _(b'[-nibtB] [-r REV] [SOURCE]'),
3703 _(b'[-nibtB] [-r REV] [SOURCE]'),
3704 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3704 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3705 optionalrepo=True,
3705 optionalrepo=True,
3706 intents={INTENT_READONLY},
3706 intents={INTENT_READONLY},
3707 )
3707 )
3708 def identify(
3708 def identify(
3709 ui,
3709 ui,
3710 repo,
3710 repo,
3711 source=None,
3711 source=None,
3712 rev=None,
3712 rev=None,
3713 num=None,
3713 num=None,
3714 id=None,
3714 id=None,
3715 branch=None,
3715 branch=None,
3716 tags=None,
3716 tags=None,
3717 bookmarks=None,
3717 bookmarks=None,
3718 **opts
3718 **opts
3719 ):
3719 ):
3720 """identify the working directory or specified revision
3720 """identify the working directory or specified revision
3721
3721
3722 Print a summary identifying the repository state at REV using one or
3722 Print a summary identifying the repository state at REV using one or
3723 two parent hash identifiers, followed by a "+" if the working
3723 two parent hash identifiers, followed by a "+" if the working
3724 directory has uncommitted changes, the branch name (if not default),
3724 directory has uncommitted changes, the branch name (if not default),
3725 a list of tags, and a list of bookmarks.
3725 a list of tags, and a list of bookmarks.
3726
3726
3727 When REV is not given, print a summary of the current state of the
3727 When REV is not given, print a summary of the current state of the
3728 repository including the working directory. Specify -r. to get information
3728 repository including the working directory. Specify -r. to get information
3729 of the working directory parent without scanning uncommitted changes.
3729 of the working directory parent without scanning uncommitted changes.
3730
3730
3731 Specifying a path to a repository root or Mercurial bundle will
3731 Specifying a path to a repository root or Mercurial bundle will
3732 cause lookup to operate on that repository/bundle.
3732 cause lookup to operate on that repository/bundle.
3733
3733
3734 .. container:: verbose
3734 .. container:: verbose
3735
3735
3736 Template:
3736 Template:
3737
3737
3738 The following keywords are supported in addition to the common template
3738 The following keywords are supported in addition to the common template
3739 keywords and functions. See also :hg:`help templates`.
3739 keywords and functions. See also :hg:`help templates`.
3740
3740
3741 :dirty: String. Character ``+`` denoting if the working directory has
3741 :dirty: String. Character ``+`` denoting if the working directory has
3742 uncommitted changes.
3742 uncommitted changes.
3743 :id: String. One or two nodes, optionally followed by ``+``.
3743 :id: String. One or two nodes, optionally followed by ``+``.
3744 :parents: List of strings. Parent nodes of the changeset.
3744 :parents: List of strings. Parent nodes of the changeset.
3745
3745
3746 Examples:
3746 Examples:
3747
3747
3748 - generate a build identifier for the working directory::
3748 - generate a build identifier for the working directory::
3749
3749
3750 hg id --id > build-id.dat
3750 hg id --id > build-id.dat
3751
3751
3752 - find the revision corresponding to a tag::
3752 - find the revision corresponding to a tag::
3753
3753
3754 hg id -n -r 1.3
3754 hg id -n -r 1.3
3755
3755
3756 - check the most recent revision of a remote repository::
3756 - check the most recent revision of a remote repository::
3757
3757
3758 hg id -r tip https://www.mercurial-scm.org/repo/hg/
3758 hg id -r tip https://www.mercurial-scm.org/repo/hg/
3759
3759
3760 See :hg:`log` for generating more information about specific revisions,
3760 See :hg:`log` for generating more information about specific revisions,
3761 including full hash identifiers.
3761 including full hash identifiers.
3762
3762
3763 Returns 0 if successful.
3763 Returns 0 if successful.
3764 """
3764 """
3765
3765
3766 opts = pycompat.byteskwargs(opts)
3766 opts = pycompat.byteskwargs(opts)
3767 if not repo and not source:
3767 if not repo and not source:
3768 raise error.Abort(
3768 raise error.Abort(
3769 _(b"there is no Mercurial repository here (.hg not found)")
3769 _(b"there is no Mercurial repository here (.hg not found)")
3770 )
3770 )
3771
3771
3772 default = not (num or id or branch or tags or bookmarks)
3772 default = not (num or id or branch or tags or bookmarks)
3773 output = []
3773 output = []
3774 revs = []
3774 revs = []
3775
3775
3776 if source:
3776 if source:
3777 source, branches = hg.parseurl(ui.expandpath(source))
3777 source, branches = hg.parseurl(ui.expandpath(source))
3778 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3778 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3779 repo = peer.local()
3779 repo = peer.local()
3780 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3780 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3781
3781
3782 fm = ui.formatter(b'identify', opts)
3782 fm = ui.formatter(b'identify', opts)
3783 fm.startitem()
3783 fm.startitem()
3784
3784
3785 if not repo:
3785 if not repo:
3786 if num or branch or tags:
3786 if num or branch or tags:
3787 raise error.Abort(
3787 raise error.Abort(
3788 _(b"can't query remote revision number, branch, or tags")
3788 _(b"can't query remote revision number, branch, or tags")
3789 )
3789 )
3790 if not rev and revs:
3790 if not rev and revs:
3791 rev = revs[0]
3791 rev = revs[0]
3792 if not rev:
3792 if not rev:
3793 rev = b"tip"
3793 rev = b"tip"
3794
3794
3795 remoterev = peer.lookup(rev)
3795 remoterev = peer.lookup(rev)
3796 hexrev = fm.hexfunc(remoterev)
3796 hexrev = fm.hexfunc(remoterev)
3797 if default or id:
3797 if default or id:
3798 output = [hexrev]
3798 output = [hexrev]
3799 fm.data(id=hexrev)
3799 fm.data(id=hexrev)
3800
3800
3801 @util.cachefunc
3801 @util.cachefunc
3802 def getbms():
3802 def getbms():
3803 bms = []
3803 bms = []
3804
3804
3805 if b'bookmarks' in peer.listkeys(b'namespaces'):
3805 if b'bookmarks' in peer.listkeys(b'namespaces'):
3806 hexremoterev = hex(remoterev)
3806 hexremoterev = hex(remoterev)
3807 bms = [
3807 bms = [
3808 bm
3808 bm
3809 for bm, bmr in pycompat.iteritems(
3809 for bm, bmr in pycompat.iteritems(
3810 peer.listkeys(b'bookmarks')
3810 peer.listkeys(b'bookmarks')
3811 )
3811 )
3812 if bmr == hexremoterev
3812 if bmr == hexremoterev
3813 ]
3813 ]
3814
3814
3815 return sorted(bms)
3815 return sorted(bms)
3816
3816
3817 if fm.isplain():
3817 if fm.isplain():
3818 if bookmarks:
3818 if bookmarks:
3819 output.extend(getbms())
3819 output.extend(getbms())
3820 elif default and not ui.quiet:
3820 elif default and not ui.quiet:
3821 # multiple bookmarks for a single parent separated by '/'
3821 # multiple bookmarks for a single parent separated by '/'
3822 bm = b'/'.join(getbms())
3822 bm = b'/'.join(getbms())
3823 if bm:
3823 if bm:
3824 output.append(bm)
3824 output.append(bm)
3825 else:
3825 else:
3826 fm.data(node=hex(remoterev))
3826 fm.data(node=hex(remoterev))
3827 if bookmarks or b'bookmarks' in fm.datahint():
3827 if bookmarks or b'bookmarks' in fm.datahint():
3828 fm.data(bookmarks=fm.formatlist(getbms(), name=b'bookmark'))
3828 fm.data(bookmarks=fm.formatlist(getbms(), name=b'bookmark'))
3829 else:
3829 else:
3830 if rev:
3830 if rev:
3831 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
3831 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
3832 ctx = scmutil.revsingle(repo, rev, None)
3832 ctx = scmutil.revsingle(repo, rev, None)
3833
3833
3834 if ctx.rev() is None:
3834 if ctx.rev() is None:
3835 ctx = repo[None]
3835 ctx = repo[None]
3836 parents = ctx.parents()
3836 parents = ctx.parents()
3837 taglist = []
3837 taglist = []
3838 for p in parents:
3838 for p in parents:
3839 taglist.extend(p.tags())
3839 taglist.extend(p.tags())
3840
3840
3841 dirty = b""
3841 dirty = b""
3842 if ctx.dirty(missing=True, merge=False, branch=False):
3842 if ctx.dirty(missing=True, merge=False, branch=False):
3843 dirty = b'+'
3843 dirty = b'+'
3844 fm.data(dirty=dirty)
3844 fm.data(dirty=dirty)
3845
3845
3846 hexoutput = [fm.hexfunc(p.node()) for p in parents]
3846 hexoutput = [fm.hexfunc(p.node()) for p in parents]
3847 if default or id:
3847 if default or id:
3848 output = [b"%s%s" % (b'+'.join(hexoutput), dirty)]
3848 output = [b"%s%s" % (b'+'.join(hexoutput), dirty)]
3849 fm.data(id=b"%s%s" % (b'+'.join(hexoutput), dirty))
3849 fm.data(id=b"%s%s" % (b'+'.join(hexoutput), dirty))
3850
3850
3851 if num:
3851 if num:
3852 numoutput = [b"%d" % p.rev() for p in parents]
3852 numoutput = [b"%d" % p.rev() for p in parents]
3853 output.append(b"%s%s" % (b'+'.join(numoutput), dirty))
3853 output.append(b"%s%s" % (b'+'.join(numoutput), dirty))
3854
3854
3855 fm.data(
3855 fm.data(
3856 parents=fm.formatlist(
3856 parents=fm.formatlist(
3857 [fm.hexfunc(p.node()) for p in parents], name=b'node'
3857 [fm.hexfunc(p.node()) for p in parents], name=b'node'
3858 )
3858 )
3859 )
3859 )
3860 else:
3860 else:
3861 hexoutput = fm.hexfunc(ctx.node())
3861 hexoutput = fm.hexfunc(ctx.node())
3862 if default or id:
3862 if default or id:
3863 output = [hexoutput]
3863 output = [hexoutput]
3864 fm.data(id=hexoutput)
3864 fm.data(id=hexoutput)
3865
3865
3866 if num:
3866 if num:
3867 output.append(pycompat.bytestr(ctx.rev()))
3867 output.append(pycompat.bytestr(ctx.rev()))
3868 taglist = ctx.tags()
3868 taglist = ctx.tags()
3869
3869
3870 if default and not ui.quiet:
3870 if default and not ui.quiet:
3871 b = ctx.branch()
3871 b = ctx.branch()
3872 if b != b'default':
3872 if b != b'default':
3873 output.append(b"(%s)" % b)
3873 output.append(b"(%s)" % b)
3874
3874
3875 # multiple tags for a single parent separated by '/'
3875 # multiple tags for a single parent separated by '/'
3876 t = b'/'.join(taglist)
3876 t = b'/'.join(taglist)
3877 if t:
3877 if t:
3878 output.append(t)
3878 output.append(t)
3879
3879
3880 # multiple bookmarks for a single parent separated by '/'
3880 # multiple bookmarks for a single parent separated by '/'
3881 bm = b'/'.join(ctx.bookmarks())
3881 bm = b'/'.join(ctx.bookmarks())
3882 if bm:
3882 if bm:
3883 output.append(bm)
3883 output.append(bm)
3884 else:
3884 else:
3885 if branch:
3885 if branch:
3886 output.append(ctx.branch())
3886 output.append(ctx.branch())
3887
3887
3888 if tags:
3888 if tags:
3889 output.extend(taglist)
3889 output.extend(taglist)
3890
3890
3891 if bookmarks:
3891 if bookmarks:
3892 output.extend(ctx.bookmarks())
3892 output.extend(ctx.bookmarks())
3893
3893
3894 fm.data(node=ctx.hex())
3894 fm.data(node=ctx.hex())
3895 fm.data(branch=ctx.branch())
3895 fm.data(branch=ctx.branch())
3896 fm.data(tags=fm.formatlist(taglist, name=b'tag', sep=b':'))
3896 fm.data(tags=fm.formatlist(taglist, name=b'tag', sep=b':'))
3897 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name=b'bookmark'))
3897 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name=b'bookmark'))
3898 fm.context(ctx=ctx)
3898 fm.context(ctx=ctx)
3899
3899
3900 fm.plain(b"%s\n" % b' '.join(output))
3900 fm.plain(b"%s\n" % b' '.join(output))
3901 fm.end()
3901 fm.end()
3902
3902
3903
3903
3904 @command(
3904 @command(
3905 b'import|patch',
3905 b'import|patch',
3906 [
3906 [
3907 (
3907 (
3908 b'p',
3908 b'p',
3909 b'strip',
3909 b'strip',
3910 1,
3910 1,
3911 _(
3911 _(
3912 b'directory strip option for patch. This has the same '
3912 b'directory strip option for patch. This has the same '
3913 b'meaning as the corresponding patch option'
3913 b'meaning as the corresponding patch option'
3914 ),
3914 ),
3915 _(b'NUM'),
3915 _(b'NUM'),
3916 ),
3916 ),
3917 (b'b', b'base', b'', _(b'base path (DEPRECATED)'), _(b'PATH')),
3917 (b'b', b'base', b'', _(b'base path (DEPRECATED)'), _(b'PATH')),
3918 (b'', b'secret', None, _(b'use the secret phase for committing')),
3918 (b'', b'secret', None, _(b'use the secret phase for committing')),
3919 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
3919 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
3920 (
3920 (
3921 b'f',
3921 b'f',
3922 b'force',
3922 b'force',
3923 None,
3923 None,
3924 _(b'skip check for outstanding uncommitted changes (DEPRECATED)'),
3924 _(b'skip check for outstanding uncommitted changes (DEPRECATED)'),
3925 ),
3925 ),
3926 (
3926 (
3927 b'',
3927 b'',
3928 b'no-commit',
3928 b'no-commit',
3929 None,
3929 None,
3930 _(b"don't commit, just update the working directory"),
3930 _(b"don't commit, just update the working directory"),
3931 ),
3931 ),
3932 (
3932 (
3933 b'',
3933 b'',
3934 b'bypass',
3934 b'bypass',
3935 None,
3935 None,
3936 _(b"apply patch without touching the working directory"),
3936 _(b"apply patch without touching the working directory"),
3937 ),
3937 ),
3938 (b'', b'partial', None, _(b'commit even if some hunks fail')),
3938 (b'', b'partial', None, _(b'commit even if some hunks fail')),
3939 (b'', b'exact', None, _(b'abort if patch would apply lossily')),
3939 (b'', b'exact', None, _(b'abort if patch would apply lossily')),
3940 (b'', b'prefix', b'', _(b'apply patch to subdirectory'), _(b'DIR')),
3940 (b'', b'prefix', b'', _(b'apply patch to subdirectory'), _(b'DIR')),
3941 (
3941 (
3942 b'',
3942 b'',
3943 b'import-branch',
3943 b'import-branch',
3944 None,
3944 None,
3945 _(b'use any branch information in patch (implied by --exact)'),
3945 _(b'use any branch information in patch (implied by --exact)'),
3946 ),
3946 ),
3947 ]
3947 ]
3948 + commitopts
3948 + commitopts
3949 + commitopts2
3949 + commitopts2
3950 + similarityopts,
3950 + similarityopts,
3951 _(b'[OPTION]... PATCH...'),
3951 _(b'[OPTION]... PATCH...'),
3952 helpcategory=command.CATEGORY_IMPORT_EXPORT,
3952 helpcategory=command.CATEGORY_IMPORT_EXPORT,
3953 )
3953 )
3954 def import_(ui, repo, patch1=None, *patches, **opts):
3954 def import_(ui, repo, patch1=None, *patches, **opts):
3955 """import an ordered set of patches
3955 """import an ordered set of patches
3956
3956
3957 Import a list of patches and commit them individually (unless
3957 Import a list of patches and commit them individually (unless
3958 --no-commit is specified).
3958 --no-commit is specified).
3959
3959
3960 To read a patch from standard input (stdin), use "-" as the patch
3960 To read a patch from standard input (stdin), use "-" as the patch
3961 name. If a URL is specified, the patch will be downloaded from
3961 name. If a URL is specified, the patch will be downloaded from
3962 there.
3962 there.
3963
3963
3964 Import first applies changes to the working directory (unless
3964 Import first applies changes to the working directory (unless
3965 --bypass is specified), import will abort if there are outstanding
3965 --bypass is specified), import will abort if there are outstanding
3966 changes.
3966 changes.
3967
3967
3968 Use --bypass to apply and commit patches directly to the
3968 Use --bypass to apply and commit patches directly to the
3969 repository, without affecting the working directory. Without
3969 repository, without affecting the working directory. Without
3970 --exact, patches will be applied on top of the working directory
3970 --exact, patches will be applied on top of the working directory
3971 parent revision.
3971 parent revision.
3972
3972
3973 You can import a patch straight from a mail message. Even patches
3973 You can import a patch straight from a mail message. Even patches
3974 as attachments work (to use the body part, it must have type
3974 as attachments work (to use the body part, it must have type
3975 text/plain or text/x-patch). From and Subject headers of email
3975 text/plain or text/x-patch). From and Subject headers of email
3976 message are used as default committer and commit message. All
3976 message are used as default committer and commit message. All
3977 text/plain body parts before first diff are added to the commit
3977 text/plain body parts before first diff are added to the commit
3978 message.
3978 message.
3979
3979
3980 If the imported patch was generated by :hg:`export`, user and
3980 If the imported patch was generated by :hg:`export`, user and
3981 description from patch override values from message headers and
3981 description from patch override values from message headers and
3982 body. Values given on command line with -m/--message and -u/--user
3982 body. Values given on command line with -m/--message and -u/--user
3983 override these.
3983 override these.
3984
3984
3985 If --exact is specified, import will set the working directory to
3985 If --exact is specified, import will set the working directory to
3986 the parent of each patch before applying it, and will abort if the
3986 the parent of each patch before applying it, and will abort if the
3987 resulting changeset has a different ID than the one recorded in
3987 resulting changeset has a different ID than the one recorded in
3988 the patch. This will guard against various ways that portable
3988 the patch. This will guard against various ways that portable
3989 patch formats and mail systems might fail to transfer Mercurial
3989 patch formats and mail systems might fail to transfer Mercurial
3990 data or metadata. See :hg:`bundle` for lossless transmission.
3990 data or metadata. See :hg:`bundle` for lossless transmission.
3991
3991
3992 Use --partial to ensure a changeset will be created from the patch
3992 Use --partial to ensure a changeset will be created from the patch
3993 even if some hunks fail to apply. Hunks that fail to apply will be
3993 even if some hunks fail to apply. Hunks that fail to apply will be
3994 written to a <target-file>.rej file. Conflicts can then be resolved
3994 written to a <target-file>.rej file. Conflicts can then be resolved
3995 by hand before :hg:`commit --amend` is run to update the created
3995 by hand before :hg:`commit --amend` is run to update the created
3996 changeset. This flag exists to let people import patches that
3996 changeset. This flag exists to let people import patches that
3997 partially apply without losing the associated metadata (author,
3997 partially apply without losing the associated metadata (author,
3998 date, description, ...).
3998 date, description, ...).
3999
3999
4000 .. note::
4000 .. note::
4001
4001
4002 When no hunks apply cleanly, :hg:`import --partial` will create
4002 When no hunks apply cleanly, :hg:`import --partial` will create
4003 an empty changeset, importing only the patch metadata.
4003 an empty changeset, importing only the patch metadata.
4004
4004
4005 With -s/--similarity, hg will attempt to discover renames and
4005 With -s/--similarity, hg will attempt to discover renames and
4006 copies in the patch in the same way as :hg:`addremove`.
4006 copies in the patch in the same way as :hg:`addremove`.
4007
4007
4008 It is possible to use external patch programs to perform the patch
4008 It is possible to use external patch programs to perform the patch
4009 by setting the ``ui.patch`` configuration option. For the default
4009 by setting the ``ui.patch`` configuration option. For the default
4010 internal tool, the fuzz can also be configured via ``patch.fuzz``.
4010 internal tool, the fuzz can also be configured via ``patch.fuzz``.
4011 See :hg:`help config` for more information about configuration
4011 See :hg:`help config` for more information about configuration
4012 files and how to use these options.
4012 files and how to use these options.
4013
4013
4014 See :hg:`help dates` for a list of formats valid for -d/--date.
4014 See :hg:`help dates` for a list of formats valid for -d/--date.
4015
4015
4016 .. container:: verbose
4016 .. container:: verbose
4017
4017
4018 Examples:
4018 Examples:
4019
4019
4020 - import a traditional patch from a website and detect renames::
4020 - import a traditional patch from a website and detect renames::
4021
4021
4022 hg import -s 80 http://example.com/bugfix.patch
4022 hg import -s 80 http://example.com/bugfix.patch
4023
4023
4024 - import a changeset from an hgweb server::
4024 - import a changeset from an hgweb server::
4025
4025
4026 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
4026 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
4027
4027
4028 - import all the patches in an Unix-style mbox::
4028 - import all the patches in an Unix-style mbox::
4029
4029
4030 hg import incoming-patches.mbox
4030 hg import incoming-patches.mbox
4031
4031
4032 - import patches from stdin::
4032 - import patches from stdin::
4033
4033
4034 hg import -
4034 hg import -
4035
4035
4036 - attempt to exactly restore an exported changeset (not always
4036 - attempt to exactly restore an exported changeset (not always
4037 possible)::
4037 possible)::
4038
4038
4039 hg import --exact proposed-fix.patch
4039 hg import --exact proposed-fix.patch
4040
4040
4041 - use an external tool to apply a patch which is too fuzzy for
4041 - use an external tool to apply a patch which is too fuzzy for
4042 the default internal tool.
4042 the default internal tool.
4043
4043
4044 hg import --config ui.patch="patch --merge" fuzzy.patch
4044 hg import --config ui.patch="patch --merge" fuzzy.patch
4045
4045
4046 - change the default fuzzing from 2 to a less strict 7
4046 - change the default fuzzing from 2 to a less strict 7
4047
4047
4048 hg import --config ui.fuzz=7 fuzz.patch
4048 hg import --config ui.fuzz=7 fuzz.patch
4049
4049
4050 Returns 0 on success, 1 on partial success (see --partial).
4050 Returns 0 on success, 1 on partial success (see --partial).
4051 """
4051 """
4052
4052
4053 cmdutil.check_incompatible_arguments(
4053 cmdutil.check_incompatible_arguments(
4054 opts, 'no_commit', ['bypass', 'secret']
4054 opts, 'no_commit', ['bypass', 'secret']
4055 )
4055 )
4056 cmdutil.check_incompatible_arguments(opts, 'exact', ['edit', 'prefix'])
4056 cmdutil.check_incompatible_arguments(opts, 'exact', ['edit', 'prefix'])
4057 opts = pycompat.byteskwargs(opts)
4057 opts = pycompat.byteskwargs(opts)
4058 if not patch1:
4058 if not patch1:
4059 raise error.Abort(_(b'need at least one patch to import'))
4059 raise error.Abort(_(b'need at least one patch to import'))
4060
4060
4061 patches = (patch1,) + patches
4061 patches = (patch1,) + patches
4062
4062
4063 date = opts.get(b'date')
4063 date = opts.get(b'date')
4064 if date:
4064 if date:
4065 opts[b'date'] = dateutil.parsedate(date)
4065 opts[b'date'] = dateutil.parsedate(date)
4066
4066
4067 exact = opts.get(b'exact')
4067 exact = opts.get(b'exact')
4068 update = not opts.get(b'bypass')
4068 update = not opts.get(b'bypass')
4069 try:
4069 try:
4070 sim = float(opts.get(b'similarity') or 0)
4070 sim = float(opts.get(b'similarity') or 0)
4071 except ValueError:
4071 except ValueError:
4072 raise error.Abort(_(b'similarity must be a number'))
4072 raise error.Abort(_(b'similarity must be a number'))
4073 if sim < 0 or sim > 100:
4073 if sim < 0 or sim > 100:
4074 raise error.Abort(_(b'similarity must be between 0 and 100'))
4074 raise error.Abort(_(b'similarity must be between 0 and 100'))
4075 if sim and not update:
4075 if sim and not update:
4076 raise error.Abort(_(b'cannot use --similarity with --bypass'))
4076 raise error.Abort(_(b'cannot use --similarity with --bypass'))
4077
4077
4078 base = opts[b"base"]
4078 base = opts[b"base"]
4079 msgs = []
4079 msgs = []
4080 ret = 0
4080 ret = 0
4081
4081
4082 with repo.wlock():
4082 with repo.wlock():
4083 if update:
4083 if update:
4084 cmdutil.checkunfinished(repo)
4084 cmdutil.checkunfinished(repo)
4085 if exact or not opts.get(b'force'):
4085 if exact or not opts.get(b'force'):
4086 cmdutil.bailifchanged(repo)
4086 cmdutil.bailifchanged(repo)
4087
4087
4088 if not opts.get(b'no_commit'):
4088 if not opts.get(b'no_commit'):
4089 lock = repo.lock
4089 lock = repo.lock
4090 tr = lambda: repo.transaction(b'import')
4090 tr = lambda: repo.transaction(b'import')
4091 dsguard = util.nullcontextmanager
4091 dsguard = util.nullcontextmanager
4092 else:
4092 else:
4093 lock = util.nullcontextmanager
4093 lock = util.nullcontextmanager
4094 tr = util.nullcontextmanager
4094 tr = util.nullcontextmanager
4095 dsguard = lambda: dirstateguard.dirstateguard(repo, b'import')
4095 dsguard = lambda: dirstateguard.dirstateguard(repo, b'import')
4096 with lock(), tr(), dsguard():
4096 with lock(), tr(), dsguard():
4097 parents = repo[None].parents()
4097 parents = repo[None].parents()
4098 for patchurl in patches:
4098 for patchurl in patches:
4099 if patchurl == b'-':
4099 if patchurl == b'-':
4100 ui.status(_(b'applying patch from stdin\n'))
4100 ui.status(_(b'applying patch from stdin\n'))
4101 patchfile = ui.fin
4101 patchfile = ui.fin
4102 patchurl = b'stdin' # for error message
4102 patchurl = b'stdin' # for error message
4103 else:
4103 else:
4104 patchurl = os.path.join(base, patchurl)
4104 patchurl = os.path.join(base, patchurl)
4105 ui.status(_(b'applying %s\n') % patchurl)
4105 ui.status(_(b'applying %s\n') % patchurl)
4106 patchfile = hg.openpath(ui, patchurl, sendaccept=False)
4106 patchfile = hg.openpath(ui, patchurl, sendaccept=False)
4107
4107
4108 haspatch = False
4108 haspatch = False
4109 for hunk in patch.split(patchfile):
4109 for hunk in patch.split(patchfile):
4110 with patch.extract(ui, hunk) as patchdata:
4110 with patch.extract(ui, hunk) as patchdata:
4111 msg, node, rej = cmdutil.tryimportone(
4111 msg, node, rej = cmdutil.tryimportone(
4112 ui, repo, patchdata, parents, opts, msgs, hg.clean
4112 ui, repo, patchdata, parents, opts, msgs, hg.clean
4113 )
4113 )
4114 if msg:
4114 if msg:
4115 haspatch = True
4115 haspatch = True
4116 ui.note(msg + b'\n')
4116 ui.note(msg + b'\n')
4117 if update or exact:
4117 if update or exact:
4118 parents = repo[None].parents()
4118 parents = repo[None].parents()
4119 else:
4119 else:
4120 parents = [repo[node]]
4120 parents = [repo[node]]
4121 if rej:
4121 if rej:
4122 ui.write_err(_(b"patch applied partially\n"))
4122 ui.write_err(_(b"patch applied partially\n"))
4123 ui.write_err(
4123 ui.write_err(
4124 _(
4124 _(
4125 b"(fix the .rej files and run "
4125 b"(fix the .rej files and run "
4126 b"`hg commit --amend`)\n"
4126 b"`hg commit --amend`)\n"
4127 )
4127 )
4128 )
4128 )
4129 ret = 1
4129 ret = 1
4130 break
4130 break
4131
4131
4132 if not haspatch:
4132 if not haspatch:
4133 raise error.Abort(_(b'%s: no diffs found') % patchurl)
4133 raise error.Abort(_(b'%s: no diffs found') % patchurl)
4134
4134
4135 if msgs:
4135 if msgs:
4136 repo.savecommitmessage(b'\n* * *\n'.join(msgs))
4136 repo.savecommitmessage(b'\n* * *\n'.join(msgs))
4137 return ret
4137 return ret
4138
4138
4139
4139
4140 @command(
4140 @command(
4141 b'incoming|in',
4141 b'incoming|in',
4142 [
4142 [
4143 (
4143 (
4144 b'f',
4144 b'f',
4145 b'force',
4145 b'force',
4146 None,
4146 None,
4147 _(b'run even if remote repository is unrelated'),
4147 _(b'run even if remote repository is unrelated'),
4148 ),
4148 ),
4149 (b'n', b'newest-first', None, _(b'show newest record first')),
4149 (b'n', b'newest-first', None, _(b'show newest record first')),
4150 (b'', b'bundle', b'', _(b'file to store the bundles into'), _(b'FILE')),
4150 (b'', b'bundle', b'', _(b'file to store the bundles into'), _(b'FILE')),
4151 (
4151 (
4152 b'r',
4152 b'r',
4153 b'rev',
4153 b'rev',
4154 [],
4154 [],
4155 _(b'a remote changeset intended to be added'),
4155 _(b'a remote changeset intended to be added'),
4156 _(b'REV'),
4156 _(b'REV'),
4157 ),
4157 ),
4158 (b'B', b'bookmarks', False, _(b"compare bookmarks")),
4158 (b'B', b'bookmarks', False, _(b"compare bookmarks")),
4159 (
4159 (
4160 b'b',
4160 b'b',
4161 b'branch',
4161 b'branch',
4162 [],
4162 [],
4163 _(b'a specific branch you would like to pull'),
4163 _(b'a specific branch you would like to pull'),
4164 _(b'BRANCH'),
4164 _(b'BRANCH'),
4165 ),
4165 ),
4166 ]
4166 ]
4167 + logopts
4167 + logopts
4168 + remoteopts
4168 + remoteopts
4169 + subrepoopts,
4169 + subrepoopts,
4170 _(b'[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'),
4170 _(b'[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'),
4171 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4171 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4172 )
4172 )
4173 def incoming(ui, repo, source=b"default", **opts):
4173 def incoming(ui, repo, source=b"default", **opts):
4174 """show new changesets found in source
4174 """show new changesets found in source
4175
4175
4176 Show new changesets found in the specified path/URL or the default
4176 Show new changesets found in the specified path/URL or the default
4177 pull location. These are the changesets that would have been pulled
4177 pull location. These are the changesets that would have been pulled
4178 by :hg:`pull` at the time you issued this command.
4178 by :hg:`pull` at the time you issued this command.
4179
4179
4180 See pull for valid source format details.
4180 See pull for valid source format details.
4181
4181
4182 .. container:: verbose
4182 .. container:: verbose
4183
4183
4184 With -B/--bookmarks, the result of bookmark comparison between
4184 With -B/--bookmarks, the result of bookmark comparison between
4185 local and remote repositories is displayed. With -v/--verbose,
4185 local and remote repositories is displayed. With -v/--verbose,
4186 status is also displayed for each bookmark like below::
4186 status is also displayed for each bookmark like below::
4187
4187
4188 BM1 01234567890a added
4188 BM1 01234567890a added
4189 BM2 1234567890ab advanced
4189 BM2 1234567890ab advanced
4190 BM3 234567890abc diverged
4190 BM3 234567890abc diverged
4191 BM4 34567890abcd changed
4191 BM4 34567890abcd changed
4192
4192
4193 The action taken locally when pulling depends on the
4193 The action taken locally when pulling depends on the
4194 status of each bookmark:
4194 status of each bookmark:
4195
4195
4196 :``added``: pull will create it
4196 :``added``: pull will create it
4197 :``advanced``: pull will update it
4197 :``advanced``: pull will update it
4198 :``diverged``: pull will create a divergent bookmark
4198 :``diverged``: pull will create a divergent bookmark
4199 :``changed``: result depends on remote changesets
4199 :``changed``: result depends on remote changesets
4200
4200
4201 From the point of view of pulling behavior, bookmark
4201 From the point of view of pulling behavior, bookmark
4202 existing only in the remote repository are treated as ``added``,
4202 existing only in the remote repository are treated as ``added``,
4203 even if it is in fact locally deleted.
4203 even if it is in fact locally deleted.
4204
4204
4205 .. container:: verbose
4205 .. container:: verbose
4206
4206
4207 For remote repository, using --bundle avoids downloading the
4207 For remote repository, using --bundle avoids downloading the
4208 changesets twice if the incoming is followed by a pull.
4208 changesets twice if the incoming is followed by a pull.
4209
4209
4210 Examples:
4210 Examples:
4211
4211
4212 - show incoming changes with patches and full description::
4212 - show incoming changes with patches and full description::
4213
4213
4214 hg incoming -vp
4214 hg incoming -vp
4215
4215
4216 - show incoming changes excluding merges, store a bundle::
4216 - show incoming changes excluding merges, store a bundle::
4217
4217
4218 hg in -vpM --bundle incoming.hg
4218 hg in -vpM --bundle incoming.hg
4219 hg pull incoming.hg
4219 hg pull incoming.hg
4220
4220
4221 - briefly list changes inside a bundle::
4221 - briefly list changes inside a bundle::
4222
4222
4223 hg in changes.hg -T "{desc|firstline}\\n"
4223 hg in changes.hg -T "{desc|firstline}\\n"
4224
4224
4225 Returns 0 if there are incoming changes, 1 otherwise.
4225 Returns 0 if there are incoming changes, 1 otherwise.
4226 """
4226 """
4227 opts = pycompat.byteskwargs(opts)
4227 opts = pycompat.byteskwargs(opts)
4228 if opts.get(b'graph'):
4228 if opts.get(b'graph'):
4229 logcmdutil.checkunsupportedgraphflags([], opts)
4229 logcmdutil.checkunsupportedgraphflags([], opts)
4230
4230
4231 def display(other, chlist, displayer):
4231 def display(other, chlist, displayer):
4232 revdag = logcmdutil.graphrevs(other, chlist, opts)
4232 revdag = logcmdutil.graphrevs(other, chlist, opts)
4233 logcmdutil.displaygraph(
4233 logcmdutil.displaygraph(
4234 ui, repo, revdag, displayer, graphmod.asciiedges
4234 ui, repo, revdag, displayer, graphmod.asciiedges
4235 )
4235 )
4236
4236
4237 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4237 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4238 return 0
4238 return 0
4239
4239
4240 cmdutil.check_incompatible_arguments(opts, b'subrepos', [b'bundle'])
4240 cmdutil.check_incompatible_arguments(opts, b'subrepos', [b'bundle'])
4241
4241
4242 if opts.get(b'bookmarks'):
4242 if opts.get(b'bookmarks'):
4243 source, branches = hg.parseurl(
4243 source, branches = hg.parseurl(
4244 ui.expandpath(source), opts.get(b'branch')
4244 ui.expandpath(source), opts.get(b'branch')
4245 )
4245 )
4246 other = hg.peer(repo, opts, source)
4246 other = hg.peer(repo, opts, source)
4247 if b'bookmarks' not in other.listkeys(b'namespaces'):
4247 if b'bookmarks' not in other.listkeys(b'namespaces'):
4248 ui.warn(_(b"remote doesn't support bookmarks\n"))
4248 ui.warn(_(b"remote doesn't support bookmarks\n"))
4249 return 0
4249 return 0
4250 ui.pager(b'incoming')
4250 ui.pager(b'incoming')
4251 ui.status(_(b'comparing with %s\n') % util.hidepassword(source))
4251 ui.status(_(b'comparing with %s\n') % util.hidepassword(source))
4252 return bookmarks.incoming(ui, repo, other)
4252 return bookmarks.incoming(ui, repo, other)
4253
4253
4254 repo._subtoppath = ui.expandpath(source)
4254 repo._subtoppath = ui.expandpath(source)
4255 try:
4255 try:
4256 return hg.incoming(ui, repo, source, opts)
4256 return hg.incoming(ui, repo, source, opts)
4257 finally:
4257 finally:
4258 del repo._subtoppath
4258 del repo._subtoppath
4259
4259
4260
4260
4261 @command(
4261 @command(
4262 b'init',
4262 b'init',
4263 remoteopts,
4263 remoteopts,
4264 _(b'[-e CMD] [--remotecmd CMD] [DEST]'),
4264 _(b'[-e CMD] [--remotecmd CMD] [DEST]'),
4265 helpcategory=command.CATEGORY_REPO_CREATION,
4265 helpcategory=command.CATEGORY_REPO_CREATION,
4266 helpbasic=True,
4266 helpbasic=True,
4267 norepo=True,
4267 norepo=True,
4268 )
4268 )
4269 def init(ui, dest=b".", **opts):
4269 def init(ui, dest=b".", **opts):
4270 """create a new repository in the given directory
4270 """create a new repository in the given directory
4271
4271
4272 Initialize a new repository in the given directory. If the given
4272 Initialize a new repository in the given directory. If the given
4273 directory does not exist, it will be created.
4273 directory does not exist, it will be created.
4274
4274
4275 If no directory is given, the current directory is used.
4275 If no directory is given, the current directory is used.
4276
4276
4277 It is possible to specify an ``ssh://`` URL as the destination.
4277 It is possible to specify an ``ssh://`` URL as the destination.
4278 See :hg:`help urls` for more information.
4278 See :hg:`help urls` for more information.
4279
4279
4280 Returns 0 on success.
4280 Returns 0 on success.
4281 """
4281 """
4282 opts = pycompat.byteskwargs(opts)
4282 opts = pycompat.byteskwargs(opts)
4283 hg.peer(ui, opts, ui.expandpath(dest), create=True)
4283 hg.peer(ui, opts, ui.expandpath(dest), create=True)
4284
4284
4285
4285
4286 @command(
4286 @command(
4287 b'locate',
4287 b'locate',
4288 [
4288 [
4289 (
4289 (
4290 b'r',
4290 b'r',
4291 b'rev',
4291 b'rev',
4292 b'',
4292 b'',
4293 _(b'search the repository as it is in REV'),
4293 _(b'search the repository as it is in REV'),
4294 _(b'REV'),
4294 _(b'REV'),
4295 ),
4295 ),
4296 (
4296 (
4297 b'0',
4297 b'0',
4298 b'print0',
4298 b'print0',
4299 None,
4299 None,
4300 _(b'end filenames with NUL, for use with xargs'),
4300 _(b'end filenames with NUL, for use with xargs'),
4301 ),
4301 ),
4302 (
4302 (
4303 b'f',
4303 b'f',
4304 b'fullpath',
4304 b'fullpath',
4305 None,
4305 None,
4306 _(b'print complete paths from the filesystem root'),
4306 _(b'print complete paths from the filesystem root'),
4307 ),
4307 ),
4308 ]
4308 ]
4309 + walkopts,
4309 + walkopts,
4310 _(b'[OPTION]... [PATTERN]...'),
4310 _(b'[OPTION]... [PATTERN]...'),
4311 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
4311 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
4312 )
4312 )
4313 def locate(ui, repo, *pats, **opts):
4313 def locate(ui, repo, *pats, **opts):
4314 """locate files matching specific patterns (DEPRECATED)
4314 """locate files matching specific patterns (DEPRECATED)
4315
4315
4316 Print files under Mercurial control in the working directory whose
4316 Print files under Mercurial control in the working directory whose
4317 names match the given patterns.
4317 names match the given patterns.
4318
4318
4319 By default, this command searches all directories in the working
4319 By default, this command searches all directories in the working
4320 directory. To search just the current directory and its
4320 directory. To search just the current directory and its
4321 subdirectories, use "--include .".
4321 subdirectories, use "--include .".
4322
4322
4323 If no patterns are given to match, this command prints the names
4323 If no patterns are given to match, this command prints the names
4324 of all files under Mercurial control in the working directory.
4324 of all files under Mercurial control in the working directory.
4325
4325
4326 If you want to feed the output of this command into the "xargs"
4326 If you want to feed the output of this command into the "xargs"
4327 command, use the -0 option to both this command and "xargs". This
4327 command, use the -0 option to both this command and "xargs". This
4328 will avoid the problem of "xargs" treating single filenames that
4328 will avoid the problem of "xargs" treating single filenames that
4329 contain whitespace as multiple filenames.
4329 contain whitespace as multiple filenames.
4330
4330
4331 See :hg:`help files` for a more versatile command.
4331 See :hg:`help files` for a more versatile command.
4332
4332
4333 Returns 0 if a match is found, 1 otherwise.
4333 Returns 0 if a match is found, 1 otherwise.
4334 """
4334 """
4335 opts = pycompat.byteskwargs(opts)
4335 opts = pycompat.byteskwargs(opts)
4336 if opts.get(b'print0'):
4336 if opts.get(b'print0'):
4337 end = b'\0'
4337 end = b'\0'
4338 else:
4338 else:
4339 end = b'\n'
4339 end = b'\n'
4340 ctx = scmutil.revsingle(repo, opts.get(b'rev'), None)
4340 ctx = scmutil.revsingle(repo, opts.get(b'rev'), None)
4341
4341
4342 ret = 1
4342 ret = 1
4343 m = scmutil.match(
4343 m = scmutil.match(
4344 ctx, pats, opts, default=b'relglob', badfn=lambda x, y: False
4344 ctx, pats, opts, default=b'relglob', badfn=lambda x, y: False
4345 )
4345 )
4346
4346
4347 ui.pager(b'locate')
4347 ui.pager(b'locate')
4348 if ctx.rev() is None:
4348 if ctx.rev() is None:
4349 # When run on the working copy, "locate" includes removed files, so
4349 # When run on the working copy, "locate" includes removed files, so
4350 # we get the list of files from the dirstate.
4350 # we get the list of files from the dirstate.
4351 filesgen = sorted(repo.dirstate.matches(m))
4351 filesgen = sorted(repo.dirstate.matches(m))
4352 else:
4352 else:
4353 filesgen = ctx.matches(m)
4353 filesgen = ctx.matches(m)
4354 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=bool(pats))
4354 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=bool(pats))
4355 for abs in filesgen:
4355 for abs in filesgen:
4356 if opts.get(b'fullpath'):
4356 if opts.get(b'fullpath'):
4357 ui.write(repo.wjoin(abs), end)
4357 ui.write(repo.wjoin(abs), end)
4358 else:
4358 else:
4359 ui.write(uipathfn(abs), end)
4359 ui.write(uipathfn(abs), end)
4360 ret = 0
4360 ret = 0
4361
4361
4362 return ret
4362 return ret
4363
4363
4364
4364
4365 @command(
4365 @command(
4366 b'log|history',
4366 b'log|history',
4367 [
4367 [
4368 (
4368 (
4369 b'f',
4369 b'f',
4370 b'follow',
4370 b'follow',
4371 None,
4371 None,
4372 _(
4372 _(
4373 b'follow changeset history, or file history across copies and renames'
4373 b'follow changeset history, or file history across copies and renames'
4374 ),
4374 ),
4375 ),
4375 ),
4376 (
4376 (
4377 b'',
4377 b'',
4378 b'follow-first',
4378 b'follow-first',
4379 None,
4379 None,
4380 _(b'only follow the first parent of merge changesets (DEPRECATED)'),
4380 _(b'only follow the first parent of merge changesets (DEPRECATED)'),
4381 ),
4381 ),
4382 (
4382 (
4383 b'd',
4383 b'd',
4384 b'date',
4384 b'date',
4385 b'',
4385 b'',
4386 _(b'show revisions matching date spec'),
4386 _(b'show revisions matching date spec'),
4387 _(b'DATE'),
4387 _(b'DATE'),
4388 ),
4388 ),
4389 (b'C', b'copies', None, _(b'show copied files')),
4389 (b'C', b'copies', None, _(b'show copied files')),
4390 (
4390 (
4391 b'k',
4391 b'k',
4392 b'keyword',
4392 b'keyword',
4393 [],
4393 [],
4394 _(b'do case-insensitive search for a given text'),
4394 _(b'do case-insensitive search for a given text'),
4395 _(b'TEXT'),
4395 _(b'TEXT'),
4396 ),
4396 ),
4397 (
4397 (
4398 b'r',
4398 b'r',
4399 b'rev',
4399 b'rev',
4400 [],
4400 [],
4401 _(b'show the specified revision or revset'),
4401 _(b'show the specified revision or revset'),
4402 _(b'REV'),
4402 _(b'REV'),
4403 ),
4403 ),
4404 (
4404 (
4405 b'L',
4405 b'L',
4406 b'line-range',
4406 b'line-range',
4407 [],
4407 [],
4408 _(b'follow line range of specified file (EXPERIMENTAL)'),
4408 _(b'follow line range of specified file (EXPERIMENTAL)'),
4409 _(b'FILE,RANGE'),
4409 _(b'FILE,RANGE'),
4410 ),
4410 ),
4411 (
4411 (
4412 b'',
4412 b'',
4413 b'removed',
4413 b'removed',
4414 None,
4414 None,
4415 _(b'include revisions where files were removed'),
4415 _(b'include revisions where files were removed'),
4416 ),
4416 ),
4417 (
4417 (
4418 b'm',
4418 b'm',
4419 b'only-merges',
4419 b'only-merges',
4420 None,
4420 None,
4421 _(b'show only merges (DEPRECATED) (use -r "merge()" instead)'),
4421 _(b'show only merges (DEPRECATED) (use -r "merge()" instead)'),
4422 ),
4422 ),
4423 (b'u', b'user', [], _(b'revisions committed by user'), _(b'USER')),
4423 (b'u', b'user', [], _(b'revisions committed by user'), _(b'USER')),
4424 (
4424 (
4425 b'',
4425 b'',
4426 b'only-branch',
4426 b'only-branch',
4427 [],
4427 [],
4428 _(
4428 _(
4429 b'show only changesets within the given named branch (DEPRECATED)'
4429 b'show only changesets within the given named branch (DEPRECATED)'
4430 ),
4430 ),
4431 _(b'BRANCH'),
4431 _(b'BRANCH'),
4432 ),
4432 ),
4433 (
4433 (
4434 b'b',
4434 b'b',
4435 b'branch',
4435 b'branch',
4436 [],
4436 [],
4437 _(b'show changesets within the given named branch'),
4437 _(b'show changesets within the given named branch'),
4438 _(b'BRANCH'),
4438 _(b'BRANCH'),
4439 ),
4439 ),
4440 (
4440 (
4441 b'P',
4441 b'P',
4442 b'prune',
4442 b'prune',
4443 [],
4443 [],
4444 _(b'do not display revision or any of its ancestors'),
4444 _(b'do not display revision or any of its ancestors'),
4445 _(b'REV'),
4445 _(b'REV'),
4446 ),
4446 ),
4447 ]
4447 ]
4448 + logopts
4448 + logopts
4449 + walkopts,
4449 + walkopts,
4450 _(b'[OPTION]... [FILE]'),
4450 _(b'[OPTION]... [FILE]'),
4451 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
4451 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
4452 helpbasic=True,
4452 helpbasic=True,
4453 inferrepo=True,
4453 inferrepo=True,
4454 intents={INTENT_READONLY},
4454 intents={INTENT_READONLY},
4455 )
4455 )
4456 def log(ui, repo, *pats, **opts):
4456 def log(ui, repo, *pats, **opts):
4457 """show revision history of entire repository or files
4457 """show revision history of entire repository or files
4458
4458
4459 Print the revision history of the specified files or the entire
4459 Print the revision history of the specified files or the entire
4460 project.
4460 project.
4461
4461
4462 If no revision range is specified, the default is ``tip:0`` unless
4462 If no revision range is specified, the default is ``tip:0`` unless
4463 --follow is set, in which case the working directory parent is
4463 --follow is set, in which case the working directory parent is
4464 used as the starting revision.
4464 used as the starting revision.
4465
4465
4466 File history is shown without following rename or copy history of
4466 File history is shown without following rename or copy history of
4467 files. Use -f/--follow with a filename to follow history across
4467 files. Use -f/--follow with a filename to follow history across
4468 renames and copies. --follow without a filename will only show
4468 renames and copies. --follow without a filename will only show
4469 ancestors of the starting revision.
4469 ancestors of the starting revision.
4470
4470
4471 By default this command prints revision number and changeset id,
4471 By default this command prints revision number and changeset id,
4472 tags, non-trivial parents, user, date and time, and a summary for
4472 tags, non-trivial parents, user, date and time, and a summary for
4473 each commit. When the -v/--verbose switch is used, the list of
4473 each commit. When the -v/--verbose switch is used, the list of
4474 changed files and full commit message are shown.
4474 changed files and full commit message are shown.
4475
4475
4476 With --graph the revisions are shown as an ASCII art DAG with the most
4476 With --graph the revisions are shown as an ASCII art DAG with the most
4477 recent changeset at the top.
4477 recent changeset at the top.
4478 'o' is a changeset, '@' is a working directory parent, '%' is a changeset
4478 'o' is a changeset, '@' is a working directory parent, '%' is a changeset
4479 involved in an unresolved merge conflict, '_' closes a branch,
4479 involved in an unresolved merge conflict, '_' closes a branch,
4480 'x' is obsolete, '*' is unstable, and '+' represents a fork where the
4480 'x' is obsolete, '*' is unstable, and '+' represents a fork where the
4481 changeset from the lines below is a parent of the 'o' merge on the same
4481 changeset from the lines below is a parent of the 'o' merge on the same
4482 line.
4482 line.
4483 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
4483 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
4484 of a '|' indicates one or more revisions in a path are omitted.
4484 of a '|' indicates one or more revisions in a path are omitted.
4485
4485
4486 .. container:: verbose
4486 .. container:: verbose
4487
4487
4488 Use -L/--line-range FILE,M:N options to follow the history of lines
4488 Use -L/--line-range FILE,M:N options to follow the history of lines
4489 from M to N in FILE. With -p/--patch only diff hunks affecting
4489 from M to N in FILE. With -p/--patch only diff hunks affecting
4490 specified line range will be shown. This option requires --follow;
4490 specified line range will be shown. This option requires --follow;
4491 it can be specified multiple times. Currently, this option is not
4491 it can be specified multiple times. Currently, this option is not
4492 compatible with --graph. This option is experimental.
4492 compatible with --graph. This option is experimental.
4493
4493
4494 .. note::
4494 .. note::
4495
4495
4496 :hg:`log --patch` may generate unexpected diff output for merge
4496 :hg:`log --patch` may generate unexpected diff output for merge
4497 changesets, as it will only compare the merge changeset against
4497 changesets, as it will only compare the merge changeset against
4498 its first parent. Also, only files different from BOTH parents
4498 its first parent. Also, only files different from BOTH parents
4499 will appear in files:.
4499 will appear in files:.
4500
4500
4501 .. note::
4501 .. note::
4502
4502
4503 For performance reasons, :hg:`log FILE` may omit duplicate changes
4503 For performance reasons, :hg:`log FILE` may omit duplicate changes
4504 made on branches and will not show removals or mode changes. To
4504 made on branches and will not show removals or mode changes. To
4505 see all such changes, use the --removed switch.
4505 see all such changes, use the --removed switch.
4506
4506
4507 .. container:: verbose
4507 .. container:: verbose
4508
4508
4509 .. note::
4509 .. note::
4510
4510
4511 The history resulting from -L/--line-range options depends on diff
4511 The history resulting from -L/--line-range options depends on diff
4512 options; for instance if white-spaces are ignored, respective changes
4512 options; for instance if white-spaces are ignored, respective changes
4513 with only white-spaces in specified line range will not be listed.
4513 with only white-spaces in specified line range will not be listed.
4514
4514
4515 .. container:: verbose
4515 .. container:: verbose
4516
4516
4517 Some examples:
4517 Some examples:
4518
4518
4519 - changesets with full descriptions and file lists::
4519 - changesets with full descriptions and file lists::
4520
4520
4521 hg log -v
4521 hg log -v
4522
4522
4523 - changesets ancestral to the working directory::
4523 - changesets ancestral to the working directory::
4524
4524
4525 hg log -f
4525 hg log -f
4526
4526
4527 - last 10 commits on the current branch::
4527 - last 10 commits on the current branch::
4528
4528
4529 hg log -l 10 -b .
4529 hg log -l 10 -b .
4530
4530
4531 - changesets showing all modifications of a file, including removals::
4531 - changesets showing all modifications of a file, including removals::
4532
4532
4533 hg log --removed file.c
4533 hg log --removed file.c
4534
4534
4535 - all changesets that touch a directory, with diffs, excluding merges::
4535 - all changesets that touch a directory, with diffs, excluding merges::
4536
4536
4537 hg log -Mp lib/
4537 hg log -Mp lib/
4538
4538
4539 - all revision numbers that match a keyword::
4539 - all revision numbers that match a keyword::
4540
4540
4541 hg log -k bug --template "{rev}\\n"
4541 hg log -k bug --template "{rev}\\n"
4542
4542
4543 - the full hash identifier of the working directory parent::
4543 - the full hash identifier of the working directory parent::
4544
4544
4545 hg log -r . --template "{node}\\n"
4545 hg log -r . --template "{node}\\n"
4546
4546
4547 - list available log templates::
4547 - list available log templates::
4548
4548
4549 hg log -T list
4549 hg log -T list
4550
4550
4551 - check if a given changeset is included in a tagged release::
4551 - check if a given changeset is included in a tagged release::
4552
4552
4553 hg log -r "a21ccf and ancestor(1.9)"
4553 hg log -r "a21ccf and ancestor(1.9)"
4554
4554
4555 - find all changesets by some user in a date range::
4555 - find all changesets by some user in a date range::
4556
4556
4557 hg log -k alice -d "may 2008 to jul 2008"
4557 hg log -k alice -d "may 2008 to jul 2008"
4558
4558
4559 - summary of all changesets after the last tag::
4559 - summary of all changesets after the last tag::
4560
4560
4561 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4561 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4562
4562
4563 - changesets touching lines 13 to 23 for file.c::
4563 - changesets touching lines 13 to 23 for file.c::
4564
4564
4565 hg log -L file.c,13:23
4565 hg log -L file.c,13:23
4566
4566
4567 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
4567 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
4568 main.c with patch::
4568 main.c with patch::
4569
4569
4570 hg log -L file.c,13:23 -L main.c,2:6 -p
4570 hg log -L file.c,13:23 -L main.c,2:6 -p
4571
4571
4572 See :hg:`help dates` for a list of formats valid for -d/--date.
4572 See :hg:`help dates` for a list of formats valid for -d/--date.
4573
4573
4574 See :hg:`help revisions` for more about specifying and ordering
4574 See :hg:`help revisions` for more about specifying and ordering
4575 revisions.
4575 revisions.
4576
4576
4577 See :hg:`help templates` for more about pre-packaged styles and
4577 See :hg:`help templates` for more about pre-packaged styles and
4578 specifying custom templates. The default template used by the log
4578 specifying custom templates. The default template used by the log
4579 command can be customized via the ``command-templates.log`` configuration
4579 command can be customized via the ``command-templates.log`` configuration
4580 setting.
4580 setting.
4581
4581
4582 Returns 0 on success.
4582 Returns 0 on success.
4583
4583
4584 """
4584 """
4585 opts = pycompat.byteskwargs(opts)
4585 opts = pycompat.byteskwargs(opts)
4586 linerange = opts.get(b'line_range')
4586 linerange = opts.get(b'line_range')
4587
4587
4588 if linerange and not opts.get(b'follow'):
4588 if linerange and not opts.get(b'follow'):
4589 raise error.Abort(_(b'--line-range requires --follow'))
4589 raise error.Abort(_(b'--line-range requires --follow'))
4590
4590
4591 if linerange and pats:
4591 if linerange and pats:
4592 # TODO: take pats as patterns with no line-range filter
4592 # TODO: take pats as patterns with no line-range filter
4593 raise error.Abort(
4593 raise error.Abort(
4594 _(b'FILE arguments are not compatible with --line-range option')
4594 _(b'FILE arguments are not compatible with --line-range option')
4595 )
4595 )
4596
4596
4597 repo = scmutil.unhidehashlikerevs(repo, opts.get(b'rev'), b'nowarn')
4597 repo = scmutil.unhidehashlikerevs(repo, opts.get(b'rev'), b'nowarn')
4598 revs, differ = logcmdutil.getrevs(
4598 revs, differ = logcmdutil.getrevs(
4599 repo, logcmdutil.parseopts(ui, pats, opts)
4599 repo, logcmdutil.parseopts(ui, pats, opts)
4600 )
4600 )
4601 if linerange:
4601 if linerange:
4602 # TODO: should follow file history from logcmdutil._initialrevs(),
4602 # TODO: should follow file history from logcmdutil._initialrevs(),
4603 # then filter the result by logcmdutil._makerevset() and --limit
4603 # then filter the result by logcmdutil._makerevset() and --limit
4604 revs, differ = logcmdutil.getlinerangerevs(repo, revs, opts)
4604 revs, differ = logcmdutil.getlinerangerevs(repo, revs, opts)
4605
4605
4606 getcopies = None
4606 getcopies = None
4607 if opts.get(b'copies'):
4607 if opts.get(b'copies'):
4608 endrev = None
4608 endrev = None
4609 if revs:
4609 if revs:
4610 endrev = revs.max() + 1
4610 endrev = revs.max() + 1
4611 getcopies = scmutil.getcopiesfn(repo, endrev=endrev)
4611 getcopies = scmutil.getcopiesfn(repo, endrev=endrev)
4612
4612
4613 ui.pager(b'log')
4613 ui.pager(b'log')
4614 displayer = logcmdutil.changesetdisplayer(
4614 displayer = logcmdutil.changesetdisplayer(
4615 ui, repo, opts, differ, buffered=True
4615 ui, repo, opts, differ, buffered=True
4616 )
4616 )
4617 if opts.get(b'graph'):
4617 if opts.get(b'graph'):
4618 displayfn = logcmdutil.displaygraphrevs
4618 displayfn = logcmdutil.displaygraphrevs
4619 else:
4619 else:
4620 displayfn = logcmdutil.displayrevs
4620 displayfn = logcmdutil.displayrevs
4621 displayfn(ui, repo, revs, displayer, getcopies)
4621 displayfn(ui, repo, revs, displayer, getcopies)
4622
4622
4623
4623
4624 @command(
4624 @command(
4625 b'manifest',
4625 b'manifest',
4626 [
4626 [
4627 (b'r', b'rev', b'', _(b'revision to display'), _(b'REV')),
4627 (b'r', b'rev', b'', _(b'revision to display'), _(b'REV')),
4628 (b'', b'all', False, _(b"list files from all revisions")),
4628 (b'', b'all', False, _(b"list files from all revisions")),
4629 ]
4629 ]
4630 + formatteropts,
4630 + formatteropts,
4631 _(b'[-r REV]'),
4631 _(b'[-r REV]'),
4632 helpcategory=command.CATEGORY_MAINTENANCE,
4632 helpcategory=command.CATEGORY_MAINTENANCE,
4633 intents={INTENT_READONLY},
4633 intents={INTENT_READONLY},
4634 )
4634 )
4635 def manifest(ui, repo, node=None, rev=None, **opts):
4635 def manifest(ui, repo, node=None, rev=None, **opts):
4636 """output the current or given revision of the project manifest
4636 """output the current or given revision of the project manifest
4637
4637
4638 Print a list of version controlled files for the given revision.
4638 Print a list of version controlled files for the given revision.
4639 If no revision is given, the first parent of the working directory
4639 If no revision is given, the first parent of the working directory
4640 is used, or the null revision if no revision is checked out.
4640 is used, or the null revision if no revision is checked out.
4641
4641
4642 With -v, print file permissions, symlink and executable bits.
4642 With -v, print file permissions, symlink and executable bits.
4643 With --debug, print file revision hashes.
4643 With --debug, print file revision hashes.
4644
4644
4645 If option --all is specified, the list of all files from all revisions
4645 If option --all is specified, the list of all files from all revisions
4646 is printed. This includes deleted and renamed files.
4646 is printed. This includes deleted and renamed files.
4647
4647
4648 Returns 0 on success.
4648 Returns 0 on success.
4649 """
4649 """
4650 opts = pycompat.byteskwargs(opts)
4650 opts = pycompat.byteskwargs(opts)
4651 fm = ui.formatter(b'manifest', opts)
4651 fm = ui.formatter(b'manifest', opts)
4652
4652
4653 if opts.get(b'all'):
4653 if opts.get(b'all'):
4654 if rev or node:
4654 if rev or node:
4655 raise error.Abort(_(b"can't specify a revision with --all"))
4655 raise error.Abort(_(b"can't specify a revision with --all"))
4656
4656
4657 res = set()
4657 res = set()
4658 for rev in repo:
4658 for rev in repo:
4659 ctx = repo[rev]
4659 ctx = repo[rev]
4660 res |= set(ctx.files())
4660 res |= set(ctx.files())
4661
4661
4662 ui.pager(b'manifest')
4662 ui.pager(b'manifest')
4663 for f in sorted(res):
4663 for f in sorted(res):
4664 fm.startitem()
4664 fm.startitem()
4665 fm.write(b"path", b'%s\n', f)
4665 fm.write(b"path", b'%s\n', f)
4666 fm.end()
4666 fm.end()
4667 return
4667 return
4668
4668
4669 if rev and node:
4669 if rev and node:
4670 raise error.Abort(_(b"please specify just one revision"))
4670 raise error.Abort(_(b"please specify just one revision"))
4671
4671
4672 if not node:
4672 if not node:
4673 node = rev
4673 node = rev
4674
4674
4675 char = {b'l': b'@', b'x': b'*', b'': b'', b't': b'd'}
4675 char = {b'l': b'@', b'x': b'*', b'': b'', b't': b'd'}
4676 mode = {b'l': b'644', b'x': b'755', b'': b'644', b't': b'755'}
4676 mode = {b'l': b'644', b'x': b'755', b'': b'644', b't': b'755'}
4677 if node:
4677 if node:
4678 repo = scmutil.unhidehashlikerevs(repo, [node], b'nowarn')
4678 repo = scmutil.unhidehashlikerevs(repo, [node], b'nowarn')
4679 ctx = scmutil.revsingle(repo, node)
4679 ctx = scmutil.revsingle(repo, node)
4680 mf = ctx.manifest()
4680 mf = ctx.manifest()
4681 ui.pager(b'manifest')
4681 ui.pager(b'manifest')
4682 for f in ctx:
4682 for f in ctx:
4683 fm.startitem()
4683 fm.startitem()
4684 fm.context(ctx=ctx)
4684 fm.context(ctx=ctx)
4685 fl = ctx[f].flags()
4685 fl = ctx[f].flags()
4686 fm.condwrite(ui.debugflag, b'hash', b'%s ', hex(mf[f]))
4686 fm.condwrite(ui.debugflag, b'hash', b'%s ', hex(mf[f]))
4687 fm.condwrite(ui.verbose, b'mode type', b'%s %1s ', mode[fl], char[fl])
4687 fm.condwrite(ui.verbose, b'mode type', b'%s %1s ', mode[fl], char[fl])
4688 fm.write(b'path', b'%s\n', f)
4688 fm.write(b'path', b'%s\n', f)
4689 fm.end()
4689 fm.end()
4690
4690
4691
4691
4692 @command(
4692 @command(
4693 b'merge',
4693 b'merge',
4694 [
4694 [
4695 (
4695 (
4696 b'f',
4696 b'f',
4697 b'force',
4697 b'force',
4698 None,
4698 None,
4699 _(b'force a merge including outstanding changes (DEPRECATED)'),
4699 _(b'force a merge including outstanding changes (DEPRECATED)'),
4700 ),
4700 ),
4701 (b'r', b'rev', b'', _(b'revision to merge'), _(b'REV')),
4701 (b'r', b'rev', b'', _(b'revision to merge'), _(b'REV')),
4702 (
4702 (
4703 b'P',
4703 b'P',
4704 b'preview',
4704 b'preview',
4705 None,
4705 None,
4706 _(b'review revisions to merge (no merge is performed)'),
4706 _(b'review revisions to merge (no merge is performed)'),
4707 ),
4707 ),
4708 (b'', b'abort', None, _(b'abort the ongoing merge')),
4708 (b'', b'abort', None, _(b'abort the ongoing merge')),
4709 ]
4709 ]
4710 + mergetoolopts,
4710 + mergetoolopts,
4711 _(b'[-P] [[-r] REV]'),
4711 _(b'[-P] [[-r] REV]'),
4712 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
4712 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
4713 helpbasic=True,
4713 helpbasic=True,
4714 )
4714 )
4715 def merge(ui, repo, node=None, **opts):
4715 def merge(ui, repo, node=None, **opts):
4716 """merge another revision into working directory
4716 """merge another revision into working directory
4717
4717
4718 The current working directory is updated with all changes made in
4718 The current working directory is updated with all changes made in
4719 the requested revision since the last common predecessor revision.
4719 the requested revision since the last common predecessor revision.
4720
4720
4721 Files that changed between either parent are marked as changed for
4721 Files that changed between either parent are marked as changed for
4722 the next commit and a commit must be performed before any further
4722 the next commit and a commit must be performed before any further
4723 updates to the repository are allowed. The next commit will have
4723 updates to the repository are allowed. The next commit will have
4724 two parents.
4724 two parents.
4725
4725
4726 ``--tool`` can be used to specify the merge tool used for file
4726 ``--tool`` can be used to specify the merge tool used for file
4727 merges. It overrides the HGMERGE environment variable and your
4727 merges. It overrides the HGMERGE environment variable and your
4728 configuration files. See :hg:`help merge-tools` for options.
4728 configuration files. See :hg:`help merge-tools` for options.
4729
4729
4730 If no revision is specified, the working directory's parent is a
4730 If no revision is specified, the working directory's parent is a
4731 head revision, and the current branch contains exactly one other
4731 head revision, and the current branch contains exactly one other
4732 head, the other head is merged with by default. Otherwise, an
4732 head, the other head is merged with by default. Otherwise, an
4733 explicit revision with which to merge must be provided.
4733 explicit revision with which to merge must be provided.
4734
4734
4735 See :hg:`help resolve` for information on handling file conflicts.
4735 See :hg:`help resolve` for information on handling file conflicts.
4736
4736
4737 To undo an uncommitted merge, use :hg:`merge --abort` which
4737 To undo an uncommitted merge, use :hg:`merge --abort` which
4738 will check out a clean copy of the original merge parent, losing
4738 will check out a clean copy of the original merge parent, losing
4739 all changes.
4739 all changes.
4740
4740
4741 Returns 0 on success, 1 if there are unresolved files.
4741 Returns 0 on success, 1 if there are unresolved files.
4742 """
4742 """
4743
4743
4744 opts = pycompat.byteskwargs(opts)
4744 opts = pycompat.byteskwargs(opts)
4745 abort = opts.get(b'abort')
4745 abort = opts.get(b'abort')
4746 if abort and repo.dirstate.p2() == nullid:
4746 if abort and repo.dirstate.p2() == nullid:
4747 cmdutil.wrongtooltocontinue(repo, _(b'merge'))
4747 cmdutil.wrongtooltocontinue(repo, _(b'merge'))
4748 cmdutil.check_incompatible_arguments(opts, b'abort', [b'rev', b'preview'])
4748 cmdutil.check_incompatible_arguments(opts, b'abort', [b'rev', b'preview'])
4749 if abort:
4749 if abort:
4750 state = cmdutil.getunfinishedstate(repo)
4750 state = cmdutil.getunfinishedstate(repo)
4751 if state and state._opname != b'merge':
4751 if state and state._opname != b'merge':
4752 raise error.Abort(
4752 raise error.Abort(
4753 _(b'cannot abort merge with %s in progress') % (state._opname),
4753 _(b'cannot abort merge with %s in progress') % (state._opname),
4754 hint=state.hint(),
4754 hint=state.hint(),
4755 )
4755 )
4756 if node:
4756 if node:
4757 raise error.Abort(_(b"cannot specify a node with --abort"))
4757 raise error.Abort(_(b"cannot specify a node with --abort"))
4758 return hg.abortmerge(repo.ui, repo)
4758 return hg.abortmerge(repo.ui, repo)
4759
4759
4760 if opts.get(b'rev') and node:
4760 if opts.get(b'rev') and node:
4761 raise error.Abort(_(b"please specify just one revision"))
4761 raise error.Abort(_(b"please specify just one revision"))
4762 if not node:
4762 if not node:
4763 node = opts.get(b'rev')
4763 node = opts.get(b'rev')
4764
4764
4765 if node:
4765 if node:
4766 ctx = scmutil.revsingle(repo, node)
4766 ctx = scmutil.revsingle(repo, node)
4767 else:
4767 else:
4768 if ui.configbool(b'commands', b'merge.require-rev'):
4768 if ui.configbool(b'commands', b'merge.require-rev'):
4769 raise error.Abort(
4769 raise error.Abort(
4770 _(
4770 _(
4771 b'configuration requires specifying revision to merge '
4771 b'configuration requires specifying revision to merge '
4772 b'with'
4772 b'with'
4773 )
4773 )
4774 )
4774 )
4775 ctx = repo[destutil.destmerge(repo)]
4775 ctx = repo[destutil.destmerge(repo)]
4776
4776
4777 if ctx.node() is None:
4777 if ctx.node() is None:
4778 raise error.Abort(_(b'merging with the working copy has no effect'))
4778 raise error.Abort(_(b'merging with the working copy has no effect'))
4779
4779
4780 if opts.get(b'preview'):
4780 if opts.get(b'preview'):
4781 # find nodes that are ancestors of p2 but not of p1
4781 # find nodes that are ancestors of p2 but not of p1
4782 p1 = repo[b'.'].node()
4782 p1 = repo[b'.'].node()
4783 p2 = ctx.node()
4783 p2 = ctx.node()
4784 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4784 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4785
4785
4786 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4786 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4787 for node in nodes:
4787 for node in nodes:
4788 displayer.show(repo[node])
4788 displayer.show(repo[node])
4789 displayer.close()
4789 displayer.close()
4790 return 0
4790 return 0
4791
4791
4792 # ui.forcemerge is an internal variable, do not document
4792 # ui.forcemerge is an internal variable, do not document
4793 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
4793 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
4794 with ui.configoverride(overrides, b'merge'):
4794 with ui.configoverride(overrides, b'merge'):
4795 force = opts.get(b'force')
4795 force = opts.get(b'force')
4796 labels = [b'working copy', b'merge rev']
4796 labels = [b'working copy', b'merge rev']
4797 return hg.merge(ctx, force=force, labels=labels)
4797 return hg.merge(ctx, force=force, labels=labels)
4798
4798
4799
4799
4800 statemod.addunfinished(
4800 statemod.addunfinished(
4801 b'merge',
4801 b'merge',
4802 fname=None,
4802 fname=None,
4803 clearable=True,
4803 clearable=True,
4804 allowcommit=True,
4804 allowcommit=True,
4805 cmdmsg=_(b'outstanding uncommitted merge'),
4805 cmdmsg=_(b'outstanding uncommitted merge'),
4806 abortfunc=hg.abortmerge,
4806 abortfunc=hg.abortmerge,
4807 statushint=_(
4807 statushint=_(
4808 b'To continue: hg commit\nTo abort: hg merge --abort'
4808 b'To continue: hg commit\nTo abort: hg merge --abort'
4809 ),
4809 ),
4810 cmdhint=_(b"use 'hg commit' or 'hg merge --abort'"),
4810 cmdhint=_(b"use 'hg commit' or 'hg merge --abort'"),
4811 )
4811 )
4812
4812
4813
4813
4814 @command(
4814 @command(
4815 b'outgoing|out',
4815 b'outgoing|out',
4816 [
4816 [
4817 (
4817 (
4818 b'f',
4818 b'f',
4819 b'force',
4819 b'force',
4820 None,
4820 None,
4821 _(b'run even when the destination is unrelated'),
4821 _(b'run even when the destination is unrelated'),
4822 ),
4822 ),
4823 (
4823 (
4824 b'r',
4824 b'r',
4825 b'rev',
4825 b'rev',
4826 [],
4826 [],
4827 _(b'a changeset intended to be included in the destination'),
4827 _(b'a changeset intended to be included in the destination'),
4828 _(b'REV'),
4828 _(b'REV'),
4829 ),
4829 ),
4830 (b'n', b'newest-first', None, _(b'show newest record first')),
4830 (b'n', b'newest-first', None, _(b'show newest record first')),
4831 (b'B', b'bookmarks', False, _(b'compare bookmarks')),
4831 (b'B', b'bookmarks', False, _(b'compare bookmarks')),
4832 (
4832 (
4833 b'b',
4833 b'b',
4834 b'branch',
4834 b'branch',
4835 [],
4835 [],
4836 _(b'a specific branch you would like to push'),
4836 _(b'a specific branch you would like to push'),
4837 _(b'BRANCH'),
4837 _(b'BRANCH'),
4838 ),
4838 ),
4839 ]
4839 ]
4840 + logopts
4840 + logopts
4841 + remoteopts
4841 + remoteopts
4842 + subrepoopts,
4842 + subrepoopts,
4843 _(b'[-M] [-p] [-n] [-f] [-r REV]... [DEST]'),
4843 _(b'[-M] [-p] [-n] [-f] [-r REV]... [DEST]'),
4844 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4844 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4845 )
4845 )
4846 def outgoing(ui, repo, dest=None, **opts):
4846 def outgoing(ui, repo, dest=None, **opts):
4847 """show changesets not found in the destination
4847 """show changesets not found in the destination
4848
4848
4849 Show changesets not found in the specified destination repository
4849 Show changesets not found in the specified destination repository
4850 or the default push location. These are the changesets that would
4850 or the default push location. These are the changesets that would
4851 be pushed if a push was requested.
4851 be pushed if a push was requested.
4852
4852
4853 See pull for details of valid destination formats.
4853 See pull for details of valid destination formats.
4854
4854
4855 .. container:: verbose
4855 .. container:: verbose
4856
4856
4857 With -B/--bookmarks, the result of bookmark comparison between
4857 With -B/--bookmarks, the result of bookmark comparison between
4858 local and remote repositories is displayed. With -v/--verbose,
4858 local and remote repositories is displayed. With -v/--verbose,
4859 status is also displayed for each bookmark like below::
4859 status is also displayed for each bookmark like below::
4860
4860
4861 BM1 01234567890a added
4861 BM1 01234567890a added
4862 BM2 deleted
4862 BM2 deleted
4863 BM3 234567890abc advanced
4863 BM3 234567890abc advanced
4864 BM4 34567890abcd diverged
4864 BM4 34567890abcd diverged
4865 BM5 4567890abcde changed
4865 BM5 4567890abcde changed
4866
4866
4867 The action taken when pushing depends on the
4867 The action taken when pushing depends on the
4868 status of each bookmark:
4868 status of each bookmark:
4869
4869
4870 :``added``: push with ``-B`` will create it
4870 :``added``: push with ``-B`` will create it
4871 :``deleted``: push with ``-B`` will delete it
4871 :``deleted``: push with ``-B`` will delete it
4872 :``advanced``: push will update it
4872 :``advanced``: push will update it
4873 :``diverged``: push with ``-B`` will update it
4873 :``diverged``: push with ``-B`` will update it
4874 :``changed``: push with ``-B`` will update it
4874 :``changed``: push with ``-B`` will update it
4875
4875
4876 From the point of view of pushing behavior, bookmarks
4876 From the point of view of pushing behavior, bookmarks
4877 existing only in the remote repository are treated as
4877 existing only in the remote repository are treated as
4878 ``deleted``, even if it is in fact added remotely.
4878 ``deleted``, even if it is in fact added remotely.
4879
4879
4880 Returns 0 if there are outgoing changes, 1 otherwise.
4880 Returns 0 if there are outgoing changes, 1 otherwise.
4881 """
4881 """
4882 # hg._outgoing() needs to re-resolve the path in order to handle #branch
4882 # hg._outgoing() needs to re-resolve the path in order to handle #branch
4883 # style URLs, so don't overwrite dest.
4883 # style URLs, so don't overwrite dest.
4884 path = ui.paths.getpath(dest, default=(b'default-push', b'default'))
4884 path = ui.paths.getpath(dest, default=(b'default-push', b'default'))
4885 if not path:
4885 if not path:
4886 raise error.Abort(
4886 raise error.Abort(
4887 _(b'default repository not configured!'),
4887 _(b'default repository not configured!'),
4888 hint=_(b"see 'hg help config.paths'"),
4888 hint=_(b"see 'hg help config.paths'"),
4889 )
4889 )
4890
4890
4891 opts = pycompat.byteskwargs(opts)
4891 opts = pycompat.byteskwargs(opts)
4892 if opts.get(b'graph'):
4892 if opts.get(b'graph'):
4893 logcmdutil.checkunsupportedgraphflags([], opts)
4893 logcmdutil.checkunsupportedgraphflags([], opts)
4894 o, other = hg._outgoing(ui, repo, dest, opts)
4894 o, other = hg._outgoing(ui, repo, dest, opts)
4895 if not o:
4895 if not o:
4896 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4896 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4897 return
4897 return
4898
4898
4899 revdag = logcmdutil.graphrevs(repo, o, opts)
4899 revdag = logcmdutil.graphrevs(repo, o, opts)
4900 ui.pager(b'outgoing')
4900 ui.pager(b'outgoing')
4901 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, buffered=True)
4901 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, buffered=True)
4902 logcmdutil.displaygraph(
4902 logcmdutil.displaygraph(
4903 ui, repo, revdag, displayer, graphmod.asciiedges
4903 ui, repo, revdag, displayer, graphmod.asciiedges
4904 )
4904 )
4905 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4905 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4906 return 0
4906 return 0
4907
4907
4908 if opts.get(b'bookmarks'):
4908 if opts.get(b'bookmarks'):
4909 dest = path.pushloc or path.loc
4909 dest = path.pushloc or path.loc
4910 other = hg.peer(repo, opts, dest)
4910 other = hg.peer(repo, opts, dest)
4911 if b'bookmarks' not in other.listkeys(b'namespaces'):
4911 if b'bookmarks' not in other.listkeys(b'namespaces'):
4912 ui.warn(_(b"remote doesn't support bookmarks\n"))
4912 ui.warn(_(b"remote doesn't support bookmarks\n"))
4913 return 0
4913 return 0
4914 ui.status(_(b'comparing with %s\n') % util.hidepassword(dest))
4914 ui.status(_(b'comparing with %s\n') % util.hidepassword(dest))
4915 ui.pager(b'outgoing')
4915 ui.pager(b'outgoing')
4916 return bookmarks.outgoing(ui, repo, other)
4916 return bookmarks.outgoing(ui, repo, other)
4917
4917
4918 repo._subtoppath = path.pushloc or path.loc
4918 repo._subtoppath = path.pushloc or path.loc
4919 try:
4919 try:
4920 return hg.outgoing(ui, repo, dest, opts)
4920 return hg.outgoing(ui, repo, dest, opts)
4921 finally:
4921 finally:
4922 del repo._subtoppath
4922 del repo._subtoppath
4923
4923
4924
4924
4925 @command(
4925 @command(
4926 b'parents',
4926 b'parents',
4927 [
4927 [
4928 (
4928 (
4929 b'r',
4929 b'r',
4930 b'rev',
4930 b'rev',
4931 b'',
4931 b'',
4932 _(b'show parents of the specified revision'),
4932 _(b'show parents of the specified revision'),
4933 _(b'REV'),
4933 _(b'REV'),
4934 ),
4934 ),
4935 ]
4935 ]
4936 + templateopts,
4936 + templateopts,
4937 _(b'[-r REV] [FILE]'),
4937 _(b'[-r REV] [FILE]'),
4938 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
4938 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
4939 inferrepo=True,
4939 inferrepo=True,
4940 )
4940 )
4941 def parents(ui, repo, file_=None, **opts):
4941 def parents(ui, repo, file_=None, **opts):
4942 """show the parents of the working directory or revision (DEPRECATED)
4942 """show the parents of the working directory or revision (DEPRECATED)
4943
4943
4944 Print the working directory's parent revisions. If a revision is
4944 Print the working directory's parent revisions. If a revision is
4945 given via -r/--rev, the parent of that revision will be printed.
4945 given via -r/--rev, the parent of that revision will be printed.
4946 If a file argument is given, the revision in which the file was
4946 If a file argument is given, the revision in which the file was
4947 last changed (before the working directory revision or the
4947 last changed (before the working directory revision or the
4948 argument to --rev if given) is printed.
4948 argument to --rev if given) is printed.
4949
4949
4950 This command is equivalent to::
4950 This command is equivalent to::
4951
4951
4952 hg log -r "p1()+p2()" or
4952 hg log -r "p1()+p2()" or
4953 hg log -r "p1(REV)+p2(REV)" or
4953 hg log -r "p1(REV)+p2(REV)" or
4954 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
4954 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
4955 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
4955 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
4956
4956
4957 See :hg:`summary` and :hg:`help revsets` for related information.
4957 See :hg:`summary` and :hg:`help revsets` for related information.
4958
4958
4959 Returns 0 on success.
4959 Returns 0 on success.
4960 """
4960 """
4961
4961
4962 opts = pycompat.byteskwargs(opts)
4962 opts = pycompat.byteskwargs(opts)
4963 rev = opts.get(b'rev')
4963 rev = opts.get(b'rev')
4964 if rev:
4964 if rev:
4965 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
4965 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
4966 ctx = scmutil.revsingle(repo, rev, None)
4966 ctx = scmutil.revsingle(repo, rev, None)
4967
4967
4968 if file_:
4968 if file_:
4969 m = scmutil.match(ctx, (file_,), opts)
4969 m = scmutil.match(ctx, (file_,), opts)
4970 if m.anypats() or len(m.files()) != 1:
4970 if m.anypats() or len(m.files()) != 1:
4971 raise error.Abort(_(b'can only specify an explicit filename'))
4971 raise error.Abort(_(b'can only specify an explicit filename'))
4972 file_ = m.files()[0]
4972 file_ = m.files()[0]
4973 filenodes = []
4973 filenodes = []
4974 for cp in ctx.parents():
4974 for cp in ctx.parents():
4975 if not cp:
4975 if not cp:
4976 continue
4976 continue
4977 try:
4977 try:
4978 filenodes.append(cp.filenode(file_))
4978 filenodes.append(cp.filenode(file_))
4979 except error.LookupError:
4979 except error.LookupError:
4980 pass
4980 pass
4981 if not filenodes:
4981 if not filenodes:
4982 raise error.Abort(_(b"'%s' not found in manifest!") % file_)
4982 raise error.Abort(_(b"'%s' not found in manifest!") % file_)
4983 p = []
4983 p = []
4984 for fn in filenodes:
4984 for fn in filenodes:
4985 fctx = repo.filectx(file_, fileid=fn)
4985 fctx = repo.filectx(file_, fileid=fn)
4986 p.append(fctx.node())
4986 p.append(fctx.node())
4987 else:
4987 else:
4988 p = [cp.node() for cp in ctx.parents()]
4988 p = [cp.node() for cp in ctx.parents()]
4989
4989
4990 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4990 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4991 for n in p:
4991 for n in p:
4992 if n != nullid:
4992 if n != nullid:
4993 displayer.show(repo[n])
4993 displayer.show(repo[n])
4994 displayer.close()
4994 displayer.close()
4995
4995
4996
4996
4997 @command(
4997 @command(
4998 b'paths',
4998 b'paths',
4999 formatteropts,
4999 formatteropts,
5000 _(b'[NAME]'),
5000 _(b'[NAME]'),
5001 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5001 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5002 optionalrepo=True,
5002 optionalrepo=True,
5003 intents={INTENT_READONLY},
5003 intents={INTENT_READONLY},
5004 )
5004 )
5005 def paths(ui, repo, search=None, **opts):
5005 def paths(ui, repo, search=None, **opts):
5006 """show aliases for remote repositories
5006 """show aliases for remote repositories
5007
5007
5008 Show definition of symbolic path name NAME. If no name is given,
5008 Show definition of symbolic path name NAME. If no name is given,
5009 show definition of all available names.
5009 show definition of all available names.
5010
5010
5011 Option -q/--quiet suppresses all output when searching for NAME
5011 Option -q/--quiet suppresses all output when searching for NAME
5012 and shows only the path names when listing all definitions.
5012 and shows only the path names when listing all definitions.
5013
5013
5014 Path names are defined in the [paths] section of your
5014 Path names are defined in the [paths] section of your
5015 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
5015 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
5016 repository, ``.hg/hgrc`` is used, too.
5016 repository, ``.hg/hgrc`` is used, too.
5017
5017
5018 The path names ``default`` and ``default-push`` have a special
5018 The path names ``default`` and ``default-push`` have a special
5019 meaning. When performing a push or pull operation, they are used
5019 meaning. When performing a push or pull operation, they are used
5020 as fallbacks if no location is specified on the command-line.
5020 as fallbacks if no location is specified on the command-line.
5021 When ``default-push`` is set, it will be used for push and
5021 When ``default-push`` is set, it will be used for push and
5022 ``default`` will be used for pull; otherwise ``default`` is used
5022 ``default`` will be used for pull; otherwise ``default`` is used
5023 as the fallback for both. When cloning a repository, the clone
5023 as the fallback for both. When cloning a repository, the clone
5024 source is written as ``default`` in ``.hg/hgrc``.
5024 source is written as ``default`` in ``.hg/hgrc``.
5025
5025
5026 .. note::
5026 .. note::
5027
5027
5028 ``default`` and ``default-push`` apply to all inbound (e.g.
5028 ``default`` and ``default-push`` apply to all inbound (e.g.
5029 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
5029 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
5030 and :hg:`bundle`) operations.
5030 and :hg:`bundle`) operations.
5031
5031
5032 See :hg:`help urls` for more information.
5032 See :hg:`help urls` for more information.
5033
5033
5034 .. container:: verbose
5034 .. container:: verbose
5035
5035
5036 Template:
5036 Template:
5037
5037
5038 The following keywords are supported. See also :hg:`help templates`.
5038 The following keywords are supported. See also :hg:`help templates`.
5039
5039
5040 :name: String. Symbolic name of the path alias.
5040 :name: String. Symbolic name of the path alias.
5041 :pushurl: String. URL for push operations.
5041 :pushurl: String. URL for push operations.
5042 :url: String. URL or directory path for the other operations.
5042 :url: String. URL or directory path for the other operations.
5043
5043
5044 Returns 0 on success.
5044 Returns 0 on success.
5045 """
5045 """
5046
5046
5047 opts = pycompat.byteskwargs(opts)
5047 opts = pycompat.byteskwargs(opts)
5048 ui.pager(b'paths')
5048 ui.pager(b'paths')
5049 if search:
5049 if search:
5050 pathitems = [
5050 pathitems = [
5051 (name, path)
5051 (name, path)
5052 for name, path in pycompat.iteritems(ui.paths)
5052 for name, path in pycompat.iteritems(ui.paths)
5053 if name == search
5053 if name == search
5054 ]
5054 ]
5055 else:
5055 else:
5056 pathitems = sorted(pycompat.iteritems(ui.paths))
5056 pathitems = sorted(pycompat.iteritems(ui.paths))
5057
5057
5058 fm = ui.formatter(b'paths', opts)
5058 fm = ui.formatter(b'paths', opts)
5059 if fm.isplain():
5059 if fm.isplain():
5060 hidepassword = util.hidepassword
5060 hidepassword = util.hidepassword
5061 else:
5061 else:
5062 hidepassword = bytes
5062 hidepassword = bytes
5063 if ui.quiet:
5063 if ui.quiet:
5064 namefmt = b'%s\n'
5064 namefmt = b'%s\n'
5065 else:
5065 else:
5066 namefmt = b'%s = '
5066 namefmt = b'%s = '
5067 showsubopts = not search and not ui.quiet
5067 showsubopts = not search and not ui.quiet
5068
5068
5069 for name, path in pathitems:
5069 for name, path in pathitems:
5070 fm.startitem()
5070 fm.startitem()
5071 fm.condwrite(not search, b'name', namefmt, name)
5071 fm.condwrite(not search, b'name', namefmt, name)
5072 fm.condwrite(not ui.quiet, b'url', b'%s\n', hidepassword(path.rawloc))
5072 fm.condwrite(not ui.quiet, b'url', b'%s\n', hidepassword(path.rawloc))
5073 for subopt, value in sorted(path.suboptions.items()):
5073 for subopt, value in sorted(path.suboptions.items()):
5074 assert subopt not in (b'name', b'url')
5074 assert subopt not in (b'name', b'url')
5075 if showsubopts:
5075 if showsubopts:
5076 fm.plain(b'%s:%s = ' % (name, subopt))
5076 fm.plain(b'%s:%s = ' % (name, subopt))
5077 fm.condwrite(showsubopts, subopt, b'%s\n', value)
5077 fm.condwrite(showsubopts, subopt, b'%s\n', value)
5078
5078
5079 fm.end()
5079 fm.end()
5080
5080
5081 if search and not pathitems:
5081 if search and not pathitems:
5082 if not ui.quiet:
5082 if not ui.quiet:
5083 ui.warn(_(b"not found!\n"))
5083 ui.warn(_(b"not found!\n"))
5084 return 1
5084 return 1
5085 else:
5085 else:
5086 return 0
5086 return 0
5087
5087
5088
5088
5089 @command(
5089 @command(
5090 b'phase',
5090 b'phase',
5091 [
5091 [
5092 (b'p', b'public', False, _(b'set changeset phase to public')),
5092 (b'p', b'public', False, _(b'set changeset phase to public')),
5093 (b'd', b'draft', False, _(b'set changeset phase to draft')),
5093 (b'd', b'draft', False, _(b'set changeset phase to draft')),
5094 (b's', b'secret', False, _(b'set changeset phase to secret')),
5094 (b's', b'secret', False, _(b'set changeset phase to secret')),
5095 (b'f', b'force', False, _(b'allow to move boundary backward')),
5095 (b'f', b'force', False, _(b'allow to move boundary backward')),
5096 (b'r', b'rev', [], _(b'target revision'), _(b'REV')),
5096 (b'r', b'rev', [], _(b'target revision'), _(b'REV')),
5097 ],
5097 ],
5098 _(b'[-p|-d|-s] [-f] [-r] [REV...]'),
5098 _(b'[-p|-d|-s] [-f] [-r] [REV...]'),
5099 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
5099 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
5100 )
5100 )
5101 def phase(ui, repo, *revs, **opts):
5101 def phase(ui, repo, *revs, **opts):
5102 """set or show the current phase name
5102 """set or show the current phase name
5103
5103
5104 With no argument, show the phase name of the current revision(s).
5104 With no argument, show the phase name of the current revision(s).
5105
5105
5106 With one of -p/--public, -d/--draft or -s/--secret, change the
5106 With one of -p/--public, -d/--draft or -s/--secret, change the
5107 phase value of the specified revisions.
5107 phase value of the specified revisions.
5108
5108
5109 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
5109 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
5110 lower phase to a higher phase. Phases are ordered as follows::
5110 lower phase to a higher phase. Phases are ordered as follows::
5111
5111
5112 public < draft < secret
5112 public < draft < secret
5113
5113
5114 Returns 0 on success, 1 if some phases could not be changed.
5114 Returns 0 on success, 1 if some phases could not be changed.
5115
5115
5116 (For more information about the phases concept, see :hg:`help phases`.)
5116 (For more information about the phases concept, see :hg:`help phases`.)
5117 """
5117 """
5118 opts = pycompat.byteskwargs(opts)
5118 opts = pycompat.byteskwargs(opts)
5119 # search for a unique phase argument
5119 # search for a unique phase argument
5120 targetphase = None
5120 targetphase = None
5121 for idx, name in enumerate(phases.cmdphasenames):
5121 for idx, name in enumerate(phases.cmdphasenames):
5122 if opts[name]:
5122 if opts[name]:
5123 if targetphase is not None:
5123 if targetphase is not None:
5124 raise error.Abort(_(b'only one phase can be specified'))
5124 raise error.Abort(_(b'only one phase can be specified'))
5125 targetphase = idx
5125 targetphase = idx
5126
5126
5127 # look for specified revision
5127 # look for specified revision
5128 revs = list(revs)
5128 revs = list(revs)
5129 revs.extend(opts[b'rev'])
5129 revs.extend(opts[b'rev'])
5130 if not revs:
5130 if not revs:
5131 # display both parents as the second parent phase can influence
5131 # display both parents as the second parent phase can influence
5132 # the phase of a merge commit
5132 # the phase of a merge commit
5133 revs = [c.rev() for c in repo[None].parents()]
5133 revs = [c.rev() for c in repo[None].parents()]
5134
5134
5135 revs = scmutil.revrange(repo, revs)
5135 revs = scmutil.revrange(repo, revs)
5136
5136
5137 ret = 0
5137 ret = 0
5138 if targetphase is None:
5138 if targetphase is None:
5139 # display
5139 # display
5140 for r in revs:
5140 for r in revs:
5141 ctx = repo[r]
5141 ctx = repo[r]
5142 ui.write(b'%i: %s\n' % (ctx.rev(), ctx.phasestr()))
5142 ui.write(b'%i: %s\n' % (ctx.rev(), ctx.phasestr()))
5143 else:
5143 else:
5144 with repo.lock(), repo.transaction(b"phase") as tr:
5144 with repo.lock(), repo.transaction(b"phase") as tr:
5145 # set phase
5145 # set phase
5146 if not revs:
5146 if not revs:
5147 raise error.Abort(_(b'empty revision set'))
5147 raise error.Abort(_(b'empty revision set'))
5148 nodes = [repo[r].node() for r in revs]
5148 nodes = [repo[r].node() for r in revs]
5149 # moving revision from public to draft may hide them
5149 # moving revision from public to draft may hide them
5150 # We have to check result on an unfiltered repository
5150 # We have to check result on an unfiltered repository
5151 unfi = repo.unfiltered()
5151 unfi = repo.unfiltered()
5152 getphase = unfi._phasecache.phase
5152 getphase = unfi._phasecache.phase
5153 olddata = [getphase(unfi, r) for r in unfi]
5153 olddata = [getphase(unfi, r) for r in unfi]
5154 phases.advanceboundary(repo, tr, targetphase, nodes)
5154 phases.advanceboundary(repo, tr, targetphase, nodes)
5155 if opts[b'force']:
5155 if opts[b'force']:
5156 phases.retractboundary(repo, tr, targetphase, nodes)
5156 phases.retractboundary(repo, tr, targetphase, nodes)
5157 getphase = unfi._phasecache.phase
5157 getphase = unfi._phasecache.phase
5158 newdata = [getphase(unfi, r) for r in unfi]
5158 newdata = [getphase(unfi, r) for r in unfi]
5159 changes = sum(newdata[r] != olddata[r] for r in unfi)
5159 changes = sum(newdata[r] != olddata[r] for r in unfi)
5160 cl = unfi.changelog
5160 cl = unfi.changelog
5161 rejected = [n for n in nodes if newdata[cl.rev(n)] < targetphase]
5161 rejected = [n for n in nodes if newdata[cl.rev(n)] < targetphase]
5162 if rejected:
5162 if rejected:
5163 ui.warn(
5163 ui.warn(
5164 _(
5164 _(
5165 b'cannot move %i changesets to a higher '
5165 b'cannot move %i changesets to a higher '
5166 b'phase, use --force\n'
5166 b'phase, use --force\n'
5167 )
5167 )
5168 % len(rejected)
5168 % len(rejected)
5169 )
5169 )
5170 ret = 1
5170 ret = 1
5171 if changes:
5171 if changes:
5172 msg = _(b'phase changed for %i changesets\n') % changes
5172 msg = _(b'phase changed for %i changesets\n') % changes
5173 if ret:
5173 if ret:
5174 ui.status(msg)
5174 ui.status(msg)
5175 else:
5175 else:
5176 ui.note(msg)
5176 ui.note(msg)
5177 else:
5177 else:
5178 ui.warn(_(b'no phases changed\n'))
5178 ui.warn(_(b'no phases changed\n'))
5179 return ret
5179 return ret
5180
5180
5181
5181
5182 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
5182 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
5183 """Run after a changegroup has been added via pull/unbundle
5183 """Run after a changegroup has been added via pull/unbundle
5184
5184
5185 This takes arguments below:
5185 This takes arguments below:
5186
5186
5187 :modheads: change of heads by pull/unbundle
5187 :modheads: change of heads by pull/unbundle
5188 :optupdate: updating working directory is needed or not
5188 :optupdate: updating working directory is needed or not
5189 :checkout: update destination revision (or None to default destination)
5189 :checkout: update destination revision (or None to default destination)
5190 :brev: a name, which might be a bookmark to be activated after updating
5190 :brev: a name, which might be a bookmark to be activated after updating
5191 """
5191 """
5192 if modheads == 0:
5192 if modheads == 0:
5193 return
5193 return
5194 if optupdate:
5194 if optupdate:
5195 try:
5195 try:
5196 return hg.updatetotally(ui, repo, checkout, brev)
5196 return hg.updatetotally(ui, repo, checkout, brev)
5197 except error.UpdateAbort as inst:
5197 except error.UpdateAbort as inst:
5198 msg = _(b"not updating: %s") % stringutil.forcebytestr(inst)
5198 msg = _(b"not updating: %s") % stringutil.forcebytestr(inst)
5199 hint = inst.hint
5199 hint = inst.hint
5200 raise error.UpdateAbort(msg, hint=hint)
5200 raise error.UpdateAbort(msg, hint=hint)
5201 if modheads is not None and modheads > 1:
5201 if modheads is not None and modheads > 1:
5202 currentbranchheads = len(repo.branchheads())
5202 currentbranchheads = len(repo.branchheads())
5203 if currentbranchheads == modheads:
5203 if currentbranchheads == modheads:
5204 ui.status(
5204 ui.status(
5205 _(b"(run 'hg heads' to see heads, 'hg merge' to merge)\n")
5205 _(b"(run 'hg heads' to see heads, 'hg merge' to merge)\n")
5206 )
5206 )
5207 elif currentbranchheads > 1:
5207 elif currentbranchheads > 1:
5208 ui.status(
5208 ui.status(
5209 _(b"(run 'hg heads .' to see heads, 'hg merge' to merge)\n")
5209 _(b"(run 'hg heads .' to see heads, 'hg merge' to merge)\n")
5210 )
5210 )
5211 else:
5211 else:
5212 ui.status(_(b"(run 'hg heads' to see heads)\n"))
5212 ui.status(_(b"(run 'hg heads' to see heads)\n"))
5213 elif not ui.configbool(b'commands', b'update.requiredest'):
5213 elif not ui.configbool(b'commands', b'update.requiredest'):
5214 ui.status(_(b"(run 'hg update' to get a working copy)\n"))
5214 ui.status(_(b"(run 'hg update' to get a working copy)\n"))
5215
5215
5216
5216
5217 @command(
5217 @command(
5218 b'pull',
5218 b'pull',
5219 [
5219 [
5220 (
5220 (
5221 b'u',
5221 b'u',
5222 b'update',
5222 b'update',
5223 None,
5223 None,
5224 _(b'update to new branch head if new descendants were pulled'),
5224 _(b'update to new branch head if new descendants were pulled'),
5225 ),
5225 ),
5226 (
5226 (
5227 b'f',
5227 b'f',
5228 b'force',
5228 b'force',
5229 None,
5229 None,
5230 _(b'run even when remote repository is unrelated'),
5230 _(b'run even when remote repository is unrelated'),
5231 ),
5231 ),
5232 (b'', b'confirm', None, _(b'confirm pull before applying changes'),),
5232 (b'', b'confirm', None, _(b'confirm pull before applying changes'),),
5233 (
5233 (
5234 b'r',
5234 b'r',
5235 b'rev',
5235 b'rev',
5236 [],
5236 [],
5237 _(b'a remote changeset intended to be added'),
5237 _(b'a remote changeset intended to be added'),
5238 _(b'REV'),
5238 _(b'REV'),
5239 ),
5239 ),
5240 (b'B', b'bookmark', [], _(b"bookmark to pull"), _(b'BOOKMARK')),
5240 (b'B', b'bookmark', [], _(b"bookmark to pull"), _(b'BOOKMARK')),
5241 (
5241 (
5242 b'b',
5242 b'b',
5243 b'branch',
5243 b'branch',
5244 [],
5244 [],
5245 _(b'a specific branch you would like to pull'),
5245 _(b'a specific branch you would like to pull'),
5246 _(b'BRANCH'),
5246 _(b'BRANCH'),
5247 ),
5247 ),
5248 ]
5248 ]
5249 + remoteopts,
5249 + remoteopts,
5250 _(b'[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'),
5250 _(b'[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'),
5251 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5251 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5252 helpbasic=True,
5252 helpbasic=True,
5253 )
5253 )
5254 def pull(ui, repo, source=b"default", **opts):
5254 def pull(ui, repo, source=b"default", **opts):
5255 """pull changes from the specified source
5255 """pull changes from the specified source
5256
5256
5257 Pull changes from a remote repository to a local one.
5257 Pull changes from a remote repository to a local one.
5258
5258
5259 This finds all changes from the repository at the specified path
5259 This finds all changes from the repository at the specified path
5260 or URL and adds them to a local repository (the current one unless
5260 or URL and adds them to a local repository (the current one unless
5261 -R is specified). By default, this does not update the copy of the
5261 -R is specified). By default, this does not update the copy of the
5262 project in the working directory.
5262 project in the working directory.
5263
5263
5264 When cloning from servers that support it, Mercurial may fetch
5264 When cloning from servers that support it, Mercurial may fetch
5265 pre-generated data. When this is done, hooks operating on incoming
5265 pre-generated data. When this is done, hooks operating on incoming
5266 changesets and changegroups may fire more than once, once for each
5266 changesets and changegroups may fire more than once, once for each
5267 pre-generated bundle and as well as for any additional remaining
5267 pre-generated bundle and as well as for any additional remaining
5268 data. See :hg:`help -e clonebundles` for more.
5268 data. See :hg:`help -e clonebundles` for more.
5269
5269
5270 Use :hg:`incoming` if you want to see what would have been added
5270 Use :hg:`incoming` if you want to see what would have been added
5271 by a pull at the time you issued this command. If you then decide
5271 by a pull at the time you issued this command. If you then decide
5272 to add those changes to the repository, you should use :hg:`pull
5272 to add those changes to the repository, you should use :hg:`pull
5273 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
5273 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
5274
5274
5275 If SOURCE is omitted, the 'default' path will be used.
5275 If SOURCE is omitted, the 'default' path will be used.
5276 See :hg:`help urls` for more information.
5276 See :hg:`help urls` for more information.
5277
5277
5278 Specifying bookmark as ``.`` is equivalent to specifying the active
5278 Specifying bookmark as ``.`` is equivalent to specifying the active
5279 bookmark's name.
5279 bookmark's name.
5280
5280
5281 Returns 0 on success, 1 if an update had unresolved files.
5281 Returns 0 on success, 1 if an update had unresolved files.
5282 """
5282 """
5283
5283
5284 opts = pycompat.byteskwargs(opts)
5284 opts = pycompat.byteskwargs(opts)
5285 if ui.configbool(b'commands', b'update.requiredest') and opts.get(
5285 if ui.configbool(b'commands', b'update.requiredest') and opts.get(
5286 b'update'
5286 b'update'
5287 ):
5287 ):
5288 msg = _(b'update destination required by configuration')
5288 msg = _(b'update destination required by configuration')
5289 hint = _(b'use hg pull followed by hg update DEST')
5289 hint = _(b'use hg pull followed by hg update DEST')
5290 raise error.Abort(msg, hint=hint)
5290 raise error.Abort(msg, hint=hint)
5291
5291
5292 source, branches = hg.parseurl(ui.expandpath(source), opts.get(b'branch'))
5292 source, branches = hg.parseurl(ui.expandpath(source), opts.get(b'branch'))
5293 ui.status(_(b'pulling from %s\n') % util.hidepassword(source))
5293 ui.status(_(b'pulling from %s\n') % util.hidepassword(source))
5294 other = hg.peer(repo, opts, source)
5294 other = hg.peer(repo, opts, source)
5295 try:
5295 try:
5296 revs, checkout = hg.addbranchrevs(
5296 revs, checkout = hg.addbranchrevs(
5297 repo, other, branches, opts.get(b'rev')
5297 repo, other, branches, opts.get(b'rev')
5298 )
5298 )
5299
5299
5300 pullopargs = {}
5300 pullopargs = {}
5301
5301
5302 nodes = None
5302 nodes = None
5303 if opts.get(b'bookmark') or revs:
5303 if opts.get(b'bookmark') or revs:
5304 # The list of bookmark used here is the same used to actually update
5304 # The list of bookmark used here is the same used to actually update
5305 # the bookmark names, to avoid the race from issue 4689 and we do
5305 # the bookmark names, to avoid the race from issue 4689 and we do
5306 # all lookup and bookmark queries in one go so they see the same
5306 # all lookup and bookmark queries in one go so they see the same
5307 # version of the server state (issue 4700).
5307 # version of the server state (issue 4700).
5308 nodes = []
5308 nodes = []
5309 fnodes = []
5309 fnodes = []
5310 revs = revs or []
5310 revs = revs or []
5311 if revs and not other.capable(b'lookup'):
5311 if revs and not other.capable(b'lookup'):
5312 err = _(
5312 err = _(
5313 b"other repository doesn't support revision lookup, "
5313 b"other repository doesn't support revision lookup, "
5314 b"so a rev cannot be specified."
5314 b"so a rev cannot be specified."
5315 )
5315 )
5316 raise error.Abort(err)
5316 raise error.Abort(err)
5317 with other.commandexecutor() as e:
5317 with other.commandexecutor() as e:
5318 fremotebookmarks = e.callcommand(
5318 fremotebookmarks = e.callcommand(
5319 b'listkeys', {b'namespace': b'bookmarks'}
5319 b'listkeys', {b'namespace': b'bookmarks'}
5320 )
5320 )
5321 for r in revs:
5321 for r in revs:
5322 fnodes.append(e.callcommand(b'lookup', {b'key': r}))
5322 fnodes.append(e.callcommand(b'lookup', {b'key': r}))
5323 remotebookmarks = fremotebookmarks.result()
5323 remotebookmarks = fremotebookmarks.result()
5324 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
5324 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
5325 pullopargs[b'remotebookmarks'] = remotebookmarks
5325 pullopargs[b'remotebookmarks'] = remotebookmarks
5326 for b in opts.get(b'bookmark', []):
5326 for b in opts.get(b'bookmark', []):
5327 b = repo._bookmarks.expandname(b)
5327 b = repo._bookmarks.expandname(b)
5328 if b not in remotebookmarks:
5328 if b not in remotebookmarks:
5329 raise error.Abort(_(b'remote bookmark %s not found!') % b)
5329 raise error.Abort(_(b'remote bookmark %s not found!') % b)
5330 nodes.append(remotebookmarks[b])
5330 nodes.append(remotebookmarks[b])
5331 for i, rev in enumerate(revs):
5331 for i, rev in enumerate(revs):
5332 node = fnodes[i].result()
5332 node = fnodes[i].result()
5333 nodes.append(node)
5333 nodes.append(node)
5334 if rev == checkout:
5334 if rev == checkout:
5335 checkout = node
5335 checkout = node
5336
5336
5337 wlock = util.nullcontextmanager()
5337 wlock = util.nullcontextmanager()
5338 if opts.get(b'update'):
5338 if opts.get(b'update'):
5339 wlock = repo.wlock()
5339 wlock = repo.wlock()
5340 with wlock:
5340 with wlock:
5341 pullopargs.update(opts.get(b'opargs', {}))
5341 pullopargs.update(opts.get(b'opargs', {}))
5342 modheads = exchange.pull(
5342 modheads = exchange.pull(
5343 repo,
5343 repo,
5344 other,
5344 other,
5345 heads=nodes,
5345 heads=nodes,
5346 force=opts.get(b'force'),
5346 force=opts.get(b'force'),
5347 bookmarks=opts.get(b'bookmark', ()),
5347 bookmarks=opts.get(b'bookmark', ()),
5348 opargs=pullopargs,
5348 opargs=pullopargs,
5349 confirm=opts.get(b'confirm'),
5349 confirm=opts.get(b'confirm'),
5350 ).cgresult
5350 ).cgresult
5351
5351
5352 # brev is a name, which might be a bookmark to be activated at
5352 # brev is a name, which might be a bookmark to be activated at
5353 # the end of the update. In other words, it is an explicit
5353 # the end of the update. In other words, it is an explicit
5354 # destination of the update
5354 # destination of the update
5355 brev = None
5355 brev = None
5356
5356
5357 if checkout:
5357 if checkout:
5358 checkout = repo.unfiltered().changelog.rev(checkout)
5358 checkout = repo.unfiltered().changelog.rev(checkout)
5359
5359
5360 # order below depends on implementation of
5360 # order below depends on implementation of
5361 # hg.addbranchrevs(). opts['bookmark'] is ignored,
5361 # hg.addbranchrevs(). opts['bookmark'] is ignored,
5362 # because 'checkout' is determined without it.
5362 # because 'checkout' is determined without it.
5363 if opts.get(b'rev'):
5363 if opts.get(b'rev'):
5364 brev = opts[b'rev'][0]
5364 brev = opts[b'rev'][0]
5365 elif opts.get(b'branch'):
5365 elif opts.get(b'branch'):
5366 brev = opts[b'branch'][0]
5366 brev = opts[b'branch'][0]
5367 else:
5367 else:
5368 brev = branches[0]
5368 brev = branches[0]
5369 repo._subtoppath = source
5369 repo._subtoppath = source
5370 try:
5370 try:
5371 ret = postincoming(
5371 ret = postincoming(
5372 ui, repo, modheads, opts.get(b'update'), checkout, brev
5372 ui, repo, modheads, opts.get(b'update'), checkout, brev
5373 )
5373 )
5374 except error.FilteredRepoLookupError as exc:
5374 except error.FilteredRepoLookupError as exc:
5375 msg = _(b'cannot update to target: %s') % exc.args[0]
5375 msg = _(b'cannot update to target: %s') % exc.args[0]
5376 exc.args = (msg,) + exc.args[1:]
5376 exc.args = (msg,) + exc.args[1:]
5377 raise
5377 raise
5378 finally:
5378 finally:
5379 del repo._subtoppath
5379 del repo._subtoppath
5380
5380
5381 finally:
5381 finally:
5382 other.close()
5382 other.close()
5383 return ret
5383 return ret
5384
5384
5385
5385
5386 @command(
5386 @command(
5387 b'push',
5387 b'push',
5388 [
5388 [
5389 (b'f', b'force', None, _(b'force push')),
5389 (b'f', b'force', None, _(b'force push')),
5390 (
5390 (
5391 b'r',
5391 b'r',
5392 b'rev',
5392 b'rev',
5393 [],
5393 [],
5394 _(b'a changeset intended to be included in the destination'),
5394 _(b'a changeset intended to be included in the destination'),
5395 _(b'REV'),
5395 _(b'REV'),
5396 ),
5396 ),
5397 (b'B', b'bookmark', [], _(b"bookmark to push"), _(b'BOOKMARK')),
5397 (b'B', b'bookmark', [], _(b"bookmark to push"), _(b'BOOKMARK')),
5398 (b'', b'all-bookmarks', None, _(b"push all bookmarks (EXPERIMENTAL)")),
5398 (b'', b'all-bookmarks', None, _(b"push all bookmarks (EXPERIMENTAL)")),
5399 (
5399 (
5400 b'b',
5400 b'b',
5401 b'branch',
5401 b'branch',
5402 [],
5402 [],
5403 _(b'a specific branch you would like to push'),
5403 _(b'a specific branch you would like to push'),
5404 _(b'BRANCH'),
5404 _(b'BRANCH'),
5405 ),
5405 ),
5406 (b'', b'new-branch', False, _(b'allow pushing a new branch')),
5406 (b'', b'new-branch', False, _(b'allow pushing a new branch')),
5407 (
5407 (
5408 b'',
5408 b'',
5409 b'pushvars',
5409 b'pushvars',
5410 [],
5410 [],
5411 _(b'variables that can be sent to server (ADVANCED)'),
5411 _(b'variables that can be sent to server (ADVANCED)'),
5412 ),
5412 ),
5413 (
5413 (
5414 b'',
5414 b'',
5415 b'publish',
5415 b'publish',
5416 False,
5416 False,
5417 _(b'push the changeset as public (EXPERIMENTAL)'),
5417 _(b'push the changeset as public (EXPERIMENTAL)'),
5418 ),
5418 ),
5419 ]
5419 ]
5420 + remoteopts,
5420 + remoteopts,
5421 _(b'[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'),
5421 _(b'[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'),
5422 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5422 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5423 helpbasic=True,
5423 helpbasic=True,
5424 )
5424 )
5425 def push(ui, repo, dest=None, **opts):
5425 def push(ui, repo, dest=None, **opts):
5426 """push changes to the specified destination
5426 """push changes to the specified destination
5427
5427
5428 Push changesets from the local repository to the specified
5428 Push changesets from the local repository to the specified
5429 destination.
5429 destination.
5430
5430
5431 This operation is symmetrical to pull: it is identical to a pull
5431 This operation is symmetrical to pull: it is identical to a pull
5432 in the destination repository from the current one.
5432 in the destination repository from the current one.
5433
5433
5434 By default, push will not allow creation of new heads at the
5434 By default, push will not allow creation of new heads at the
5435 destination, since multiple heads would make it unclear which head
5435 destination, since multiple heads would make it unclear which head
5436 to use. In this situation, it is recommended to pull and merge
5436 to use. In this situation, it is recommended to pull and merge
5437 before pushing.
5437 before pushing.
5438
5438
5439 Use --new-branch if you want to allow push to create a new named
5439 Use --new-branch if you want to allow push to create a new named
5440 branch that is not present at the destination. This allows you to
5440 branch that is not present at the destination. This allows you to
5441 only create a new branch without forcing other changes.
5441 only create a new branch without forcing other changes.
5442
5442
5443 .. note::
5443 .. note::
5444
5444
5445 Extra care should be taken with the -f/--force option,
5445 Extra care should be taken with the -f/--force option,
5446 which will push all new heads on all branches, an action which will
5446 which will push all new heads on all branches, an action which will
5447 almost always cause confusion for collaborators.
5447 almost always cause confusion for collaborators.
5448
5448
5449 If -r/--rev is used, the specified revision and all its ancestors
5449 If -r/--rev is used, the specified revision and all its ancestors
5450 will be pushed to the remote repository.
5450 will be pushed to the remote repository.
5451
5451
5452 If -B/--bookmark is used, the specified bookmarked revision, its
5452 If -B/--bookmark is used, the specified bookmarked revision, its
5453 ancestors, and the bookmark will be pushed to the remote
5453 ancestors, and the bookmark will be pushed to the remote
5454 repository. Specifying ``.`` is equivalent to specifying the active
5454 repository. Specifying ``.`` is equivalent to specifying the active
5455 bookmark's name. Use the --all-bookmarks option for pushing all
5455 bookmark's name. Use the --all-bookmarks option for pushing all
5456 current bookmarks.
5456 current bookmarks.
5457
5457
5458 Please see :hg:`help urls` for important details about ``ssh://``
5458 Please see :hg:`help urls` for important details about ``ssh://``
5459 URLs. If DESTINATION is omitted, a default path will be used.
5459 URLs. If DESTINATION is omitted, a default path will be used.
5460
5460
5461 .. container:: verbose
5461 .. container:: verbose
5462
5462
5463 The --pushvars option sends strings to the server that become
5463 The --pushvars option sends strings to the server that become
5464 environment variables prepended with ``HG_USERVAR_``. For example,
5464 environment variables prepended with ``HG_USERVAR_``. For example,
5465 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
5465 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
5466 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
5466 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
5467
5467
5468 pushvars can provide for user-overridable hooks as well as set debug
5468 pushvars can provide for user-overridable hooks as well as set debug
5469 levels. One example is having a hook that blocks commits containing
5469 levels. One example is having a hook that blocks commits containing
5470 conflict markers, but enables the user to override the hook if the file
5470 conflict markers, but enables the user to override the hook if the file
5471 is using conflict markers for testing purposes or the file format has
5471 is using conflict markers for testing purposes or the file format has
5472 strings that look like conflict markers.
5472 strings that look like conflict markers.
5473
5473
5474 By default, servers will ignore `--pushvars`. To enable it add the
5474 By default, servers will ignore `--pushvars`. To enable it add the
5475 following to your configuration file::
5475 following to your configuration file::
5476
5476
5477 [push]
5477 [push]
5478 pushvars.server = true
5478 pushvars.server = true
5479
5479
5480 Returns 0 if push was successful, 1 if nothing to push.
5480 Returns 0 if push was successful, 1 if nothing to push.
5481 """
5481 """
5482
5482
5483 opts = pycompat.byteskwargs(opts)
5483 opts = pycompat.byteskwargs(opts)
5484
5484
5485 if opts.get(b'all_bookmarks'):
5485 if opts.get(b'all_bookmarks'):
5486 cmdutil.check_incompatible_arguments(
5486 cmdutil.check_incompatible_arguments(
5487 opts, b'all_bookmarks', [b'bookmark', b'rev'],
5487 opts, b'all_bookmarks', [b'bookmark', b'rev'],
5488 )
5488 )
5489 opts[b'bookmark'] = list(repo._bookmarks)
5489 opts[b'bookmark'] = list(repo._bookmarks)
5490
5490
5491 if opts.get(b'bookmark'):
5491 if opts.get(b'bookmark'):
5492 ui.setconfig(b'bookmarks', b'pushing', opts[b'bookmark'], b'push')
5492 ui.setconfig(b'bookmarks', b'pushing', opts[b'bookmark'], b'push')
5493 for b in opts[b'bookmark']:
5493 for b in opts[b'bookmark']:
5494 # translate -B options to -r so changesets get pushed
5494 # translate -B options to -r so changesets get pushed
5495 b = repo._bookmarks.expandname(b)
5495 b = repo._bookmarks.expandname(b)
5496 if b in repo._bookmarks:
5496 if b in repo._bookmarks:
5497 opts.setdefault(b'rev', []).append(b)
5497 opts.setdefault(b'rev', []).append(b)
5498 else:
5498 else:
5499 # if we try to push a deleted bookmark, translate it to null
5499 # if we try to push a deleted bookmark, translate it to null
5500 # this lets simultaneous -r, -b options continue working
5500 # this lets simultaneous -r, -b options continue working
5501 opts.setdefault(b'rev', []).append(b"null")
5501 opts.setdefault(b'rev', []).append(b"null")
5502
5502
5503 path = ui.paths.getpath(dest, default=(b'default-push', b'default'))
5503 path = ui.paths.getpath(dest, default=(b'default-push', b'default'))
5504 if not path:
5504 if not path:
5505 raise error.Abort(
5505 raise error.Abort(
5506 _(b'default repository not configured!'),
5506 _(b'default repository not configured!'),
5507 hint=_(b"see 'hg help config.paths'"),
5507 hint=_(b"see 'hg help config.paths'"),
5508 )
5508 )
5509 dest = path.pushloc or path.loc
5509 dest = path.pushloc or path.loc
5510 branches = (path.branch, opts.get(b'branch') or [])
5510 branches = (path.branch, opts.get(b'branch') or [])
5511 ui.status(_(b'pushing to %s\n') % util.hidepassword(dest))
5511 ui.status(_(b'pushing to %s\n') % util.hidepassword(dest))
5512 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get(b'rev'))
5512 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get(b'rev'))
5513 other = hg.peer(repo, opts, dest)
5513 other = hg.peer(repo, opts, dest)
5514
5514
5515 if revs:
5515 if revs:
5516 revs = [repo[r].node() for r in scmutil.revrange(repo, revs)]
5516 revs = [repo[r].node() for r in scmutil.revrange(repo, revs)]
5517 if not revs:
5517 if not revs:
5518 raise error.Abort(
5518 raise error.Abort(
5519 _(b"specified revisions evaluate to an empty set"),
5519 _(b"specified revisions evaluate to an empty set"),
5520 hint=_(b"use different revision arguments"),
5520 hint=_(b"use different revision arguments"),
5521 )
5521 )
5522 elif path.pushrev:
5522 elif path.pushrev:
5523 # It doesn't make any sense to specify ancestor revisions. So limit
5523 # It doesn't make any sense to specify ancestor revisions. So limit
5524 # to DAG heads to make discovery simpler.
5524 # to DAG heads to make discovery simpler.
5525 expr = revsetlang.formatspec(b'heads(%r)', path.pushrev)
5525 expr = revsetlang.formatspec(b'heads(%r)', path.pushrev)
5526 revs = scmutil.revrange(repo, [expr])
5526 revs = scmutil.revrange(repo, [expr])
5527 revs = [repo[rev].node() for rev in revs]
5527 revs = [repo[rev].node() for rev in revs]
5528 if not revs:
5528 if not revs:
5529 raise error.Abort(
5529 raise error.Abort(
5530 _(b'default push revset for path evaluates to an empty set')
5530 _(b'default push revset for path evaluates to an empty set')
5531 )
5531 )
5532 elif ui.configbool(b'commands', b'push.require-revs'):
5532 elif ui.configbool(b'commands', b'push.require-revs'):
5533 raise error.Abort(
5533 raise error.Abort(
5534 _(b'no revisions specified to push'),
5534 _(b'no revisions specified to push'),
5535 hint=_(b'did you mean "hg push -r ."?'),
5535 hint=_(b'did you mean "hg push -r ."?'),
5536 )
5536 )
5537
5537
5538 repo._subtoppath = dest
5538 repo._subtoppath = dest
5539 try:
5539 try:
5540 # push subrepos depth-first for coherent ordering
5540 # push subrepos depth-first for coherent ordering
5541 c = repo[b'.']
5541 c = repo[b'.']
5542 subs = c.substate # only repos that are committed
5542 subs = c.substate # only repos that are committed
5543 for s in sorted(subs):
5543 for s in sorted(subs):
5544 result = c.sub(s).push(opts)
5544 result = c.sub(s).push(opts)
5545 if result == 0:
5545 if result == 0:
5546 return not result
5546 return not result
5547 finally:
5547 finally:
5548 del repo._subtoppath
5548 del repo._subtoppath
5549
5549
5550 opargs = dict(opts.get(b'opargs', {})) # copy opargs since we may mutate it
5550 opargs = dict(opts.get(b'opargs', {})) # copy opargs since we may mutate it
5551 opargs.setdefault(b'pushvars', []).extend(opts.get(b'pushvars', []))
5551 opargs.setdefault(b'pushvars', []).extend(opts.get(b'pushvars', []))
5552
5552
5553 pushop = exchange.push(
5553 pushop = exchange.push(
5554 repo,
5554 repo,
5555 other,
5555 other,
5556 opts.get(b'force'),
5556 opts.get(b'force'),
5557 revs=revs,
5557 revs=revs,
5558 newbranch=opts.get(b'new_branch'),
5558 newbranch=opts.get(b'new_branch'),
5559 bookmarks=opts.get(b'bookmark', ()),
5559 bookmarks=opts.get(b'bookmark', ()),
5560 publish=opts.get(b'publish'),
5560 publish=opts.get(b'publish'),
5561 opargs=opargs,
5561 opargs=opargs,
5562 )
5562 )
5563
5563
5564 result = not pushop.cgresult
5564 result = not pushop.cgresult
5565
5565
5566 if pushop.bkresult is not None:
5566 if pushop.bkresult is not None:
5567 if pushop.bkresult == 2:
5567 if pushop.bkresult == 2:
5568 result = 2
5568 result = 2
5569 elif not result and pushop.bkresult:
5569 elif not result and pushop.bkresult:
5570 result = 2
5570 result = 2
5571
5571
5572 return result
5572 return result
5573
5573
5574
5574
5575 @command(
5575 @command(
5576 b'recover',
5576 b'recover',
5577 [(b'', b'verify', False, b"run `hg verify` after successful recover"),],
5577 [(b'', b'verify', False, b"run `hg verify` after successful recover"),],
5578 helpcategory=command.CATEGORY_MAINTENANCE,
5578 helpcategory=command.CATEGORY_MAINTENANCE,
5579 )
5579 )
5580 def recover(ui, repo, **opts):
5580 def recover(ui, repo, **opts):
5581 """roll back an interrupted transaction
5581 """roll back an interrupted transaction
5582
5582
5583 Recover from an interrupted commit or pull.
5583 Recover from an interrupted commit or pull.
5584
5584
5585 This command tries to fix the repository status after an
5585 This command tries to fix the repository status after an
5586 interrupted operation. It should only be necessary when Mercurial
5586 interrupted operation. It should only be necessary when Mercurial
5587 suggests it.
5587 suggests it.
5588
5588
5589 Returns 0 if successful, 1 if nothing to recover or verify fails.
5589 Returns 0 if successful, 1 if nothing to recover or verify fails.
5590 """
5590 """
5591 ret = repo.recover()
5591 ret = repo.recover()
5592 if ret:
5592 if ret:
5593 if opts['verify']:
5593 if opts['verify']:
5594 return hg.verify(repo)
5594 return hg.verify(repo)
5595 else:
5595 else:
5596 msg = _(
5596 msg = _(
5597 b"(verify step skipped, run `hg verify` to check your "
5597 b"(verify step skipped, run `hg verify` to check your "
5598 b"repository content)\n"
5598 b"repository content)\n"
5599 )
5599 )
5600 ui.warn(msg)
5600 ui.warn(msg)
5601 return 0
5601 return 0
5602 return 1
5602 return 1
5603
5603
5604
5604
5605 @command(
5605 @command(
5606 b'remove|rm',
5606 b'remove|rm',
5607 [
5607 [
5608 (b'A', b'after', None, _(b'record delete for missing files')),
5608 (b'A', b'after', None, _(b'record delete for missing files')),
5609 (b'f', b'force', None, _(b'forget added files, delete modified files')),
5609 (b'f', b'force', None, _(b'forget added files, delete modified files')),
5610 ]
5610 ]
5611 + subrepoopts
5611 + subrepoopts
5612 + walkopts
5612 + walkopts
5613 + dryrunopts,
5613 + dryrunopts,
5614 _(b'[OPTION]... FILE...'),
5614 _(b'[OPTION]... FILE...'),
5615 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5615 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5616 helpbasic=True,
5616 helpbasic=True,
5617 inferrepo=True,
5617 inferrepo=True,
5618 )
5618 )
5619 def remove(ui, repo, *pats, **opts):
5619 def remove(ui, repo, *pats, **opts):
5620 """remove the specified files on the next commit
5620 """remove the specified files on the next commit
5621
5621
5622 Schedule the indicated files for removal from the current branch.
5622 Schedule the indicated files for removal from the current branch.
5623
5623
5624 This command schedules the files to be removed at the next commit.
5624 This command schedules the files to be removed at the next commit.
5625 To undo a remove before that, see :hg:`revert`. To undo added
5625 To undo a remove before that, see :hg:`revert`. To undo added
5626 files, see :hg:`forget`.
5626 files, see :hg:`forget`.
5627
5627
5628 .. container:: verbose
5628 .. container:: verbose
5629
5629
5630 -A/--after can be used to remove only files that have already
5630 -A/--after can be used to remove only files that have already
5631 been deleted, -f/--force can be used to force deletion, and -Af
5631 been deleted, -f/--force can be used to force deletion, and -Af
5632 can be used to remove files from the next revision without
5632 can be used to remove files from the next revision without
5633 deleting them from the working directory.
5633 deleting them from the working directory.
5634
5634
5635 The following table details the behavior of remove for different
5635 The following table details the behavior of remove for different
5636 file states (columns) and option combinations (rows). The file
5636 file states (columns) and option combinations (rows). The file
5637 states are Added [A], Clean [C], Modified [M] and Missing [!]
5637 states are Added [A], Clean [C], Modified [M] and Missing [!]
5638 (as reported by :hg:`status`). The actions are Warn, Remove
5638 (as reported by :hg:`status`). The actions are Warn, Remove
5639 (from branch) and Delete (from disk):
5639 (from branch) and Delete (from disk):
5640
5640
5641 ========= == == == ==
5641 ========= == == == ==
5642 opt/state A C M !
5642 opt/state A C M !
5643 ========= == == == ==
5643 ========= == == == ==
5644 none W RD W R
5644 none W RD W R
5645 -f R RD RD R
5645 -f R RD RD R
5646 -A W W W R
5646 -A W W W R
5647 -Af R R R R
5647 -Af R R R R
5648 ========= == == == ==
5648 ========= == == == ==
5649
5649
5650 .. note::
5650 .. note::
5651
5651
5652 :hg:`remove` never deletes files in Added [A] state from the
5652 :hg:`remove` never deletes files in Added [A] state from the
5653 working directory, not even if ``--force`` is specified.
5653 working directory, not even if ``--force`` is specified.
5654
5654
5655 Returns 0 on success, 1 if any warnings encountered.
5655 Returns 0 on success, 1 if any warnings encountered.
5656 """
5656 """
5657
5657
5658 opts = pycompat.byteskwargs(opts)
5658 opts = pycompat.byteskwargs(opts)
5659 after, force = opts.get(b'after'), opts.get(b'force')
5659 after, force = opts.get(b'after'), opts.get(b'force')
5660 dryrun = opts.get(b'dry_run')
5660 dryrun = opts.get(b'dry_run')
5661 if not pats and not after:
5661 if not pats and not after:
5662 raise error.Abort(_(b'no files specified'))
5662 raise error.Abort(_(b'no files specified'))
5663
5663
5664 m = scmutil.match(repo[None], pats, opts)
5664 m = scmutil.match(repo[None], pats, opts)
5665 subrepos = opts.get(b'subrepos')
5665 subrepos = opts.get(b'subrepos')
5666 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
5666 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
5667 return cmdutil.remove(
5667 return cmdutil.remove(
5668 ui, repo, m, b"", uipathfn, after, force, subrepos, dryrun=dryrun
5668 ui, repo, m, b"", uipathfn, after, force, subrepos, dryrun=dryrun
5669 )
5669 )
5670
5670
5671
5671
5672 @command(
5672 @command(
5673 b'rename|move|mv',
5673 b'rename|move|mv',
5674 [
5674 [
5675 (b'A', b'after', None, _(b'record a rename that has already occurred')),
5675 (b'A', b'after', None, _(b'record a rename that has already occurred')),
5676 (
5676 (
5677 b'',
5677 b'',
5678 b'at-rev',
5678 b'at-rev',
5679 b'',
5679 b'',
5680 _(b'(un)mark renames in the given revision (EXPERIMENTAL)'),
5680 _(b'(un)mark renames in the given revision (EXPERIMENTAL)'),
5681 _(b'REV'),
5681 _(b'REV'),
5682 ),
5682 ),
5683 (
5683 (
5684 b'f',
5684 b'f',
5685 b'force',
5685 b'force',
5686 None,
5686 None,
5687 _(b'forcibly move over an existing managed file'),
5687 _(b'forcibly move over an existing managed file'),
5688 ),
5688 ),
5689 ]
5689 ]
5690 + walkopts
5690 + walkopts
5691 + dryrunopts,
5691 + dryrunopts,
5692 _(b'[OPTION]... SOURCE... DEST'),
5692 _(b'[OPTION]... SOURCE... DEST'),
5693 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5693 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5694 )
5694 )
5695 def rename(ui, repo, *pats, **opts):
5695 def rename(ui, repo, *pats, **opts):
5696 """rename files; equivalent of copy + remove
5696 """rename files; equivalent of copy + remove
5697
5697
5698 Mark dest as copies of sources; mark sources for deletion. If dest
5698 Mark dest as copies of sources; mark sources for deletion. If dest
5699 is a directory, copies are put in that directory. If dest is a
5699 is a directory, copies are put in that directory. If dest is a
5700 file, there can only be one source.
5700 file, there can only be one source.
5701
5701
5702 By default, this command copies the contents of files as they
5702 By default, this command copies the contents of files as they
5703 exist in the working directory. If invoked with -A/--after, the
5703 exist in the working directory. If invoked with -A/--after, the
5704 operation is recorded, but no copying is performed.
5704 operation is recorded, but no copying is performed.
5705
5705
5706 This command takes effect at the next commit. To undo a rename
5706 This command takes effect at the next commit. To undo a rename
5707 before that, see :hg:`revert`.
5707 before that, see :hg:`revert`.
5708
5708
5709 Returns 0 on success, 1 if errors are encountered.
5709 Returns 0 on success, 1 if errors are encountered.
5710 """
5710 """
5711 opts = pycompat.byteskwargs(opts)
5711 opts = pycompat.byteskwargs(opts)
5712 with repo.wlock():
5712 with repo.wlock():
5713 return cmdutil.copy(ui, repo, pats, opts, rename=True)
5713 return cmdutil.copy(ui, repo, pats, opts, rename=True)
5714
5714
5715
5715
5716 @command(
5716 @command(
5717 b'resolve',
5717 b'resolve',
5718 [
5718 [
5719 (b'a', b'all', None, _(b'select all unresolved files')),
5719 (b'a', b'all', None, _(b'select all unresolved files')),
5720 (b'l', b'list', None, _(b'list state of files needing merge')),
5720 (b'l', b'list', None, _(b'list state of files needing merge')),
5721 (b'm', b'mark', None, _(b'mark files as resolved')),
5721 (b'm', b'mark', None, _(b'mark files as resolved')),
5722 (b'u', b'unmark', None, _(b'mark files as unresolved')),
5722 (b'u', b'unmark', None, _(b'mark files as unresolved')),
5723 (b'n', b'no-status', None, _(b'hide status prefix')),
5723 (b'n', b'no-status', None, _(b'hide status prefix')),
5724 (b'', b're-merge', None, _(b're-merge files')),
5724 (b'', b're-merge', None, _(b're-merge files')),
5725 ]
5725 ]
5726 + mergetoolopts
5726 + mergetoolopts
5727 + walkopts
5727 + walkopts
5728 + formatteropts,
5728 + formatteropts,
5729 _(b'[OPTION]... [FILE]...'),
5729 _(b'[OPTION]... [FILE]...'),
5730 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5730 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5731 inferrepo=True,
5731 inferrepo=True,
5732 )
5732 )
5733 def resolve(ui, repo, *pats, **opts):
5733 def resolve(ui, repo, *pats, **opts):
5734 """redo merges or set/view the merge status of files
5734 """redo merges or set/view the merge status of files
5735
5735
5736 Merges with unresolved conflicts are often the result of
5736 Merges with unresolved conflicts are often the result of
5737 non-interactive merging using the ``internal:merge`` configuration
5737 non-interactive merging using the ``internal:merge`` configuration
5738 setting, or a command-line merge tool like ``diff3``. The resolve
5738 setting, or a command-line merge tool like ``diff3``. The resolve
5739 command is used to manage the files involved in a merge, after
5739 command is used to manage the files involved in a merge, after
5740 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
5740 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
5741 working directory must have two parents). See :hg:`help
5741 working directory must have two parents). See :hg:`help
5742 merge-tools` for information on configuring merge tools.
5742 merge-tools` for information on configuring merge tools.
5743
5743
5744 The resolve command can be used in the following ways:
5744 The resolve command can be used in the following ways:
5745
5745
5746 - :hg:`resolve [--re-merge] [--tool TOOL] FILE...`: attempt to re-merge
5746 - :hg:`resolve [--re-merge] [--tool TOOL] FILE...`: attempt to re-merge
5747 the specified files, discarding any previous merge attempts. Re-merging
5747 the specified files, discarding any previous merge attempts. Re-merging
5748 is not performed for files already marked as resolved. Use ``--all/-a``
5748 is not performed for files already marked as resolved. Use ``--all/-a``
5749 to select all unresolved files. ``--tool`` can be used to specify
5749 to select all unresolved files. ``--tool`` can be used to specify
5750 the merge tool used for the given files. It overrides the HGMERGE
5750 the merge tool used for the given files. It overrides the HGMERGE
5751 environment variable and your configuration files. Previous file
5751 environment variable and your configuration files. Previous file
5752 contents are saved with a ``.orig`` suffix.
5752 contents are saved with a ``.orig`` suffix.
5753
5753
5754 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
5754 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
5755 (e.g. after having manually fixed-up the files). The default is
5755 (e.g. after having manually fixed-up the files). The default is
5756 to mark all unresolved files.
5756 to mark all unresolved files.
5757
5757
5758 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
5758 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
5759 default is to mark all resolved files.
5759 default is to mark all resolved files.
5760
5760
5761 - :hg:`resolve -l`: list files which had or still have conflicts.
5761 - :hg:`resolve -l`: list files which had or still have conflicts.
5762 In the printed list, ``U`` = unresolved and ``R`` = resolved.
5762 In the printed list, ``U`` = unresolved and ``R`` = resolved.
5763 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
5763 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
5764 the list. See :hg:`help filesets` for details.
5764 the list. See :hg:`help filesets` for details.
5765
5765
5766 .. note::
5766 .. note::
5767
5767
5768 Mercurial will not let you commit files with unresolved merge
5768 Mercurial will not let you commit files with unresolved merge
5769 conflicts. You must use :hg:`resolve -m ...` before you can
5769 conflicts. You must use :hg:`resolve -m ...` before you can
5770 commit after a conflicting merge.
5770 commit after a conflicting merge.
5771
5771
5772 .. container:: verbose
5772 .. container:: verbose
5773
5773
5774 Template:
5774 Template:
5775
5775
5776 The following keywords are supported in addition to the common template
5776 The following keywords are supported in addition to the common template
5777 keywords and functions. See also :hg:`help templates`.
5777 keywords and functions. See also :hg:`help templates`.
5778
5778
5779 :mergestatus: String. Character denoting merge conflicts, ``U`` or ``R``.
5779 :mergestatus: String. Character denoting merge conflicts, ``U`` or ``R``.
5780 :path: String. Repository-absolute path of the file.
5780 :path: String. Repository-absolute path of the file.
5781
5781
5782 Returns 0 on success, 1 if any files fail a resolve attempt.
5782 Returns 0 on success, 1 if any files fail a resolve attempt.
5783 """
5783 """
5784
5784
5785 opts = pycompat.byteskwargs(opts)
5785 opts = pycompat.byteskwargs(opts)
5786 confirm = ui.configbool(b'commands', b'resolve.confirm')
5786 confirm = ui.configbool(b'commands', b'resolve.confirm')
5787 flaglist = b'all mark unmark list no_status re_merge'.split()
5787 flaglist = b'all mark unmark list no_status re_merge'.split()
5788 all, mark, unmark, show, nostatus, remerge = [opts.get(o) for o in flaglist]
5788 all, mark, unmark, show, nostatus, remerge = [opts.get(o) for o in flaglist]
5789
5789
5790 actioncount = len(list(filter(None, [show, mark, unmark, remerge])))
5790 actioncount = len(list(filter(None, [show, mark, unmark, remerge])))
5791 if actioncount > 1:
5791 if actioncount > 1:
5792 raise error.Abort(_(b"too many actions specified"))
5792 raise error.Abort(_(b"too many actions specified"))
5793 elif actioncount == 0 and ui.configbool(
5793 elif actioncount == 0 and ui.configbool(
5794 b'commands', b'resolve.explicit-re-merge'
5794 b'commands', b'resolve.explicit-re-merge'
5795 ):
5795 ):
5796 hint = _(b'use --mark, --unmark, --list or --re-merge')
5796 hint = _(b'use --mark, --unmark, --list or --re-merge')
5797 raise error.Abort(_(b'no action specified'), hint=hint)
5797 raise error.Abort(_(b'no action specified'), hint=hint)
5798 if pats and all:
5798 if pats and all:
5799 raise error.Abort(_(b"can't specify --all and patterns"))
5799 raise error.Abort(_(b"can't specify --all and patterns"))
5800 if not (all or pats or show or mark or unmark):
5800 if not (all or pats or show or mark or unmark):
5801 raise error.Abort(
5801 raise error.Abort(
5802 _(b'no files or directories specified'),
5802 _(b'no files or directories specified'),
5803 hint=b'use --all to re-merge all unresolved files',
5803 hint=b'use --all to re-merge all unresolved files',
5804 )
5804 )
5805
5805
5806 if confirm:
5806 if confirm:
5807 if all:
5807 if all:
5808 if ui.promptchoice(
5808 if ui.promptchoice(
5809 _(b're-merge all unresolved files (yn)?$$ &Yes $$ &No')
5809 _(b're-merge all unresolved files (yn)?$$ &Yes $$ &No')
5810 ):
5810 ):
5811 raise error.Abort(_(b'user quit'))
5811 raise error.Abort(_(b'user quit'))
5812 if mark and not pats:
5812 if mark and not pats:
5813 if ui.promptchoice(
5813 if ui.promptchoice(
5814 _(
5814 _(
5815 b'mark all unresolved files as resolved (yn)?'
5815 b'mark all unresolved files as resolved (yn)?'
5816 b'$$ &Yes $$ &No'
5816 b'$$ &Yes $$ &No'
5817 )
5817 )
5818 ):
5818 ):
5819 raise error.Abort(_(b'user quit'))
5819 raise error.Abort(_(b'user quit'))
5820 if unmark and not pats:
5820 if unmark and not pats:
5821 if ui.promptchoice(
5821 if ui.promptchoice(
5822 _(
5822 _(
5823 b'mark all resolved files as unresolved (yn)?'
5823 b'mark all resolved files as unresolved (yn)?'
5824 b'$$ &Yes $$ &No'
5824 b'$$ &Yes $$ &No'
5825 )
5825 )
5826 ):
5826 ):
5827 raise error.Abort(_(b'user quit'))
5827 raise error.Abort(_(b'user quit'))
5828
5828
5829 uipathfn = scmutil.getuipathfn(repo)
5829 uipathfn = scmutil.getuipathfn(repo)
5830
5830
5831 if show:
5831 if show:
5832 ui.pager(b'resolve')
5832 ui.pager(b'resolve')
5833 fm = ui.formatter(b'resolve', opts)
5833 fm = ui.formatter(b'resolve', opts)
5834 ms = mergestatemod.mergestate.read(repo)
5834 ms = mergestatemod.mergestate.read(repo)
5835 wctx = repo[None]
5835 wctx = repo[None]
5836 m = scmutil.match(wctx, pats, opts)
5836 m = scmutil.match(wctx, pats, opts)
5837
5837
5838 # Labels and keys based on merge state. Unresolved path conflicts show
5838 # Labels and keys based on merge state. Unresolved path conflicts show
5839 # as 'P'. Resolved path conflicts show as 'R', the same as normal
5839 # as 'P'. Resolved path conflicts show as 'R', the same as normal
5840 # resolved conflicts.
5840 # resolved conflicts.
5841 mergestateinfo = {
5841 mergestateinfo = {
5842 mergestatemod.MERGE_RECORD_UNRESOLVED: (
5842 mergestatemod.MERGE_RECORD_UNRESOLVED: (
5843 b'resolve.unresolved',
5843 b'resolve.unresolved',
5844 b'U',
5844 b'U',
5845 ),
5845 ),
5846 mergestatemod.MERGE_RECORD_RESOLVED: (b'resolve.resolved', b'R'),
5846 mergestatemod.MERGE_RECORD_RESOLVED: (b'resolve.resolved', b'R'),
5847 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH: (
5847 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH: (
5848 b'resolve.unresolved',
5848 b'resolve.unresolved',
5849 b'P',
5849 b'P',
5850 ),
5850 ),
5851 mergestatemod.MERGE_RECORD_RESOLVED_PATH: (
5851 mergestatemod.MERGE_RECORD_RESOLVED_PATH: (
5852 b'resolve.resolved',
5852 b'resolve.resolved',
5853 b'R',
5853 b'R',
5854 ),
5854 ),
5855 }
5855 }
5856
5856
5857 for f in ms:
5857 for f in ms:
5858 if not m(f):
5858 if not m(f):
5859 continue
5859 continue
5860
5860
5861 label, key = mergestateinfo[ms[f]]
5861 label, key = mergestateinfo[ms[f]]
5862 fm.startitem()
5862 fm.startitem()
5863 fm.context(ctx=wctx)
5863 fm.context(ctx=wctx)
5864 fm.condwrite(not nostatus, b'mergestatus', b'%s ', key, label=label)
5864 fm.condwrite(not nostatus, b'mergestatus', b'%s ', key, label=label)
5865 fm.data(path=f)
5865 fm.data(path=f)
5866 fm.plain(b'%s\n' % uipathfn(f), label=label)
5866 fm.plain(b'%s\n' % uipathfn(f), label=label)
5867 fm.end()
5867 fm.end()
5868 return 0
5868 return 0
5869
5869
5870 with repo.wlock():
5870 with repo.wlock():
5871 ms = mergestatemod.mergestate.read(repo)
5871 ms = mergestatemod.mergestate.read(repo)
5872
5872
5873 if not (ms.active() or repo.dirstate.p2() != nullid):
5873 if not (ms.active() or repo.dirstate.p2() != nullid):
5874 raise error.Abort(
5874 raise error.Abort(
5875 _(b'resolve command not applicable when not merging')
5875 _(b'resolve command not applicable when not merging')
5876 )
5876 )
5877
5877
5878 wctx = repo[None]
5878 wctx = repo[None]
5879 m = scmutil.match(wctx, pats, opts)
5879 m = scmutil.match(wctx, pats, opts)
5880 ret = 0
5880 ret = 0
5881 didwork = False
5881 didwork = False
5882
5882
5883 tocomplete = []
5883 tocomplete = []
5884 hasconflictmarkers = []
5884 hasconflictmarkers = []
5885 if mark:
5885 if mark:
5886 markcheck = ui.config(b'commands', b'resolve.mark-check')
5886 markcheck = ui.config(b'commands', b'resolve.mark-check')
5887 if markcheck not in [b'warn', b'abort']:
5887 if markcheck not in [b'warn', b'abort']:
5888 # Treat all invalid / unrecognized values as 'none'.
5888 # Treat all invalid / unrecognized values as 'none'.
5889 markcheck = False
5889 markcheck = False
5890 for f in ms:
5890 for f in ms:
5891 if not m(f):
5891 if not m(f):
5892 continue
5892 continue
5893
5893
5894 didwork = True
5894 didwork = True
5895
5895
5896 # path conflicts must be resolved manually
5896 # path conflicts must be resolved manually
5897 if ms[f] in (
5897 if ms[f] in (
5898 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH,
5898 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH,
5899 mergestatemod.MERGE_RECORD_RESOLVED_PATH,
5899 mergestatemod.MERGE_RECORD_RESOLVED_PATH,
5900 ):
5900 ):
5901 if mark:
5901 if mark:
5902 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED_PATH)
5902 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED_PATH)
5903 elif unmark:
5903 elif unmark:
5904 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED_PATH)
5904 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED_PATH)
5905 elif ms[f] == mergestatemod.MERGE_RECORD_UNRESOLVED_PATH:
5905 elif ms[f] == mergestatemod.MERGE_RECORD_UNRESOLVED_PATH:
5906 ui.warn(
5906 ui.warn(
5907 _(b'%s: path conflict must be resolved manually\n')
5907 _(b'%s: path conflict must be resolved manually\n')
5908 % uipathfn(f)
5908 % uipathfn(f)
5909 )
5909 )
5910 continue
5910 continue
5911
5911
5912 if mark:
5912 if mark:
5913 if markcheck:
5913 if markcheck:
5914 fdata = repo.wvfs.tryread(f)
5914 fdata = repo.wvfs.tryread(f)
5915 if (
5915 if (
5916 filemerge.hasconflictmarkers(fdata)
5916 filemerge.hasconflictmarkers(fdata)
5917 and ms[f] != mergestatemod.MERGE_RECORD_RESOLVED
5917 and ms[f] != mergestatemod.MERGE_RECORD_RESOLVED
5918 ):
5918 ):
5919 hasconflictmarkers.append(f)
5919 hasconflictmarkers.append(f)
5920 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED)
5920 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED)
5921 elif unmark:
5921 elif unmark:
5922 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED)
5922 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED)
5923 else:
5923 else:
5924 # backup pre-resolve (merge uses .orig for its own purposes)
5924 # backup pre-resolve (merge uses .orig for its own purposes)
5925 a = repo.wjoin(f)
5925 a = repo.wjoin(f)
5926 try:
5926 try:
5927 util.copyfile(a, a + b".resolve")
5927 util.copyfile(a, a + b".resolve")
5928 except (IOError, OSError) as inst:
5928 except (IOError, OSError) as inst:
5929 if inst.errno != errno.ENOENT:
5929 if inst.errno != errno.ENOENT:
5930 raise
5930 raise
5931
5931
5932 try:
5932 try:
5933 # preresolve file
5933 # preresolve file
5934 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
5934 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
5935 with ui.configoverride(overrides, b'resolve'):
5935 with ui.configoverride(overrides, b'resolve'):
5936 complete, r = ms.preresolve(f, wctx)
5936 complete, r = ms.preresolve(f, wctx)
5937 if not complete:
5937 if not complete:
5938 tocomplete.append(f)
5938 tocomplete.append(f)
5939 elif r:
5939 elif r:
5940 ret = 1
5940 ret = 1
5941 finally:
5941 finally:
5942 ms.commit()
5942 ms.commit()
5943
5943
5944 # replace filemerge's .orig file with our resolve file, but only
5944 # replace filemerge's .orig file with our resolve file, but only
5945 # for merges that are complete
5945 # for merges that are complete
5946 if complete:
5946 if complete:
5947 try:
5947 try:
5948 util.rename(
5948 util.rename(
5949 a + b".resolve", scmutil.backuppath(ui, repo, f)
5949 a + b".resolve", scmutil.backuppath(ui, repo, f)
5950 )
5950 )
5951 except OSError as inst:
5951 except OSError as inst:
5952 if inst.errno != errno.ENOENT:
5952 if inst.errno != errno.ENOENT:
5953 raise
5953 raise
5954
5954
5955 if hasconflictmarkers:
5955 if hasconflictmarkers:
5956 ui.warn(
5956 ui.warn(
5957 _(
5957 _(
5958 b'warning: the following files still have conflict '
5958 b'warning: the following files still have conflict '
5959 b'markers:\n'
5959 b'markers:\n'
5960 )
5960 )
5961 + b''.join(
5961 + b''.join(
5962 b' ' + uipathfn(f) + b'\n' for f in hasconflictmarkers
5962 b' ' + uipathfn(f) + b'\n' for f in hasconflictmarkers
5963 )
5963 )
5964 )
5964 )
5965 if markcheck == b'abort' and not all and not pats:
5965 if markcheck == b'abort' and not all and not pats:
5966 raise error.Abort(
5966 raise error.Abort(
5967 _(b'conflict markers detected'),
5967 _(b'conflict markers detected'),
5968 hint=_(b'use --all to mark anyway'),
5968 hint=_(b'use --all to mark anyway'),
5969 )
5969 )
5970
5970
5971 for f in tocomplete:
5971 for f in tocomplete:
5972 try:
5972 try:
5973 # resolve file
5973 # resolve file
5974 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
5974 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
5975 with ui.configoverride(overrides, b'resolve'):
5975 with ui.configoverride(overrides, b'resolve'):
5976 r = ms.resolve(f, wctx)
5976 r = ms.resolve(f, wctx)
5977 if r:
5977 if r:
5978 ret = 1
5978 ret = 1
5979 finally:
5979 finally:
5980 ms.commit()
5980 ms.commit()
5981
5981
5982 # replace filemerge's .orig file with our resolve file
5982 # replace filemerge's .orig file with our resolve file
5983 a = repo.wjoin(f)
5983 a = repo.wjoin(f)
5984 try:
5984 try:
5985 util.rename(a + b".resolve", scmutil.backuppath(ui, repo, f))
5985 util.rename(a + b".resolve", scmutil.backuppath(ui, repo, f))
5986 except OSError as inst:
5986 except OSError as inst:
5987 if inst.errno != errno.ENOENT:
5987 if inst.errno != errno.ENOENT:
5988 raise
5988 raise
5989
5989
5990 ms.commit()
5990 ms.commit()
5991 branchmerge = repo.dirstate.p2() != nullid
5991 branchmerge = repo.dirstate.p2() != nullid
5992 mergestatemod.recordupdates(repo, ms.actions(), branchmerge, None)
5992 mergestatemod.recordupdates(repo, ms.actions(), branchmerge, None)
5993
5993
5994 if not didwork and pats:
5994 if not didwork and pats:
5995 hint = None
5995 hint = None
5996 if not any([p for p in pats if p.find(b':') >= 0]):
5996 if not any([p for p in pats if p.find(b':') >= 0]):
5997 pats = [b'path:%s' % p for p in pats]
5997 pats = [b'path:%s' % p for p in pats]
5998 m = scmutil.match(wctx, pats, opts)
5998 m = scmutil.match(wctx, pats, opts)
5999 for f in ms:
5999 for f in ms:
6000 if not m(f):
6000 if not m(f):
6001 continue
6001 continue
6002
6002
6003 def flag(o):
6003 def flag(o):
6004 if o == b're_merge':
6004 if o == b're_merge':
6005 return b'--re-merge '
6005 return b'--re-merge '
6006 return b'-%s ' % o[0:1]
6006 return b'-%s ' % o[0:1]
6007
6007
6008 flags = b''.join([flag(o) for o in flaglist if opts.get(o)])
6008 flags = b''.join([flag(o) for o in flaglist if opts.get(o)])
6009 hint = _(b"(try: hg resolve %s%s)\n") % (
6009 hint = _(b"(try: hg resolve %s%s)\n") % (
6010 flags,
6010 flags,
6011 b' '.join(pats),
6011 b' '.join(pats),
6012 )
6012 )
6013 break
6013 break
6014 ui.warn(_(b"arguments do not match paths that need resolving\n"))
6014 ui.warn(_(b"arguments do not match paths that need resolving\n"))
6015 if hint:
6015 if hint:
6016 ui.warn(hint)
6016 ui.warn(hint)
6017
6017
6018 unresolvedf = list(ms.unresolved())
6018 unresolvedf = list(ms.unresolved())
6019 if not unresolvedf:
6019 if not unresolvedf:
6020 ui.status(_(b'(no more unresolved files)\n'))
6020 ui.status(_(b'(no more unresolved files)\n'))
6021 cmdutil.checkafterresolved(repo)
6021 cmdutil.checkafterresolved(repo)
6022
6022
6023 return ret
6023 return ret
6024
6024
6025
6025
6026 @command(
6026 @command(
6027 b'revert',
6027 b'revert',
6028 [
6028 [
6029 (b'a', b'all', None, _(b'revert all changes when no arguments given')),
6029 (b'a', b'all', None, _(b'revert all changes when no arguments given')),
6030 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
6030 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
6031 (b'r', b'rev', b'', _(b'revert to the specified revision'), _(b'REV')),
6031 (b'r', b'rev', b'', _(b'revert to the specified revision'), _(b'REV')),
6032 (b'C', b'no-backup', None, _(b'do not save backup copies of files')),
6032 (b'C', b'no-backup', None, _(b'do not save backup copies of files')),
6033 (b'i', b'interactive', None, _(b'interactively select the changes')),
6033 (b'i', b'interactive', None, _(b'interactively select the changes')),
6034 ]
6034 ]
6035 + walkopts
6035 + walkopts
6036 + dryrunopts,
6036 + dryrunopts,
6037 _(b'[OPTION]... [-r REV] [NAME]...'),
6037 _(b'[OPTION]... [-r REV] [NAME]...'),
6038 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6038 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6039 )
6039 )
6040 def revert(ui, repo, *pats, **opts):
6040 def revert(ui, repo, *pats, **opts):
6041 """restore files to their checkout state
6041 """restore files to their checkout state
6042
6042
6043 .. note::
6043 .. note::
6044
6044
6045 To check out earlier revisions, you should use :hg:`update REV`.
6045 To check out earlier revisions, you should use :hg:`update REV`.
6046 To cancel an uncommitted merge (and lose your changes),
6046 To cancel an uncommitted merge (and lose your changes),
6047 use :hg:`merge --abort`.
6047 use :hg:`merge --abort`.
6048
6048
6049 With no revision specified, revert the specified files or directories
6049 With no revision specified, revert the specified files or directories
6050 to the contents they had in the parent of the working directory.
6050 to the contents they had in the parent of the working directory.
6051 This restores the contents of files to an unmodified
6051 This restores the contents of files to an unmodified
6052 state and unschedules adds, removes, copies, and renames. If the
6052 state and unschedules adds, removes, copies, and renames. If the
6053 working directory has two parents, you must explicitly specify a
6053 working directory has two parents, you must explicitly specify a
6054 revision.
6054 revision.
6055
6055
6056 Using the -r/--rev or -d/--date options, revert the given files or
6056 Using the -r/--rev or -d/--date options, revert the given files or
6057 directories to their states as of a specific revision. Because
6057 directories to their states as of a specific revision. Because
6058 revert does not change the working directory parents, this will
6058 revert does not change the working directory parents, this will
6059 cause these files to appear modified. This can be helpful to "back
6059 cause these files to appear modified. This can be helpful to "back
6060 out" some or all of an earlier change. See :hg:`backout` for a
6060 out" some or all of an earlier change. See :hg:`backout` for a
6061 related method.
6061 related method.
6062
6062
6063 Modified files are saved with a .orig suffix before reverting.
6063 Modified files are saved with a .orig suffix before reverting.
6064 To disable these backups, use --no-backup. It is possible to store
6064 To disable these backups, use --no-backup. It is possible to store
6065 the backup files in a custom directory relative to the root of the
6065 the backup files in a custom directory relative to the root of the
6066 repository by setting the ``ui.origbackuppath`` configuration
6066 repository by setting the ``ui.origbackuppath`` configuration
6067 option.
6067 option.
6068
6068
6069 See :hg:`help dates` for a list of formats valid for -d/--date.
6069 See :hg:`help dates` for a list of formats valid for -d/--date.
6070
6070
6071 See :hg:`help backout` for a way to reverse the effect of an
6071 See :hg:`help backout` for a way to reverse the effect of an
6072 earlier changeset.
6072 earlier changeset.
6073
6073
6074 Returns 0 on success.
6074 Returns 0 on success.
6075 """
6075 """
6076
6076
6077 opts = pycompat.byteskwargs(opts)
6077 opts = pycompat.byteskwargs(opts)
6078 if opts.get(b"date"):
6078 if opts.get(b"date"):
6079 cmdutil.check_incompatible_arguments(opts, b'date', [b'rev'])
6079 cmdutil.check_incompatible_arguments(opts, b'date', [b'rev'])
6080 opts[b"rev"] = cmdutil.finddate(ui, repo, opts[b"date"])
6080 opts[b"rev"] = cmdutil.finddate(ui, repo, opts[b"date"])
6081
6081
6082 parent, p2 = repo.dirstate.parents()
6082 parent, p2 = repo.dirstate.parents()
6083 if not opts.get(b'rev') and p2 != nullid:
6083 if not opts.get(b'rev') and p2 != nullid:
6084 # revert after merge is a trap for new users (issue2915)
6084 # revert after merge is a trap for new users (issue2915)
6085 raise error.Abort(
6085 raise error.Abort(
6086 _(b'uncommitted merge with no revision specified'),
6086 _(b'uncommitted merge with no revision specified'),
6087 hint=_(b"use 'hg update' or see 'hg help revert'"),
6087 hint=_(b"use 'hg update' or see 'hg help revert'"),
6088 )
6088 )
6089
6089
6090 rev = opts.get(b'rev')
6090 rev = opts.get(b'rev')
6091 if rev:
6091 if rev:
6092 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
6092 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
6093 ctx = scmutil.revsingle(repo, rev)
6093 ctx = scmutil.revsingle(repo, rev)
6094
6094
6095 if not (
6095 if not (
6096 pats
6096 pats
6097 or opts.get(b'include')
6097 or opts.get(b'include')
6098 or opts.get(b'exclude')
6098 or opts.get(b'exclude')
6099 or opts.get(b'all')
6099 or opts.get(b'all')
6100 or opts.get(b'interactive')
6100 or opts.get(b'interactive')
6101 ):
6101 ):
6102 msg = _(b"no files or directories specified")
6102 msg = _(b"no files or directories specified")
6103 if p2 != nullid:
6103 if p2 != nullid:
6104 hint = _(
6104 hint = _(
6105 b"uncommitted merge, use --all to discard all changes,"
6105 b"uncommitted merge, use --all to discard all changes,"
6106 b" or 'hg update -C .' to abort the merge"
6106 b" or 'hg update -C .' to abort the merge"
6107 )
6107 )
6108 raise error.Abort(msg, hint=hint)
6108 raise error.Abort(msg, hint=hint)
6109 dirty = any(repo.status())
6109 dirty = any(repo.status())
6110 node = ctx.node()
6110 node = ctx.node()
6111 if node != parent:
6111 if node != parent:
6112 if dirty:
6112 if dirty:
6113 hint = (
6113 hint = (
6114 _(
6114 _(
6115 b"uncommitted changes, use --all to discard all"
6115 b"uncommitted changes, use --all to discard all"
6116 b" changes, or 'hg update %d' to update"
6116 b" changes, or 'hg update %d' to update"
6117 )
6117 )
6118 % ctx.rev()
6118 % ctx.rev()
6119 )
6119 )
6120 else:
6120 else:
6121 hint = (
6121 hint = (
6122 _(
6122 _(
6123 b"use --all to revert all files,"
6123 b"use --all to revert all files,"
6124 b" or 'hg update %d' to update"
6124 b" or 'hg update %d' to update"
6125 )
6125 )
6126 % ctx.rev()
6126 % ctx.rev()
6127 )
6127 )
6128 elif dirty:
6128 elif dirty:
6129 hint = _(b"uncommitted changes, use --all to discard all changes")
6129 hint = _(b"uncommitted changes, use --all to discard all changes")
6130 else:
6130 else:
6131 hint = _(b"use --all to revert all files")
6131 hint = _(b"use --all to revert all files")
6132 raise error.Abort(msg, hint=hint)
6132 raise error.Abort(msg, hint=hint)
6133
6133
6134 return cmdutil.revert(ui, repo, ctx, *pats, **pycompat.strkwargs(opts))
6134 return cmdutil.revert(ui, repo, ctx, *pats, **pycompat.strkwargs(opts))
6135
6135
6136
6136
6137 @command(
6137 @command(
6138 b'rollback',
6138 b'rollback',
6139 dryrunopts + [(b'f', b'force', False, _(b'ignore safety measures'))],
6139 dryrunopts + [(b'f', b'force', False, _(b'ignore safety measures'))],
6140 helpcategory=command.CATEGORY_MAINTENANCE,
6140 helpcategory=command.CATEGORY_MAINTENANCE,
6141 )
6141 )
6142 def rollback(ui, repo, **opts):
6142 def rollback(ui, repo, **opts):
6143 """roll back the last transaction (DANGEROUS) (DEPRECATED)
6143 """roll back the last transaction (DANGEROUS) (DEPRECATED)
6144
6144
6145 Please use :hg:`commit --amend` instead of rollback to correct
6145 Please use :hg:`commit --amend` instead of rollback to correct
6146 mistakes in the last commit.
6146 mistakes in the last commit.
6147
6147
6148 This command should be used with care. There is only one level of
6148 This command should be used with care. There is only one level of
6149 rollback, and there is no way to undo a rollback. It will also
6149 rollback, and there is no way to undo a rollback. It will also
6150 restore the dirstate at the time of the last transaction, losing
6150 restore the dirstate at the time of the last transaction, losing
6151 any dirstate changes since that time. This command does not alter
6151 any dirstate changes since that time. This command does not alter
6152 the working directory.
6152 the working directory.
6153
6153
6154 Transactions are used to encapsulate the effects of all commands
6154 Transactions are used to encapsulate the effects of all commands
6155 that create new changesets or propagate existing changesets into a
6155 that create new changesets or propagate existing changesets into a
6156 repository.
6156 repository.
6157
6157
6158 .. container:: verbose
6158 .. container:: verbose
6159
6159
6160 For example, the following commands are transactional, and their
6160 For example, the following commands are transactional, and their
6161 effects can be rolled back:
6161 effects can be rolled back:
6162
6162
6163 - commit
6163 - commit
6164 - import
6164 - import
6165 - pull
6165 - pull
6166 - push (with this repository as the destination)
6166 - push (with this repository as the destination)
6167 - unbundle
6167 - unbundle
6168
6168
6169 To avoid permanent data loss, rollback will refuse to rollback a
6169 To avoid permanent data loss, rollback will refuse to rollback a
6170 commit transaction if it isn't checked out. Use --force to
6170 commit transaction if it isn't checked out. Use --force to
6171 override this protection.
6171 override this protection.
6172
6172
6173 The rollback command can be entirely disabled by setting the
6173 The rollback command can be entirely disabled by setting the
6174 ``ui.rollback`` configuration setting to false. If you're here
6174 ``ui.rollback`` configuration setting to false. If you're here
6175 because you want to use rollback and it's disabled, you can
6175 because you want to use rollback and it's disabled, you can
6176 re-enable the command by setting ``ui.rollback`` to true.
6176 re-enable the command by setting ``ui.rollback`` to true.
6177
6177
6178 This command is not intended for use on public repositories. Once
6178 This command is not intended for use on public repositories. Once
6179 changes are visible for pull by other users, rolling a transaction
6179 changes are visible for pull by other users, rolling a transaction
6180 back locally is ineffective (someone else may already have pulled
6180 back locally is ineffective (someone else may already have pulled
6181 the changes). Furthermore, a race is possible with readers of the
6181 the changes). Furthermore, a race is possible with readers of the
6182 repository; for example an in-progress pull from the repository
6182 repository; for example an in-progress pull from the repository
6183 may fail if a rollback is performed.
6183 may fail if a rollback is performed.
6184
6184
6185 Returns 0 on success, 1 if no rollback data is available.
6185 Returns 0 on success, 1 if no rollback data is available.
6186 """
6186 """
6187 if not ui.configbool(b'ui', b'rollback'):
6187 if not ui.configbool(b'ui', b'rollback'):
6188 raise error.Abort(
6188 raise error.Abort(
6189 _(b'rollback is disabled because it is unsafe'),
6189 _(b'rollback is disabled because it is unsafe'),
6190 hint=b'see `hg help -v rollback` for information',
6190 hint=b'see `hg help -v rollback` for information',
6191 )
6191 )
6192 return repo.rollback(dryrun=opts.get('dry_run'), force=opts.get('force'))
6192 return repo.rollback(dryrun=opts.get('dry_run'), force=opts.get('force'))
6193
6193
6194
6194
6195 @command(
6195 @command(
6196 b'root',
6196 b'root',
6197 [] + formatteropts,
6197 [] + formatteropts,
6198 intents={INTENT_READONLY},
6198 intents={INTENT_READONLY},
6199 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6199 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6200 )
6200 )
6201 def root(ui, repo, **opts):
6201 def root(ui, repo, **opts):
6202 """print the root (top) of the current working directory
6202 """print the root (top) of the current working directory
6203
6203
6204 Print the root directory of the current repository.
6204 Print the root directory of the current repository.
6205
6205
6206 .. container:: verbose
6206 .. container:: verbose
6207
6207
6208 Template:
6208 Template:
6209
6209
6210 The following keywords are supported in addition to the common template
6210 The following keywords are supported in addition to the common template
6211 keywords and functions. See also :hg:`help templates`.
6211 keywords and functions. See also :hg:`help templates`.
6212
6212
6213 :hgpath: String. Path to the .hg directory.
6213 :hgpath: String. Path to the .hg directory.
6214 :storepath: String. Path to the directory holding versioned data.
6214 :storepath: String. Path to the directory holding versioned data.
6215
6215
6216 Returns 0 on success.
6216 Returns 0 on success.
6217 """
6217 """
6218 opts = pycompat.byteskwargs(opts)
6218 opts = pycompat.byteskwargs(opts)
6219 with ui.formatter(b'root', opts) as fm:
6219 with ui.formatter(b'root', opts) as fm:
6220 fm.startitem()
6220 fm.startitem()
6221 fm.write(b'reporoot', b'%s\n', repo.root)
6221 fm.write(b'reporoot', b'%s\n', repo.root)
6222 fm.data(hgpath=repo.path, storepath=repo.spath)
6222 fm.data(hgpath=repo.path, storepath=repo.spath)
6223
6223
6224
6224
6225 @command(
6225 @command(
6226 b'serve',
6226 b'serve',
6227 [
6227 [
6228 (
6228 (
6229 b'A',
6229 b'A',
6230 b'accesslog',
6230 b'accesslog',
6231 b'',
6231 b'',
6232 _(b'name of access log file to write to'),
6232 _(b'name of access log file to write to'),
6233 _(b'FILE'),
6233 _(b'FILE'),
6234 ),
6234 ),
6235 (b'd', b'daemon', None, _(b'run server in background')),
6235 (b'd', b'daemon', None, _(b'run server in background')),
6236 (b'', b'daemon-postexec', [], _(b'used internally by daemon mode')),
6236 (b'', b'daemon-postexec', [], _(b'used internally by daemon mode')),
6237 (
6237 (
6238 b'E',
6238 b'E',
6239 b'errorlog',
6239 b'errorlog',
6240 b'',
6240 b'',
6241 _(b'name of error log file to write to'),
6241 _(b'name of error log file to write to'),
6242 _(b'FILE'),
6242 _(b'FILE'),
6243 ),
6243 ),
6244 # use string type, then we can check if something was passed
6244 # use string type, then we can check if something was passed
6245 (
6245 (
6246 b'p',
6246 b'p',
6247 b'port',
6247 b'port',
6248 b'',
6248 b'',
6249 _(b'port to listen on (default: 8000)'),
6249 _(b'port to listen on (default: 8000)'),
6250 _(b'PORT'),
6250 _(b'PORT'),
6251 ),
6251 ),
6252 (
6252 (
6253 b'a',
6253 b'a',
6254 b'address',
6254 b'address',
6255 b'',
6255 b'',
6256 _(b'address to listen on (default: all interfaces)'),
6256 _(b'address to listen on (default: all interfaces)'),
6257 _(b'ADDR'),
6257 _(b'ADDR'),
6258 ),
6258 ),
6259 (
6259 (
6260 b'',
6260 b'',
6261 b'prefix',
6261 b'prefix',
6262 b'',
6262 b'',
6263 _(b'prefix path to serve from (default: server root)'),
6263 _(b'prefix path to serve from (default: server root)'),
6264 _(b'PREFIX'),
6264 _(b'PREFIX'),
6265 ),
6265 ),
6266 (
6266 (
6267 b'n',
6267 b'n',
6268 b'name',
6268 b'name',
6269 b'',
6269 b'',
6270 _(b'name to show in web pages (default: working directory)'),
6270 _(b'name to show in web pages (default: working directory)'),
6271 _(b'NAME'),
6271 _(b'NAME'),
6272 ),
6272 ),
6273 (
6273 (
6274 b'',
6274 b'',
6275 b'web-conf',
6275 b'web-conf',
6276 b'',
6276 b'',
6277 _(b"name of the hgweb config file (see 'hg help hgweb')"),
6277 _(b"name of the hgweb config file (see 'hg help hgweb')"),
6278 _(b'FILE'),
6278 _(b'FILE'),
6279 ),
6279 ),
6280 (
6280 (
6281 b'',
6281 b'',
6282 b'webdir-conf',
6282 b'webdir-conf',
6283 b'',
6283 b'',
6284 _(b'name of the hgweb config file (DEPRECATED)'),
6284 _(b'name of the hgweb config file (DEPRECATED)'),
6285 _(b'FILE'),
6285 _(b'FILE'),
6286 ),
6286 ),
6287 (
6287 (
6288 b'',
6288 b'',
6289 b'pid-file',
6289 b'pid-file',
6290 b'',
6290 b'',
6291 _(b'name of file to write process ID to'),
6291 _(b'name of file to write process ID to'),
6292 _(b'FILE'),
6292 _(b'FILE'),
6293 ),
6293 ),
6294 (b'', b'stdio', None, _(b'for remote clients (ADVANCED)')),
6294 (b'', b'stdio', None, _(b'for remote clients (ADVANCED)')),
6295 (
6295 (
6296 b'',
6296 b'',
6297 b'cmdserver',
6297 b'cmdserver',
6298 b'',
6298 b'',
6299 _(b'for remote clients (ADVANCED)'),
6299 _(b'for remote clients (ADVANCED)'),
6300 _(b'MODE'),
6300 _(b'MODE'),
6301 ),
6301 ),
6302 (b't', b'templates', b'', _(b'web templates to use'), _(b'TEMPLATE')),
6302 (b't', b'templates', b'', _(b'web templates to use'), _(b'TEMPLATE')),
6303 (b'', b'style', b'', _(b'template style to use'), _(b'STYLE')),
6303 (b'', b'style', b'', _(b'template style to use'), _(b'STYLE')),
6304 (b'6', b'ipv6', None, _(b'use IPv6 in addition to IPv4')),
6304 (b'6', b'ipv6', None, _(b'use IPv6 in addition to IPv4')),
6305 (b'', b'certificate', b'', _(b'SSL certificate file'), _(b'FILE')),
6305 (b'', b'certificate', b'', _(b'SSL certificate file'), _(b'FILE')),
6306 (b'', b'print-url', None, _(b'start and print only the URL')),
6306 (b'', b'print-url', None, _(b'start and print only the URL')),
6307 ]
6307 ]
6308 + subrepoopts,
6308 + subrepoopts,
6309 _(b'[OPTION]...'),
6309 _(b'[OPTION]...'),
6310 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
6310 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
6311 helpbasic=True,
6311 helpbasic=True,
6312 optionalrepo=True,
6312 optionalrepo=True,
6313 )
6313 )
6314 def serve(ui, repo, **opts):
6314 def serve(ui, repo, **opts):
6315 """start stand-alone webserver
6315 """start stand-alone webserver
6316
6316
6317 Start a local HTTP repository browser and pull server. You can use
6317 Start a local HTTP repository browser and pull server. You can use
6318 this for ad-hoc sharing and browsing of repositories. It is
6318 this for ad-hoc sharing and browsing of repositories. It is
6319 recommended to use a real web server to serve a repository for
6319 recommended to use a real web server to serve a repository for
6320 longer periods of time.
6320 longer periods of time.
6321
6321
6322 Please note that the server does not implement access control.
6322 Please note that the server does not implement access control.
6323 This means that, by default, anybody can read from the server and
6323 This means that, by default, anybody can read from the server and
6324 nobody can write to it by default. Set the ``web.allow-push``
6324 nobody can write to it by default. Set the ``web.allow-push``
6325 option to ``*`` to allow everybody to push to the server. You
6325 option to ``*`` to allow everybody to push to the server. You
6326 should use a real web server if you need to authenticate users.
6326 should use a real web server if you need to authenticate users.
6327
6327
6328 By default, the server logs accesses to stdout and errors to
6328 By default, the server logs accesses to stdout and errors to
6329 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
6329 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
6330 files.
6330 files.
6331
6331
6332 To have the server choose a free port number to listen on, specify
6332 To have the server choose a free port number to listen on, specify
6333 a port number of 0; in this case, the server will print the port
6333 a port number of 0; in this case, the server will print the port
6334 number it uses.
6334 number it uses.
6335
6335
6336 Returns 0 on success.
6336 Returns 0 on success.
6337 """
6337 """
6338
6338
6339 cmdutil.check_incompatible_arguments(opts, 'stdio', ['cmdserver'])
6339 cmdutil.check_incompatible_arguments(opts, 'stdio', ['cmdserver'])
6340 opts = pycompat.byteskwargs(opts)
6340 opts = pycompat.byteskwargs(opts)
6341 if opts[b"print_url"] and ui.verbose:
6341 if opts[b"print_url"] and ui.verbose:
6342 raise error.Abort(_(b"cannot use --print-url with --verbose"))
6342 raise error.Abort(_(b"cannot use --print-url with --verbose"))
6343
6343
6344 if opts[b"stdio"]:
6344 if opts[b"stdio"]:
6345 if repo is None:
6345 if repo is None:
6346 raise error.RepoError(
6346 raise error.RepoError(
6347 _(b"there is no Mercurial repository here (.hg not found)")
6347 _(b"there is no Mercurial repository here (.hg not found)")
6348 )
6348 )
6349 s = wireprotoserver.sshserver(ui, repo)
6349 s = wireprotoserver.sshserver(ui, repo)
6350 s.serve_forever()
6350 s.serve_forever()
6351 sys.exit(0)
6351
6352
6352 service = server.createservice(ui, repo, opts)
6353 service = server.createservice(ui, repo, opts)
6353 return server.runservice(opts, initfn=service.init, runfn=service.run)
6354 return server.runservice(opts, initfn=service.init, runfn=service.run)
6354
6355
6355
6356
6356 @command(
6357 @command(
6357 b'shelve',
6358 b'shelve',
6358 [
6359 [
6359 (
6360 (
6360 b'A',
6361 b'A',
6361 b'addremove',
6362 b'addremove',
6362 None,
6363 None,
6363 _(b'mark new/missing files as added/removed before shelving'),
6364 _(b'mark new/missing files as added/removed before shelving'),
6364 ),
6365 ),
6365 (b'u', b'unknown', None, _(b'store unknown files in the shelve')),
6366 (b'u', b'unknown', None, _(b'store unknown files in the shelve')),
6366 (b'', b'cleanup', None, _(b'delete all shelved changes')),
6367 (b'', b'cleanup', None, _(b'delete all shelved changes')),
6367 (
6368 (
6368 b'',
6369 b'',
6369 b'date',
6370 b'date',
6370 b'',
6371 b'',
6371 _(b'shelve with the specified commit date'),
6372 _(b'shelve with the specified commit date'),
6372 _(b'DATE'),
6373 _(b'DATE'),
6373 ),
6374 ),
6374 (b'd', b'delete', None, _(b'delete the named shelved change(s)')),
6375 (b'd', b'delete', None, _(b'delete the named shelved change(s)')),
6375 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
6376 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
6376 (
6377 (
6377 b'k',
6378 b'k',
6378 b'keep',
6379 b'keep',
6379 False,
6380 False,
6380 _(b'shelve, but keep changes in the working directory'),
6381 _(b'shelve, but keep changes in the working directory'),
6381 ),
6382 ),
6382 (b'l', b'list', None, _(b'list current shelves')),
6383 (b'l', b'list', None, _(b'list current shelves')),
6383 (b'm', b'message', b'', _(b'use text as shelve message'), _(b'TEXT')),
6384 (b'm', b'message', b'', _(b'use text as shelve message'), _(b'TEXT')),
6384 (
6385 (
6385 b'n',
6386 b'n',
6386 b'name',
6387 b'name',
6387 b'',
6388 b'',
6388 _(b'use the given name for the shelved commit'),
6389 _(b'use the given name for the shelved commit'),
6389 _(b'NAME'),
6390 _(b'NAME'),
6390 ),
6391 ),
6391 (
6392 (
6392 b'p',
6393 b'p',
6393 b'patch',
6394 b'patch',
6394 None,
6395 None,
6395 _(
6396 _(
6396 b'output patches for changes (provide the names of the shelved '
6397 b'output patches for changes (provide the names of the shelved '
6397 b'changes as positional arguments)'
6398 b'changes as positional arguments)'
6398 ),
6399 ),
6399 ),
6400 ),
6400 (b'i', b'interactive', None, _(b'interactive mode')),
6401 (b'i', b'interactive', None, _(b'interactive mode')),
6401 (
6402 (
6402 b'',
6403 b'',
6403 b'stat',
6404 b'stat',
6404 None,
6405 None,
6405 _(
6406 _(
6406 b'output diffstat-style summary of changes (provide the names of '
6407 b'output diffstat-style summary of changes (provide the names of '
6407 b'the shelved changes as positional arguments)'
6408 b'the shelved changes as positional arguments)'
6408 ),
6409 ),
6409 ),
6410 ),
6410 ]
6411 ]
6411 + cmdutil.walkopts,
6412 + cmdutil.walkopts,
6412 _(b'hg shelve [OPTION]... [FILE]...'),
6413 _(b'hg shelve [OPTION]... [FILE]...'),
6413 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6414 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6414 )
6415 )
6415 def shelve(ui, repo, *pats, **opts):
6416 def shelve(ui, repo, *pats, **opts):
6416 '''save and set aside changes from the working directory
6417 '''save and set aside changes from the working directory
6417
6418
6418 Shelving takes files that "hg status" reports as not clean, saves
6419 Shelving takes files that "hg status" reports as not clean, saves
6419 the modifications to a bundle (a shelved change), and reverts the
6420 the modifications to a bundle (a shelved change), and reverts the
6420 files so that their state in the working directory becomes clean.
6421 files so that their state in the working directory becomes clean.
6421
6422
6422 To restore these changes to the working directory, using "hg
6423 To restore these changes to the working directory, using "hg
6423 unshelve"; this will work even if you switch to a different
6424 unshelve"; this will work even if you switch to a different
6424 commit.
6425 commit.
6425
6426
6426 When no files are specified, "hg shelve" saves all not-clean
6427 When no files are specified, "hg shelve" saves all not-clean
6427 files. If specific files or directories are named, only changes to
6428 files. If specific files or directories are named, only changes to
6428 those files are shelved.
6429 those files are shelved.
6429
6430
6430 In bare shelve (when no files are specified, without interactive,
6431 In bare shelve (when no files are specified, without interactive,
6431 include and exclude option), shelving remembers information if the
6432 include and exclude option), shelving remembers information if the
6432 working directory was on newly created branch, in other words working
6433 working directory was on newly created branch, in other words working
6433 directory was on different branch than its first parent. In this
6434 directory was on different branch than its first parent. In this
6434 situation unshelving restores branch information to the working directory.
6435 situation unshelving restores branch information to the working directory.
6435
6436
6436 Each shelved change has a name that makes it easier to find later.
6437 Each shelved change has a name that makes it easier to find later.
6437 The name of a shelved change defaults to being based on the active
6438 The name of a shelved change defaults to being based on the active
6438 bookmark, or if there is no active bookmark, the current named
6439 bookmark, or if there is no active bookmark, the current named
6439 branch. To specify a different name, use ``--name``.
6440 branch. To specify a different name, use ``--name``.
6440
6441
6441 To see a list of existing shelved changes, use the ``--list``
6442 To see a list of existing shelved changes, use the ``--list``
6442 option. For each shelved change, this will print its name, age,
6443 option. For each shelved change, this will print its name, age,
6443 and description; use ``--patch`` or ``--stat`` for more details.
6444 and description; use ``--patch`` or ``--stat`` for more details.
6444
6445
6445 To delete specific shelved changes, use ``--delete``. To delete
6446 To delete specific shelved changes, use ``--delete``. To delete
6446 all shelved changes, use ``--cleanup``.
6447 all shelved changes, use ``--cleanup``.
6447 '''
6448 '''
6448 opts = pycompat.byteskwargs(opts)
6449 opts = pycompat.byteskwargs(opts)
6449 allowables = [
6450 allowables = [
6450 (b'addremove', {b'create'}), # 'create' is pseudo action
6451 (b'addremove', {b'create'}), # 'create' is pseudo action
6451 (b'unknown', {b'create'}),
6452 (b'unknown', {b'create'}),
6452 (b'cleanup', {b'cleanup'}),
6453 (b'cleanup', {b'cleanup'}),
6453 # ('date', {'create'}), # ignored for passing '--date "0 0"' in tests
6454 # ('date', {'create'}), # ignored for passing '--date "0 0"' in tests
6454 (b'delete', {b'delete'}),
6455 (b'delete', {b'delete'}),
6455 (b'edit', {b'create'}),
6456 (b'edit', {b'create'}),
6456 (b'keep', {b'create'}),
6457 (b'keep', {b'create'}),
6457 (b'list', {b'list'}),
6458 (b'list', {b'list'}),
6458 (b'message', {b'create'}),
6459 (b'message', {b'create'}),
6459 (b'name', {b'create'}),
6460 (b'name', {b'create'}),
6460 (b'patch', {b'patch', b'list'}),
6461 (b'patch', {b'patch', b'list'}),
6461 (b'stat', {b'stat', b'list'}),
6462 (b'stat', {b'stat', b'list'}),
6462 ]
6463 ]
6463
6464
6464 def checkopt(opt):
6465 def checkopt(opt):
6465 if opts.get(opt):
6466 if opts.get(opt):
6466 for i, allowable in allowables:
6467 for i, allowable in allowables:
6467 if opts[i] and opt not in allowable:
6468 if opts[i] and opt not in allowable:
6468 raise error.Abort(
6469 raise error.Abort(
6469 _(
6470 _(
6470 b"options '--%s' and '--%s' may not be "
6471 b"options '--%s' and '--%s' may not be "
6471 b"used together"
6472 b"used together"
6472 )
6473 )
6473 % (opt, i)
6474 % (opt, i)
6474 )
6475 )
6475 return True
6476 return True
6476
6477
6477 if checkopt(b'cleanup'):
6478 if checkopt(b'cleanup'):
6478 if pats:
6479 if pats:
6479 raise error.Abort(_(b"cannot specify names when using '--cleanup'"))
6480 raise error.Abort(_(b"cannot specify names when using '--cleanup'"))
6480 return shelvemod.cleanupcmd(ui, repo)
6481 return shelvemod.cleanupcmd(ui, repo)
6481 elif checkopt(b'delete'):
6482 elif checkopt(b'delete'):
6482 return shelvemod.deletecmd(ui, repo, pats)
6483 return shelvemod.deletecmd(ui, repo, pats)
6483 elif checkopt(b'list'):
6484 elif checkopt(b'list'):
6484 return shelvemod.listcmd(ui, repo, pats, opts)
6485 return shelvemod.listcmd(ui, repo, pats, opts)
6485 elif checkopt(b'patch') or checkopt(b'stat'):
6486 elif checkopt(b'patch') or checkopt(b'stat'):
6486 return shelvemod.patchcmds(ui, repo, pats, opts)
6487 return shelvemod.patchcmds(ui, repo, pats, opts)
6487 else:
6488 else:
6488 return shelvemod.createcmd(ui, repo, pats, opts)
6489 return shelvemod.createcmd(ui, repo, pats, opts)
6489
6490
6490
6491
6491 _NOTTERSE = b'nothing'
6492 _NOTTERSE = b'nothing'
6492
6493
6493
6494
6494 @command(
6495 @command(
6495 b'status|st',
6496 b'status|st',
6496 [
6497 [
6497 (b'A', b'all', None, _(b'show status of all files')),
6498 (b'A', b'all', None, _(b'show status of all files')),
6498 (b'm', b'modified', None, _(b'show only modified files')),
6499 (b'm', b'modified', None, _(b'show only modified files')),
6499 (b'a', b'added', None, _(b'show only added files')),
6500 (b'a', b'added', None, _(b'show only added files')),
6500 (b'r', b'removed', None, _(b'show only removed files')),
6501 (b'r', b'removed', None, _(b'show only removed files')),
6501 (b'd', b'deleted', None, _(b'show only missing files')),
6502 (b'd', b'deleted', None, _(b'show only missing files')),
6502 (b'c', b'clean', None, _(b'show only files without changes')),
6503 (b'c', b'clean', None, _(b'show only files without changes')),
6503 (b'u', b'unknown', None, _(b'show only unknown (not tracked) files')),
6504 (b'u', b'unknown', None, _(b'show only unknown (not tracked) files')),
6504 (b'i', b'ignored', None, _(b'show only ignored files')),
6505 (b'i', b'ignored', None, _(b'show only ignored files')),
6505 (b'n', b'no-status', None, _(b'hide status prefix')),
6506 (b'n', b'no-status', None, _(b'hide status prefix')),
6506 (b't', b'terse', _NOTTERSE, _(b'show the terse output (EXPERIMENTAL)')),
6507 (b't', b'terse', _NOTTERSE, _(b'show the terse output (EXPERIMENTAL)')),
6507 (
6508 (
6508 b'C',
6509 b'C',
6509 b'copies',
6510 b'copies',
6510 None,
6511 None,
6511 _(b'show source of copied files (DEFAULT: ui.statuscopies)'),
6512 _(b'show source of copied files (DEFAULT: ui.statuscopies)'),
6512 ),
6513 ),
6513 (
6514 (
6514 b'0',
6515 b'0',
6515 b'print0',
6516 b'print0',
6516 None,
6517 None,
6517 _(b'end filenames with NUL, for use with xargs'),
6518 _(b'end filenames with NUL, for use with xargs'),
6518 ),
6519 ),
6519 (b'', b'rev', [], _(b'show difference from revision'), _(b'REV')),
6520 (b'', b'rev', [], _(b'show difference from revision'), _(b'REV')),
6520 (
6521 (
6521 b'',
6522 b'',
6522 b'change',
6523 b'change',
6523 b'',
6524 b'',
6524 _(b'list the changed files of a revision'),
6525 _(b'list the changed files of a revision'),
6525 _(b'REV'),
6526 _(b'REV'),
6526 ),
6527 ),
6527 ]
6528 ]
6528 + walkopts
6529 + walkopts
6529 + subrepoopts
6530 + subrepoopts
6530 + formatteropts,
6531 + formatteropts,
6531 _(b'[OPTION]... [FILE]...'),
6532 _(b'[OPTION]... [FILE]...'),
6532 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6533 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6533 helpbasic=True,
6534 helpbasic=True,
6534 inferrepo=True,
6535 inferrepo=True,
6535 intents={INTENT_READONLY},
6536 intents={INTENT_READONLY},
6536 )
6537 )
6537 def status(ui, repo, *pats, **opts):
6538 def status(ui, repo, *pats, **opts):
6538 """show changed files in the working directory
6539 """show changed files in the working directory
6539
6540
6540 Show status of files in the repository. If names are given, only
6541 Show status of files in the repository. If names are given, only
6541 files that match are shown. Files that are clean or ignored or
6542 files that match are shown. Files that are clean or ignored or
6542 the source of a copy/move operation, are not listed unless
6543 the source of a copy/move operation, are not listed unless
6543 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
6544 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
6544 Unless options described with "show only ..." are given, the
6545 Unless options described with "show only ..." are given, the
6545 options -mardu are used.
6546 options -mardu are used.
6546
6547
6547 Option -q/--quiet hides untracked (unknown and ignored) files
6548 Option -q/--quiet hides untracked (unknown and ignored) files
6548 unless explicitly requested with -u/--unknown or -i/--ignored.
6549 unless explicitly requested with -u/--unknown or -i/--ignored.
6549
6550
6550 .. note::
6551 .. note::
6551
6552
6552 :hg:`status` may appear to disagree with diff if permissions have
6553 :hg:`status` may appear to disagree with diff if permissions have
6553 changed or a merge has occurred. The standard diff format does
6554 changed or a merge has occurred. The standard diff format does
6554 not report permission changes and diff only reports changes
6555 not report permission changes and diff only reports changes
6555 relative to one merge parent.
6556 relative to one merge parent.
6556
6557
6557 If one revision is given, it is used as the base revision.
6558 If one revision is given, it is used as the base revision.
6558 If two revisions are given, the differences between them are
6559 If two revisions are given, the differences between them are
6559 shown. The --change option can also be used as a shortcut to list
6560 shown. The --change option can also be used as a shortcut to list
6560 the changed files of a revision from its first parent.
6561 the changed files of a revision from its first parent.
6561
6562
6562 The codes used to show the status of files are::
6563 The codes used to show the status of files are::
6563
6564
6564 M = modified
6565 M = modified
6565 A = added
6566 A = added
6566 R = removed
6567 R = removed
6567 C = clean
6568 C = clean
6568 ! = missing (deleted by non-hg command, but still tracked)
6569 ! = missing (deleted by non-hg command, but still tracked)
6569 ? = not tracked
6570 ? = not tracked
6570 I = ignored
6571 I = ignored
6571 = origin of the previous file (with --copies)
6572 = origin of the previous file (with --copies)
6572
6573
6573 .. container:: verbose
6574 .. container:: verbose
6574
6575
6575 The -t/--terse option abbreviates the output by showing only the directory
6576 The -t/--terse option abbreviates the output by showing only the directory
6576 name if all the files in it share the same status. The option takes an
6577 name if all the files in it share the same status. The option takes an
6577 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
6578 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
6578 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
6579 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
6579 for 'ignored' and 'c' for clean.
6580 for 'ignored' and 'c' for clean.
6580
6581
6581 It abbreviates only those statuses which are passed. Note that clean and
6582 It abbreviates only those statuses which are passed. Note that clean and
6582 ignored files are not displayed with '--terse ic' unless the -c/--clean
6583 ignored files are not displayed with '--terse ic' unless the -c/--clean
6583 and -i/--ignored options are also used.
6584 and -i/--ignored options are also used.
6584
6585
6585 The -v/--verbose option shows information when the repository is in an
6586 The -v/--verbose option shows information when the repository is in an
6586 unfinished merge, shelve, rebase state etc. You can have this behavior
6587 unfinished merge, shelve, rebase state etc. You can have this behavior
6587 turned on by default by enabling the ``commands.status.verbose`` option.
6588 turned on by default by enabling the ``commands.status.verbose`` option.
6588
6589
6589 You can skip displaying some of these states by setting
6590 You can skip displaying some of these states by setting
6590 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
6591 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
6591 'histedit', 'merge', 'rebase', or 'unshelve'.
6592 'histedit', 'merge', 'rebase', or 'unshelve'.
6592
6593
6593 Template:
6594 Template:
6594
6595
6595 The following keywords are supported in addition to the common template
6596 The following keywords are supported in addition to the common template
6596 keywords and functions. See also :hg:`help templates`.
6597 keywords and functions. See also :hg:`help templates`.
6597
6598
6598 :path: String. Repository-absolute path of the file.
6599 :path: String. Repository-absolute path of the file.
6599 :source: String. Repository-absolute path of the file originated from.
6600 :source: String. Repository-absolute path of the file originated from.
6600 Available if ``--copies`` is specified.
6601 Available if ``--copies`` is specified.
6601 :status: String. Character denoting file's status.
6602 :status: String. Character denoting file's status.
6602
6603
6603 Examples:
6604 Examples:
6604
6605
6605 - show changes in the working directory relative to a
6606 - show changes in the working directory relative to a
6606 changeset::
6607 changeset::
6607
6608
6608 hg status --rev 9353
6609 hg status --rev 9353
6609
6610
6610 - show changes in the working directory relative to the
6611 - show changes in the working directory relative to the
6611 current directory (see :hg:`help patterns` for more information)::
6612 current directory (see :hg:`help patterns` for more information)::
6612
6613
6613 hg status re:
6614 hg status re:
6614
6615
6615 - show all changes including copies in an existing changeset::
6616 - show all changes including copies in an existing changeset::
6616
6617
6617 hg status --copies --change 9353
6618 hg status --copies --change 9353
6618
6619
6619 - get a NUL separated list of added files, suitable for xargs::
6620 - get a NUL separated list of added files, suitable for xargs::
6620
6621
6621 hg status -an0
6622 hg status -an0
6622
6623
6623 - show more information about the repository status, abbreviating
6624 - show more information about the repository status, abbreviating
6624 added, removed, modified, deleted, and untracked paths::
6625 added, removed, modified, deleted, and untracked paths::
6625
6626
6626 hg status -v -t mardu
6627 hg status -v -t mardu
6627
6628
6628 Returns 0 on success.
6629 Returns 0 on success.
6629
6630
6630 """
6631 """
6631
6632
6632 cmdutil.check_at_most_one_arg(opts, 'rev', 'change')
6633 cmdutil.check_at_most_one_arg(opts, 'rev', 'change')
6633 opts = pycompat.byteskwargs(opts)
6634 opts = pycompat.byteskwargs(opts)
6634 revs = opts.get(b'rev')
6635 revs = opts.get(b'rev')
6635 change = opts.get(b'change')
6636 change = opts.get(b'change')
6636 terse = opts.get(b'terse')
6637 terse = opts.get(b'terse')
6637 if terse is _NOTTERSE:
6638 if terse is _NOTTERSE:
6638 if revs:
6639 if revs:
6639 terse = b''
6640 terse = b''
6640 else:
6641 else:
6641 terse = ui.config(b'commands', b'status.terse')
6642 terse = ui.config(b'commands', b'status.terse')
6642
6643
6643 if revs and terse:
6644 if revs and terse:
6644 msg = _(b'cannot use --terse with --rev')
6645 msg = _(b'cannot use --terse with --rev')
6645 raise error.Abort(msg)
6646 raise error.Abort(msg)
6646 elif change:
6647 elif change:
6647 repo = scmutil.unhidehashlikerevs(repo, [change], b'nowarn')
6648 repo = scmutil.unhidehashlikerevs(repo, [change], b'nowarn')
6648 ctx2 = scmutil.revsingle(repo, change, None)
6649 ctx2 = scmutil.revsingle(repo, change, None)
6649 ctx1 = ctx2.p1()
6650 ctx1 = ctx2.p1()
6650 else:
6651 else:
6651 repo = scmutil.unhidehashlikerevs(repo, revs, b'nowarn')
6652 repo = scmutil.unhidehashlikerevs(repo, revs, b'nowarn')
6652 ctx1, ctx2 = scmutil.revpair(repo, revs)
6653 ctx1, ctx2 = scmutil.revpair(repo, revs)
6653
6654
6654 forcerelativevalue = None
6655 forcerelativevalue = None
6655 if ui.hasconfig(b'commands', b'status.relative'):
6656 if ui.hasconfig(b'commands', b'status.relative'):
6656 forcerelativevalue = ui.configbool(b'commands', b'status.relative')
6657 forcerelativevalue = ui.configbool(b'commands', b'status.relative')
6657 uipathfn = scmutil.getuipathfn(
6658 uipathfn = scmutil.getuipathfn(
6658 repo,
6659 repo,
6659 legacyrelativevalue=bool(pats),
6660 legacyrelativevalue=bool(pats),
6660 forcerelativevalue=forcerelativevalue,
6661 forcerelativevalue=forcerelativevalue,
6661 )
6662 )
6662
6663
6663 if opts.get(b'print0'):
6664 if opts.get(b'print0'):
6664 end = b'\0'
6665 end = b'\0'
6665 else:
6666 else:
6666 end = b'\n'
6667 end = b'\n'
6667 states = b'modified added removed deleted unknown ignored clean'.split()
6668 states = b'modified added removed deleted unknown ignored clean'.split()
6668 show = [k for k in states if opts.get(k)]
6669 show = [k for k in states if opts.get(k)]
6669 if opts.get(b'all'):
6670 if opts.get(b'all'):
6670 show += ui.quiet and (states[:4] + [b'clean']) or states
6671 show += ui.quiet and (states[:4] + [b'clean']) or states
6671
6672
6672 if not show:
6673 if not show:
6673 if ui.quiet:
6674 if ui.quiet:
6674 show = states[:4]
6675 show = states[:4]
6675 else:
6676 else:
6676 show = states[:5]
6677 show = states[:5]
6677
6678
6678 m = scmutil.match(ctx2, pats, opts)
6679 m = scmutil.match(ctx2, pats, opts)
6679 if terse:
6680 if terse:
6680 # we need to compute clean and unknown to terse
6681 # we need to compute clean and unknown to terse
6681 stat = repo.status(
6682 stat = repo.status(
6682 ctx1.node(),
6683 ctx1.node(),
6683 ctx2.node(),
6684 ctx2.node(),
6684 m,
6685 m,
6685 b'ignored' in show or b'i' in terse,
6686 b'ignored' in show or b'i' in terse,
6686 clean=True,
6687 clean=True,
6687 unknown=True,
6688 unknown=True,
6688 listsubrepos=opts.get(b'subrepos'),
6689 listsubrepos=opts.get(b'subrepos'),
6689 )
6690 )
6690
6691
6691 stat = cmdutil.tersedir(stat, terse)
6692 stat = cmdutil.tersedir(stat, terse)
6692 else:
6693 else:
6693 stat = repo.status(
6694 stat = repo.status(
6694 ctx1.node(),
6695 ctx1.node(),
6695 ctx2.node(),
6696 ctx2.node(),
6696 m,
6697 m,
6697 b'ignored' in show,
6698 b'ignored' in show,
6698 b'clean' in show,
6699 b'clean' in show,
6699 b'unknown' in show,
6700 b'unknown' in show,
6700 opts.get(b'subrepos'),
6701 opts.get(b'subrepos'),
6701 )
6702 )
6702
6703
6703 changestates = zip(
6704 changestates = zip(
6704 states,
6705 states,
6705 pycompat.iterbytestr(b'MAR!?IC'),
6706 pycompat.iterbytestr(b'MAR!?IC'),
6706 [getattr(stat, s.decode('utf8')) for s in states],
6707 [getattr(stat, s.decode('utf8')) for s in states],
6707 )
6708 )
6708
6709
6709 copy = {}
6710 copy = {}
6710 if (
6711 if (
6711 opts.get(b'all')
6712 opts.get(b'all')
6712 or opts.get(b'copies')
6713 or opts.get(b'copies')
6713 or ui.configbool(b'ui', b'statuscopies')
6714 or ui.configbool(b'ui', b'statuscopies')
6714 ) and not opts.get(b'no_status'):
6715 ) and not opts.get(b'no_status'):
6715 copy = copies.pathcopies(ctx1, ctx2, m)
6716 copy = copies.pathcopies(ctx1, ctx2, m)
6716
6717
6717 morestatus = None
6718 morestatus = None
6718 if (
6719 if (
6719 ui.verbose or ui.configbool(b'commands', b'status.verbose')
6720 ui.verbose or ui.configbool(b'commands', b'status.verbose')
6720 ) and not ui.plain():
6721 ) and not ui.plain():
6721 morestatus = cmdutil.readmorestatus(repo)
6722 morestatus = cmdutil.readmorestatus(repo)
6722
6723
6723 ui.pager(b'status')
6724 ui.pager(b'status')
6724 fm = ui.formatter(b'status', opts)
6725 fm = ui.formatter(b'status', opts)
6725 fmt = b'%s' + end
6726 fmt = b'%s' + end
6726 showchar = not opts.get(b'no_status')
6727 showchar = not opts.get(b'no_status')
6727
6728
6728 for state, char, files in changestates:
6729 for state, char, files in changestates:
6729 if state in show:
6730 if state in show:
6730 label = b'status.' + state
6731 label = b'status.' + state
6731 for f in files:
6732 for f in files:
6732 fm.startitem()
6733 fm.startitem()
6733 fm.context(ctx=ctx2)
6734 fm.context(ctx=ctx2)
6734 fm.data(itemtype=b'file', path=f)
6735 fm.data(itemtype=b'file', path=f)
6735 fm.condwrite(showchar, b'status', b'%s ', char, label=label)
6736 fm.condwrite(showchar, b'status', b'%s ', char, label=label)
6736 fm.plain(fmt % uipathfn(f), label=label)
6737 fm.plain(fmt % uipathfn(f), label=label)
6737 if f in copy:
6738 if f in copy:
6738 fm.data(source=copy[f])
6739 fm.data(source=copy[f])
6739 fm.plain(
6740 fm.plain(
6740 (b' %s' + end) % uipathfn(copy[f]),
6741 (b' %s' + end) % uipathfn(copy[f]),
6741 label=b'status.copied',
6742 label=b'status.copied',
6742 )
6743 )
6743 if morestatus:
6744 if morestatus:
6744 morestatus.formatfile(f, fm)
6745 morestatus.formatfile(f, fm)
6745
6746
6746 if morestatus:
6747 if morestatus:
6747 morestatus.formatfooter(fm)
6748 morestatus.formatfooter(fm)
6748 fm.end()
6749 fm.end()
6749
6750
6750
6751
6751 @command(
6752 @command(
6752 b'summary|sum',
6753 b'summary|sum',
6753 [(b'', b'remote', None, _(b'check for push and pull'))],
6754 [(b'', b'remote', None, _(b'check for push and pull'))],
6754 b'[--remote]',
6755 b'[--remote]',
6755 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6756 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6756 helpbasic=True,
6757 helpbasic=True,
6757 intents={INTENT_READONLY},
6758 intents={INTENT_READONLY},
6758 )
6759 )
6759 def summary(ui, repo, **opts):
6760 def summary(ui, repo, **opts):
6760 """summarize working directory state
6761 """summarize working directory state
6761
6762
6762 This generates a brief summary of the working directory state,
6763 This generates a brief summary of the working directory state,
6763 including parents, branch, commit status, phase and available updates.
6764 including parents, branch, commit status, phase and available updates.
6764
6765
6765 With the --remote option, this will check the default paths for
6766 With the --remote option, this will check the default paths for
6766 incoming and outgoing changes. This can be time-consuming.
6767 incoming and outgoing changes. This can be time-consuming.
6767
6768
6768 Returns 0 on success.
6769 Returns 0 on success.
6769 """
6770 """
6770
6771
6771 opts = pycompat.byteskwargs(opts)
6772 opts = pycompat.byteskwargs(opts)
6772 ui.pager(b'summary')
6773 ui.pager(b'summary')
6773 ctx = repo[None]
6774 ctx = repo[None]
6774 parents = ctx.parents()
6775 parents = ctx.parents()
6775 pnode = parents[0].node()
6776 pnode = parents[0].node()
6776 marks = []
6777 marks = []
6777
6778
6778 try:
6779 try:
6779 ms = mergestatemod.mergestate.read(repo)
6780 ms = mergestatemod.mergestate.read(repo)
6780 except error.UnsupportedMergeRecords as e:
6781 except error.UnsupportedMergeRecords as e:
6781 s = b' '.join(e.recordtypes)
6782 s = b' '.join(e.recordtypes)
6782 ui.warn(
6783 ui.warn(
6783 _(b'warning: merge state has unsupported record types: %s\n') % s
6784 _(b'warning: merge state has unsupported record types: %s\n') % s
6784 )
6785 )
6785 unresolved = []
6786 unresolved = []
6786 else:
6787 else:
6787 unresolved = list(ms.unresolved())
6788 unresolved = list(ms.unresolved())
6788
6789
6789 for p in parents:
6790 for p in parents:
6790 # label with log.changeset (instead of log.parent) since this
6791 # label with log.changeset (instead of log.parent) since this
6791 # shows a working directory parent *changeset*:
6792 # shows a working directory parent *changeset*:
6792 # i18n: column positioning for "hg summary"
6793 # i18n: column positioning for "hg summary"
6793 ui.write(
6794 ui.write(
6794 _(b'parent: %d:%s ') % (p.rev(), p),
6795 _(b'parent: %d:%s ') % (p.rev(), p),
6795 label=logcmdutil.changesetlabels(p),
6796 label=logcmdutil.changesetlabels(p),
6796 )
6797 )
6797 ui.write(b' '.join(p.tags()), label=b'log.tag')
6798 ui.write(b' '.join(p.tags()), label=b'log.tag')
6798 if p.bookmarks():
6799 if p.bookmarks():
6799 marks.extend(p.bookmarks())
6800 marks.extend(p.bookmarks())
6800 if p.rev() == -1:
6801 if p.rev() == -1:
6801 if not len(repo):
6802 if not len(repo):
6802 ui.write(_(b' (empty repository)'))
6803 ui.write(_(b' (empty repository)'))
6803 else:
6804 else:
6804 ui.write(_(b' (no revision checked out)'))
6805 ui.write(_(b' (no revision checked out)'))
6805 if p.obsolete():
6806 if p.obsolete():
6806 ui.write(_(b' (obsolete)'))
6807 ui.write(_(b' (obsolete)'))
6807 if p.isunstable():
6808 if p.isunstable():
6808 instabilities = (
6809 instabilities = (
6809 ui.label(instability, b'trouble.%s' % instability)
6810 ui.label(instability, b'trouble.%s' % instability)
6810 for instability in p.instabilities()
6811 for instability in p.instabilities()
6811 )
6812 )
6812 ui.write(b' (' + b', '.join(instabilities) + b')')
6813 ui.write(b' (' + b', '.join(instabilities) + b')')
6813 ui.write(b'\n')
6814 ui.write(b'\n')
6814 if p.description():
6815 if p.description():
6815 ui.status(
6816 ui.status(
6816 b' ' + p.description().splitlines()[0].strip() + b'\n',
6817 b' ' + p.description().splitlines()[0].strip() + b'\n',
6817 label=b'log.summary',
6818 label=b'log.summary',
6818 )
6819 )
6819
6820
6820 branch = ctx.branch()
6821 branch = ctx.branch()
6821 bheads = repo.branchheads(branch)
6822 bheads = repo.branchheads(branch)
6822 # i18n: column positioning for "hg summary"
6823 # i18n: column positioning for "hg summary"
6823 m = _(b'branch: %s\n') % branch
6824 m = _(b'branch: %s\n') % branch
6824 if branch != b'default':
6825 if branch != b'default':
6825 ui.write(m, label=b'log.branch')
6826 ui.write(m, label=b'log.branch')
6826 else:
6827 else:
6827 ui.status(m, label=b'log.branch')
6828 ui.status(m, label=b'log.branch')
6828
6829
6829 if marks:
6830 if marks:
6830 active = repo._activebookmark
6831 active = repo._activebookmark
6831 # i18n: column positioning for "hg summary"
6832 # i18n: column positioning for "hg summary"
6832 ui.write(_(b'bookmarks:'), label=b'log.bookmark')
6833 ui.write(_(b'bookmarks:'), label=b'log.bookmark')
6833 if active is not None:
6834 if active is not None:
6834 if active in marks:
6835 if active in marks:
6835 ui.write(b' *' + active, label=bookmarks.activebookmarklabel)
6836 ui.write(b' *' + active, label=bookmarks.activebookmarklabel)
6836 marks.remove(active)
6837 marks.remove(active)
6837 else:
6838 else:
6838 ui.write(b' [%s]' % active, label=bookmarks.activebookmarklabel)
6839 ui.write(b' [%s]' % active, label=bookmarks.activebookmarklabel)
6839 for m in marks:
6840 for m in marks:
6840 ui.write(b' ' + m, label=b'log.bookmark')
6841 ui.write(b' ' + m, label=b'log.bookmark')
6841 ui.write(b'\n', label=b'log.bookmark')
6842 ui.write(b'\n', label=b'log.bookmark')
6842
6843
6843 status = repo.status(unknown=True)
6844 status = repo.status(unknown=True)
6844
6845
6845 c = repo.dirstate.copies()
6846 c = repo.dirstate.copies()
6846 copied, renamed = [], []
6847 copied, renamed = [], []
6847 for d, s in pycompat.iteritems(c):
6848 for d, s in pycompat.iteritems(c):
6848 if s in status.removed:
6849 if s in status.removed:
6849 status.removed.remove(s)
6850 status.removed.remove(s)
6850 renamed.append(d)
6851 renamed.append(d)
6851 else:
6852 else:
6852 copied.append(d)
6853 copied.append(d)
6853 if d in status.added:
6854 if d in status.added:
6854 status.added.remove(d)
6855 status.added.remove(d)
6855
6856
6856 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
6857 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
6857
6858
6858 labels = [
6859 labels = [
6859 (ui.label(_(b'%d modified'), b'status.modified'), status.modified),
6860 (ui.label(_(b'%d modified'), b'status.modified'), status.modified),
6860 (ui.label(_(b'%d added'), b'status.added'), status.added),
6861 (ui.label(_(b'%d added'), b'status.added'), status.added),
6861 (ui.label(_(b'%d removed'), b'status.removed'), status.removed),
6862 (ui.label(_(b'%d removed'), b'status.removed'), status.removed),
6862 (ui.label(_(b'%d renamed'), b'status.copied'), renamed),
6863 (ui.label(_(b'%d renamed'), b'status.copied'), renamed),
6863 (ui.label(_(b'%d copied'), b'status.copied'), copied),
6864 (ui.label(_(b'%d copied'), b'status.copied'), copied),
6864 (ui.label(_(b'%d deleted'), b'status.deleted'), status.deleted),
6865 (ui.label(_(b'%d deleted'), b'status.deleted'), status.deleted),
6865 (ui.label(_(b'%d unknown'), b'status.unknown'), status.unknown),
6866 (ui.label(_(b'%d unknown'), b'status.unknown'), status.unknown),
6866 (ui.label(_(b'%d unresolved'), b'resolve.unresolved'), unresolved),
6867 (ui.label(_(b'%d unresolved'), b'resolve.unresolved'), unresolved),
6867 (ui.label(_(b'%d subrepos'), b'status.modified'), subs),
6868 (ui.label(_(b'%d subrepos'), b'status.modified'), subs),
6868 ]
6869 ]
6869 t = []
6870 t = []
6870 for l, s in labels:
6871 for l, s in labels:
6871 if s:
6872 if s:
6872 t.append(l % len(s))
6873 t.append(l % len(s))
6873
6874
6874 t = b', '.join(t)
6875 t = b', '.join(t)
6875 cleanworkdir = False
6876 cleanworkdir = False
6876
6877
6877 if repo.vfs.exists(b'graftstate'):
6878 if repo.vfs.exists(b'graftstate'):
6878 t += _(b' (graft in progress)')
6879 t += _(b' (graft in progress)')
6879 if repo.vfs.exists(b'updatestate'):
6880 if repo.vfs.exists(b'updatestate'):
6880 t += _(b' (interrupted update)')
6881 t += _(b' (interrupted update)')
6881 elif len(parents) > 1:
6882 elif len(parents) > 1:
6882 t += _(b' (merge)')
6883 t += _(b' (merge)')
6883 elif branch != parents[0].branch():
6884 elif branch != parents[0].branch():
6884 t += _(b' (new branch)')
6885 t += _(b' (new branch)')
6885 elif parents[0].closesbranch() and pnode in repo.branchheads(
6886 elif parents[0].closesbranch() and pnode in repo.branchheads(
6886 branch, closed=True
6887 branch, closed=True
6887 ):
6888 ):
6888 t += _(b' (head closed)')
6889 t += _(b' (head closed)')
6889 elif not (
6890 elif not (
6890 status.modified
6891 status.modified
6891 or status.added
6892 or status.added
6892 or status.removed
6893 or status.removed
6893 or renamed
6894 or renamed
6894 or copied
6895 or copied
6895 or subs
6896 or subs
6896 ):
6897 ):
6897 t += _(b' (clean)')
6898 t += _(b' (clean)')
6898 cleanworkdir = True
6899 cleanworkdir = True
6899 elif pnode not in bheads:
6900 elif pnode not in bheads:
6900 t += _(b' (new branch head)')
6901 t += _(b' (new branch head)')
6901
6902
6902 if parents:
6903 if parents:
6903 pendingphase = max(p.phase() for p in parents)
6904 pendingphase = max(p.phase() for p in parents)
6904 else:
6905 else:
6905 pendingphase = phases.public
6906 pendingphase = phases.public
6906
6907
6907 if pendingphase > phases.newcommitphase(ui):
6908 if pendingphase > phases.newcommitphase(ui):
6908 t += b' (%s)' % phases.phasenames[pendingphase]
6909 t += b' (%s)' % phases.phasenames[pendingphase]
6909
6910
6910 if cleanworkdir:
6911 if cleanworkdir:
6911 # i18n: column positioning for "hg summary"
6912 # i18n: column positioning for "hg summary"
6912 ui.status(_(b'commit: %s\n') % t.strip())
6913 ui.status(_(b'commit: %s\n') % t.strip())
6913 else:
6914 else:
6914 # i18n: column positioning for "hg summary"
6915 # i18n: column positioning for "hg summary"
6915 ui.write(_(b'commit: %s\n') % t.strip())
6916 ui.write(_(b'commit: %s\n') % t.strip())
6916
6917
6917 # all ancestors of branch heads - all ancestors of parent = new csets
6918 # all ancestors of branch heads - all ancestors of parent = new csets
6918 new = len(
6919 new = len(
6919 repo.changelog.findmissing([pctx.node() for pctx in parents], bheads)
6920 repo.changelog.findmissing([pctx.node() for pctx in parents], bheads)
6920 )
6921 )
6921
6922
6922 if new == 0:
6923 if new == 0:
6923 # i18n: column positioning for "hg summary"
6924 # i18n: column positioning for "hg summary"
6924 ui.status(_(b'update: (current)\n'))
6925 ui.status(_(b'update: (current)\n'))
6925 elif pnode not in bheads:
6926 elif pnode not in bheads:
6926 # i18n: column positioning for "hg summary"
6927 # i18n: column positioning for "hg summary"
6927 ui.write(_(b'update: %d new changesets (update)\n') % new)
6928 ui.write(_(b'update: %d new changesets (update)\n') % new)
6928 else:
6929 else:
6929 # i18n: column positioning for "hg summary"
6930 # i18n: column positioning for "hg summary"
6930 ui.write(
6931 ui.write(
6931 _(b'update: %d new changesets, %d branch heads (merge)\n')
6932 _(b'update: %d new changesets, %d branch heads (merge)\n')
6932 % (new, len(bheads))
6933 % (new, len(bheads))
6933 )
6934 )
6934
6935
6935 t = []
6936 t = []
6936 draft = len(repo.revs(b'draft()'))
6937 draft = len(repo.revs(b'draft()'))
6937 if draft:
6938 if draft:
6938 t.append(_(b'%d draft') % draft)
6939 t.append(_(b'%d draft') % draft)
6939 secret = len(repo.revs(b'secret()'))
6940 secret = len(repo.revs(b'secret()'))
6940 if secret:
6941 if secret:
6941 t.append(_(b'%d secret') % secret)
6942 t.append(_(b'%d secret') % secret)
6942
6943
6943 if draft or secret:
6944 if draft or secret:
6944 ui.status(_(b'phases: %s\n') % b', '.join(t))
6945 ui.status(_(b'phases: %s\n') % b', '.join(t))
6945
6946
6946 if obsolete.isenabled(repo, obsolete.createmarkersopt):
6947 if obsolete.isenabled(repo, obsolete.createmarkersopt):
6947 for trouble in (b"orphan", b"contentdivergent", b"phasedivergent"):
6948 for trouble in (b"orphan", b"contentdivergent", b"phasedivergent"):
6948 numtrouble = len(repo.revs(trouble + b"()"))
6949 numtrouble = len(repo.revs(trouble + b"()"))
6949 # We write all the possibilities to ease translation
6950 # We write all the possibilities to ease translation
6950 troublemsg = {
6951 troublemsg = {
6951 b"orphan": _(b"orphan: %d changesets"),
6952 b"orphan": _(b"orphan: %d changesets"),
6952 b"contentdivergent": _(b"content-divergent: %d changesets"),
6953 b"contentdivergent": _(b"content-divergent: %d changesets"),
6953 b"phasedivergent": _(b"phase-divergent: %d changesets"),
6954 b"phasedivergent": _(b"phase-divergent: %d changesets"),
6954 }
6955 }
6955 if numtrouble > 0:
6956 if numtrouble > 0:
6956 ui.status(troublemsg[trouble] % numtrouble + b"\n")
6957 ui.status(troublemsg[trouble] % numtrouble + b"\n")
6957
6958
6958 cmdutil.summaryhooks(ui, repo)
6959 cmdutil.summaryhooks(ui, repo)
6959
6960
6960 if opts.get(b'remote'):
6961 if opts.get(b'remote'):
6961 needsincoming, needsoutgoing = True, True
6962 needsincoming, needsoutgoing = True, True
6962 else:
6963 else:
6963 needsincoming, needsoutgoing = False, False
6964 needsincoming, needsoutgoing = False, False
6964 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
6965 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
6965 if i:
6966 if i:
6966 needsincoming = True
6967 needsincoming = True
6967 if o:
6968 if o:
6968 needsoutgoing = True
6969 needsoutgoing = True
6969 if not needsincoming and not needsoutgoing:
6970 if not needsincoming and not needsoutgoing:
6970 return
6971 return
6971
6972
6972 def getincoming():
6973 def getincoming():
6973 source, branches = hg.parseurl(ui.expandpath(b'default'))
6974 source, branches = hg.parseurl(ui.expandpath(b'default'))
6974 sbranch = branches[0]
6975 sbranch = branches[0]
6975 try:
6976 try:
6976 other = hg.peer(repo, {}, source)
6977 other = hg.peer(repo, {}, source)
6977 except error.RepoError:
6978 except error.RepoError:
6978 if opts.get(b'remote'):
6979 if opts.get(b'remote'):
6979 raise
6980 raise
6980 return source, sbranch, None, None, None
6981 return source, sbranch, None, None, None
6981 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
6982 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
6982 if revs:
6983 if revs:
6983 revs = [other.lookup(rev) for rev in revs]
6984 revs = [other.lookup(rev) for rev in revs]
6984 ui.debug(b'comparing with %s\n' % util.hidepassword(source))
6985 ui.debug(b'comparing with %s\n' % util.hidepassword(source))
6985 repo.ui.pushbuffer()
6986 repo.ui.pushbuffer()
6986 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
6987 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
6987 repo.ui.popbuffer()
6988 repo.ui.popbuffer()
6988 return source, sbranch, other, commoninc, commoninc[1]
6989 return source, sbranch, other, commoninc, commoninc[1]
6989
6990
6990 if needsincoming:
6991 if needsincoming:
6991 source, sbranch, sother, commoninc, incoming = getincoming()
6992 source, sbranch, sother, commoninc, incoming = getincoming()
6992 else:
6993 else:
6993 source = sbranch = sother = commoninc = incoming = None
6994 source = sbranch = sother = commoninc = incoming = None
6994
6995
6995 def getoutgoing():
6996 def getoutgoing():
6996 dest, branches = hg.parseurl(ui.expandpath(b'default-push', b'default'))
6997 dest, branches = hg.parseurl(ui.expandpath(b'default-push', b'default'))
6997 dbranch = branches[0]
6998 dbranch = branches[0]
6998 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
6999 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
6999 if source != dest:
7000 if source != dest:
7000 try:
7001 try:
7001 dother = hg.peer(repo, {}, dest)
7002 dother = hg.peer(repo, {}, dest)
7002 except error.RepoError:
7003 except error.RepoError:
7003 if opts.get(b'remote'):
7004 if opts.get(b'remote'):
7004 raise
7005 raise
7005 return dest, dbranch, None, None
7006 return dest, dbranch, None, None
7006 ui.debug(b'comparing with %s\n' % util.hidepassword(dest))
7007 ui.debug(b'comparing with %s\n' % util.hidepassword(dest))
7007 elif sother is None:
7008 elif sother is None:
7008 # there is no explicit destination peer, but source one is invalid
7009 # there is no explicit destination peer, but source one is invalid
7009 return dest, dbranch, None, None
7010 return dest, dbranch, None, None
7010 else:
7011 else:
7011 dother = sother
7012 dother = sother
7012 if source != dest or (sbranch is not None and sbranch != dbranch):
7013 if source != dest or (sbranch is not None and sbranch != dbranch):
7013 common = None
7014 common = None
7014 else:
7015 else:
7015 common = commoninc
7016 common = commoninc
7016 if revs:
7017 if revs:
7017 revs = [repo.lookup(rev) for rev in revs]
7018 revs = [repo.lookup(rev) for rev in revs]
7018 repo.ui.pushbuffer()
7019 repo.ui.pushbuffer()
7019 outgoing = discovery.findcommonoutgoing(
7020 outgoing = discovery.findcommonoutgoing(
7020 repo, dother, onlyheads=revs, commoninc=common
7021 repo, dother, onlyheads=revs, commoninc=common
7021 )
7022 )
7022 repo.ui.popbuffer()
7023 repo.ui.popbuffer()
7023 return dest, dbranch, dother, outgoing
7024 return dest, dbranch, dother, outgoing
7024
7025
7025 if needsoutgoing:
7026 if needsoutgoing:
7026 dest, dbranch, dother, outgoing = getoutgoing()
7027 dest, dbranch, dother, outgoing = getoutgoing()
7027 else:
7028 else:
7028 dest = dbranch = dother = outgoing = None
7029 dest = dbranch = dother = outgoing = None
7029
7030
7030 if opts.get(b'remote'):
7031 if opts.get(b'remote'):
7031 t = []
7032 t = []
7032 if incoming:
7033 if incoming:
7033 t.append(_(b'1 or more incoming'))
7034 t.append(_(b'1 or more incoming'))
7034 o = outgoing.missing
7035 o = outgoing.missing
7035 if o:
7036 if o:
7036 t.append(_(b'%d outgoing') % len(o))
7037 t.append(_(b'%d outgoing') % len(o))
7037 other = dother or sother
7038 other = dother or sother
7038 if b'bookmarks' in other.listkeys(b'namespaces'):
7039 if b'bookmarks' in other.listkeys(b'namespaces'):
7039 counts = bookmarks.summary(repo, other)
7040 counts = bookmarks.summary(repo, other)
7040 if counts[0] > 0:
7041 if counts[0] > 0:
7041 t.append(_(b'%d incoming bookmarks') % counts[0])
7042 t.append(_(b'%d incoming bookmarks') % counts[0])
7042 if counts[1] > 0:
7043 if counts[1] > 0:
7043 t.append(_(b'%d outgoing bookmarks') % counts[1])
7044 t.append(_(b'%d outgoing bookmarks') % counts[1])
7044
7045
7045 if t:
7046 if t:
7046 # i18n: column positioning for "hg summary"
7047 # i18n: column positioning for "hg summary"
7047 ui.write(_(b'remote: %s\n') % (b', '.join(t)))
7048 ui.write(_(b'remote: %s\n') % (b', '.join(t)))
7048 else:
7049 else:
7049 # i18n: column positioning for "hg summary"
7050 # i18n: column positioning for "hg summary"
7050 ui.status(_(b'remote: (synced)\n'))
7051 ui.status(_(b'remote: (synced)\n'))
7051
7052
7052 cmdutil.summaryremotehooks(
7053 cmdutil.summaryremotehooks(
7053 ui,
7054 ui,
7054 repo,
7055 repo,
7055 opts,
7056 opts,
7056 (
7057 (
7057 (source, sbranch, sother, commoninc),
7058 (source, sbranch, sother, commoninc),
7058 (dest, dbranch, dother, outgoing),
7059 (dest, dbranch, dother, outgoing),
7059 ),
7060 ),
7060 )
7061 )
7061
7062
7062
7063
7063 @command(
7064 @command(
7064 b'tag',
7065 b'tag',
7065 [
7066 [
7066 (b'f', b'force', None, _(b'force tag')),
7067 (b'f', b'force', None, _(b'force tag')),
7067 (b'l', b'local', None, _(b'make the tag local')),
7068 (b'l', b'local', None, _(b'make the tag local')),
7068 (b'r', b'rev', b'', _(b'revision to tag'), _(b'REV')),
7069 (b'r', b'rev', b'', _(b'revision to tag'), _(b'REV')),
7069 (b'', b'remove', None, _(b'remove a tag')),
7070 (b'', b'remove', None, _(b'remove a tag')),
7070 # -l/--local is already there, commitopts cannot be used
7071 # -l/--local is already there, commitopts cannot be used
7071 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
7072 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
7072 (b'm', b'message', b'', _(b'use text as commit message'), _(b'TEXT')),
7073 (b'm', b'message', b'', _(b'use text as commit message'), _(b'TEXT')),
7073 ]
7074 ]
7074 + commitopts2,
7075 + commitopts2,
7075 _(b'[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'),
7076 _(b'[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'),
7076 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7077 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7077 )
7078 )
7078 def tag(ui, repo, name1, *names, **opts):
7079 def tag(ui, repo, name1, *names, **opts):
7079 """add one or more tags for the current or given revision
7080 """add one or more tags for the current or given revision
7080
7081
7081 Name a particular revision using <name>.
7082 Name a particular revision using <name>.
7082
7083
7083 Tags are used to name particular revisions of the repository and are
7084 Tags are used to name particular revisions of the repository and are
7084 very useful to compare different revisions, to go back to significant
7085 very useful to compare different revisions, to go back to significant
7085 earlier versions or to mark branch points as releases, etc. Changing
7086 earlier versions or to mark branch points as releases, etc. Changing
7086 an existing tag is normally disallowed; use -f/--force to override.
7087 an existing tag is normally disallowed; use -f/--force to override.
7087
7088
7088 If no revision is given, the parent of the working directory is
7089 If no revision is given, the parent of the working directory is
7089 used.
7090 used.
7090
7091
7091 To facilitate version control, distribution, and merging of tags,
7092 To facilitate version control, distribution, and merging of tags,
7092 they are stored as a file named ".hgtags" which is managed similarly
7093 they are stored as a file named ".hgtags" which is managed similarly
7093 to other project files and can be hand-edited if necessary. This
7094 to other project files and can be hand-edited if necessary. This
7094 also means that tagging creates a new commit. The file
7095 also means that tagging creates a new commit. The file
7095 ".hg/localtags" is used for local tags (not shared among
7096 ".hg/localtags" is used for local tags (not shared among
7096 repositories).
7097 repositories).
7097
7098
7098 Tag commits are usually made at the head of a branch. If the parent
7099 Tag commits are usually made at the head of a branch. If the parent
7099 of the working directory is not a branch head, :hg:`tag` aborts; use
7100 of the working directory is not a branch head, :hg:`tag` aborts; use
7100 -f/--force to force the tag commit to be based on a non-head
7101 -f/--force to force the tag commit to be based on a non-head
7101 changeset.
7102 changeset.
7102
7103
7103 See :hg:`help dates` for a list of formats valid for -d/--date.
7104 See :hg:`help dates` for a list of formats valid for -d/--date.
7104
7105
7105 Since tag names have priority over branch names during revision
7106 Since tag names have priority over branch names during revision
7106 lookup, using an existing branch name as a tag name is discouraged.
7107 lookup, using an existing branch name as a tag name is discouraged.
7107
7108
7108 Returns 0 on success.
7109 Returns 0 on success.
7109 """
7110 """
7110 cmdutil.check_incompatible_arguments(opts, 'remove', ['rev'])
7111 cmdutil.check_incompatible_arguments(opts, 'remove', ['rev'])
7111 opts = pycompat.byteskwargs(opts)
7112 opts = pycompat.byteskwargs(opts)
7112 with repo.wlock(), repo.lock():
7113 with repo.wlock(), repo.lock():
7113 rev_ = b"."
7114 rev_ = b"."
7114 names = [t.strip() for t in (name1,) + names]
7115 names = [t.strip() for t in (name1,) + names]
7115 if len(names) != len(set(names)):
7116 if len(names) != len(set(names)):
7116 raise error.Abort(_(b'tag names must be unique'))
7117 raise error.Abort(_(b'tag names must be unique'))
7117 for n in names:
7118 for n in names:
7118 scmutil.checknewlabel(repo, n, b'tag')
7119 scmutil.checknewlabel(repo, n, b'tag')
7119 if not n:
7120 if not n:
7120 raise error.Abort(
7121 raise error.Abort(
7121 _(b'tag names cannot consist entirely of whitespace')
7122 _(b'tag names cannot consist entirely of whitespace')
7122 )
7123 )
7123 if opts.get(b'rev'):
7124 if opts.get(b'rev'):
7124 rev_ = opts[b'rev']
7125 rev_ = opts[b'rev']
7125 message = opts.get(b'message')
7126 message = opts.get(b'message')
7126 if opts.get(b'remove'):
7127 if opts.get(b'remove'):
7127 if opts.get(b'local'):
7128 if opts.get(b'local'):
7128 expectedtype = b'local'
7129 expectedtype = b'local'
7129 else:
7130 else:
7130 expectedtype = b'global'
7131 expectedtype = b'global'
7131
7132
7132 for n in names:
7133 for n in names:
7133 if repo.tagtype(n) == b'global':
7134 if repo.tagtype(n) == b'global':
7134 alltags = tagsmod.findglobaltags(ui, repo)
7135 alltags = tagsmod.findglobaltags(ui, repo)
7135 if alltags[n][0] == nullid:
7136 if alltags[n][0] == nullid:
7136 raise error.Abort(_(b"tag '%s' is already removed") % n)
7137 raise error.Abort(_(b"tag '%s' is already removed") % n)
7137 if not repo.tagtype(n):
7138 if not repo.tagtype(n):
7138 raise error.Abort(_(b"tag '%s' does not exist") % n)
7139 raise error.Abort(_(b"tag '%s' does not exist") % n)
7139 if repo.tagtype(n) != expectedtype:
7140 if repo.tagtype(n) != expectedtype:
7140 if expectedtype == b'global':
7141 if expectedtype == b'global':
7141 raise error.Abort(
7142 raise error.Abort(
7142 _(b"tag '%s' is not a global tag") % n
7143 _(b"tag '%s' is not a global tag") % n
7143 )
7144 )
7144 else:
7145 else:
7145 raise error.Abort(_(b"tag '%s' is not a local tag") % n)
7146 raise error.Abort(_(b"tag '%s' is not a local tag") % n)
7146 rev_ = b'null'
7147 rev_ = b'null'
7147 if not message:
7148 if not message:
7148 # we don't translate commit messages
7149 # we don't translate commit messages
7149 message = b'Removed tag %s' % b', '.join(names)
7150 message = b'Removed tag %s' % b', '.join(names)
7150 elif not opts.get(b'force'):
7151 elif not opts.get(b'force'):
7151 for n in names:
7152 for n in names:
7152 if n in repo.tags():
7153 if n in repo.tags():
7153 raise error.Abort(
7154 raise error.Abort(
7154 _(b"tag '%s' already exists (use -f to force)") % n
7155 _(b"tag '%s' already exists (use -f to force)") % n
7155 )
7156 )
7156 if not opts.get(b'local'):
7157 if not opts.get(b'local'):
7157 p1, p2 = repo.dirstate.parents()
7158 p1, p2 = repo.dirstate.parents()
7158 if p2 != nullid:
7159 if p2 != nullid:
7159 raise error.Abort(_(b'uncommitted merge'))
7160 raise error.Abort(_(b'uncommitted merge'))
7160 bheads = repo.branchheads()
7161 bheads = repo.branchheads()
7161 if not opts.get(b'force') and bheads and p1 not in bheads:
7162 if not opts.get(b'force') and bheads and p1 not in bheads:
7162 raise error.Abort(
7163 raise error.Abort(
7163 _(
7164 _(
7164 b'working directory is not at a branch head '
7165 b'working directory is not at a branch head '
7165 b'(use -f to force)'
7166 b'(use -f to force)'
7166 )
7167 )
7167 )
7168 )
7168 node = scmutil.revsingle(repo, rev_).node()
7169 node = scmutil.revsingle(repo, rev_).node()
7169
7170
7170 if not message:
7171 if not message:
7171 # we don't translate commit messages
7172 # we don't translate commit messages
7172 message = b'Added tag %s for changeset %s' % (
7173 message = b'Added tag %s for changeset %s' % (
7173 b', '.join(names),
7174 b', '.join(names),
7174 short(node),
7175 short(node),
7175 )
7176 )
7176
7177
7177 date = opts.get(b'date')
7178 date = opts.get(b'date')
7178 if date:
7179 if date:
7179 date = dateutil.parsedate(date)
7180 date = dateutil.parsedate(date)
7180
7181
7181 if opts.get(b'remove'):
7182 if opts.get(b'remove'):
7182 editform = b'tag.remove'
7183 editform = b'tag.remove'
7183 else:
7184 else:
7184 editform = b'tag.add'
7185 editform = b'tag.add'
7185 editor = cmdutil.getcommiteditor(
7186 editor = cmdutil.getcommiteditor(
7186 editform=editform, **pycompat.strkwargs(opts)
7187 editform=editform, **pycompat.strkwargs(opts)
7187 )
7188 )
7188
7189
7189 # don't allow tagging the null rev
7190 # don't allow tagging the null rev
7190 if (
7191 if (
7191 not opts.get(b'remove')
7192 not opts.get(b'remove')
7192 and scmutil.revsingle(repo, rev_).rev() == nullrev
7193 and scmutil.revsingle(repo, rev_).rev() == nullrev
7193 ):
7194 ):
7194 raise error.Abort(_(b"cannot tag null revision"))
7195 raise error.Abort(_(b"cannot tag null revision"))
7195
7196
7196 tagsmod.tag(
7197 tagsmod.tag(
7197 repo,
7198 repo,
7198 names,
7199 names,
7199 node,
7200 node,
7200 message,
7201 message,
7201 opts.get(b'local'),
7202 opts.get(b'local'),
7202 opts.get(b'user'),
7203 opts.get(b'user'),
7203 date,
7204 date,
7204 editor=editor,
7205 editor=editor,
7205 )
7206 )
7206
7207
7207
7208
7208 @command(
7209 @command(
7209 b'tags',
7210 b'tags',
7210 formatteropts,
7211 formatteropts,
7211 b'',
7212 b'',
7212 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7213 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7213 intents={INTENT_READONLY},
7214 intents={INTENT_READONLY},
7214 )
7215 )
7215 def tags(ui, repo, **opts):
7216 def tags(ui, repo, **opts):
7216 """list repository tags
7217 """list repository tags
7217
7218
7218 This lists both regular and local tags. When the -v/--verbose
7219 This lists both regular and local tags. When the -v/--verbose
7219 switch is used, a third column "local" is printed for local tags.
7220 switch is used, a third column "local" is printed for local tags.
7220 When the -q/--quiet switch is used, only the tag name is printed.
7221 When the -q/--quiet switch is used, only the tag name is printed.
7221
7222
7222 .. container:: verbose
7223 .. container:: verbose
7223
7224
7224 Template:
7225 Template:
7225
7226
7226 The following keywords are supported in addition to the common template
7227 The following keywords are supported in addition to the common template
7227 keywords and functions such as ``{tag}``. See also
7228 keywords and functions such as ``{tag}``. See also
7228 :hg:`help templates`.
7229 :hg:`help templates`.
7229
7230
7230 :type: String. ``local`` for local tags.
7231 :type: String. ``local`` for local tags.
7231
7232
7232 Returns 0 on success.
7233 Returns 0 on success.
7233 """
7234 """
7234
7235
7235 opts = pycompat.byteskwargs(opts)
7236 opts = pycompat.byteskwargs(opts)
7236 ui.pager(b'tags')
7237 ui.pager(b'tags')
7237 fm = ui.formatter(b'tags', opts)
7238 fm = ui.formatter(b'tags', opts)
7238 hexfunc = fm.hexfunc
7239 hexfunc = fm.hexfunc
7239
7240
7240 for t, n in reversed(repo.tagslist()):
7241 for t, n in reversed(repo.tagslist()):
7241 hn = hexfunc(n)
7242 hn = hexfunc(n)
7242 label = b'tags.normal'
7243 label = b'tags.normal'
7243 tagtype = b''
7244 tagtype = b''
7244 if repo.tagtype(t) == b'local':
7245 if repo.tagtype(t) == b'local':
7245 label = b'tags.local'
7246 label = b'tags.local'
7246 tagtype = b'local'
7247 tagtype = b'local'
7247
7248
7248 fm.startitem()
7249 fm.startitem()
7249 fm.context(repo=repo)
7250 fm.context(repo=repo)
7250 fm.write(b'tag', b'%s', t, label=label)
7251 fm.write(b'tag', b'%s', t, label=label)
7251 fmt = b" " * (30 - encoding.colwidth(t)) + b' %5d:%s'
7252 fmt = b" " * (30 - encoding.colwidth(t)) + b' %5d:%s'
7252 fm.condwrite(
7253 fm.condwrite(
7253 not ui.quiet,
7254 not ui.quiet,
7254 b'rev node',
7255 b'rev node',
7255 fmt,
7256 fmt,
7256 repo.changelog.rev(n),
7257 repo.changelog.rev(n),
7257 hn,
7258 hn,
7258 label=label,
7259 label=label,
7259 )
7260 )
7260 fm.condwrite(
7261 fm.condwrite(
7261 ui.verbose and tagtype, b'type', b' %s', tagtype, label=label
7262 ui.verbose and tagtype, b'type', b' %s', tagtype, label=label
7262 )
7263 )
7263 fm.plain(b'\n')
7264 fm.plain(b'\n')
7264 fm.end()
7265 fm.end()
7265
7266
7266
7267
7267 @command(
7268 @command(
7268 b'tip',
7269 b'tip',
7269 [
7270 [
7270 (b'p', b'patch', None, _(b'show patch')),
7271 (b'p', b'patch', None, _(b'show patch')),
7271 (b'g', b'git', None, _(b'use git extended diff format')),
7272 (b'g', b'git', None, _(b'use git extended diff format')),
7272 ]
7273 ]
7273 + templateopts,
7274 + templateopts,
7274 _(b'[-p] [-g]'),
7275 _(b'[-p] [-g]'),
7275 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
7276 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
7276 )
7277 )
7277 def tip(ui, repo, **opts):
7278 def tip(ui, repo, **opts):
7278 """show the tip revision (DEPRECATED)
7279 """show the tip revision (DEPRECATED)
7279
7280
7280 The tip revision (usually just called the tip) is the changeset
7281 The tip revision (usually just called the tip) is the changeset
7281 most recently added to the repository (and therefore the most
7282 most recently added to the repository (and therefore the most
7282 recently changed head).
7283 recently changed head).
7283
7284
7284 If you have just made a commit, that commit will be the tip. If
7285 If you have just made a commit, that commit will be the tip. If
7285 you have just pulled changes from another repository, the tip of
7286 you have just pulled changes from another repository, the tip of
7286 that repository becomes the current tip. The "tip" tag is special
7287 that repository becomes the current tip. The "tip" tag is special
7287 and cannot be renamed or assigned to a different changeset.
7288 and cannot be renamed or assigned to a different changeset.
7288
7289
7289 This command is deprecated, please use :hg:`heads` instead.
7290 This command is deprecated, please use :hg:`heads` instead.
7290
7291
7291 Returns 0 on success.
7292 Returns 0 on success.
7292 """
7293 """
7293 opts = pycompat.byteskwargs(opts)
7294 opts = pycompat.byteskwargs(opts)
7294 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
7295 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
7295 displayer.show(repo[b'tip'])
7296 displayer.show(repo[b'tip'])
7296 displayer.close()
7297 displayer.close()
7297
7298
7298
7299
7299 @command(
7300 @command(
7300 b'unbundle',
7301 b'unbundle',
7301 [
7302 [
7302 (
7303 (
7303 b'u',
7304 b'u',
7304 b'update',
7305 b'update',
7305 None,
7306 None,
7306 _(b'update to new branch head if changesets were unbundled'),
7307 _(b'update to new branch head if changesets were unbundled'),
7307 )
7308 )
7308 ],
7309 ],
7309 _(b'[-u] FILE...'),
7310 _(b'[-u] FILE...'),
7310 helpcategory=command.CATEGORY_IMPORT_EXPORT,
7311 helpcategory=command.CATEGORY_IMPORT_EXPORT,
7311 )
7312 )
7312 def unbundle(ui, repo, fname1, *fnames, **opts):
7313 def unbundle(ui, repo, fname1, *fnames, **opts):
7313 """apply one or more bundle files
7314 """apply one or more bundle files
7314
7315
7315 Apply one or more bundle files generated by :hg:`bundle`.
7316 Apply one or more bundle files generated by :hg:`bundle`.
7316
7317
7317 Returns 0 on success, 1 if an update has unresolved files.
7318 Returns 0 on success, 1 if an update has unresolved files.
7318 """
7319 """
7319 fnames = (fname1,) + fnames
7320 fnames = (fname1,) + fnames
7320
7321
7321 with repo.lock():
7322 with repo.lock():
7322 for fname in fnames:
7323 for fname in fnames:
7323 f = hg.openpath(ui, fname)
7324 f = hg.openpath(ui, fname)
7324 gen = exchange.readbundle(ui, f, fname)
7325 gen = exchange.readbundle(ui, f, fname)
7325 if isinstance(gen, streamclone.streamcloneapplier):
7326 if isinstance(gen, streamclone.streamcloneapplier):
7326 raise error.Abort(
7327 raise error.Abort(
7327 _(
7328 _(
7328 b'packed bundles cannot be applied with '
7329 b'packed bundles cannot be applied with '
7329 b'"hg unbundle"'
7330 b'"hg unbundle"'
7330 ),
7331 ),
7331 hint=_(b'use "hg debugapplystreamclonebundle"'),
7332 hint=_(b'use "hg debugapplystreamclonebundle"'),
7332 )
7333 )
7333 url = b'bundle:' + fname
7334 url = b'bundle:' + fname
7334 try:
7335 try:
7335 txnname = b'unbundle'
7336 txnname = b'unbundle'
7336 if not isinstance(gen, bundle2.unbundle20):
7337 if not isinstance(gen, bundle2.unbundle20):
7337 txnname = b'unbundle\n%s' % util.hidepassword(url)
7338 txnname = b'unbundle\n%s' % util.hidepassword(url)
7338 with repo.transaction(txnname) as tr:
7339 with repo.transaction(txnname) as tr:
7339 op = bundle2.applybundle(
7340 op = bundle2.applybundle(
7340 repo, gen, tr, source=b'unbundle', url=url
7341 repo, gen, tr, source=b'unbundle', url=url
7341 )
7342 )
7342 except error.BundleUnknownFeatureError as exc:
7343 except error.BundleUnknownFeatureError as exc:
7343 raise error.Abort(
7344 raise error.Abort(
7344 _(b'%s: unknown bundle feature, %s') % (fname, exc),
7345 _(b'%s: unknown bundle feature, %s') % (fname, exc),
7345 hint=_(
7346 hint=_(
7346 b"see https://mercurial-scm.org/"
7347 b"see https://mercurial-scm.org/"
7347 b"wiki/BundleFeature for more "
7348 b"wiki/BundleFeature for more "
7348 b"information"
7349 b"information"
7349 ),
7350 ),
7350 )
7351 )
7351 modheads = bundle2.combinechangegroupresults(op)
7352 modheads = bundle2.combinechangegroupresults(op)
7352
7353
7353 return postincoming(ui, repo, modheads, opts.get('update'), None, None)
7354 return postincoming(ui, repo, modheads, opts.get('update'), None, None)
7354
7355
7355
7356
7356 @command(
7357 @command(
7357 b'unshelve',
7358 b'unshelve',
7358 [
7359 [
7359 (b'a', b'abort', None, _(b'abort an incomplete unshelve operation')),
7360 (b'a', b'abort', None, _(b'abort an incomplete unshelve operation')),
7360 (
7361 (
7361 b'c',
7362 b'c',
7362 b'continue',
7363 b'continue',
7363 None,
7364 None,
7364 _(b'continue an incomplete unshelve operation'),
7365 _(b'continue an incomplete unshelve operation'),
7365 ),
7366 ),
7366 (b'i', b'interactive', None, _(b'use interactive mode (EXPERIMENTAL)')),
7367 (b'i', b'interactive', None, _(b'use interactive mode (EXPERIMENTAL)')),
7367 (b'k', b'keep', None, _(b'keep shelve after unshelving')),
7368 (b'k', b'keep', None, _(b'keep shelve after unshelving')),
7368 (
7369 (
7369 b'n',
7370 b'n',
7370 b'name',
7371 b'name',
7371 b'',
7372 b'',
7372 _(b'restore shelved change with given name'),
7373 _(b'restore shelved change with given name'),
7373 _(b'NAME'),
7374 _(b'NAME'),
7374 ),
7375 ),
7375 (b't', b'tool', b'', _(b'specify merge tool')),
7376 (b't', b'tool', b'', _(b'specify merge tool')),
7376 (
7377 (
7377 b'',
7378 b'',
7378 b'date',
7379 b'date',
7379 b'',
7380 b'',
7380 _(b'set date for temporary commits (DEPRECATED)'),
7381 _(b'set date for temporary commits (DEPRECATED)'),
7381 _(b'DATE'),
7382 _(b'DATE'),
7382 ),
7383 ),
7383 ],
7384 ],
7384 _(b'hg unshelve [OPTION]... [[-n] SHELVED]'),
7385 _(b'hg unshelve [OPTION]... [[-n] SHELVED]'),
7385 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7386 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7386 )
7387 )
7387 def unshelve(ui, repo, *shelved, **opts):
7388 def unshelve(ui, repo, *shelved, **opts):
7388 """restore a shelved change to the working directory
7389 """restore a shelved change to the working directory
7389
7390
7390 This command accepts an optional name of a shelved change to
7391 This command accepts an optional name of a shelved change to
7391 restore. If none is given, the most recent shelved change is used.
7392 restore. If none is given, the most recent shelved change is used.
7392
7393
7393 If a shelved change is applied successfully, the bundle that
7394 If a shelved change is applied successfully, the bundle that
7394 contains the shelved changes is moved to a backup location
7395 contains the shelved changes is moved to a backup location
7395 (.hg/shelve-backup).
7396 (.hg/shelve-backup).
7396
7397
7397 Since you can restore a shelved change on top of an arbitrary
7398 Since you can restore a shelved change on top of an arbitrary
7398 commit, it is possible that unshelving will result in a conflict
7399 commit, it is possible that unshelving will result in a conflict
7399 between your changes and the commits you are unshelving onto. If
7400 between your changes and the commits you are unshelving onto. If
7400 this occurs, you must resolve the conflict, then use
7401 this occurs, you must resolve the conflict, then use
7401 ``--continue`` to complete the unshelve operation. (The bundle
7402 ``--continue`` to complete the unshelve operation. (The bundle
7402 will not be moved until you successfully complete the unshelve.)
7403 will not be moved until you successfully complete the unshelve.)
7403
7404
7404 (Alternatively, you can use ``--abort`` to abandon an unshelve
7405 (Alternatively, you can use ``--abort`` to abandon an unshelve
7405 that causes a conflict. This reverts the unshelved changes, and
7406 that causes a conflict. This reverts the unshelved changes, and
7406 leaves the bundle in place.)
7407 leaves the bundle in place.)
7407
7408
7408 If bare shelved change (without interactive, include and exclude
7409 If bare shelved change (without interactive, include and exclude
7409 option) was done on newly created branch it would restore branch
7410 option) was done on newly created branch it would restore branch
7410 information to the working directory.
7411 information to the working directory.
7411
7412
7412 After a successful unshelve, the shelved changes are stored in a
7413 After a successful unshelve, the shelved changes are stored in a
7413 backup directory. Only the N most recent backups are kept. N
7414 backup directory. Only the N most recent backups are kept. N
7414 defaults to 10 but can be overridden using the ``shelve.maxbackups``
7415 defaults to 10 but can be overridden using the ``shelve.maxbackups``
7415 configuration option.
7416 configuration option.
7416
7417
7417 .. container:: verbose
7418 .. container:: verbose
7418
7419
7419 Timestamp in seconds is used to decide order of backups. More
7420 Timestamp in seconds is used to decide order of backups. More
7420 than ``maxbackups`` backups are kept, if same timestamp
7421 than ``maxbackups`` backups are kept, if same timestamp
7421 prevents from deciding exact order of them, for safety.
7422 prevents from deciding exact order of them, for safety.
7422
7423
7423 Selected changes can be unshelved with ``--interactive`` flag.
7424 Selected changes can be unshelved with ``--interactive`` flag.
7424 The working directory is updated with the selected changes, and
7425 The working directory is updated with the selected changes, and
7425 only the unselected changes remain shelved.
7426 only the unselected changes remain shelved.
7426 Note: The whole shelve is applied to working directory first before
7427 Note: The whole shelve is applied to working directory first before
7427 running interactively. So, this will bring up all the conflicts between
7428 running interactively. So, this will bring up all the conflicts between
7428 working directory and the shelve, irrespective of which changes will be
7429 working directory and the shelve, irrespective of which changes will be
7429 unshelved.
7430 unshelved.
7430 """
7431 """
7431 with repo.wlock():
7432 with repo.wlock():
7432 return shelvemod.unshelvecmd(ui, repo, *shelved, **opts)
7433 return shelvemod.unshelvecmd(ui, repo, *shelved, **opts)
7433
7434
7434
7435
7435 statemod.addunfinished(
7436 statemod.addunfinished(
7436 b'unshelve',
7437 b'unshelve',
7437 fname=b'shelvedstate',
7438 fname=b'shelvedstate',
7438 continueflag=True,
7439 continueflag=True,
7439 abortfunc=shelvemod.hgabortunshelve,
7440 abortfunc=shelvemod.hgabortunshelve,
7440 continuefunc=shelvemod.hgcontinueunshelve,
7441 continuefunc=shelvemod.hgcontinueunshelve,
7441 cmdmsg=_(b'unshelve already in progress'),
7442 cmdmsg=_(b'unshelve already in progress'),
7442 )
7443 )
7443
7444
7444
7445
7445 @command(
7446 @command(
7446 b'update|up|checkout|co',
7447 b'update|up|checkout|co',
7447 [
7448 [
7448 (b'C', b'clean', None, _(b'discard uncommitted changes (no backup)')),
7449 (b'C', b'clean', None, _(b'discard uncommitted changes (no backup)')),
7449 (b'c', b'check', None, _(b'require clean working directory')),
7450 (b'c', b'check', None, _(b'require clean working directory')),
7450 (b'm', b'merge', None, _(b'merge uncommitted changes')),
7451 (b'm', b'merge', None, _(b'merge uncommitted changes')),
7451 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
7452 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
7452 (b'r', b'rev', b'', _(b'revision'), _(b'REV')),
7453 (b'r', b'rev', b'', _(b'revision'), _(b'REV')),
7453 ]
7454 ]
7454 + mergetoolopts,
7455 + mergetoolopts,
7455 _(b'[-C|-c|-m] [-d DATE] [[-r] REV]'),
7456 _(b'[-C|-c|-m] [-d DATE] [[-r] REV]'),
7456 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7457 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7457 helpbasic=True,
7458 helpbasic=True,
7458 )
7459 )
7459 def update(ui, repo, node=None, **opts):
7460 def update(ui, repo, node=None, **opts):
7460 """update working directory (or switch revisions)
7461 """update working directory (or switch revisions)
7461
7462
7462 Update the repository's working directory to the specified
7463 Update the repository's working directory to the specified
7463 changeset. If no changeset is specified, update to the tip of the
7464 changeset. If no changeset is specified, update to the tip of the
7464 current named branch and move the active bookmark (see :hg:`help
7465 current named branch and move the active bookmark (see :hg:`help
7465 bookmarks`).
7466 bookmarks`).
7466
7467
7467 Update sets the working directory's parent revision to the specified
7468 Update sets the working directory's parent revision to the specified
7468 changeset (see :hg:`help parents`).
7469 changeset (see :hg:`help parents`).
7469
7470
7470 If the changeset is not a descendant or ancestor of the working
7471 If the changeset is not a descendant or ancestor of the working
7471 directory's parent and there are uncommitted changes, the update is
7472 directory's parent and there are uncommitted changes, the update is
7472 aborted. With the -c/--check option, the working directory is checked
7473 aborted. With the -c/--check option, the working directory is checked
7473 for uncommitted changes; if none are found, the working directory is
7474 for uncommitted changes; if none are found, the working directory is
7474 updated to the specified changeset.
7475 updated to the specified changeset.
7475
7476
7476 .. container:: verbose
7477 .. container:: verbose
7477
7478
7478 The -C/--clean, -c/--check, and -m/--merge options control what
7479 The -C/--clean, -c/--check, and -m/--merge options control what
7479 happens if the working directory contains uncommitted changes.
7480 happens if the working directory contains uncommitted changes.
7480 At most of one of them can be specified.
7481 At most of one of them can be specified.
7481
7482
7482 1. If no option is specified, and if
7483 1. If no option is specified, and if
7483 the requested changeset is an ancestor or descendant of
7484 the requested changeset is an ancestor or descendant of
7484 the working directory's parent, the uncommitted changes
7485 the working directory's parent, the uncommitted changes
7485 are merged into the requested changeset and the merged
7486 are merged into the requested changeset and the merged
7486 result is left uncommitted. If the requested changeset is
7487 result is left uncommitted. If the requested changeset is
7487 not an ancestor or descendant (that is, it is on another
7488 not an ancestor or descendant (that is, it is on another
7488 branch), the update is aborted and the uncommitted changes
7489 branch), the update is aborted and the uncommitted changes
7489 are preserved.
7490 are preserved.
7490
7491
7491 2. With the -m/--merge option, the update is allowed even if the
7492 2. With the -m/--merge option, the update is allowed even if the
7492 requested changeset is not an ancestor or descendant of
7493 requested changeset is not an ancestor or descendant of
7493 the working directory's parent.
7494 the working directory's parent.
7494
7495
7495 3. With the -c/--check option, the update is aborted and the
7496 3. With the -c/--check option, the update is aborted and the
7496 uncommitted changes are preserved.
7497 uncommitted changes are preserved.
7497
7498
7498 4. With the -C/--clean option, uncommitted changes are discarded and
7499 4. With the -C/--clean option, uncommitted changes are discarded and
7499 the working directory is updated to the requested changeset.
7500 the working directory is updated to the requested changeset.
7500
7501
7501 To cancel an uncommitted merge (and lose your changes), use
7502 To cancel an uncommitted merge (and lose your changes), use
7502 :hg:`merge --abort`.
7503 :hg:`merge --abort`.
7503
7504
7504 Use null as the changeset to remove the working directory (like
7505 Use null as the changeset to remove the working directory (like
7505 :hg:`clone -U`).
7506 :hg:`clone -U`).
7506
7507
7507 If you want to revert just one file to an older revision, use
7508 If you want to revert just one file to an older revision, use
7508 :hg:`revert [-r REV] NAME`.
7509 :hg:`revert [-r REV] NAME`.
7509
7510
7510 See :hg:`help dates` for a list of formats valid for -d/--date.
7511 See :hg:`help dates` for a list of formats valid for -d/--date.
7511
7512
7512 Returns 0 on success, 1 if there are unresolved files.
7513 Returns 0 on success, 1 if there are unresolved files.
7513 """
7514 """
7514 cmdutil.check_at_most_one_arg(opts, 'clean', 'check', 'merge')
7515 cmdutil.check_at_most_one_arg(opts, 'clean', 'check', 'merge')
7515 rev = opts.get('rev')
7516 rev = opts.get('rev')
7516 date = opts.get('date')
7517 date = opts.get('date')
7517 clean = opts.get('clean')
7518 clean = opts.get('clean')
7518 check = opts.get('check')
7519 check = opts.get('check')
7519 merge = opts.get('merge')
7520 merge = opts.get('merge')
7520 if rev and node:
7521 if rev and node:
7521 raise error.Abort(_(b"please specify just one revision"))
7522 raise error.Abort(_(b"please specify just one revision"))
7522
7523
7523 if ui.configbool(b'commands', b'update.requiredest'):
7524 if ui.configbool(b'commands', b'update.requiredest'):
7524 if not node and not rev and not date:
7525 if not node and not rev and not date:
7525 raise error.Abort(
7526 raise error.Abort(
7526 _(b'you must specify a destination'),
7527 _(b'you must specify a destination'),
7527 hint=_(b'for example: hg update ".::"'),
7528 hint=_(b'for example: hg update ".::"'),
7528 )
7529 )
7529
7530
7530 if rev is None or rev == b'':
7531 if rev is None or rev == b'':
7531 rev = node
7532 rev = node
7532
7533
7533 if date and rev is not None:
7534 if date and rev is not None:
7534 raise error.Abort(_(b"you can't specify a revision and a date"))
7535 raise error.Abort(_(b"you can't specify a revision and a date"))
7535
7536
7536 updatecheck = None
7537 updatecheck = None
7537 if check:
7538 if check:
7538 updatecheck = b'abort'
7539 updatecheck = b'abort'
7539 elif merge:
7540 elif merge:
7540 updatecheck = b'none'
7541 updatecheck = b'none'
7541
7542
7542 with repo.wlock():
7543 with repo.wlock():
7543 cmdutil.clearunfinished(repo)
7544 cmdutil.clearunfinished(repo)
7544 if date:
7545 if date:
7545 rev = cmdutil.finddate(ui, repo, date)
7546 rev = cmdutil.finddate(ui, repo, date)
7546
7547
7547 # if we defined a bookmark, we have to remember the original name
7548 # if we defined a bookmark, we have to remember the original name
7548 brev = rev
7549 brev = rev
7549 if rev:
7550 if rev:
7550 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
7551 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
7551 ctx = scmutil.revsingle(repo, rev, default=None)
7552 ctx = scmutil.revsingle(repo, rev, default=None)
7552 rev = ctx.rev()
7553 rev = ctx.rev()
7553 hidden = ctx.hidden()
7554 hidden = ctx.hidden()
7554 overrides = {(b'ui', b'forcemerge'): opts.get('tool', b'')}
7555 overrides = {(b'ui', b'forcemerge'): opts.get('tool', b'')}
7555 with ui.configoverride(overrides, b'update'):
7556 with ui.configoverride(overrides, b'update'):
7556 ret = hg.updatetotally(
7557 ret = hg.updatetotally(
7557 ui, repo, rev, brev, clean=clean, updatecheck=updatecheck
7558 ui, repo, rev, brev, clean=clean, updatecheck=updatecheck
7558 )
7559 )
7559 if hidden:
7560 if hidden:
7560 ctxstr = ctx.hex()[:12]
7561 ctxstr = ctx.hex()[:12]
7561 ui.warn(_(b"updated to hidden changeset %s\n") % ctxstr)
7562 ui.warn(_(b"updated to hidden changeset %s\n") % ctxstr)
7562
7563
7563 if ctx.obsolete():
7564 if ctx.obsolete():
7564 obsfatemsg = obsutil._getfilteredreason(repo, ctxstr, ctx)
7565 obsfatemsg = obsutil._getfilteredreason(repo, ctxstr, ctx)
7565 ui.warn(b"(%s)\n" % obsfatemsg)
7566 ui.warn(b"(%s)\n" % obsfatemsg)
7566 return ret
7567 return ret
7567
7568
7568
7569
7569 @command(
7570 @command(
7570 b'verify',
7571 b'verify',
7571 [(b'', b'full', False, b'perform more checks (EXPERIMENTAL)')],
7572 [(b'', b'full', False, b'perform more checks (EXPERIMENTAL)')],
7572 helpcategory=command.CATEGORY_MAINTENANCE,
7573 helpcategory=command.CATEGORY_MAINTENANCE,
7573 )
7574 )
7574 def verify(ui, repo, **opts):
7575 def verify(ui, repo, **opts):
7575 """verify the integrity of the repository
7576 """verify the integrity of the repository
7576
7577
7577 Verify the integrity of the current repository.
7578 Verify the integrity of the current repository.
7578
7579
7579 This will perform an extensive check of the repository's
7580 This will perform an extensive check of the repository's
7580 integrity, validating the hashes and checksums of each entry in
7581 integrity, validating the hashes and checksums of each entry in
7581 the changelog, manifest, and tracked files, as well as the
7582 the changelog, manifest, and tracked files, as well as the
7582 integrity of their crosslinks and indices.
7583 integrity of their crosslinks and indices.
7583
7584
7584 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
7585 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
7585 for more information about recovery from corruption of the
7586 for more information about recovery from corruption of the
7586 repository.
7587 repository.
7587
7588
7588 Returns 0 on success, 1 if errors are encountered.
7589 Returns 0 on success, 1 if errors are encountered.
7589 """
7590 """
7590 opts = pycompat.byteskwargs(opts)
7591 opts = pycompat.byteskwargs(opts)
7591
7592
7592 level = None
7593 level = None
7593 if opts[b'full']:
7594 if opts[b'full']:
7594 level = verifymod.VERIFY_FULL
7595 level = verifymod.VERIFY_FULL
7595 return hg.verify(repo, level)
7596 return hg.verify(repo, level)
7596
7597
7597
7598
7598 @command(
7599 @command(
7599 b'version',
7600 b'version',
7600 [] + formatteropts,
7601 [] + formatteropts,
7601 helpcategory=command.CATEGORY_HELP,
7602 helpcategory=command.CATEGORY_HELP,
7602 norepo=True,
7603 norepo=True,
7603 intents={INTENT_READONLY},
7604 intents={INTENT_READONLY},
7604 )
7605 )
7605 def version_(ui, **opts):
7606 def version_(ui, **opts):
7606 """output version and copyright information
7607 """output version and copyright information
7607
7608
7608 .. container:: verbose
7609 .. container:: verbose
7609
7610
7610 Template:
7611 Template:
7611
7612
7612 The following keywords are supported. See also :hg:`help templates`.
7613 The following keywords are supported. See also :hg:`help templates`.
7613
7614
7614 :extensions: List of extensions.
7615 :extensions: List of extensions.
7615 :ver: String. Version number.
7616 :ver: String. Version number.
7616
7617
7617 And each entry of ``{extensions}`` provides the following sub-keywords
7618 And each entry of ``{extensions}`` provides the following sub-keywords
7618 in addition to ``{ver}``.
7619 in addition to ``{ver}``.
7619
7620
7620 :bundled: Boolean. True if included in the release.
7621 :bundled: Boolean. True if included in the release.
7621 :name: String. Extension name.
7622 :name: String. Extension name.
7622 """
7623 """
7623 opts = pycompat.byteskwargs(opts)
7624 opts = pycompat.byteskwargs(opts)
7624 if ui.verbose:
7625 if ui.verbose:
7625 ui.pager(b'version')
7626 ui.pager(b'version')
7626 fm = ui.formatter(b"version", opts)
7627 fm = ui.formatter(b"version", opts)
7627 fm.startitem()
7628 fm.startitem()
7628 fm.write(
7629 fm.write(
7629 b"ver", _(b"Mercurial Distributed SCM (version %s)\n"), util.version()
7630 b"ver", _(b"Mercurial Distributed SCM (version %s)\n"), util.version()
7630 )
7631 )
7631 license = _(
7632 license = _(
7632 b"(see https://mercurial-scm.org for more information)\n"
7633 b"(see https://mercurial-scm.org for more information)\n"
7633 b"\nCopyright (C) 2005-2020 Matt Mackall and others\n"
7634 b"\nCopyright (C) 2005-2020 Matt Mackall and others\n"
7634 b"This is free software; see the source for copying conditions. "
7635 b"This is free software; see the source for copying conditions. "
7635 b"There is NO\nwarranty; "
7636 b"There is NO\nwarranty; "
7636 b"not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
7637 b"not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
7637 )
7638 )
7638 if not ui.quiet:
7639 if not ui.quiet:
7639 fm.plain(license)
7640 fm.plain(license)
7640
7641
7641 if ui.verbose:
7642 if ui.verbose:
7642 fm.plain(_(b"\nEnabled extensions:\n\n"))
7643 fm.plain(_(b"\nEnabled extensions:\n\n"))
7643 # format names and versions into columns
7644 # format names and versions into columns
7644 names = []
7645 names = []
7645 vers = []
7646 vers = []
7646 isinternals = []
7647 isinternals = []
7647 for name, module in sorted(extensions.extensions()):
7648 for name, module in sorted(extensions.extensions()):
7648 names.append(name)
7649 names.append(name)
7649 vers.append(extensions.moduleversion(module) or None)
7650 vers.append(extensions.moduleversion(module) or None)
7650 isinternals.append(extensions.ismoduleinternal(module))
7651 isinternals.append(extensions.ismoduleinternal(module))
7651 fn = fm.nested(b"extensions", tmpl=b'{name}\n')
7652 fn = fm.nested(b"extensions", tmpl=b'{name}\n')
7652 if names:
7653 if names:
7653 namefmt = b" %%-%ds " % max(len(n) for n in names)
7654 namefmt = b" %%-%ds " % max(len(n) for n in names)
7654 places = [_(b"external"), _(b"internal")]
7655 places = [_(b"external"), _(b"internal")]
7655 for n, v, p in zip(names, vers, isinternals):
7656 for n, v, p in zip(names, vers, isinternals):
7656 fn.startitem()
7657 fn.startitem()
7657 fn.condwrite(ui.verbose, b"name", namefmt, n)
7658 fn.condwrite(ui.verbose, b"name", namefmt, n)
7658 if ui.verbose:
7659 if ui.verbose:
7659 fn.plain(b"%s " % places[p])
7660 fn.plain(b"%s " % places[p])
7660 fn.data(bundled=p)
7661 fn.data(bundled=p)
7661 fn.condwrite(ui.verbose and v, b"ver", b"%s", v)
7662 fn.condwrite(ui.verbose and v, b"ver", b"%s", v)
7662 if ui.verbose:
7663 if ui.verbose:
7663 fn.plain(b"\n")
7664 fn.plain(b"\n")
7664 fn.end()
7665 fn.end()
7665 fm.end()
7666 fm.end()
7666
7667
7667
7668
7668 def loadcmdtable(ui, name, cmdtable):
7669 def loadcmdtable(ui, name, cmdtable):
7669 """Load command functions from specified cmdtable
7670 """Load command functions from specified cmdtable
7670 """
7671 """
7671 overrides = [cmd for cmd in cmdtable if cmd in table]
7672 overrides = [cmd for cmd in cmdtable if cmd in table]
7672 if overrides:
7673 if overrides:
7673 ui.warn(
7674 ui.warn(
7674 _(b"extension '%s' overrides commands: %s\n")
7675 _(b"extension '%s' overrides commands: %s\n")
7675 % (name, b" ".join(overrides))
7676 % (name, b" ".join(overrides))
7676 )
7677 )
7677 table.update(cmdtable)
7678 table.update(cmdtable)
@@ -1,4578 +1,4579 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 codecs
10 import codecs
11 import collections
11 import collections
12 import difflib
12 import difflib
13 import errno
13 import errno
14 import glob
14 import glob
15 import operator
15 import operator
16 import os
16 import os
17 import platform
17 import platform
18 import random
18 import random
19 import re
19 import re
20 import socket
20 import socket
21 import ssl
21 import ssl
22 import stat
22 import stat
23 import string
23 import string
24 import subprocess
24 import subprocess
25 import sys
25 import sys
26 import time
26 import time
27
27
28 from .i18n import _
28 from .i18n import _
29 from .node import (
29 from .node import (
30 bin,
30 bin,
31 hex,
31 hex,
32 nullid,
32 nullid,
33 nullrev,
33 nullrev,
34 short,
34 short,
35 )
35 )
36 from .pycompat import (
36 from .pycompat import (
37 getattr,
37 getattr,
38 open,
38 open,
39 )
39 )
40 from . import (
40 from . import (
41 bundle2,
41 bundle2,
42 bundlerepo,
42 bundlerepo,
43 changegroup,
43 changegroup,
44 cmdutil,
44 cmdutil,
45 color,
45 color,
46 context,
46 context,
47 copies,
47 copies,
48 dagparser,
48 dagparser,
49 encoding,
49 encoding,
50 error,
50 error,
51 exchange,
51 exchange,
52 extensions,
52 extensions,
53 filemerge,
53 filemerge,
54 filesetlang,
54 filesetlang,
55 formatter,
55 formatter,
56 hg,
56 hg,
57 httppeer,
57 httppeer,
58 localrepo,
58 localrepo,
59 lock as lockmod,
59 lock as lockmod,
60 logcmdutil,
60 logcmdutil,
61 mergestate as mergestatemod,
61 mergestate as mergestatemod,
62 metadata,
62 metadata,
63 obsolete,
63 obsolete,
64 obsutil,
64 obsutil,
65 pathutil,
65 pathutil,
66 phases,
66 phases,
67 policy,
67 policy,
68 pvec,
68 pvec,
69 pycompat,
69 pycompat,
70 registrar,
70 registrar,
71 repair,
71 repair,
72 revlog,
72 revlog,
73 revset,
73 revset,
74 revsetlang,
74 revsetlang,
75 scmutil,
75 scmutil,
76 setdiscovery,
76 setdiscovery,
77 simplemerge,
77 simplemerge,
78 sshpeer,
78 sshpeer,
79 sslutil,
79 sslutil,
80 streamclone,
80 streamclone,
81 tags as tagsmod,
81 tags as tagsmod,
82 templater,
82 templater,
83 treediscovery,
83 treediscovery,
84 upgrade,
84 upgrade,
85 url as urlmod,
85 url as urlmod,
86 util,
86 util,
87 vfs as vfsmod,
87 vfs as vfsmod,
88 wireprotoframing,
88 wireprotoframing,
89 wireprotoserver,
89 wireprotoserver,
90 wireprotov2peer,
90 wireprotov2peer,
91 )
91 )
92 from .utils import (
92 from .utils import (
93 cborutil,
93 cborutil,
94 compression,
94 compression,
95 dateutil,
95 dateutil,
96 procutil,
96 procutil,
97 stringutil,
97 stringutil,
98 )
98 )
99
99
100 from .revlogutils import (
100 from .revlogutils import (
101 deltas as deltautil,
101 deltas as deltautil,
102 nodemap,
102 nodemap,
103 sidedata,
103 sidedata,
104 )
104 )
105
105
106 release = lockmod.release
106 release = lockmod.release
107
107
108 command = registrar.command()
108 command = registrar.command()
109
109
110
110
111 @command(b'debugancestor', [], _(b'[INDEX] REV1 REV2'), optionalrepo=True)
111 @command(b'debugancestor', [], _(b'[INDEX] REV1 REV2'), optionalrepo=True)
112 def debugancestor(ui, repo, *args):
112 def debugancestor(ui, repo, *args):
113 """find the ancestor revision of two revisions in a given index"""
113 """find the ancestor revision of two revisions in a given index"""
114 if len(args) == 3:
114 if len(args) == 3:
115 index, rev1, rev2 = args
115 index, rev1, rev2 = args
116 r = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False), index)
116 r = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False), index)
117 lookup = r.lookup
117 lookup = r.lookup
118 elif len(args) == 2:
118 elif len(args) == 2:
119 if not repo:
119 if not repo:
120 raise error.Abort(
120 raise error.Abort(
121 _(b'there is no Mercurial repository here (.hg not found)')
121 _(b'there is no Mercurial repository here (.hg not found)')
122 )
122 )
123 rev1, rev2 = args
123 rev1, rev2 = args
124 r = repo.changelog
124 r = repo.changelog
125 lookup = repo.lookup
125 lookup = repo.lookup
126 else:
126 else:
127 raise error.Abort(_(b'either two or three arguments required'))
127 raise error.Abort(_(b'either two or three arguments required'))
128 a = r.ancestor(lookup(rev1), lookup(rev2))
128 a = r.ancestor(lookup(rev1), lookup(rev2))
129 ui.write(b'%d:%s\n' % (r.rev(a), hex(a)))
129 ui.write(b'%d:%s\n' % (r.rev(a), hex(a)))
130
130
131
131
132 @command(b'debugantivirusrunning', [])
132 @command(b'debugantivirusrunning', [])
133 def debugantivirusrunning(ui, repo):
133 def debugantivirusrunning(ui, repo):
134 """attempt to trigger an antivirus scanner to see if one is active"""
134 """attempt to trigger an antivirus scanner to see if one is active"""
135 with repo.cachevfs.open('eicar-test-file.com', b'wb') as f:
135 with repo.cachevfs.open('eicar-test-file.com', b'wb') as f:
136 f.write(
136 f.write(
137 util.b85decode(
137 util.b85decode(
138 # This is a base85-armored version of the EICAR test file. See
138 # This is a base85-armored version of the EICAR test file. See
139 # https://en.wikipedia.org/wiki/EICAR_test_file for details.
139 # https://en.wikipedia.org/wiki/EICAR_test_file for details.
140 b'ST#=}P$fV?P+K%yP+C|uG$>GBDK|qyDK~v2MM*<JQY}+dK~6+LQba95P'
140 b'ST#=}P$fV?P+K%yP+C|uG$>GBDK|qyDK~v2MM*<JQY}+dK~6+LQba95P'
141 b'E<)&Nm5l)EmTEQR4qnHOhq9iNGnJx'
141 b'E<)&Nm5l)EmTEQR4qnHOhq9iNGnJx'
142 )
142 )
143 )
143 )
144 # Give an AV engine time to scan the file.
144 # Give an AV engine time to scan the file.
145 time.sleep(2)
145 time.sleep(2)
146 util.unlink(repo.cachevfs.join('eicar-test-file.com'))
146 util.unlink(repo.cachevfs.join('eicar-test-file.com'))
147
147
148
148
149 @command(b'debugapplystreamclonebundle', [], b'FILE')
149 @command(b'debugapplystreamclonebundle', [], b'FILE')
150 def debugapplystreamclonebundle(ui, repo, fname):
150 def debugapplystreamclonebundle(ui, repo, fname):
151 """apply a stream clone bundle file"""
151 """apply a stream clone bundle file"""
152 f = hg.openpath(ui, fname)
152 f = hg.openpath(ui, fname)
153 gen = exchange.readbundle(ui, f, fname)
153 gen = exchange.readbundle(ui, f, fname)
154 gen.apply(repo)
154 gen.apply(repo)
155
155
156
156
157 @command(
157 @command(
158 b'debugbuilddag',
158 b'debugbuilddag',
159 [
159 [
160 (
160 (
161 b'm',
161 b'm',
162 b'mergeable-file',
162 b'mergeable-file',
163 None,
163 None,
164 _(b'add single file mergeable changes'),
164 _(b'add single file mergeable changes'),
165 ),
165 ),
166 (
166 (
167 b'o',
167 b'o',
168 b'overwritten-file',
168 b'overwritten-file',
169 None,
169 None,
170 _(b'add single file all revs overwrite'),
170 _(b'add single file all revs overwrite'),
171 ),
171 ),
172 (b'n', b'new-file', None, _(b'add new file at each rev')),
172 (b'n', b'new-file', None, _(b'add new file at each rev')),
173 ],
173 ],
174 _(b'[OPTION]... [TEXT]'),
174 _(b'[OPTION]... [TEXT]'),
175 )
175 )
176 def debugbuilddag(
176 def debugbuilddag(
177 ui,
177 ui,
178 repo,
178 repo,
179 text=None,
179 text=None,
180 mergeable_file=False,
180 mergeable_file=False,
181 overwritten_file=False,
181 overwritten_file=False,
182 new_file=False,
182 new_file=False,
183 ):
183 ):
184 """builds a repo with a given DAG from scratch in the current empty repo
184 """builds a repo with a given DAG from scratch in the current empty repo
185
185
186 The description of the DAG is read from stdin if not given on the
186 The description of the DAG is read from stdin if not given on the
187 command line.
187 command line.
188
188
189 Elements:
189 Elements:
190
190
191 - "+n" is a linear run of n nodes based on the current default parent
191 - "+n" is a linear run of n nodes based on the current default parent
192 - "." is a single node based on the current default parent
192 - "." is a single node based on the current default parent
193 - "$" resets the default parent to null (implied at the start);
193 - "$" resets the default parent to null (implied at the start);
194 otherwise the default parent is always the last node created
194 otherwise the default parent is always the last node created
195 - "<p" sets the default parent to the backref p
195 - "<p" sets the default parent to the backref p
196 - "*p" is a fork at parent p, which is a backref
196 - "*p" is a fork at parent p, which is a backref
197 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
197 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
198 - "/p2" is a merge of the preceding node and p2
198 - "/p2" is a merge of the preceding node and p2
199 - ":tag" defines a local tag for the preceding node
199 - ":tag" defines a local tag for the preceding node
200 - "@branch" sets the named branch for subsequent nodes
200 - "@branch" sets the named branch for subsequent nodes
201 - "#...\\n" is a comment up to the end of the line
201 - "#...\\n" is a comment up to the end of the line
202
202
203 Whitespace between the above elements is ignored.
203 Whitespace between the above elements is ignored.
204
204
205 A backref is either
205 A backref is either
206
206
207 - a number n, which references the node curr-n, where curr is the current
207 - a number n, which references the node curr-n, where curr is the current
208 node, or
208 node, or
209 - the name of a local tag you placed earlier using ":tag", or
209 - the name of a local tag you placed earlier using ":tag", or
210 - empty to denote the default parent.
210 - empty to denote the default parent.
211
211
212 All string valued-elements are either strictly alphanumeric, or must
212 All string valued-elements are either strictly alphanumeric, or must
213 be enclosed in double quotes ("..."), with "\\" as escape character.
213 be enclosed in double quotes ("..."), with "\\" as escape character.
214 """
214 """
215
215
216 if text is None:
216 if text is None:
217 ui.status(_(b"reading DAG from stdin\n"))
217 ui.status(_(b"reading DAG from stdin\n"))
218 text = ui.fin.read()
218 text = ui.fin.read()
219
219
220 cl = repo.changelog
220 cl = repo.changelog
221 if len(cl) > 0:
221 if len(cl) > 0:
222 raise error.Abort(_(b'repository is not empty'))
222 raise error.Abort(_(b'repository is not empty'))
223
223
224 # determine number of revs in DAG
224 # determine number of revs in DAG
225 total = 0
225 total = 0
226 for type, data in dagparser.parsedag(text):
226 for type, data in dagparser.parsedag(text):
227 if type == b'n':
227 if type == b'n':
228 total += 1
228 total += 1
229
229
230 if mergeable_file:
230 if mergeable_file:
231 linesperrev = 2
231 linesperrev = 2
232 # make a file with k lines per rev
232 # make a file with k lines per rev
233 initialmergedlines = [
233 initialmergedlines = [
234 b'%d' % i for i in pycompat.xrange(0, total * linesperrev)
234 b'%d' % i for i in pycompat.xrange(0, total * linesperrev)
235 ]
235 ]
236 initialmergedlines.append(b"")
236 initialmergedlines.append(b"")
237
237
238 tags = []
238 tags = []
239 progress = ui.makeprogress(
239 progress = ui.makeprogress(
240 _(b'building'), unit=_(b'revisions'), total=total
240 _(b'building'), unit=_(b'revisions'), total=total
241 )
241 )
242 with progress, repo.wlock(), repo.lock(), repo.transaction(b"builddag"):
242 with progress, repo.wlock(), repo.lock(), repo.transaction(b"builddag"):
243 at = -1
243 at = -1
244 atbranch = b'default'
244 atbranch = b'default'
245 nodeids = []
245 nodeids = []
246 id = 0
246 id = 0
247 progress.update(id)
247 progress.update(id)
248 for type, data in dagparser.parsedag(text):
248 for type, data in dagparser.parsedag(text):
249 if type == b'n':
249 if type == b'n':
250 ui.note((b'node %s\n' % pycompat.bytestr(data)))
250 ui.note((b'node %s\n' % pycompat.bytestr(data)))
251 id, ps = data
251 id, ps = data
252
252
253 files = []
253 files = []
254 filecontent = {}
254 filecontent = {}
255
255
256 p2 = None
256 p2 = None
257 if mergeable_file:
257 if mergeable_file:
258 fn = b"mf"
258 fn = b"mf"
259 p1 = repo[ps[0]]
259 p1 = repo[ps[0]]
260 if len(ps) > 1:
260 if len(ps) > 1:
261 p2 = repo[ps[1]]
261 p2 = repo[ps[1]]
262 pa = p1.ancestor(p2)
262 pa = p1.ancestor(p2)
263 base, local, other = [
263 base, local, other = [
264 x[fn].data() for x in (pa, p1, p2)
264 x[fn].data() for x in (pa, p1, p2)
265 ]
265 ]
266 m3 = simplemerge.Merge3Text(base, local, other)
266 m3 = simplemerge.Merge3Text(base, local, other)
267 ml = [l.strip() for l in m3.merge_lines()]
267 ml = [l.strip() for l in m3.merge_lines()]
268 ml.append(b"")
268 ml.append(b"")
269 elif at > 0:
269 elif at > 0:
270 ml = p1[fn].data().split(b"\n")
270 ml = p1[fn].data().split(b"\n")
271 else:
271 else:
272 ml = initialmergedlines
272 ml = initialmergedlines
273 ml[id * linesperrev] += b" r%i" % id
273 ml[id * linesperrev] += b" r%i" % id
274 mergedtext = b"\n".join(ml)
274 mergedtext = b"\n".join(ml)
275 files.append(fn)
275 files.append(fn)
276 filecontent[fn] = mergedtext
276 filecontent[fn] = mergedtext
277
277
278 if overwritten_file:
278 if overwritten_file:
279 fn = b"of"
279 fn = b"of"
280 files.append(fn)
280 files.append(fn)
281 filecontent[fn] = b"r%i\n" % id
281 filecontent[fn] = b"r%i\n" % id
282
282
283 if new_file:
283 if new_file:
284 fn = b"nf%i" % id
284 fn = b"nf%i" % id
285 files.append(fn)
285 files.append(fn)
286 filecontent[fn] = b"r%i\n" % id
286 filecontent[fn] = b"r%i\n" % id
287 if len(ps) > 1:
287 if len(ps) > 1:
288 if not p2:
288 if not p2:
289 p2 = repo[ps[1]]
289 p2 = repo[ps[1]]
290 for fn in p2:
290 for fn in p2:
291 if fn.startswith(b"nf"):
291 if fn.startswith(b"nf"):
292 files.append(fn)
292 files.append(fn)
293 filecontent[fn] = p2[fn].data()
293 filecontent[fn] = p2[fn].data()
294
294
295 def fctxfn(repo, cx, path):
295 def fctxfn(repo, cx, path):
296 if path in filecontent:
296 if path in filecontent:
297 return context.memfilectx(
297 return context.memfilectx(
298 repo, cx, path, filecontent[path]
298 repo, cx, path, filecontent[path]
299 )
299 )
300 return None
300 return None
301
301
302 if len(ps) == 0 or ps[0] < 0:
302 if len(ps) == 0 or ps[0] < 0:
303 pars = [None, None]
303 pars = [None, None]
304 elif len(ps) == 1:
304 elif len(ps) == 1:
305 pars = [nodeids[ps[0]], None]
305 pars = [nodeids[ps[0]], None]
306 else:
306 else:
307 pars = [nodeids[p] for p in ps]
307 pars = [nodeids[p] for p in ps]
308 cx = context.memctx(
308 cx = context.memctx(
309 repo,
309 repo,
310 pars,
310 pars,
311 b"r%i" % id,
311 b"r%i" % id,
312 files,
312 files,
313 fctxfn,
313 fctxfn,
314 date=(id, 0),
314 date=(id, 0),
315 user=b"debugbuilddag",
315 user=b"debugbuilddag",
316 extra={b'branch': atbranch},
316 extra={b'branch': atbranch},
317 )
317 )
318 nodeid = repo.commitctx(cx)
318 nodeid = repo.commitctx(cx)
319 nodeids.append(nodeid)
319 nodeids.append(nodeid)
320 at = id
320 at = id
321 elif type == b'l':
321 elif type == b'l':
322 id, name = data
322 id, name = data
323 ui.note((b'tag %s\n' % name))
323 ui.note((b'tag %s\n' % name))
324 tags.append(b"%s %s\n" % (hex(repo.changelog.node(id)), name))
324 tags.append(b"%s %s\n" % (hex(repo.changelog.node(id)), name))
325 elif type == b'a':
325 elif type == b'a':
326 ui.note((b'branch %s\n' % data))
326 ui.note((b'branch %s\n' % data))
327 atbranch = data
327 atbranch = data
328 progress.update(id)
328 progress.update(id)
329
329
330 if tags:
330 if tags:
331 repo.vfs.write(b"localtags", b"".join(tags))
331 repo.vfs.write(b"localtags", b"".join(tags))
332
332
333
333
334 def _debugchangegroup(ui, gen, all=None, indent=0, **opts):
334 def _debugchangegroup(ui, gen, all=None, indent=0, **opts):
335 indent_string = b' ' * indent
335 indent_string = b' ' * indent
336 if all:
336 if all:
337 ui.writenoi18n(
337 ui.writenoi18n(
338 b"%sformat: id, p1, p2, cset, delta base, len(delta)\n"
338 b"%sformat: id, p1, p2, cset, delta base, len(delta)\n"
339 % indent_string
339 % indent_string
340 )
340 )
341
341
342 def showchunks(named):
342 def showchunks(named):
343 ui.write(b"\n%s%s\n" % (indent_string, named))
343 ui.write(b"\n%s%s\n" % (indent_string, named))
344 for deltadata in gen.deltaiter():
344 for deltadata in gen.deltaiter():
345 node, p1, p2, cs, deltabase, delta, flags = deltadata
345 node, p1, p2, cs, deltabase, delta, flags = deltadata
346 ui.write(
346 ui.write(
347 b"%s%s %s %s %s %s %d\n"
347 b"%s%s %s %s %s %s %d\n"
348 % (
348 % (
349 indent_string,
349 indent_string,
350 hex(node),
350 hex(node),
351 hex(p1),
351 hex(p1),
352 hex(p2),
352 hex(p2),
353 hex(cs),
353 hex(cs),
354 hex(deltabase),
354 hex(deltabase),
355 len(delta),
355 len(delta),
356 )
356 )
357 )
357 )
358
358
359 gen.changelogheader()
359 gen.changelogheader()
360 showchunks(b"changelog")
360 showchunks(b"changelog")
361 gen.manifestheader()
361 gen.manifestheader()
362 showchunks(b"manifest")
362 showchunks(b"manifest")
363 for chunkdata in iter(gen.filelogheader, {}):
363 for chunkdata in iter(gen.filelogheader, {}):
364 fname = chunkdata[b'filename']
364 fname = chunkdata[b'filename']
365 showchunks(fname)
365 showchunks(fname)
366 else:
366 else:
367 if isinstance(gen, bundle2.unbundle20):
367 if isinstance(gen, bundle2.unbundle20):
368 raise error.Abort(_(b'use debugbundle2 for this file'))
368 raise error.Abort(_(b'use debugbundle2 for this file'))
369 gen.changelogheader()
369 gen.changelogheader()
370 for deltadata in gen.deltaiter():
370 for deltadata in gen.deltaiter():
371 node, p1, p2, cs, deltabase, delta, flags = deltadata
371 node, p1, p2, cs, deltabase, delta, flags = deltadata
372 ui.write(b"%s%s\n" % (indent_string, hex(node)))
372 ui.write(b"%s%s\n" % (indent_string, hex(node)))
373
373
374
374
375 def _debugobsmarkers(ui, part, indent=0, **opts):
375 def _debugobsmarkers(ui, part, indent=0, **opts):
376 """display version and markers contained in 'data'"""
376 """display version and markers contained in 'data'"""
377 opts = pycompat.byteskwargs(opts)
377 opts = pycompat.byteskwargs(opts)
378 data = part.read()
378 data = part.read()
379 indent_string = b' ' * indent
379 indent_string = b' ' * indent
380 try:
380 try:
381 version, markers = obsolete._readmarkers(data)
381 version, markers = obsolete._readmarkers(data)
382 except error.UnknownVersion as exc:
382 except error.UnknownVersion as exc:
383 msg = b"%sunsupported version: %s (%d bytes)\n"
383 msg = b"%sunsupported version: %s (%d bytes)\n"
384 msg %= indent_string, exc.version, len(data)
384 msg %= indent_string, exc.version, len(data)
385 ui.write(msg)
385 ui.write(msg)
386 else:
386 else:
387 msg = b"%sversion: %d (%d bytes)\n"
387 msg = b"%sversion: %d (%d bytes)\n"
388 msg %= indent_string, version, len(data)
388 msg %= indent_string, version, len(data)
389 ui.write(msg)
389 ui.write(msg)
390 fm = ui.formatter(b'debugobsolete', opts)
390 fm = ui.formatter(b'debugobsolete', opts)
391 for rawmarker in sorted(markers):
391 for rawmarker in sorted(markers):
392 m = obsutil.marker(None, rawmarker)
392 m = obsutil.marker(None, rawmarker)
393 fm.startitem()
393 fm.startitem()
394 fm.plain(indent_string)
394 fm.plain(indent_string)
395 cmdutil.showmarker(fm, m)
395 cmdutil.showmarker(fm, m)
396 fm.end()
396 fm.end()
397
397
398
398
399 def _debugphaseheads(ui, data, indent=0):
399 def _debugphaseheads(ui, data, indent=0):
400 """display version and markers contained in 'data'"""
400 """display version and markers contained in 'data'"""
401 indent_string = b' ' * indent
401 indent_string = b' ' * indent
402 headsbyphase = phases.binarydecode(data)
402 headsbyphase = phases.binarydecode(data)
403 for phase in phases.allphases:
403 for phase in phases.allphases:
404 for head in headsbyphase[phase]:
404 for head in headsbyphase[phase]:
405 ui.write(indent_string)
405 ui.write(indent_string)
406 ui.write(b'%s %s\n' % (hex(head), phases.phasenames[phase]))
406 ui.write(b'%s %s\n' % (hex(head), phases.phasenames[phase]))
407
407
408
408
409 def _quasirepr(thing):
409 def _quasirepr(thing):
410 if isinstance(thing, (dict, util.sortdict, collections.OrderedDict)):
410 if isinstance(thing, (dict, util.sortdict, collections.OrderedDict)):
411 return b'{%s}' % (
411 return b'{%s}' % (
412 b', '.join(b'%s: %s' % (k, thing[k]) for k in sorted(thing))
412 b', '.join(b'%s: %s' % (k, thing[k]) for k in sorted(thing))
413 )
413 )
414 return pycompat.bytestr(repr(thing))
414 return pycompat.bytestr(repr(thing))
415
415
416
416
417 def _debugbundle2(ui, gen, all=None, **opts):
417 def _debugbundle2(ui, gen, all=None, **opts):
418 """lists the contents of a bundle2"""
418 """lists the contents of a bundle2"""
419 if not isinstance(gen, bundle2.unbundle20):
419 if not isinstance(gen, bundle2.unbundle20):
420 raise error.Abort(_(b'not a bundle2 file'))
420 raise error.Abort(_(b'not a bundle2 file'))
421 ui.write((b'Stream params: %s\n' % _quasirepr(gen.params)))
421 ui.write((b'Stream params: %s\n' % _quasirepr(gen.params)))
422 parttypes = opts.get('part_type', [])
422 parttypes = opts.get('part_type', [])
423 for part in gen.iterparts():
423 for part in gen.iterparts():
424 if parttypes and part.type not in parttypes:
424 if parttypes and part.type not in parttypes:
425 continue
425 continue
426 msg = b'%s -- %s (mandatory: %r)\n'
426 msg = b'%s -- %s (mandatory: %r)\n'
427 ui.write((msg % (part.type, _quasirepr(part.params), part.mandatory)))
427 ui.write((msg % (part.type, _quasirepr(part.params), part.mandatory)))
428 if part.type == b'changegroup':
428 if part.type == b'changegroup':
429 version = part.params.get(b'version', b'01')
429 version = part.params.get(b'version', b'01')
430 cg = changegroup.getunbundler(version, part, b'UN')
430 cg = changegroup.getunbundler(version, part, b'UN')
431 if not ui.quiet:
431 if not ui.quiet:
432 _debugchangegroup(ui, cg, all=all, indent=4, **opts)
432 _debugchangegroup(ui, cg, all=all, indent=4, **opts)
433 if part.type == b'obsmarkers':
433 if part.type == b'obsmarkers':
434 if not ui.quiet:
434 if not ui.quiet:
435 _debugobsmarkers(ui, part, indent=4, **opts)
435 _debugobsmarkers(ui, part, indent=4, **opts)
436 if part.type == b'phase-heads':
436 if part.type == b'phase-heads':
437 if not ui.quiet:
437 if not ui.quiet:
438 _debugphaseheads(ui, part, indent=4)
438 _debugphaseheads(ui, part, indent=4)
439
439
440
440
441 @command(
441 @command(
442 b'debugbundle',
442 b'debugbundle',
443 [
443 [
444 (b'a', b'all', None, _(b'show all details')),
444 (b'a', b'all', None, _(b'show all details')),
445 (b'', b'part-type', [], _(b'show only the named part type')),
445 (b'', b'part-type', [], _(b'show only the named part type')),
446 (b'', b'spec', None, _(b'print the bundlespec of the bundle')),
446 (b'', b'spec', None, _(b'print the bundlespec of the bundle')),
447 ],
447 ],
448 _(b'FILE'),
448 _(b'FILE'),
449 norepo=True,
449 norepo=True,
450 )
450 )
451 def debugbundle(ui, bundlepath, all=None, spec=None, **opts):
451 def debugbundle(ui, bundlepath, all=None, spec=None, **opts):
452 """lists the contents of a bundle"""
452 """lists the contents of a bundle"""
453 with hg.openpath(ui, bundlepath) as f:
453 with hg.openpath(ui, bundlepath) as f:
454 if spec:
454 if spec:
455 spec = exchange.getbundlespec(ui, f)
455 spec = exchange.getbundlespec(ui, f)
456 ui.write(b'%s\n' % spec)
456 ui.write(b'%s\n' % spec)
457 return
457 return
458
458
459 gen = exchange.readbundle(ui, f, bundlepath)
459 gen = exchange.readbundle(ui, f, bundlepath)
460 if isinstance(gen, bundle2.unbundle20):
460 if isinstance(gen, bundle2.unbundle20):
461 return _debugbundle2(ui, gen, all=all, **opts)
461 return _debugbundle2(ui, gen, all=all, **opts)
462 _debugchangegroup(ui, gen, all=all, **opts)
462 _debugchangegroup(ui, gen, all=all, **opts)
463
463
464
464
465 @command(b'debugcapabilities', [], _(b'PATH'), norepo=True)
465 @command(b'debugcapabilities', [], _(b'PATH'), norepo=True)
466 def debugcapabilities(ui, path, **opts):
466 def debugcapabilities(ui, path, **opts):
467 """lists the capabilities of a remote peer"""
467 """lists the capabilities of a remote peer"""
468 opts = pycompat.byteskwargs(opts)
468 opts = pycompat.byteskwargs(opts)
469 peer = hg.peer(ui, opts, path)
469 peer = hg.peer(ui, opts, path)
470 caps = peer.capabilities()
470 caps = peer.capabilities()
471 ui.writenoi18n(b'Main capabilities:\n')
471 ui.writenoi18n(b'Main capabilities:\n')
472 for c in sorted(caps):
472 for c in sorted(caps):
473 ui.write(b' %s\n' % c)
473 ui.write(b' %s\n' % c)
474 b2caps = bundle2.bundle2caps(peer)
474 b2caps = bundle2.bundle2caps(peer)
475 if b2caps:
475 if b2caps:
476 ui.writenoi18n(b'Bundle2 capabilities:\n')
476 ui.writenoi18n(b'Bundle2 capabilities:\n')
477 for key, values in sorted(pycompat.iteritems(b2caps)):
477 for key, values in sorted(pycompat.iteritems(b2caps)):
478 ui.write(b' %s\n' % key)
478 ui.write(b' %s\n' % key)
479 for v in values:
479 for v in values:
480 ui.write(b' %s\n' % v)
480 ui.write(b' %s\n' % v)
481
481
482
482
483 @command(b'debugchangedfiles', [], b'REV')
483 @command(b'debugchangedfiles', [], b'REV')
484 def debugchangedfiles(ui, repo, rev):
484 def debugchangedfiles(ui, repo, rev):
485 """list the stored files changes for a revision"""
485 """list the stored files changes for a revision"""
486 ctx = scmutil.revsingle(repo, rev, None)
486 ctx = scmutil.revsingle(repo, rev, None)
487 sd = repo.changelog.sidedata(ctx.rev())
487 sd = repo.changelog.sidedata(ctx.rev())
488 files_block = sd.get(sidedata.SD_FILES)
488 files_block = sd.get(sidedata.SD_FILES)
489 if files_block is not None:
489 if files_block is not None:
490 files = metadata.decode_files_sidedata(sd)
490 files = metadata.decode_files_sidedata(sd)
491 for f in sorted(files.touched):
491 for f in sorted(files.touched):
492 if f in files.added:
492 if f in files.added:
493 action = b"added"
493 action = b"added"
494 elif f in files.removed:
494 elif f in files.removed:
495 action = b"removed"
495 action = b"removed"
496 elif f in files.merged:
496 elif f in files.merged:
497 action = b"merged"
497 action = b"merged"
498 elif f in files.salvaged:
498 elif f in files.salvaged:
499 action = b"salvaged"
499 action = b"salvaged"
500 else:
500 else:
501 action = b"touched"
501 action = b"touched"
502
502
503 copy_parent = b""
503 copy_parent = b""
504 copy_source = b""
504 copy_source = b""
505 if f in files.copied_from_p1:
505 if f in files.copied_from_p1:
506 copy_parent = b"p1"
506 copy_parent = b"p1"
507 copy_source = files.copied_from_p1[f]
507 copy_source = files.copied_from_p1[f]
508 elif f in files.copied_from_p2:
508 elif f in files.copied_from_p2:
509 copy_parent = b"p2"
509 copy_parent = b"p2"
510 copy_source = files.copied_from_p2[f]
510 copy_source = files.copied_from_p2[f]
511
511
512 data = (action, copy_parent, f, copy_source)
512 data = (action, copy_parent, f, copy_source)
513 template = b"%-8s %2s: %s, %s;\n"
513 template = b"%-8s %2s: %s, %s;\n"
514 ui.write(template % data)
514 ui.write(template % data)
515
515
516
516
517 @command(b'debugcheckstate', [], b'')
517 @command(b'debugcheckstate', [], b'')
518 def debugcheckstate(ui, repo):
518 def debugcheckstate(ui, repo):
519 """validate the correctness of the current dirstate"""
519 """validate the correctness of the current dirstate"""
520 parent1, parent2 = repo.dirstate.parents()
520 parent1, parent2 = repo.dirstate.parents()
521 m1 = repo[parent1].manifest()
521 m1 = repo[parent1].manifest()
522 m2 = repo[parent2].manifest()
522 m2 = repo[parent2].manifest()
523 errors = 0
523 errors = 0
524 for f in repo.dirstate:
524 for f in repo.dirstate:
525 state = repo.dirstate[f]
525 state = repo.dirstate[f]
526 if state in b"nr" and f not in m1:
526 if state in b"nr" and f not in m1:
527 ui.warn(_(b"%s in state %s, but not in manifest1\n") % (f, state))
527 ui.warn(_(b"%s in state %s, but not in manifest1\n") % (f, state))
528 errors += 1
528 errors += 1
529 if state in b"a" and f in m1:
529 if state in b"a" and f in m1:
530 ui.warn(_(b"%s in state %s, but also in manifest1\n") % (f, state))
530 ui.warn(_(b"%s in state %s, but also in manifest1\n") % (f, state))
531 errors += 1
531 errors += 1
532 if state in b"m" and f not in m1 and f not in m2:
532 if state in b"m" and f not in m1 and f not in m2:
533 ui.warn(
533 ui.warn(
534 _(b"%s in state %s, but not in either manifest\n") % (f, state)
534 _(b"%s in state %s, but not in either manifest\n") % (f, state)
535 )
535 )
536 errors += 1
536 errors += 1
537 for f in m1:
537 for f in m1:
538 state = repo.dirstate[f]
538 state = repo.dirstate[f]
539 if state not in b"nrm":
539 if state not in b"nrm":
540 ui.warn(_(b"%s in manifest1, but listed as state %s") % (f, state))
540 ui.warn(_(b"%s in manifest1, but listed as state %s") % (f, state))
541 errors += 1
541 errors += 1
542 if errors:
542 if errors:
543 errstr = _(b".hg/dirstate inconsistent with current parent's manifest")
543 errstr = _(b".hg/dirstate inconsistent with current parent's manifest")
544 raise error.Abort(errstr)
544 raise error.Abort(errstr)
545
545
546
546
547 @command(
547 @command(
548 b'debugcolor',
548 b'debugcolor',
549 [(b'', b'style', None, _(b'show all configured styles'))],
549 [(b'', b'style', None, _(b'show all configured styles'))],
550 b'hg debugcolor',
550 b'hg debugcolor',
551 )
551 )
552 def debugcolor(ui, repo, **opts):
552 def debugcolor(ui, repo, **opts):
553 """show available color, effects or style"""
553 """show available color, effects or style"""
554 ui.writenoi18n(b'color mode: %s\n' % stringutil.pprint(ui._colormode))
554 ui.writenoi18n(b'color mode: %s\n' % stringutil.pprint(ui._colormode))
555 if opts.get('style'):
555 if opts.get('style'):
556 return _debugdisplaystyle(ui)
556 return _debugdisplaystyle(ui)
557 else:
557 else:
558 return _debugdisplaycolor(ui)
558 return _debugdisplaycolor(ui)
559
559
560
560
561 def _debugdisplaycolor(ui):
561 def _debugdisplaycolor(ui):
562 ui = ui.copy()
562 ui = ui.copy()
563 ui._styles.clear()
563 ui._styles.clear()
564 for effect in color._activeeffects(ui).keys():
564 for effect in color._activeeffects(ui).keys():
565 ui._styles[effect] = effect
565 ui._styles[effect] = effect
566 if ui._terminfoparams:
566 if ui._terminfoparams:
567 for k, v in ui.configitems(b'color'):
567 for k, v in ui.configitems(b'color'):
568 if k.startswith(b'color.'):
568 if k.startswith(b'color.'):
569 ui._styles[k] = k[6:]
569 ui._styles[k] = k[6:]
570 elif k.startswith(b'terminfo.'):
570 elif k.startswith(b'terminfo.'):
571 ui._styles[k] = k[9:]
571 ui._styles[k] = k[9:]
572 ui.write(_(b'available colors:\n'))
572 ui.write(_(b'available colors:\n'))
573 # sort label with a '_' after the other to group '_background' entry.
573 # sort label with a '_' after the other to group '_background' entry.
574 items = sorted(ui._styles.items(), key=lambda i: (b'_' in i[0], i[0], i[1]))
574 items = sorted(ui._styles.items(), key=lambda i: (b'_' in i[0], i[0], i[1]))
575 for colorname, label in items:
575 for colorname, label in items:
576 ui.write(b'%s\n' % colorname, label=label)
576 ui.write(b'%s\n' % colorname, label=label)
577
577
578
578
579 def _debugdisplaystyle(ui):
579 def _debugdisplaystyle(ui):
580 ui.write(_(b'available style:\n'))
580 ui.write(_(b'available style:\n'))
581 if not ui._styles:
581 if not ui._styles:
582 return
582 return
583 width = max(len(s) for s in ui._styles)
583 width = max(len(s) for s in ui._styles)
584 for label, effects in sorted(ui._styles.items()):
584 for label, effects in sorted(ui._styles.items()):
585 ui.write(b'%s' % label, label=label)
585 ui.write(b'%s' % label, label=label)
586 if effects:
586 if effects:
587 # 50
587 # 50
588 ui.write(b': ')
588 ui.write(b': ')
589 ui.write(b' ' * (max(0, width - len(label))))
589 ui.write(b' ' * (max(0, width - len(label))))
590 ui.write(b', '.join(ui.label(e, e) for e in effects.split()))
590 ui.write(b', '.join(ui.label(e, e) for e in effects.split()))
591 ui.write(b'\n')
591 ui.write(b'\n')
592
592
593
593
594 @command(b'debugcreatestreamclonebundle', [], b'FILE')
594 @command(b'debugcreatestreamclonebundle', [], b'FILE')
595 def debugcreatestreamclonebundle(ui, repo, fname):
595 def debugcreatestreamclonebundle(ui, repo, fname):
596 """create a stream clone bundle file
596 """create a stream clone bundle file
597
597
598 Stream bundles are special bundles that are essentially archives of
598 Stream bundles are special bundles that are essentially archives of
599 revlog files. They are commonly used for cloning very quickly.
599 revlog files. They are commonly used for cloning very quickly.
600 """
600 """
601 # TODO we may want to turn this into an abort when this functionality
601 # TODO we may want to turn this into an abort when this functionality
602 # is moved into `hg bundle`.
602 # is moved into `hg bundle`.
603 if phases.hassecret(repo):
603 if phases.hassecret(repo):
604 ui.warn(
604 ui.warn(
605 _(
605 _(
606 b'(warning: stream clone bundle will contain secret '
606 b'(warning: stream clone bundle will contain secret '
607 b'revisions)\n'
607 b'revisions)\n'
608 )
608 )
609 )
609 )
610
610
611 requirements, gen = streamclone.generatebundlev1(repo)
611 requirements, gen = streamclone.generatebundlev1(repo)
612 changegroup.writechunks(ui, gen, fname)
612 changegroup.writechunks(ui, gen, fname)
613
613
614 ui.write(_(b'bundle requirements: %s\n') % b', '.join(sorted(requirements)))
614 ui.write(_(b'bundle requirements: %s\n') % b', '.join(sorted(requirements)))
615
615
616
616
617 @command(
617 @command(
618 b'debugdag',
618 b'debugdag',
619 [
619 [
620 (b't', b'tags', None, _(b'use tags as labels')),
620 (b't', b'tags', None, _(b'use tags as labels')),
621 (b'b', b'branches', None, _(b'annotate with branch names')),
621 (b'b', b'branches', None, _(b'annotate with branch names')),
622 (b'', b'dots', None, _(b'use dots for runs')),
622 (b'', b'dots', None, _(b'use dots for runs')),
623 (b's', b'spaces', None, _(b'separate elements by spaces')),
623 (b's', b'spaces', None, _(b'separate elements by spaces')),
624 ],
624 ],
625 _(b'[OPTION]... [FILE [REV]...]'),
625 _(b'[OPTION]... [FILE [REV]...]'),
626 optionalrepo=True,
626 optionalrepo=True,
627 )
627 )
628 def debugdag(ui, repo, file_=None, *revs, **opts):
628 def debugdag(ui, repo, file_=None, *revs, **opts):
629 """format the changelog or an index DAG as a concise textual description
629 """format the changelog or an index DAG as a concise textual description
630
630
631 If you pass a revlog index, the revlog's DAG is emitted. If you list
631 If you pass a revlog index, the revlog's DAG is emitted. If you list
632 revision numbers, they get labeled in the output as rN.
632 revision numbers, they get labeled in the output as rN.
633
633
634 Otherwise, the changelog DAG of the current repo is emitted.
634 Otherwise, the changelog DAG of the current repo is emitted.
635 """
635 """
636 spaces = opts.get('spaces')
636 spaces = opts.get('spaces')
637 dots = opts.get('dots')
637 dots = opts.get('dots')
638 if file_:
638 if file_:
639 rlog = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False), file_)
639 rlog = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False), file_)
640 revs = {int(r) for r in revs}
640 revs = {int(r) for r in revs}
641
641
642 def events():
642 def events():
643 for r in rlog:
643 for r in rlog:
644 yield b'n', (r, list(p for p in rlog.parentrevs(r) if p != -1))
644 yield b'n', (r, list(p for p in rlog.parentrevs(r) if p != -1))
645 if r in revs:
645 if r in revs:
646 yield b'l', (r, b"r%i" % r)
646 yield b'l', (r, b"r%i" % r)
647
647
648 elif repo:
648 elif repo:
649 cl = repo.changelog
649 cl = repo.changelog
650 tags = opts.get('tags')
650 tags = opts.get('tags')
651 branches = opts.get('branches')
651 branches = opts.get('branches')
652 if tags:
652 if tags:
653 labels = {}
653 labels = {}
654 for l, n in repo.tags().items():
654 for l, n in repo.tags().items():
655 labels.setdefault(cl.rev(n), []).append(l)
655 labels.setdefault(cl.rev(n), []).append(l)
656
656
657 def events():
657 def events():
658 b = b"default"
658 b = b"default"
659 for r in cl:
659 for r in cl:
660 if branches:
660 if branches:
661 newb = cl.read(cl.node(r))[5][b'branch']
661 newb = cl.read(cl.node(r))[5][b'branch']
662 if newb != b:
662 if newb != b:
663 yield b'a', newb
663 yield b'a', newb
664 b = newb
664 b = newb
665 yield b'n', (r, list(p for p in cl.parentrevs(r) if p != -1))
665 yield b'n', (r, list(p for p in cl.parentrevs(r) if p != -1))
666 if tags:
666 if tags:
667 ls = labels.get(r)
667 ls = labels.get(r)
668 if ls:
668 if ls:
669 for l in ls:
669 for l in ls:
670 yield b'l', (r, l)
670 yield b'l', (r, l)
671
671
672 else:
672 else:
673 raise error.Abort(_(b'need repo for changelog dag'))
673 raise error.Abort(_(b'need repo for changelog dag'))
674
674
675 for line in dagparser.dagtextlines(
675 for line in dagparser.dagtextlines(
676 events(),
676 events(),
677 addspaces=spaces,
677 addspaces=spaces,
678 wraplabels=True,
678 wraplabels=True,
679 wrapannotations=True,
679 wrapannotations=True,
680 wrapnonlinear=dots,
680 wrapnonlinear=dots,
681 usedots=dots,
681 usedots=dots,
682 maxlinewidth=70,
682 maxlinewidth=70,
683 ):
683 ):
684 ui.write(line)
684 ui.write(line)
685 ui.write(b"\n")
685 ui.write(b"\n")
686
686
687
687
688 @command(b'debugdata', cmdutil.debugrevlogopts, _(b'-c|-m|FILE REV'))
688 @command(b'debugdata', cmdutil.debugrevlogopts, _(b'-c|-m|FILE REV'))
689 def debugdata(ui, repo, file_, rev=None, **opts):
689 def debugdata(ui, repo, file_, rev=None, **opts):
690 """dump the contents of a data file revision"""
690 """dump the contents of a data file revision"""
691 opts = pycompat.byteskwargs(opts)
691 opts = pycompat.byteskwargs(opts)
692 if opts.get(b'changelog') or opts.get(b'manifest') or opts.get(b'dir'):
692 if opts.get(b'changelog') or opts.get(b'manifest') or opts.get(b'dir'):
693 if rev is not None:
693 if rev is not None:
694 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
694 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
695 file_, rev = None, file_
695 file_, rev = None, file_
696 elif rev is None:
696 elif rev is None:
697 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
697 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
698 r = cmdutil.openstorage(repo, b'debugdata', file_, opts)
698 r = cmdutil.openstorage(repo, b'debugdata', file_, opts)
699 try:
699 try:
700 ui.write(r.rawdata(r.lookup(rev)))
700 ui.write(r.rawdata(r.lookup(rev)))
701 except KeyError:
701 except KeyError:
702 raise error.Abort(_(b'invalid revision identifier %s') % rev)
702 raise error.Abort(_(b'invalid revision identifier %s') % rev)
703
703
704
704
705 @command(
705 @command(
706 b'debugdate',
706 b'debugdate',
707 [(b'e', b'extended', None, _(b'try extended date formats'))],
707 [(b'e', b'extended', None, _(b'try extended date formats'))],
708 _(b'[-e] DATE [RANGE]'),
708 _(b'[-e] DATE [RANGE]'),
709 norepo=True,
709 norepo=True,
710 optionalrepo=True,
710 optionalrepo=True,
711 )
711 )
712 def debugdate(ui, date, range=None, **opts):
712 def debugdate(ui, date, range=None, **opts):
713 """parse and display a date"""
713 """parse and display a date"""
714 if opts["extended"]:
714 if opts["extended"]:
715 d = dateutil.parsedate(date, dateutil.extendeddateformats)
715 d = dateutil.parsedate(date, dateutil.extendeddateformats)
716 else:
716 else:
717 d = dateutil.parsedate(date)
717 d = dateutil.parsedate(date)
718 ui.writenoi18n(b"internal: %d %d\n" % d)
718 ui.writenoi18n(b"internal: %d %d\n" % d)
719 ui.writenoi18n(b"standard: %s\n" % dateutil.datestr(d))
719 ui.writenoi18n(b"standard: %s\n" % dateutil.datestr(d))
720 if range:
720 if range:
721 m = dateutil.matchdate(range)
721 m = dateutil.matchdate(range)
722 ui.writenoi18n(b"match: %s\n" % m(d[0]))
722 ui.writenoi18n(b"match: %s\n" % m(d[0]))
723
723
724
724
725 @command(
725 @command(
726 b'debugdeltachain',
726 b'debugdeltachain',
727 cmdutil.debugrevlogopts + cmdutil.formatteropts,
727 cmdutil.debugrevlogopts + cmdutil.formatteropts,
728 _(b'-c|-m|FILE'),
728 _(b'-c|-m|FILE'),
729 optionalrepo=True,
729 optionalrepo=True,
730 )
730 )
731 def debugdeltachain(ui, repo, file_=None, **opts):
731 def debugdeltachain(ui, repo, file_=None, **opts):
732 """dump information about delta chains in a revlog
732 """dump information about delta chains in a revlog
733
733
734 Output can be templatized. Available template keywords are:
734 Output can be templatized. Available template keywords are:
735
735
736 :``rev``: revision number
736 :``rev``: revision number
737 :``chainid``: delta chain identifier (numbered by unique base)
737 :``chainid``: delta chain identifier (numbered by unique base)
738 :``chainlen``: delta chain length to this revision
738 :``chainlen``: delta chain length to this revision
739 :``prevrev``: previous revision in delta chain
739 :``prevrev``: previous revision in delta chain
740 :``deltatype``: role of delta / how it was computed
740 :``deltatype``: role of delta / how it was computed
741 :``compsize``: compressed size of revision
741 :``compsize``: compressed size of revision
742 :``uncompsize``: uncompressed size of revision
742 :``uncompsize``: uncompressed size of revision
743 :``chainsize``: total size of compressed revisions in chain
743 :``chainsize``: total size of compressed revisions in chain
744 :``chainratio``: total chain size divided by uncompressed revision size
744 :``chainratio``: total chain size divided by uncompressed revision size
745 (new delta chains typically start at ratio 2.00)
745 (new delta chains typically start at ratio 2.00)
746 :``lindist``: linear distance from base revision in delta chain to end
746 :``lindist``: linear distance from base revision in delta chain to end
747 of this revision
747 of this revision
748 :``extradist``: total size of revisions not part of this delta chain from
748 :``extradist``: total size of revisions not part of this delta chain from
749 base of delta chain to end of this revision; a measurement
749 base of delta chain to end of this revision; a measurement
750 of how much extra data we need to read/seek across to read
750 of how much extra data we need to read/seek across to read
751 the delta chain for this revision
751 the delta chain for this revision
752 :``extraratio``: extradist divided by chainsize; another representation of
752 :``extraratio``: extradist divided by chainsize; another representation of
753 how much unrelated data is needed to load this delta chain
753 how much unrelated data is needed to load this delta chain
754
754
755 If the repository is configured to use the sparse read, additional keywords
755 If the repository is configured to use the sparse read, additional keywords
756 are available:
756 are available:
757
757
758 :``readsize``: total size of data read from the disk for a revision
758 :``readsize``: total size of data read from the disk for a revision
759 (sum of the sizes of all the blocks)
759 (sum of the sizes of all the blocks)
760 :``largestblock``: size of the largest block of data read from the disk
760 :``largestblock``: size of the largest block of data read from the disk
761 :``readdensity``: density of useful bytes in the data read from the disk
761 :``readdensity``: density of useful bytes in the data read from the disk
762 :``srchunks``: in how many data hunks the whole revision would be read
762 :``srchunks``: in how many data hunks the whole revision would be read
763
763
764 The sparse read can be enabled with experimental.sparse-read = True
764 The sparse read can be enabled with experimental.sparse-read = True
765 """
765 """
766 opts = pycompat.byteskwargs(opts)
766 opts = pycompat.byteskwargs(opts)
767 r = cmdutil.openrevlog(repo, b'debugdeltachain', file_, opts)
767 r = cmdutil.openrevlog(repo, b'debugdeltachain', file_, opts)
768 index = r.index
768 index = r.index
769 start = r.start
769 start = r.start
770 length = r.length
770 length = r.length
771 generaldelta = r.version & revlog.FLAG_GENERALDELTA
771 generaldelta = r.version & revlog.FLAG_GENERALDELTA
772 withsparseread = getattr(r, '_withsparseread', False)
772 withsparseread = getattr(r, '_withsparseread', False)
773
773
774 def revinfo(rev):
774 def revinfo(rev):
775 e = index[rev]
775 e = index[rev]
776 compsize = e[1]
776 compsize = e[1]
777 uncompsize = e[2]
777 uncompsize = e[2]
778 chainsize = 0
778 chainsize = 0
779
779
780 if generaldelta:
780 if generaldelta:
781 if e[3] == e[5]:
781 if e[3] == e[5]:
782 deltatype = b'p1'
782 deltatype = b'p1'
783 elif e[3] == e[6]:
783 elif e[3] == e[6]:
784 deltatype = b'p2'
784 deltatype = b'p2'
785 elif e[3] == rev - 1:
785 elif e[3] == rev - 1:
786 deltatype = b'prev'
786 deltatype = b'prev'
787 elif e[3] == rev:
787 elif e[3] == rev:
788 deltatype = b'base'
788 deltatype = b'base'
789 else:
789 else:
790 deltatype = b'other'
790 deltatype = b'other'
791 else:
791 else:
792 if e[3] == rev:
792 if e[3] == rev:
793 deltatype = b'base'
793 deltatype = b'base'
794 else:
794 else:
795 deltatype = b'prev'
795 deltatype = b'prev'
796
796
797 chain = r._deltachain(rev)[0]
797 chain = r._deltachain(rev)[0]
798 for iterrev in chain:
798 for iterrev in chain:
799 e = index[iterrev]
799 e = index[iterrev]
800 chainsize += e[1]
800 chainsize += e[1]
801
801
802 return compsize, uncompsize, deltatype, chain, chainsize
802 return compsize, uncompsize, deltatype, chain, chainsize
803
803
804 fm = ui.formatter(b'debugdeltachain', opts)
804 fm = ui.formatter(b'debugdeltachain', opts)
805
805
806 fm.plain(
806 fm.plain(
807 b' rev chain# chainlen prev delta '
807 b' rev chain# chainlen prev delta '
808 b'size rawsize chainsize ratio lindist extradist '
808 b'size rawsize chainsize ratio lindist extradist '
809 b'extraratio'
809 b'extraratio'
810 )
810 )
811 if withsparseread:
811 if withsparseread:
812 fm.plain(b' readsize largestblk rddensity srchunks')
812 fm.plain(b' readsize largestblk rddensity srchunks')
813 fm.plain(b'\n')
813 fm.plain(b'\n')
814
814
815 chainbases = {}
815 chainbases = {}
816 for rev in r:
816 for rev in r:
817 comp, uncomp, deltatype, chain, chainsize = revinfo(rev)
817 comp, uncomp, deltatype, chain, chainsize = revinfo(rev)
818 chainbase = chain[0]
818 chainbase = chain[0]
819 chainid = chainbases.setdefault(chainbase, len(chainbases) + 1)
819 chainid = chainbases.setdefault(chainbase, len(chainbases) + 1)
820 basestart = start(chainbase)
820 basestart = start(chainbase)
821 revstart = start(rev)
821 revstart = start(rev)
822 lineardist = revstart + comp - basestart
822 lineardist = revstart + comp - basestart
823 extradist = lineardist - chainsize
823 extradist = lineardist - chainsize
824 try:
824 try:
825 prevrev = chain[-2]
825 prevrev = chain[-2]
826 except IndexError:
826 except IndexError:
827 prevrev = -1
827 prevrev = -1
828
828
829 if uncomp != 0:
829 if uncomp != 0:
830 chainratio = float(chainsize) / float(uncomp)
830 chainratio = float(chainsize) / float(uncomp)
831 else:
831 else:
832 chainratio = chainsize
832 chainratio = chainsize
833
833
834 if chainsize != 0:
834 if chainsize != 0:
835 extraratio = float(extradist) / float(chainsize)
835 extraratio = float(extradist) / float(chainsize)
836 else:
836 else:
837 extraratio = extradist
837 extraratio = extradist
838
838
839 fm.startitem()
839 fm.startitem()
840 fm.write(
840 fm.write(
841 b'rev chainid chainlen prevrev deltatype compsize '
841 b'rev chainid chainlen prevrev deltatype compsize '
842 b'uncompsize chainsize chainratio lindist extradist '
842 b'uncompsize chainsize chainratio lindist extradist '
843 b'extraratio',
843 b'extraratio',
844 b'%7d %7d %8d %8d %7s %10d %10d %10d %9.5f %9d %9d %10.5f',
844 b'%7d %7d %8d %8d %7s %10d %10d %10d %9.5f %9d %9d %10.5f',
845 rev,
845 rev,
846 chainid,
846 chainid,
847 len(chain),
847 len(chain),
848 prevrev,
848 prevrev,
849 deltatype,
849 deltatype,
850 comp,
850 comp,
851 uncomp,
851 uncomp,
852 chainsize,
852 chainsize,
853 chainratio,
853 chainratio,
854 lineardist,
854 lineardist,
855 extradist,
855 extradist,
856 extraratio,
856 extraratio,
857 rev=rev,
857 rev=rev,
858 chainid=chainid,
858 chainid=chainid,
859 chainlen=len(chain),
859 chainlen=len(chain),
860 prevrev=prevrev,
860 prevrev=prevrev,
861 deltatype=deltatype,
861 deltatype=deltatype,
862 compsize=comp,
862 compsize=comp,
863 uncompsize=uncomp,
863 uncompsize=uncomp,
864 chainsize=chainsize,
864 chainsize=chainsize,
865 chainratio=chainratio,
865 chainratio=chainratio,
866 lindist=lineardist,
866 lindist=lineardist,
867 extradist=extradist,
867 extradist=extradist,
868 extraratio=extraratio,
868 extraratio=extraratio,
869 )
869 )
870 if withsparseread:
870 if withsparseread:
871 readsize = 0
871 readsize = 0
872 largestblock = 0
872 largestblock = 0
873 srchunks = 0
873 srchunks = 0
874
874
875 for revschunk in deltautil.slicechunk(r, chain):
875 for revschunk in deltautil.slicechunk(r, chain):
876 srchunks += 1
876 srchunks += 1
877 blkend = start(revschunk[-1]) + length(revschunk[-1])
877 blkend = start(revschunk[-1]) + length(revschunk[-1])
878 blksize = blkend - start(revschunk[0])
878 blksize = blkend - start(revschunk[0])
879
879
880 readsize += blksize
880 readsize += blksize
881 if largestblock < blksize:
881 if largestblock < blksize:
882 largestblock = blksize
882 largestblock = blksize
883
883
884 if readsize:
884 if readsize:
885 readdensity = float(chainsize) / float(readsize)
885 readdensity = float(chainsize) / float(readsize)
886 else:
886 else:
887 readdensity = 1
887 readdensity = 1
888
888
889 fm.write(
889 fm.write(
890 b'readsize largestblock readdensity srchunks',
890 b'readsize largestblock readdensity srchunks',
891 b' %10d %10d %9.5f %8d',
891 b' %10d %10d %9.5f %8d',
892 readsize,
892 readsize,
893 largestblock,
893 largestblock,
894 readdensity,
894 readdensity,
895 srchunks,
895 srchunks,
896 readsize=readsize,
896 readsize=readsize,
897 largestblock=largestblock,
897 largestblock=largestblock,
898 readdensity=readdensity,
898 readdensity=readdensity,
899 srchunks=srchunks,
899 srchunks=srchunks,
900 )
900 )
901
901
902 fm.plain(b'\n')
902 fm.plain(b'\n')
903
903
904 fm.end()
904 fm.end()
905
905
906
906
907 @command(
907 @command(
908 b'debugdirstate|debugstate',
908 b'debugdirstate|debugstate',
909 [
909 [
910 (
910 (
911 b'',
911 b'',
912 b'nodates',
912 b'nodates',
913 None,
913 None,
914 _(b'do not display the saved mtime (DEPRECATED)'),
914 _(b'do not display the saved mtime (DEPRECATED)'),
915 ),
915 ),
916 (b'', b'dates', True, _(b'display the saved mtime')),
916 (b'', b'dates', True, _(b'display the saved mtime')),
917 (b'', b'datesort', None, _(b'sort by saved mtime')),
917 (b'', b'datesort', None, _(b'sort by saved mtime')),
918 ],
918 ],
919 _(b'[OPTION]...'),
919 _(b'[OPTION]...'),
920 )
920 )
921 def debugstate(ui, repo, **opts):
921 def debugstate(ui, repo, **opts):
922 """show the contents of the current dirstate"""
922 """show the contents of the current dirstate"""
923
923
924 nodates = not opts['dates']
924 nodates = not opts['dates']
925 if opts.get('nodates') is not None:
925 if opts.get('nodates') is not None:
926 nodates = True
926 nodates = True
927 datesort = opts.get('datesort')
927 datesort = opts.get('datesort')
928
928
929 if datesort:
929 if datesort:
930 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
930 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
931 else:
931 else:
932 keyfunc = None # sort by filename
932 keyfunc = None # sort by filename
933 for file_, ent in sorted(pycompat.iteritems(repo.dirstate), key=keyfunc):
933 for file_, ent in sorted(pycompat.iteritems(repo.dirstate), key=keyfunc):
934 if ent[3] == -1:
934 if ent[3] == -1:
935 timestr = b'unset '
935 timestr = b'unset '
936 elif nodates:
936 elif nodates:
937 timestr = b'set '
937 timestr = b'set '
938 else:
938 else:
939 timestr = time.strftime(
939 timestr = time.strftime(
940 "%Y-%m-%d %H:%M:%S ", time.localtime(ent[3])
940 "%Y-%m-%d %H:%M:%S ", time.localtime(ent[3])
941 )
941 )
942 timestr = encoding.strtolocal(timestr)
942 timestr = encoding.strtolocal(timestr)
943 if ent[1] & 0o20000:
943 if ent[1] & 0o20000:
944 mode = b'lnk'
944 mode = b'lnk'
945 else:
945 else:
946 mode = b'%3o' % (ent[1] & 0o777 & ~util.umask)
946 mode = b'%3o' % (ent[1] & 0o777 & ~util.umask)
947 ui.write(b"%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
947 ui.write(b"%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
948 for f in repo.dirstate.copies():
948 for f in repo.dirstate.copies():
949 ui.write(_(b"copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
949 ui.write(_(b"copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
950
950
951
951
952 @command(
952 @command(
953 b'debugdiscovery',
953 b'debugdiscovery',
954 [
954 [
955 (b'', b'old', None, _(b'use old-style discovery')),
955 (b'', b'old', None, _(b'use old-style discovery')),
956 (
956 (
957 b'',
957 b'',
958 b'nonheads',
958 b'nonheads',
959 None,
959 None,
960 _(b'use old-style discovery with non-heads included'),
960 _(b'use old-style discovery with non-heads included'),
961 ),
961 ),
962 (b'', b'rev', [], b'restrict discovery to this set of revs'),
962 (b'', b'rev', [], b'restrict discovery to this set of revs'),
963 (b'', b'seed', b'12323', b'specify the random seed use for discovery'),
963 (b'', b'seed', b'12323', b'specify the random seed use for discovery'),
964 ]
964 ]
965 + cmdutil.remoteopts,
965 + cmdutil.remoteopts,
966 _(b'[--rev REV] [OTHER]'),
966 _(b'[--rev REV] [OTHER]'),
967 )
967 )
968 def debugdiscovery(ui, repo, remoteurl=b"default", **opts):
968 def debugdiscovery(ui, repo, remoteurl=b"default", **opts):
969 """runs the changeset discovery protocol in isolation"""
969 """runs the changeset discovery protocol in isolation"""
970 opts = pycompat.byteskwargs(opts)
970 opts = pycompat.byteskwargs(opts)
971 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl))
971 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl))
972 remote = hg.peer(repo, opts, remoteurl)
972 remote = hg.peer(repo, opts, remoteurl)
973 ui.status(_(b'comparing with %s\n') % util.hidepassword(remoteurl))
973 ui.status(_(b'comparing with %s\n') % util.hidepassword(remoteurl))
974
974
975 # make sure tests are repeatable
975 # make sure tests are repeatable
976 random.seed(int(opts[b'seed']))
976 random.seed(int(opts[b'seed']))
977
977
978 if opts.get(b'old'):
978 if opts.get(b'old'):
979
979
980 def doit(pushedrevs, remoteheads, remote=remote):
980 def doit(pushedrevs, remoteheads, remote=remote):
981 if not util.safehasattr(remote, b'branches'):
981 if not util.safehasattr(remote, b'branches'):
982 # enable in-client legacy support
982 # enable in-client legacy support
983 remote = localrepo.locallegacypeer(remote.local())
983 remote = localrepo.locallegacypeer(remote.local())
984 common, _in, hds = treediscovery.findcommonincoming(
984 common, _in, hds = treediscovery.findcommonincoming(
985 repo, remote, force=True
985 repo, remote, force=True
986 )
986 )
987 common = set(common)
987 common = set(common)
988 if not opts.get(b'nonheads'):
988 if not opts.get(b'nonheads'):
989 ui.writenoi18n(
989 ui.writenoi18n(
990 b"unpruned common: %s\n"
990 b"unpruned common: %s\n"
991 % b" ".join(sorted(short(n) for n in common))
991 % b" ".join(sorted(short(n) for n in common))
992 )
992 )
993
993
994 clnode = repo.changelog.node
994 clnode = repo.changelog.node
995 common = repo.revs(b'heads(::%ln)', common)
995 common = repo.revs(b'heads(::%ln)', common)
996 common = {clnode(r) for r in common}
996 common = {clnode(r) for r in common}
997 return common, hds
997 return common, hds
998
998
999 else:
999 else:
1000
1000
1001 def doit(pushedrevs, remoteheads, remote=remote):
1001 def doit(pushedrevs, remoteheads, remote=remote):
1002 nodes = None
1002 nodes = None
1003 if pushedrevs:
1003 if pushedrevs:
1004 revs = scmutil.revrange(repo, pushedrevs)
1004 revs = scmutil.revrange(repo, pushedrevs)
1005 nodes = [repo[r].node() for r in revs]
1005 nodes = [repo[r].node() for r in revs]
1006 common, any, hds = setdiscovery.findcommonheads(
1006 common, any, hds = setdiscovery.findcommonheads(
1007 ui, repo, remote, ancestorsof=nodes
1007 ui, repo, remote, ancestorsof=nodes
1008 )
1008 )
1009 return common, hds
1009 return common, hds
1010
1010
1011 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches, revs=None)
1011 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches, revs=None)
1012 localrevs = opts[b'rev']
1012 localrevs = opts[b'rev']
1013 with util.timedcm('debug-discovery') as t:
1013 with util.timedcm('debug-discovery') as t:
1014 common, hds = doit(localrevs, remoterevs)
1014 common, hds = doit(localrevs, remoterevs)
1015
1015
1016 # compute all statistics
1016 # compute all statistics
1017 common = set(common)
1017 common = set(common)
1018 rheads = set(hds)
1018 rheads = set(hds)
1019 lheads = set(repo.heads())
1019 lheads = set(repo.heads())
1020
1020
1021 data = {}
1021 data = {}
1022 data[b'elapsed'] = t.elapsed
1022 data[b'elapsed'] = t.elapsed
1023 data[b'nb-common'] = len(common)
1023 data[b'nb-common'] = len(common)
1024 data[b'nb-common-local'] = len(common & lheads)
1024 data[b'nb-common-local'] = len(common & lheads)
1025 data[b'nb-common-remote'] = len(common & rheads)
1025 data[b'nb-common-remote'] = len(common & rheads)
1026 data[b'nb-common-both'] = len(common & rheads & lheads)
1026 data[b'nb-common-both'] = len(common & rheads & lheads)
1027 data[b'nb-local'] = len(lheads)
1027 data[b'nb-local'] = len(lheads)
1028 data[b'nb-local-missing'] = data[b'nb-local'] - data[b'nb-common-local']
1028 data[b'nb-local-missing'] = data[b'nb-local'] - data[b'nb-common-local']
1029 data[b'nb-remote'] = len(rheads)
1029 data[b'nb-remote'] = len(rheads)
1030 data[b'nb-remote-unknown'] = data[b'nb-remote'] - data[b'nb-common-remote']
1030 data[b'nb-remote-unknown'] = data[b'nb-remote'] - data[b'nb-common-remote']
1031 data[b'nb-revs'] = len(repo.revs(b'all()'))
1031 data[b'nb-revs'] = len(repo.revs(b'all()'))
1032 data[b'nb-revs-common'] = len(repo.revs(b'::%ln', common))
1032 data[b'nb-revs-common'] = len(repo.revs(b'::%ln', common))
1033 data[b'nb-revs-missing'] = data[b'nb-revs'] - data[b'nb-revs-common']
1033 data[b'nb-revs-missing'] = data[b'nb-revs'] - data[b'nb-revs-common']
1034
1034
1035 # display discovery summary
1035 # display discovery summary
1036 ui.writenoi18n(b"elapsed time: %(elapsed)f seconds\n" % data)
1036 ui.writenoi18n(b"elapsed time: %(elapsed)f seconds\n" % data)
1037 ui.writenoi18n(b"heads summary:\n")
1037 ui.writenoi18n(b"heads summary:\n")
1038 ui.writenoi18n(b" total common heads: %(nb-common)9d\n" % data)
1038 ui.writenoi18n(b" total common heads: %(nb-common)9d\n" % data)
1039 ui.writenoi18n(b" also local heads: %(nb-common-local)9d\n" % data)
1039 ui.writenoi18n(b" also local heads: %(nb-common-local)9d\n" % data)
1040 ui.writenoi18n(b" also remote heads: %(nb-common-remote)9d\n" % data)
1040 ui.writenoi18n(b" also remote heads: %(nb-common-remote)9d\n" % data)
1041 ui.writenoi18n(b" both: %(nb-common-both)9d\n" % data)
1041 ui.writenoi18n(b" both: %(nb-common-both)9d\n" % data)
1042 ui.writenoi18n(b" local heads: %(nb-local)9d\n" % data)
1042 ui.writenoi18n(b" local heads: %(nb-local)9d\n" % data)
1043 ui.writenoi18n(b" common: %(nb-common-local)9d\n" % data)
1043 ui.writenoi18n(b" common: %(nb-common-local)9d\n" % data)
1044 ui.writenoi18n(b" missing: %(nb-local-missing)9d\n" % data)
1044 ui.writenoi18n(b" missing: %(nb-local-missing)9d\n" % data)
1045 ui.writenoi18n(b" remote heads: %(nb-remote)9d\n" % data)
1045 ui.writenoi18n(b" remote heads: %(nb-remote)9d\n" % data)
1046 ui.writenoi18n(b" common: %(nb-common-remote)9d\n" % data)
1046 ui.writenoi18n(b" common: %(nb-common-remote)9d\n" % data)
1047 ui.writenoi18n(b" unknown: %(nb-remote-unknown)9d\n" % data)
1047 ui.writenoi18n(b" unknown: %(nb-remote-unknown)9d\n" % data)
1048 ui.writenoi18n(b"local changesets: %(nb-revs)9d\n" % data)
1048 ui.writenoi18n(b"local changesets: %(nb-revs)9d\n" % data)
1049 ui.writenoi18n(b" common: %(nb-revs-common)9d\n" % data)
1049 ui.writenoi18n(b" common: %(nb-revs-common)9d\n" % data)
1050 ui.writenoi18n(b" missing: %(nb-revs-missing)9d\n" % data)
1050 ui.writenoi18n(b" missing: %(nb-revs-missing)9d\n" % data)
1051
1051
1052 if ui.verbose:
1052 if ui.verbose:
1053 ui.writenoi18n(
1053 ui.writenoi18n(
1054 b"common heads: %s\n" % b" ".join(sorted(short(n) for n in common))
1054 b"common heads: %s\n" % b" ".join(sorted(short(n) for n in common))
1055 )
1055 )
1056
1056
1057
1057
1058 _chunksize = 4 << 10
1058 _chunksize = 4 << 10
1059
1059
1060
1060
1061 @command(
1061 @command(
1062 b'debugdownload', [(b'o', b'output', b'', _(b'path')),], optionalrepo=True
1062 b'debugdownload', [(b'o', b'output', b'', _(b'path')),], optionalrepo=True
1063 )
1063 )
1064 def debugdownload(ui, repo, url, output=None, **opts):
1064 def debugdownload(ui, repo, url, output=None, **opts):
1065 """download a resource using Mercurial logic and config
1065 """download a resource using Mercurial logic and config
1066 """
1066 """
1067 fh = urlmod.open(ui, url, output)
1067 fh = urlmod.open(ui, url, output)
1068
1068
1069 dest = ui
1069 dest = ui
1070 if output:
1070 if output:
1071 dest = open(output, b"wb", _chunksize)
1071 dest = open(output, b"wb", _chunksize)
1072 try:
1072 try:
1073 data = fh.read(_chunksize)
1073 data = fh.read(_chunksize)
1074 while data:
1074 while data:
1075 dest.write(data)
1075 dest.write(data)
1076 data = fh.read(_chunksize)
1076 data = fh.read(_chunksize)
1077 finally:
1077 finally:
1078 if output:
1078 if output:
1079 dest.close()
1079 dest.close()
1080
1080
1081
1081
1082 @command(b'debugextensions', cmdutil.formatteropts, [], optionalrepo=True)
1082 @command(b'debugextensions', cmdutil.formatteropts, [], optionalrepo=True)
1083 def debugextensions(ui, repo, **opts):
1083 def debugextensions(ui, repo, **opts):
1084 '''show information about active extensions'''
1084 '''show information about active extensions'''
1085 opts = pycompat.byteskwargs(opts)
1085 opts = pycompat.byteskwargs(opts)
1086 exts = extensions.extensions(ui)
1086 exts = extensions.extensions(ui)
1087 hgver = util.version()
1087 hgver = util.version()
1088 fm = ui.formatter(b'debugextensions', opts)
1088 fm = ui.formatter(b'debugextensions', opts)
1089 for extname, extmod in sorted(exts, key=operator.itemgetter(0)):
1089 for extname, extmod in sorted(exts, key=operator.itemgetter(0)):
1090 isinternal = extensions.ismoduleinternal(extmod)
1090 isinternal = extensions.ismoduleinternal(extmod)
1091 extsource = None
1091 extsource = None
1092
1092
1093 if util.safehasattr(extmod, '__file__'):
1093 if util.safehasattr(extmod, '__file__'):
1094 extsource = pycompat.fsencode(extmod.__file__)
1094 extsource = pycompat.fsencode(extmod.__file__)
1095 elif getattr(sys, 'oxidized', False):
1095 elif getattr(sys, 'oxidized', False):
1096 extsource = pycompat.sysexecutable
1096 extsource = pycompat.sysexecutable
1097 if isinternal:
1097 if isinternal:
1098 exttestedwith = [] # never expose magic string to users
1098 exttestedwith = [] # never expose magic string to users
1099 else:
1099 else:
1100 exttestedwith = getattr(extmod, 'testedwith', b'').split()
1100 exttestedwith = getattr(extmod, 'testedwith', b'').split()
1101 extbuglink = getattr(extmod, 'buglink', None)
1101 extbuglink = getattr(extmod, 'buglink', None)
1102
1102
1103 fm.startitem()
1103 fm.startitem()
1104
1104
1105 if ui.quiet or ui.verbose:
1105 if ui.quiet or ui.verbose:
1106 fm.write(b'name', b'%s\n', extname)
1106 fm.write(b'name', b'%s\n', extname)
1107 else:
1107 else:
1108 fm.write(b'name', b'%s', extname)
1108 fm.write(b'name', b'%s', extname)
1109 if isinternal or hgver in exttestedwith:
1109 if isinternal or hgver in exttestedwith:
1110 fm.plain(b'\n')
1110 fm.plain(b'\n')
1111 elif not exttestedwith:
1111 elif not exttestedwith:
1112 fm.plain(_(b' (untested!)\n'))
1112 fm.plain(_(b' (untested!)\n'))
1113 else:
1113 else:
1114 lasttestedversion = exttestedwith[-1]
1114 lasttestedversion = exttestedwith[-1]
1115 fm.plain(b' (%s!)\n' % lasttestedversion)
1115 fm.plain(b' (%s!)\n' % lasttestedversion)
1116
1116
1117 fm.condwrite(
1117 fm.condwrite(
1118 ui.verbose and extsource,
1118 ui.verbose and extsource,
1119 b'source',
1119 b'source',
1120 _(b' location: %s\n'),
1120 _(b' location: %s\n'),
1121 extsource or b"",
1121 extsource or b"",
1122 )
1122 )
1123
1123
1124 if ui.verbose:
1124 if ui.verbose:
1125 fm.plain(_(b' bundled: %s\n') % [b'no', b'yes'][isinternal])
1125 fm.plain(_(b' bundled: %s\n') % [b'no', b'yes'][isinternal])
1126 fm.data(bundled=isinternal)
1126 fm.data(bundled=isinternal)
1127
1127
1128 fm.condwrite(
1128 fm.condwrite(
1129 ui.verbose and exttestedwith,
1129 ui.verbose and exttestedwith,
1130 b'testedwith',
1130 b'testedwith',
1131 _(b' tested with: %s\n'),
1131 _(b' tested with: %s\n'),
1132 fm.formatlist(exttestedwith, name=b'ver'),
1132 fm.formatlist(exttestedwith, name=b'ver'),
1133 )
1133 )
1134
1134
1135 fm.condwrite(
1135 fm.condwrite(
1136 ui.verbose and extbuglink,
1136 ui.verbose and extbuglink,
1137 b'buglink',
1137 b'buglink',
1138 _(b' bug reporting: %s\n'),
1138 _(b' bug reporting: %s\n'),
1139 extbuglink or b"",
1139 extbuglink or b"",
1140 )
1140 )
1141
1141
1142 fm.end()
1142 fm.end()
1143
1143
1144
1144
1145 @command(
1145 @command(
1146 b'debugfileset',
1146 b'debugfileset',
1147 [
1147 [
1148 (
1148 (
1149 b'r',
1149 b'r',
1150 b'rev',
1150 b'rev',
1151 b'',
1151 b'',
1152 _(b'apply the filespec on this revision'),
1152 _(b'apply the filespec on this revision'),
1153 _(b'REV'),
1153 _(b'REV'),
1154 ),
1154 ),
1155 (
1155 (
1156 b'',
1156 b'',
1157 b'all-files',
1157 b'all-files',
1158 False,
1158 False,
1159 _(b'test files from all revisions and working directory'),
1159 _(b'test files from all revisions and working directory'),
1160 ),
1160 ),
1161 (
1161 (
1162 b's',
1162 b's',
1163 b'show-matcher',
1163 b'show-matcher',
1164 None,
1164 None,
1165 _(b'print internal representation of matcher'),
1165 _(b'print internal representation of matcher'),
1166 ),
1166 ),
1167 (
1167 (
1168 b'p',
1168 b'p',
1169 b'show-stage',
1169 b'show-stage',
1170 [],
1170 [],
1171 _(b'print parsed tree at the given stage'),
1171 _(b'print parsed tree at the given stage'),
1172 _(b'NAME'),
1172 _(b'NAME'),
1173 ),
1173 ),
1174 ],
1174 ],
1175 _(b'[-r REV] [--all-files] [OPTION]... FILESPEC'),
1175 _(b'[-r REV] [--all-files] [OPTION]... FILESPEC'),
1176 )
1176 )
1177 def debugfileset(ui, repo, expr, **opts):
1177 def debugfileset(ui, repo, expr, **opts):
1178 '''parse and apply a fileset specification'''
1178 '''parse and apply a fileset specification'''
1179 from . import fileset
1179 from . import fileset
1180
1180
1181 fileset.symbols # force import of fileset so we have predicates to optimize
1181 fileset.symbols # force import of fileset so we have predicates to optimize
1182 opts = pycompat.byteskwargs(opts)
1182 opts = pycompat.byteskwargs(opts)
1183 ctx = scmutil.revsingle(repo, opts.get(b'rev'), None)
1183 ctx = scmutil.revsingle(repo, opts.get(b'rev'), None)
1184
1184
1185 stages = [
1185 stages = [
1186 (b'parsed', pycompat.identity),
1186 (b'parsed', pycompat.identity),
1187 (b'analyzed', filesetlang.analyze),
1187 (b'analyzed', filesetlang.analyze),
1188 (b'optimized', filesetlang.optimize),
1188 (b'optimized', filesetlang.optimize),
1189 ]
1189 ]
1190 stagenames = {n for n, f in stages}
1190 stagenames = {n for n, f in stages}
1191
1191
1192 showalways = set()
1192 showalways = set()
1193 if ui.verbose and not opts[b'show_stage']:
1193 if ui.verbose and not opts[b'show_stage']:
1194 # show parsed tree by --verbose (deprecated)
1194 # show parsed tree by --verbose (deprecated)
1195 showalways.add(b'parsed')
1195 showalways.add(b'parsed')
1196 if opts[b'show_stage'] == [b'all']:
1196 if opts[b'show_stage'] == [b'all']:
1197 showalways.update(stagenames)
1197 showalways.update(stagenames)
1198 else:
1198 else:
1199 for n in opts[b'show_stage']:
1199 for n in opts[b'show_stage']:
1200 if n not in stagenames:
1200 if n not in stagenames:
1201 raise error.Abort(_(b'invalid stage name: %s') % n)
1201 raise error.Abort(_(b'invalid stage name: %s') % n)
1202 showalways.update(opts[b'show_stage'])
1202 showalways.update(opts[b'show_stage'])
1203
1203
1204 tree = filesetlang.parse(expr)
1204 tree = filesetlang.parse(expr)
1205 for n, f in stages:
1205 for n, f in stages:
1206 tree = f(tree)
1206 tree = f(tree)
1207 if n in showalways:
1207 if n in showalways:
1208 if opts[b'show_stage'] or n != b'parsed':
1208 if opts[b'show_stage'] or n != b'parsed':
1209 ui.write(b"* %s:\n" % n)
1209 ui.write(b"* %s:\n" % n)
1210 ui.write(filesetlang.prettyformat(tree), b"\n")
1210 ui.write(filesetlang.prettyformat(tree), b"\n")
1211
1211
1212 files = set()
1212 files = set()
1213 if opts[b'all_files']:
1213 if opts[b'all_files']:
1214 for r in repo:
1214 for r in repo:
1215 c = repo[r]
1215 c = repo[r]
1216 files.update(c.files())
1216 files.update(c.files())
1217 files.update(c.substate)
1217 files.update(c.substate)
1218 if opts[b'all_files'] or ctx.rev() is None:
1218 if opts[b'all_files'] or ctx.rev() is None:
1219 wctx = repo[None]
1219 wctx = repo[None]
1220 files.update(
1220 files.update(
1221 repo.dirstate.walk(
1221 repo.dirstate.walk(
1222 scmutil.matchall(repo),
1222 scmutil.matchall(repo),
1223 subrepos=list(wctx.substate),
1223 subrepos=list(wctx.substate),
1224 unknown=True,
1224 unknown=True,
1225 ignored=True,
1225 ignored=True,
1226 )
1226 )
1227 )
1227 )
1228 files.update(wctx.substate)
1228 files.update(wctx.substate)
1229 else:
1229 else:
1230 files.update(ctx.files())
1230 files.update(ctx.files())
1231 files.update(ctx.substate)
1231 files.update(ctx.substate)
1232
1232
1233 m = ctx.matchfileset(repo.getcwd(), expr)
1233 m = ctx.matchfileset(repo.getcwd(), expr)
1234 if opts[b'show_matcher'] or (opts[b'show_matcher'] is None and ui.verbose):
1234 if opts[b'show_matcher'] or (opts[b'show_matcher'] is None and ui.verbose):
1235 ui.writenoi18n(b'* matcher:\n', stringutil.prettyrepr(m), b'\n')
1235 ui.writenoi18n(b'* matcher:\n', stringutil.prettyrepr(m), b'\n')
1236 for f in sorted(files):
1236 for f in sorted(files):
1237 if not m(f):
1237 if not m(f):
1238 continue
1238 continue
1239 ui.write(b"%s\n" % f)
1239 ui.write(b"%s\n" % f)
1240
1240
1241
1241
1242 @command(b'debugformat', [] + cmdutil.formatteropts)
1242 @command(b'debugformat', [] + cmdutil.formatteropts)
1243 def debugformat(ui, repo, **opts):
1243 def debugformat(ui, repo, **opts):
1244 """display format information about the current repository
1244 """display format information about the current repository
1245
1245
1246 Use --verbose to get extra information about current config value and
1246 Use --verbose to get extra information about current config value and
1247 Mercurial default."""
1247 Mercurial default."""
1248 opts = pycompat.byteskwargs(opts)
1248 opts = pycompat.byteskwargs(opts)
1249 maxvariantlength = max(len(fv.name) for fv in upgrade.allformatvariant)
1249 maxvariantlength = max(len(fv.name) for fv in upgrade.allformatvariant)
1250 maxvariantlength = max(len(b'format-variant'), maxvariantlength)
1250 maxvariantlength = max(len(b'format-variant'), maxvariantlength)
1251
1251
1252 def makeformatname(name):
1252 def makeformatname(name):
1253 return b'%s:' + (b' ' * (maxvariantlength - len(name)))
1253 return b'%s:' + (b' ' * (maxvariantlength - len(name)))
1254
1254
1255 fm = ui.formatter(b'debugformat', opts)
1255 fm = ui.formatter(b'debugformat', opts)
1256 if fm.isplain():
1256 if fm.isplain():
1257
1257
1258 def formatvalue(value):
1258 def formatvalue(value):
1259 if util.safehasattr(value, b'startswith'):
1259 if util.safehasattr(value, b'startswith'):
1260 return value
1260 return value
1261 if value:
1261 if value:
1262 return b'yes'
1262 return b'yes'
1263 else:
1263 else:
1264 return b'no'
1264 return b'no'
1265
1265
1266 else:
1266 else:
1267 formatvalue = pycompat.identity
1267 formatvalue = pycompat.identity
1268
1268
1269 fm.plain(b'format-variant')
1269 fm.plain(b'format-variant')
1270 fm.plain(b' ' * (maxvariantlength - len(b'format-variant')))
1270 fm.plain(b' ' * (maxvariantlength - len(b'format-variant')))
1271 fm.plain(b' repo')
1271 fm.plain(b' repo')
1272 if ui.verbose:
1272 if ui.verbose:
1273 fm.plain(b' config default')
1273 fm.plain(b' config default')
1274 fm.plain(b'\n')
1274 fm.plain(b'\n')
1275 for fv in upgrade.allformatvariant:
1275 for fv in upgrade.allformatvariant:
1276 fm.startitem()
1276 fm.startitem()
1277 repovalue = fv.fromrepo(repo)
1277 repovalue = fv.fromrepo(repo)
1278 configvalue = fv.fromconfig(repo)
1278 configvalue = fv.fromconfig(repo)
1279
1279
1280 if repovalue != configvalue:
1280 if repovalue != configvalue:
1281 namelabel = b'formatvariant.name.mismatchconfig'
1281 namelabel = b'formatvariant.name.mismatchconfig'
1282 repolabel = b'formatvariant.repo.mismatchconfig'
1282 repolabel = b'formatvariant.repo.mismatchconfig'
1283 elif repovalue != fv.default:
1283 elif repovalue != fv.default:
1284 namelabel = b'formatvariant.name.mismatchdefault'
1284 namelabel = b'formatvariant.name.mismatchdefault'
1285 repolabel = b'formatvariant.repo.mismatchdefault'
1285 repolabel = b'formatvariant.repo.mismatchdefault'
1286 else:
1286 else:
1287 namelabel = b'formatvariant.name.uptodate'
1287 namelabel = b'formatvariant.name.uptodate'
1288 repolabel = b'formatvariant.repo.uptodate'
1288 repolabel = b'formatvariant.repo.uptodate'
1289
1289
1290 fm.write(b'name', makeformatname(fv.name), fv.name, label=namelabel)
1290 fm.write(b'name', makeformatname(fv.name), fv.name, label=namelabel)
1291 fm.write(b'repo', b' %3s', formatvalue(repovalue), label=repolabel)
1291 fm.write(b'repo', b' %3s', formatvalue(repovalue), label=repolabel)
1292 if fv.default != configvalue:
1292 if fv.default != configvalue:
1293 configlabel = b'formatvariant.config.special'
1293 configlabel = b'formatvariant.config.special'
1294 else:
1294 else:
1295 configlabel = b'formatvariant.config.default'
1295 configlabel = b'formatvariant.config.default'
1296 fm.condwrite(
1296 fm.condwrite(
1297 ui.verbose,
1297 ui.verbose,
1298 b'config',
1298 b'config',
1299 b' %6s',
1299 b' %6s',
1300 formatvalue(configvalue),
1300 formatvalue(configvalue),
1301 label=configlabel,
1301 label=configlabel,
1302 )
1302 )
1303 fm.condwrite(
1303 fm.condwrite(
1304 ui.verbose,
1304 ui.verbose,
1305 b'default',
1305 b'default',
1306 b' %7s',
1306 b' %7s',
1307 formatvalue(fv.default),
1307 formatvalue(fv.default),
1308 label=b'formatvariant.default',
1308 label=b'formatvariant.default',
1309 )
1309 )
1310 fm.plain(b'\n')
1310 fm.plain(b'\n')
1311 fm.end()
1311 fm.end()
1312
1312
1313
1313
1314 @command(b'debugfsinfo', [], _(b'[PATH]'), norepo=True)
1314 @command(b'debugfsinfo', [], _(b'[PATH]'), norepo=True)
1315 def debugfsinfo(ui, path=b"."):
1315 def debugfsinfo(ui, path=b"."):
1316 """show information detected about current filesystem"""
1316 """show information detected about current filesystem"""
1317 ui.writenoi18n(b'path: %s\n' % path)
1317 ui.writenoi18n(b'path: %s\n' % path)
1318 ui.writenoi18n(
1318 ui.writenoi18n(
1319 b'mounted on: %s\n' % (util.getfsmountpoint(path) or b'(unknown)')
1319 b'mounted on: %s\n' % (util.getfsmountpoint(path) or b'(unknown)')
1320 )
1320 )
1321 ui.writenoi18n(b'exec: %s\n' % (util.checkexec(path) and b'yes' or b'no'))
1321 ui.writenoi18n(b'exec: %s\n' % (util.checkexec(path) and b'yes' or b'no'))
1322 ui.writenoi18n(b'fstype: %s\n' % (util.getfstype(path) or b'(unknown)'))
1322 ui.writenoi18n(b'fstype: %s\n' % (util.getfstype(path) or b'(unknown)'))
1323 ui.writenoi18n(
1323 ui.writenoi18n(
1324 b'symlink: %s\n' % (util.checklink(path) and b'yes' or b'no')
1324 b'symlink: %s\n' % (util.checklink(path) and b'yes' or b'no')
1325 )
1325 )
1326 ui.writenoi18n(
1326 ui.writenoi18n(
1327 b'hardlink: %s\n' % (util.checknlink(path) and b'yes' or b'no')
1327 b'hardlink: %s\n' % (util.checknlink(path) and b'yes' or b'no')
1328 )
1328 )
1329 casesensitive = b'(unknown)'
1329 casesensitive = b'(unknown)'
1330 try:
1330 try:
1331 with pycompat.namedtempfile(prefix=b'.debugfsinfo', dir=path) as f:
1331 with pycompat.namedtempfile(prefix=b'.debugfsinfo', dir=path) as f:
1332 casesensitive = util.fscasesensitive(f.name) and b'yes' or b'no'
1332 casesensitive = util.fscasesensitive(f.name) and b'yes' or b'no'
1333 except OSError:
1333 except OSError:
1334 pass
1334 pass
1335 ui.writenoi18n(b'case-sensitive: %s\n' % casesensitive)
1335 ui.writenoi18n(b'case-sensitive: %s\n' % casesensitive)
1336
1336
1337
1337
1338 @command(
1338 @command(
1339 b'debuggetbundle',
1339 b'debuggetbundle',
1340 [
1340 [
1341 (b'H', b'head', [], _(b'id of head node'), _(b'ID')),
1341 (b'H', b'head', [], _(b'id of head node'), _(b'ID')),
1342 (b'C', b'common', [], _(b'id of common node'), _(b'ID')),
1342 (b'C', b'common', [], _(b'id of common node'), _(b'ID')),
1343 (
1343 (
1344 b't',
1344 b't',
1345 b'type',
1345 b'type',
1346 b'bzip2',
1346 b'bzip2',
1347 _(b'bundle compression type to use'),
1347 _(b'bundle compression type to use'),
1348 _(b'TYPE'),
1348 _(b'TYPE'),
1349 ),
1349 ),
1350 ],
1350 ],
1351 _(b'REPO FILE [-H|-C ID]...'),
1351 _(b'REPO FILE [-H|-C ID]...'),
1352 norepo=True,
1352 norepo=True,
1353 )
1353 )
1354 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1354 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1355 """retrieves a bundle from a repo
1355 """retrieves a bundle from a repo
1356
1356
1357 Every ID must be a full-length hex node id string. Saves the bundle to the
1357 Every ID must be a full-length hex node id string. Saves the bundle to the
1358 given file.
1358 given file.
1359 """
1359 """
1360 opts = pycompat.byteskwargs(opts)
1360 opts = pycompat.byteskwargs(opts)
1361 repo = hg.peer(ui, opts, repopath)
1361 repo = hg.peer(ui, opts, repopath)
1362 if not repo.capable(b'getbundle'):
1362 if not repo.capable(b'getbundle'):
1363 raise error.Abort(b"getbundle() not supported by target repository")
1363 raise error.Abort(b"getbundle() not supported by target repository")
1364 args = {}
1364 args = {}
1365 if common:
1365 if common:
1366 args['common'] = [bin(s) for s in common]
1366 args['common'] = [bin(s) for s in common]
1367 if head:
1367 if head:
1368 args['heads'] = [bin(s) for s in head]
1368 args['heads'] = [bin(s) for s in head]
1369 # TODO: get desired bundlecaps from command line.
1369 # TODO: get desired bundlecaps from command line.
1370 args['bundlecaps'] = None
1370 args['bundlecaps'] = None
1371 bundle = repo.getbundle(b'debug', **args)
1371 bundle = repo.getbundle(b'debug', **args)
1372
1372
1373 bundletype = opts.get(b'type', b'bzip2').lower()
1373 bundletype = opts.get(b'type', b'bzip2').lower()
1374 btypes = {
1374 btypes = {
1375 b'none': b'HG10UN',
1375 b'none': b'HG10UN',
1376 b'bzip2': b'HG10BZ',
1376 b'bzip2': b'HG10BZ',
1377 b'gzip': b'HG10GZ',
1377 b'gzip': b'HG10GZ',
1378 b'bundle2': b'HG20',
1378 b'bundle2': b'HG20',
1379 }
1379 }
1380 bundletype = btypes.get(bundletype)
1380 bundletype = btypes.get(bundletype)
1381 if bundletype not in bundle2.bundletypes:
1381 if bundletype not in bundle2.bundletypes:
1382 raise error.Abort(_(b'unknown bundle type specified with --type'))
1382 raise error.Abort(_(b'unknown bundle type specified with --type'))
1383 bundle2.writebundle(ui, bundle, bundlepath, bundletype)
1383 bundle2.writebundle(ui, bundle, bundlepath, bundletype)
1384
1384
1385
1385
1386 @command(b'debugignore', [], b'[FILE]')
1386 @command(b'debugignore', [], b'[FILE]')
1387 def debugignore(ui, repo, *files, **opts):
1387 def debugignore(ui, repo, *files, **opts):
1388 """display the combined ignore pattern and information about ignored files
1388 """display the combined ignore pattern and information about ignored files
1389
1389
1390 With no argument display the combined ignore pattern.
1390 With no argument display the combined ignore pattern.
1391
1391
1392 Given space separated file names, shows if the given file is ignored and
1392 Given space separated file names, shows if the given file is ignored and
1393 if so, show the ignore rule (file and line number) that matched it.
1393 if so, show the ignore rule (file and line number) that matched it.
1394 """
1394 """
1395 ignore = repo.dirstate._ignore
1395 ignore = repo.dirstate._ignore
1396 if not files:
1396 if not files:
1397 # Show all the patterns
1397 # Show all the patterns
1398 ui.write(b"%s\n" % pycompat.byterepr(ignore))
1398 ui.write(b"%s\n" % pycompat.byterepr(ignore))
1399 else:
1399 else:
1400 m = scmutil.match(repo[None], pats=files)
1400 m = scmutil.match(repo[None], pats=files)
1401 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
1401 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
1402 for f in m.files():
1402 for f in m.files():
1403 nf = util.normpath(f)
1403 nf = util.normpath(f)
1404 ignored = None
1404 ignored = None
1405 ignoredata = None
1405 ignoredata = None
1406 if nf != b'.':
1406 if nf != b'.':
1407 if ignore(nf):
1407 if ignore(nf):
1408 ignored = nf
1408 ignored = nf
1409 ignoredata = repo.dirstate._ignorefileandline(nf)
1409 ignoredata = repo.dirstate._ignorefileandline(nf)
1410 else:
1410 else:
1411 for p in pathutil.finddirs(nf):
1411 for p in pathutil.finddirs(nf):
1412 if ignore(p):
1412 if ignore(p):
1413 ignored = p
1413 ignored = p
1414 ignoredata = repo.dirstate._ignorefileandline(p)
1414 ignoredata = repo.dirstate._ignorefileandline(p)
1415 break
1415 break
1416 if ignored:
1416 if ignored:
1417 if ignored == nf:
1417 if ignored == nf:
1418 ui.write(_(b"%s is ignored\n") % uipathfn(f))
1418 ui.write(_(b"%s is ignored\n") % uipathfn(f))
1419 else:
1419 else:
1420 ui.write(
1420 ui.write(
1421 _(
1421 _(
1422 b"%s is ignored because of "
1422 b"%s is ignored because of "
1423 b"containing directory %s\n"
1423 b"containing directory %s\n"
1424 )
1424 )
1425 % (uipathfn(f), ignored)
1425 % (uipathfn(f), ignored)
1426 )
1426 )
1427 ignorefile, lineno, line = ignoredata
1427 ignorefile, lineno, line = ignoredata
1428 ui.write(
1428 ui.write(
1429 _(b"(ignore rule in %s, line %d: '%s')\n")
1429 _(b"(ignore rule in %s, line %d: '%s')\n")
1430 % (ignorefile, lineno, line)
1430 % (ignorefile, lineno, line)
1431 )
1431 )
1432 else:
1432 else:
1433 ui.write(_(b"%s is not ignored\n") % uipathfn(f))
1433 ui.write(_(b"%s is not ignored\n") % uipathfn(f))
1434
1434
1435
1435
1436 @command(
1436 @command(
1437 b'debugindex',
1437 b'debugindex',
1438 cmdutil.debugrevlogopts + cmdutil.formatteropts,
1438 cmdutil.debugrevlogopts + cmdutil.formatteropts,
1439 _(b'-c|-m|FILE'),
1439 _(b'-c|-m|FILE'),
1440 )
1440 )
1441 def debugindex(ui, repo, file_=None, **opts):
1441 def debugindex(ui, repo, file_=None, **opts):
1442 """dump index data for a storage primitive"""
1442 """dump index data for a storage primitive"""
1443 opts = pycompat.byteskwargs(opts)
1443 opts = pycompat.byteskwargs(opts)
1444 store = cmdutil.openstorage(repo, b'debugindex', file_, opts)
1444 store = cmdutil.openstorage(repo, b'debugindex', file_, opts)
1445
1445
1446 if ui.debugflag:
1446 if ui.debugflag:
1447 shortfn = hex
1447 shortfn = hex
1448 else:
1448 else:
1449 shortfn = short
1449 shortfn = short
1450
1450
1451 idlen = 12
1451 idlen = 12
1452 for i in store:
1452 for i in store:
1453 idlen = len(shortfn(store.node(i)))
1453 idlen = len(shortfn(store.node(i)))
1454 break
1454 break
1455
1455
1456 fm = ui.formatter(b'debugindex', opts)
1456 fm = ui.formatter(b'debugindex', opts)
1457 fm.plain(
1457 fm.plain(
1458 b' rev linkrev %s %s p2\n'
1458 b' rev linkrev %s %s p2\n'
1459 % (b'nodeid'.ljust(idlen), b'p1'.ljust(idlen))
1459 % (b'nodeid'.ljust(idlen), b'p1'.ljust(idlen))
1460 )
1460 )
1461
1461
1462 for rev in store:
1462 for rev in store:
1463 node = store.node(rev)
1463 node = store.node(rev)
1464 parents = store.parents(node)
1464 parents = store.parents(node)
1465
1465
1466 fm.startitem()
1466 fm.startitem()
1467 fm.write(b'rev', b'%6d ', rev)
1467 fm.write(b'rev', b'%6d ', rev)
1468 fm.write(b'linkrev', b'%7d ', store.linkrev(rev))
1468 fm.write(b'linkrev', b'%7d ', store.linkrev(rev))
1469 fm.write(b'node', b'%s ', shortfn(node))
1469 fm.write(b'node', b'%s ', shortfn(node))
1470 fm.write(b'p1', b'%s ', shortfn(parents[0]))
1470 fm.write(b'p1', b'%s ', shortfn(parents[0]))
1471 fm.write(b'p2', b'%s', shortfn(parents[1]))
1471 fm.write(b'p2', b'%s', shortfn(parents[1]))
1472 fm.plain(b'\n')
1472 fm.plain(b'\n')
1473
1473
1474 fm.end()
1474 fm.end()
1475
1475
1476
1476
1477 @command(
1477 @command(
1478 b'debugindexdot',
1478 b'debugindexdot',
1479 cmdutil.debugrevlogopts,
1479 cmdutil.debugrevlogopts,
1480 _(b'-c|-m|FILE'),
1480 _(b'-c|-m|FILE'),
1481 optionalrepo=True,
1481 optionalrepo=True,
1482 )
1482 )
1483 def debugindexdot(ui, repo, file_=None, **opts):
1483 def debugindexdot(ui, repo, file_=None, **opts):
1484 """dump an index DAG as a graphviz dot file"""
1484 """dump an index DAG as a graphviz dot file"""
1485 opts = pycompat.byteskwargs(opts)
1485 opts = pycompat.byteskwargs(opts)
1486 r = cmdutil.openstorage(repo, b'debugindexdot', file_, opts)
1486 r = cmdutil.openstorage(repo, b'debugindexdot', file_, opts)
1487 ui.writenoi18n(b"digraph G {\n")
1487 ui.writenoi18n(b"digraph G {\n")
1488 for i in r:
1488 for i in r:
1489 node = r.node(i)
1489 node = r.node(i)
1490 pp = r.parents(node)
1490 pp = r.parents(node)
1491 ui.write(b"\t%d -> %d\n" % (r.rev(pp[0]), i))
1491 ui.write(b"\t%d -> %d\n" % (r.rev(pp[0]), i))
1492 if pp[1] != nullid:
1492 if pp[1] != nullid:
1493 ui.write(b"\t%d -> %d\n" % (r.rev(pp[1]), i))
1493 ui.write(b"\t%d -> %d\n" % (r.rev(pp[1]), i))
1494 ui.write(b"}\n")
1494 ui.write(b"}\n")
1495
1495
1496
1496
1497 @command(b'debugindexstats', [])
1497 @command(b'debugindexstats', [])
1498 def debugindexstats(ui, repo):
1498 def debugindexstats(ui, repo):
1499 """show stats related to the changelog index"""
1499 """show stats related to the changelog index"""
1500 repo.changelog.shortest(nullid, 1)
1500 repo.changelog.shortest(nullid, 1)
1501 index = repo.changelog.index
1501 index = repo.changelog.index
1502 if not util.safehasattr(index, b'stats'):
1502 if not util.safehasattr(index, b'stats'):
1503 raise error.Abort(_(b'debugindexstats only works with native code'))
1503 raise error.Abort(_(b'debugindexstats only works with native code'))
1504 for k, v in sorted(index.stats().items()):
1504 for k, v in sorted(index.stats().items()):
1505 ui.write(b'%s: %d\n' % (k, v))
1505 ui.write(b'%s: %d\n' % (k, v))
1506
1506
1507
1507
1508 @command(b'debuginstall', [] + cmdutil.formatteropts, b'', norepo=True)
1508 @command(b'debuginstall', [] + cmdutil.formatteropts, b'', norepo=True)
1509 def debuginstall(ui, **opts):
1509 def debuginstall(ui, **opts):
1510 '''test Mercurial installation
1510 '''test Mercurial installation
1511
1511
1512 Returns 0 on success.
1512 Returns 0 on success.
1513 '''
1513 '''
1514 opts = pycompat.byteskwargs(opts)
1514 opts = pycompat.byteskwargs(opts)
1515
1515
1516 problems = 0
1516 problems = 0
1517
1517
1518 fm = ui.formatter(b'debuginstall', opts)
1518 fm = ui.formatter(b'debuginstall', opts)
1519 fm.startitem()
1519 fm.startitem()
1520
1520
1521 # encoding might be unknown or wrong. don't translate these messages.
1521 # encoding might be unknown or wrong. don't translate these messages.
1522 fm.write(b'encoding', b"checking encoding (%s)...\n", encoding.encoding)
1522 fm.write(b'encoding', b"checking encoding (%s)...\n", encoding.encoding)
1523 err = None
1523 err = None
1524 try:
1524 try:
1525 codecs.lookup(pycompat.sysstr(encoding.encoding))
1525 codecs.lookup(pycompat.sysstr(encoding.encoding))
1526 except LookupError as inst:
1526 except LookupError as inst:
1527 err = stringutil.forcebytestr(inst)
1527 err = stringutil.forcebytestr(inst)
1528 problems += 1
1528 problems += 1
1529 fm.condwrite(
1529 fm.condwrite(
1530 err,
1530 err,
1531 b'encodingerror',
1531 b'encodingerror',
1532 b" %s\n (check that your locale is properly set)\n",
1532 b" %s\n (check that your locale is properly set)\n",
1533 err,
1533 err,
1534 )
1534 )
1535
1535
1536 # Python
1536 # Python
1537 pythonlib = None
1537 pythonlib = None
1538 if util.safehasattr(os, '__file__'):
1538 if util.safehasattr(os, '__file__'):
1539 pythonlib = os.path.dirname(pycompat.fsencode(os.__file__))
1539 pythonlib = os.path.dirname(pycompat.fsencode(os.__file__))
1540 elif getattr(sys, 'oxidized', False):
1540 elif getattr(sys, 'oxidized', False):
1541 pythonlib = pycompat.sysexecutable
1541 pythonlib = pycompat.sysexecutable
1542
1542
1543 fm.write(
1543 fm.write(
1544 b'pythonexe',
1544 b'pythonexe',
1545 _(b"checking Python executable (%s)\n"),
1545 _(b"checking Python executable (%s)\n"),
1546 pycompat.sysexecutable or _(b"unknown"),
1546 pycompat.sysexecutable or _(b"unknown"),
1547 )
1547 )
1548 fm.write(
1548 fm.write(
1549 b'pythonimplementation',
1549 b'pythonimplementation',
1550 _(b"checking Python implementation (%s)\n"),
1550 _(b"checking Python implementation (%s)\n"),
1551 pycompat.sysbytes(platform.python_implementation()),
1551 pycompat.sysbytes(platform.python_implementation()),
1552 )
1552 )
1553 fm.write(
1553 fm.write(
1554 b'pythonver',
1554 b'pythonver',
1555 _(b"checking Python version (%s)\n"),
1555 _(b"checking Python version (%s)\n"),
1556 (b"%d.%d.%d" % sys.version_info[:3]),
1556 (b"%d.%d.%d" % sys.version_info[:3]),
1557 )
1557 )
1558 fm.write(
1558 fm.write(
1559 b'pythonlib',
1559 b'pythonlib',
1560 _(b"checking Python lib (%s)...\n"),
1560 _(b"checking Python lib (%s)...\n"),
1561 pythonlib or _(b"unknown"),
1561 pythonlib or _(b"unknown"),
1562 )
1562 )
1563
1563
1564 try:
1564 try:
1565 from . import rustext
1565 from . import rustext
1566
1566
1567 rustext.__doc__ # trigger lazy import
1567 rustext.__doc__ # trigger lazy import
1568 except ImportError:
1568 except ImportError:
1569 rustext = None
1569 rustext = None
1570
1570
1571 security = set(sslutil.supportedprotocols)
1571 security = set(sslutil.supportedprotocols)
1572 if sslutil.hassni:
1572 if sslutil.hassni:
1573 security.add(b'sni')
1573 security.add(b'sni')
1574
1574
1575 fm.write(
1575 fm.write(
1576 b'pythonsecurity',
1576 b'pythonsecurity',
1577 _(b"checking Python security support (%s)\n"),
1577 _(b"checking Python security support (%s)\n"),
1578 fm.formatlist(sorted(security), name=b'protocol', fmt=b'%s', sep=b','),
1578 fm.formatlist(sorted(security), name=b'protocol', fmt=b'%s', sep=b','),
1579 )
1579 )
1580
1580
1581 # These are warnings, not errors. So don't increment problem count. This
1581 # These are warnings, not errors. So don't increment problem count. This
1582 # may change in the future.
1582 # may change in the future.
1583 if b'tls1.2' not in security:
1583 if b'tls1.2' not in security:
1584 fm.plain(
1584 fm.plain(
1585 _(
1585 _(
1586 b' TLS 1.2 not supported by Python install; '
1586 b' TLS 1.2 not supported by Python install; '
1587 b'network connections lack modern security\n'
1587 b'network connections lack modern security\n'
1588 )
1588 )
1589 )
1589 )
1590 if b'sni' not in security:
1590 if b'sni' not in security:
1591 fm.plain(
1591 fm.plain(
1592 _(
1592 _(
1593 b' SNI not supported by Python install; may have '
1593 b' SNI not supported by Python install; may have '
1594 b'connectivity issues with some servers\n'
1594 b'connectivity issues with some servers\n'
1595 )
1595 )
1596 )
1596 )
1597
1597
1598 fm.plain(
1598 fm.plain(
1599 _(
1599 _(
1600 b"checking Rust extensions (%s)\n"
1600 b"checking Rust extensions (%s)\n"
1601 % (b'missing' if rustext is None else b'installed')
1601 % (b'missing' if rustext is None else b'installed')
1602 ),
1602 ),
1603 )
1603 )
1604
1604
1605 # TODO print CA cert info
1605 # TODO print CA cert info
1606
1606
1607 # hg version
1607 # hg version
1608 hgver = util.version()
1608 hgver = util.version()
1609 fm.write(
1609 fm.write(
1610 b'hgver', _(b"checking Mercurial version (%s)\n"), hgver.split(b'+')[0]
1610 b'hgver', _(b"checking Mercurial version (%s)\n"), hgver.split(b'+')[0]
1611 )
1611 )
1612 fm.write(
1612 fm.write(
1613 b'hgverextra',
1613 b'hgverextra',
1614 _(b"checking Mercurial custom build (%s)\n"),
1614 _(b"checking Mercurial custom build (%s)\n"),
1615 b'+'.join(hgver.split(b'+')[1:]),
1615 b'+'.join(hgver.split(b'+')[1:]),
1616 )
1616 )
1617
1617
1618 # compiled modules
1618 # compiled modules
1619 hgmodules = None
1619 hgmodules = None
1620 if util.safehasattr(sys.modules[__name__], '__file__'):
1620 if util.safehasattr(sys.modules[__name__], '__file__'):
1621 hgmodules = os.path.dirname(pycompat.fsencode(__file__))
1621 hgmodules = os.path.dirname(pycompat.fsencode(__file__))
1622 elif getattr(sys, 'oxidized', False):
1622 elif getattr(sys, 'oxidized', False):
1623 hgmodules = pycompat.sysexecutable
1623 hgmodules = pycompat.sysexecutable
1624
1624
1625 fm.write(
1625 fm.write(
1626 b'hgmodulepolicy', _(b"checking module policy (%s)\n"), policy.policy
1626 b'hgmodulepolicy', _(b"checking module policy (%s)\n"), policy.policy
1627 )
1627 )
1628 fm.write(
1628 fm.write(
1629 b'hgmodules',
1629 b'hgmodules',
1630 _(b"checking installed modules (%s)...\n"),
1630 _(b"checking installed modules (%s)...\n"),
1631 hgmodules or _(b"unknown"),
1631 hgmodules or _(b"unknown"),
1632 )
1632 )
1633
1633
1634 rustandc = policy.policy in (b'rust+c', b'rust+c-allow')
1634 rustandc = policy.policy in (b'rust+c', b'rust+c-allow')
1635 rustext = rustandc # for now, that's the only case
1635 rustext = rustandc # for now, that's the only case
1636 cext = policy.policy in (b'c', b'allow') or rustandc
1636 cext = policy.policy in (b'c', b'allow') or rustandc
1637 nopure = cext or rustext
1637 nopure = cext or rustext
1638 if nopure:
1638 if nopure:
1639 err = None
1639 err = None
1640 try:
1640 try:
1641 if cext:
1641 if cext:
1642 from .cext import ( # pytype: disable=import-error
1642 from .cext import ( # pytype: disable=import-error
1643 base85,
1643 base85,
1644 bdiff,
1644 bdiff,
1645 mpatch,
1645 mpatch,
1646 osutil,
1646 osutil,
1647 )
1647 )
1648
1648
1649 # quiet pyflakes
1649 # quiet pyflakes
1650 dir(bdiff), dir(mpatch), dir(base85), dir(osutil)
1650 dir(bdiff), dir(mpatch), dir(base85), dir(osutil)
1651 if rustext:
1651 if rustext:
1652 from .rustext import ( # pytype: disable=import-error
1652 from .rustext import ( # pytype: disable=import-error
1653 ancestor,
1653 ancestor,
1654 dirstate,
1654 dirstate,
1655 )
1655 )
1656
1656
1657 dir(ancestor), dir(dirstate) # quiet pyflakes
1657 dir(ancestor), dir(dirstate) # quiet pyflakes
1658 except Exception as inst:
1658 except Exception as inst:
1659 err = stringutil.forcebytestr(inst)
1659 err = stringutil.forcebytestr(inst)
1660 problems += 1
1660 problems += 1
1661 fm.condwrite(err, b'extensionserror', b" %s\n", err)
1661 fm.condwrite(err, b'extensionserror', b" %s\n", err)
1662
1662
1663 compengines = util.compengines._engines.values()
1663 compengines = util.compengines._engines.values()
1664 fm.write(
1664 fm.write(
1665 b'compengines',
1665 b'compengines',
1666 _(b'checking registered compression engines (%s)\n'),
1666 _(b'checking registered compression engines (%s)\n'),
1667 fm.formatlist(
1667 fm.formatlist(
1668 sorted(e.name() for e in compengines),
1668 sorted(e.name() for e in compengines),
1669 name=b'compengine',
1669 name=b'compengine',
1670 fmt=b'%s',
1670 fmt=b'%s',
1671 sep=b', ',
1671 sep=b', ',
1672 ),
1672 ),
1673 )
1673 )
1674 fm.write(
1674 fm.write(
1675 b'compenginesavail',
1675 b'compenginesavail',
1676 _(b'checking available compression engines (%s)\n'),
1676 _(b'checking available compression engines (%s)\n'),
1677 fm.formatlist(
1677 fm.formatlist(
1678 sorted(e.name() for e in compengines if e.available()),
1678 sorted(e.name() for e in compengines if e.available()),
1679 name=b'compengine',
1679 name=b'compengine',
1680 fmt=b'%s',
1680 fmt=b'%s',
1681 sep=b', ',
1681 sep=b', ',
1682 ),
1682 ),
1683 )
1683 )
1684 wirecompengines = compression.compengines.supportedwireengines(
1684 wirecompengines = compression.compengines.supportedwireengines(
1685 compression.SERVERROLE
1685 compression.SERVERROLE
1686 )
1686 )
1687 fm.write(
1687 fm.write(
1688 b'compenginesserver',
1688 b'compenginesserver',
1689 _(
1689 _(
1690 b'checking available compression engines '
1690 b'checking available compression engines '
1691 b'for wire protocol (%s)\n'
1691 b'for wire protocol (%s)\n'
1692 ),
1692 ),
1693 fm.formatlist(
1693 fm.formatlist(
1694 [e.name() for e in wirecompengines if e.wireprotosupport()],
1694 [e.name() for e in wirecompengines if e.wireprotosupport()],
1695 name=b'compengine',
1695 name=b'compengine',
1696 fmt=b'%s',
1696 fmt=b'%s',
1697 sep=b', ',
1697 sep=b', ',
1698 ),
1698 ),
1699 )
1699 )
1700 re2 = b'missing'
1700 re2 = b'missing'
1701 if util._re2:
1701 if util._re2:
1702 re2 = b'available'
1702 re2 = b'available'
1703 fm.plain(_(b'checking "re2" regexp engine (%s)\n') % re2)
1703 fm.plain(_(b'checking "re2" regexp engine (%s)\n') % re2)
1704 fm.data(re2=bool(util._re2))
1704 fm.data(re2=bool(util._re2))
1705
1705
1706 # templates
1706 # templates
1707 p = templater.templatedir()
1707 p = templater.templatedir()
1708 fm.write(b'templatedirs', b'checking templates (%s)...\n', p or b'')
1708 fm.write(b'templatedirs', b'checking templates (%s)...\n', p or b'')
1709 fm.condwrite(not p, b'', _(b" no template directories found\n"))
1709 fm.condwrite(not p, b'', _(b" no template directories found\n"))
1710 if p:
1710 if p:
1711 (m, fp) = templater.try_open_template(b"map-cmdline.default")
1711 (m, fp) = templater.try_open_template(b"map-cmdline.default")
1712 if m:
1712 if m:
1713 # template found, check if it is working
1713 # template found, check if it is working
1714 err = None
1714 err = None
1715 try:
1715 try:
1716 templater.templater.frommapfile(m)
1716 templater.templater.frommapfile(m)
1717 except Exception as inst:
1717 except Exception as inst:
1718 err = stringutil.forcebytestr(inst)
1718 err = stringutil.forcebytestr(inst)
1719 p = None
1719 p = None
1720 fm.condwrite(err, b'defaulttemplateerror', b" %s\n", err)
1720 fm.condwrite(err, b'defaulttemplateerror', b" %s\n", err)
1721 else:
1721 else:
1722 p = None
1722 p = None
1723 fm.condwrite(
1723 fm.condwrite(
1724 p, b'defaulttemplate', _(b"checking default template (%s)\n"), m
1724 p, b'defaulttemplate', _(b"checking default template (%s)\n"), m
1725 )
1725 )
1726 fm.condwrite(
1726 fm.condwrite(
1727 not m,
1727 not m,
1728 b'defaulttemplatenotfound',
1728 b'defaulttemplatenotfound',
1729 _(b" template '%s' not found\n"),
1729 _(b" template '%s' not found\n"),
1730 b"default",
1730 b"default",
1731 )
1731 )
1732 if not p:
1732 if not p:
1733 problems += 1
1733 problems += 1
1734 fm.condwrite(
1734 fm.condwrite(
1735 not p, b'', _(b" (templates seem to have been installed incorrectly)\n")
1735 not p, b'', _(b" (templates seem to have been installed incorrectly)\n")
1736 )
1736 )
1737
1737
1738 # editor
1738 # editor
1739 editor = ui.geteditor()
1739 editor = ui.geteditor()
1740 editor = util.expandpath(editor)
1740 editor = util.expandpath(editor)
1741 editorbin = procutil.shellsplit(editor)[0]
1741 editorbin = procutil.shellsplit(editor)[0]
1742 fm.write(b'editor', _(b"checking commit editor... (%s)\n"), editorbin)
1742 fm.write(b'editor', _(b"checking commit editor... (%s)\n"), editorbin)
1743 cmdpath = procutil.findexe(editorbin)
1743 cmdpath = procutil.findexe(editorbin)
1744 fm.condwrite(
1744 fm.condwrite(
1745 not cmdpath and editor == b'vi',
1745 not cmdpath and editor == b'vi',
1746 b'vinotfound',
1746 b'vinotfound',
1747 _(
1747 _(
1748 b" No commit editor set and can't find %s in PATH\n"
1748 b" No commit editor set and can't find %s in PATH\n"
1749 b" (specify a commit editor in your configuration"
1749 b" (specify a commit editor in your configuration"
1750 b" file)\n"
1750 b" file)\n"
1751 ),
1751 ),
1752 not cmdpath and editor == b'vi' and editorbin,
1752 not cmdpath and editor == b'vi' and editorbin,
1753 )
1753 )
1754 fm.condwrite(
1754 fm.condwrite(
1755 not cmdpath and editor != b'vi',
1755 not cmdpath and editor != b'vi',
1756 b'editornotfound',
1756 b'editornotfound',
1757 _(
1757 _(
1758 b" Can't find editor '%s' in PATH\n"
1758 b" Can't find editor '%s' in PATH\n"
1759 b" (specify a commit editor in your configuration"
1759 b" (specify a commit editor in your configuration"
1760 b" file)\n"
1760 b" file)\n"
1761 ),
1761 ),
1762 not cmdpath and editorbin,
1762 not cmdpath and editorbin,
1763 )
1763 )
1764 if not cmdpath and editor != b'vi':
1764 if not cmdpath and editor != b'vi':
1765 problems += 1
1765 problems += 1
1766
1766
1767 # check username
1767 # check username
1768 username = None
1768 username = None
1769 err = None
1769 err = None
1770 try:
1770 try:
1771 username = ui.username()
1771 username = ui.username()
1772 except error.Abort as e:
1772 except error.Abort as e:
1773 err = e.message
1773 err = e.message
1774 problems += 1
1774 problems += 1
1775
1775
1776 fm.condwrite(
1776 fm.condwrite(
1777 username, b'username', _(b"checking username (%s)\n"), username
1777 username, b'username', _(b"checking username (%s)\n"), username
1778 )
1778 )
1779 fm.condwrite(
1779 fm.condwrite(
1780 err,
1780 err,
1781 b'usernameerror',
1781 b'usernameerror',
1782 _(
1782 _(
1783 b"checking username...\n %s\n"
1783 b"checking username...\n %s\n"
1784 b" (specify a username in your configuration file)\n"
1784 b" (specify a username in your configuration file)\n"
1785 ),
1785 ),
1786 err,
1786 err,
1787 )
1787 )
1788
1788
1789 for name, mod in extensions.extensions():
1789 for name, mod in extensions.extensions():
1790 handler = getattr(mod, 'debuginstall', None)
1790 handler = getattr(mod, 'debuginstall', None)
1791 if handler is not None:
1791 if handler is not None:
1792 problems += handler(ui, fm)
1792 problems += handler(ui, fm)
1793
1793
1794 fm.condwrite(not problems, b'', _(b"no problems detected\n"))
1794 fm.condwrite(not problems, b'', _(b"no problems detected\n"))
1795 if not problems:
1795 if not problems:
1796 fm.data(problems=problems)
1796 fm.data(problems=problems)
1797 fm.condwrite(
1797 fm.condwrite(
1798 problems,
1798 problems,
1799 b'problems',
1799 b'problems',
1800 _(b"%d problems detected, please check your install!\n"),
1800 _(b"%d problems detected, please check your install!\n"),
1801 problems,
1801 problems,
1802 )
1802 )
1803 fm.end()
1803 fm.end()
1804
1804
1805 return problems
1805 return problems
1806
1806
1807
1807
1808 @command(b'debugknown', [], _(b'REPO ID...'), norepo=True)
1808 @command(b'debugknown', [], _(b'REPO ID...'), norepo=True)
1809 def debugknown(ui, repopath, *ids, **opts):
1809 def debugknown(ui, repopath, *ids, **opts):
1810 """test whether node ids are known to a repo
1810 """test whether node ids are known to a repo
1811
1811
1812 Every ID must be a full-length hex node id string. Returns a list of 0s
1812 Every ID must be a full-length hex node id string. Returns a list of 0s
1813 and 1s indicating unknown/known.
1813 and 1s indicating unknown/known.
1814 """
1814 """
1815 opts = pycompat.byteskwargs(opts)
1815 opts = pycompat.byteskwargs(opts)
1816 repo = hg.peer(ui, opts, repopath)
1816 repo = hg.peer(ui, opts, repopath)
1817 if not repo.capable(b'known'):
1817 if not repo.capable(b'known'):
1818 raise error.Abort(b"known() not supported by target repository")
1818 raise error.Abort(b"known() not supported by target repository")
1819 flags = repo.known([bin(s) for s in ids])
1819 flags = repo.known([bin(s) for s in ids])
1820 ui.write(b"%s\n" % (b"".join([f and b"1" or b"0" for f in flags])))
1820 ui.write(b"%s\n" % (b"".join([f and b"1" or b"0" for f in flags])))
1821
1821
1822
1822
1823 @command(b'debuglabelcomplete', [], _(b'LABEL...'))
1823 @command(b'debuglabelcomplete', [], _(b'LABEL...'))
1824 def debuglabelcomplete(ui, repo, *args):
1824 def debuglabelcomplete(ui, repo, *args):
1825 '''backwards compatibility with old bash completion scripts (DEPRECATED)'''
1825 '''backwards compatibility with old bash completion scripts (DEPRECATED)'''
1826 debugnamecomplete(ui, repo, *args)
1826 debugnamecomplete(ui, repo, *args)
1827
1827
1828
1828
1829 @command(
1829 @command(
1830 b'debuglocks',
1830 b'debuglocks',
1831 [
1831 [
1832 (b'L', b'force-lock', None, _(b'free the store lock (DANGEROUS)')),
1832 (b'L', b'force-lock', None, _(b'free the store lock (DANGEROUS)')),
1833 (
1833 (
1834 b'W',
1834 b'W',
1835 b'force-wlock',
1835 b'force-wlock',
1836 None,
1836 None,
1837 _(b'free the working state lock (DANGEROUS)'),
1837 _(b'free the working state lock (DANGEROUS)'),
1838 ),
1838 ),
1839 (b's', b'set-lock', None, _(b'set the store lock until stopped')),
1839 (b's', b'set-lock', None, _(b'set the store lock until stopped')),
1840 (
1840 (
1841 b'S',
1841 b'S',
1842 b'set-wlock',
1842 b'set-wlock',
1843 None,
1843 None,
1844 _(b'set the working state lock until stopped'),
1844 _(b'set the working state lock until stopped'),
1845 ),
1845 ),
1846 ],
1846 ],
1847 _(b'[OPTION]...'),
1847 _(b'[OPTION]...'),
1848 )
1848 )
1849 def debuglocks(ui, repo, **opts):
1849 def debuglocks(ui, repo, **opts):
1850 """show or modify state of locks
1850 """show or modify state of locks
1851
1851
1852 By default, this command will show which locks are held. This
1852 By default, this command will show which locks are held. This
1853 includes the user and process holding the lock, the amount of time
1853 includes the user and process holding the lock, the amount of time
1854 the lock has been held, and the machine name where the process is
1854 the lock has been held, and the machine name where the process is
1855 running if it's not local.
1855 running if it's not local.
1856
1856
1857 Locks protect the integrity of Mercurial's data, so should be
1857 Locks protect the integrity of Mercurial's data, so should be
1858 treated with care. System crashes or other interruptions may cause
1858 treated with care. System crashes or other interruptions may cause
1859 locks to not be properly released, though Mercurial will usually
1859 locks to not be properly released, though Mercurial will usually
1860 detect and remove such stale locks automatically.
1860 detect and remove such stale locks automatically.
1861
1861
1862 However, detecting stale locks may not always be possible (for
1862 However, detecting stale locks may not always be possible (for
1863 instance, on a shared filesystem). Removing locks may also be
1863 instance, on a shared filesystem). Removing locks may also be
1864 blocked by filesystem permissions.
1864 blocked by filesystem permissions.
1865
1865
1866 Setting a lock will prevent other commands from changing the data.
1866 Setting a lock will prevent other commands from changing the data.
1867 The command will wait until an interruption (SIGINT, SIGTERM, ...) occurs.
1867 The command will wait until an interruption (SIGINT, SIGTERM, ...) occurs.
1868 The set locks are removed when the command exits.
1868 The set locks are removed when the command exits.
1869
1869
1870 Returns 0 if no locks are held.
1870 Returns 0 if no locks are held.
1871
1871
1872 """
1872 """
1873
1873
1874 if opts.get('force_lock'):
1874 if opts.get('force_lock'):
1875 repo.svfs.unlink(b'lock')
1875 repo.svfs.unlink(b'lock')
1876 if opts.get('force_wlock'):
1876 if opts.get('force_wlock'):
1877 repo.vfs.unlink(b'wlock')
1877 repo.vfs.unlink(b'wlock')
1878 if opts.get('force_lock') or opts.get('force_wlock'):
1878 if opts.get('force_lock') or opts.get('force_wlock'):
1879 return 0
1879 return 0
1880
1880
1881 locks = []
1881 locks = []
1882 try:
1882 try:
1883 if opts.get('set_wlock'):
1883 if opts.get('set_wlock'):
1884 try:
1884 try:
1885 locks.append(repo.wlock(False))
1885 locks.append(repo.wlock(False))
1886 except error.LockHeld:
1886 except error.LockHeld:
1887 raise error.Abort(_(b'wlock is already held'))
1887 raise error.Abort(_(b'wlock is already held'))
1888 if opts.get('set_lock'):
1888 if opts.get('set_lock'):
1889 try:
1889 try:
1890 locks.append(repo.lock(False))
1890 locks.append(repo.lock(False))
1891 except error.LockHeld:
1891 except error.LockHeld:
1892 raise error.Abort(_(b'lock is already held'))
1892 raise error.Abort(_(b'lock is already held'))
1893 if len(locks):
1893 if len(locks):
1894 ui.promptchoice(_(b"ready to release the lock (y)? $$ &Yes"))
1894 ui.promptchoice(_(b"ready to release the lock (y)? $$ &Yes"))
1895 return 0
1895 return 0
1896 finally:
1896 finally:
1897 release(*locks)
1897 release(*locks)
1898
1898
1899 now = time.time()
1899 now = time.time()
1900 held = 0
1900 held = 0
1901
1901
1902 def report(vfs, name, method):
1902 def report(vfs, name, method):
1903 # this causes stale locks to get reaped for more accurate reporting
1903 # this causes stale locks to get reaped for more accurate reporting
1904 try:
1904 try:
1905 l = method(False)
1905 l = method(False)
1906 except error.LockHeld:
1906 except error.LockHeld:
1907 l = None
1907 l = None
1908
1908
1909 if l:
1909 if l:
1910 l.release()
1910 l.release()
1911 else:
1911 else:
1912 try:
1912 try:
1913 st = vfs.lstat(name)
1913 st = vfs.lstat(name)
1914 age = now - st[stat.ST_MTIME]
1914 age = now - st[stat.ST_MTIME]
1915 user = util.username(st.st_uid)
1915 user = util.username(st.st_uid)
1916 locker = vfs.readlock(name)
1916 locker = vfs.readlock(name)
1917 if b":" in locker:
1917 if b":" in locker:
1918 host, pid = locker.split(b':')
1918 host, pid = locker.split(b':')
1919 if host == socket.gethostname():
1919 if host == socket.gethostname():
1920 locker = b'user %s, process %s' % (user or b'None', pid)
1920 locker = b'user %s, process %s' % (user or b'None', pid)
1921 else:
1921 else:
1922 locker = b'user %s, process %s, host %s' % (
1922 locker = b'user %s, process %s, host %s' % (
1923 user or b'None',
1923 user or b'None',
1924 pid,
1924 pid,
1925 host,
1925 host,
1926 )
1926 )
1927 ui.writenoi18n(b"%-6s %s (%ds)\n" % (name + b":", locker, age))
1927 ui.writenoi18n(b"%-6s %s (%ds)\n" % (name + b":", locker, age))
1928 return 1
1928 return 1
1929 except OSError as e:
1929 except OSError as e:
1930 if e.errno != errno.ENOENT:
1930 if e.errno != errno.ENOENT:
1931 raise
1931 raise
1932
1932
1933 ui.writenoi18n(b"%-6s free\n" % (name + b":"))
1933 ui.writenoi18n(b"%-6s free\n" % (name + b":"))
1934 return 0
1934 return 0
1935
1935
1936 held += report(repo.svfs, b"lock", repo.lock)
1936 held += report(repo.svfs, b"lock", repo.lock)
1937 held += report(repo.vfs, b"wlock", repo.wlock)
1937 held += report(repo.vfs, b"wlock", repo.wlock)
1938
1938
1939 return held
1939 return held
1940
1940
1941
1941
1942 @command(
1942 @command(
1943 b'debugmanifestfulltextcache',
1943 b'debugmanifestfulltextcache',
1944 [
1944 [
1945 (b'', b'clear', False, _(b'clear the cache')),
1945 (b'', b'clear', False, _(b'clear the cache')),
1946 (
1946 (
1947 b'a',
1947 b'a',
1948 b'add',
1948 b'add',
1949 [],
1949 [],
1950 _(b'add the given manifest nodes to the cache'),
1950 _(b'add the given manifest nodes to the cache'),
1951 _(b'NODE'),
1951 _(b'NODE'),
1952 ),
1952 ),
1953 ],
1953 ],
1954 b'',
1954 b'',
1955 )
1955 )
1956 def debugmanifestfulltextcache(ui, repo, add=(), **opts):
1956 def debugmanifestfulltextcache(ui, repo, add=(), **opts):
1957 """show, clear or amend the contents of the manifest fulltext cache"""
1957 """show, clear or amend the contents of the manifest fulltext cache"""
1958
1958
1959 def getcache():
1959 def getcache():
1960 r = repo.manifestlog.getstorage(b'')
1960 r = repo.manifestlog.getstorage(b'')
1961 try:
1961 try:
1962 return r._fulltextcache
1962 return r._fulltextcache
1963 except AttributeError:
1963 except AttributeError:
1964 msg = _(
1964 msg = _(
1965 b"Current revlog implementation doesn't appear to have a "
1965 b"Current revlog implementation doesn't appear to have a "
1966 b"manifest fulltext cache\n"
1966 b"manifest fulltext cache\n"
1967 )
1967 )
1968 raise error.Abort(msg)
1968 raise error.Abort(msg)
1969
1969
1970 if opts.get('clear'):
1970 if opts.get('clear'):
1971 with repo.wlock():
1971 with repo.wlock():
1972 cache = getcache()
1972 cache = getcache()
1973 cache.clear(clear_persisted_data=True)
1973 cache.clear(clear_persisted_data=True)
1974 return
1974 return
1975
1975
1976 if add:
1976 if add:
1977 with repo.wlock():
1977 with repo.wlock():
1978 m = repo.manifestlog
1978 m = repo.manifestlog
1979 store = m.getstorage(b'')
1979 store = m.getstorage(b'')
1980 for n in add:
1980 for n in add:
1981 try:
1981 try:
1982 manifest = m[store.lookup(n)]
1982 manifest = m[store.lookup(n)]
1983 except error.LookupError as e:
1983 except error.LookupError as e:
1984 raise error.Abort(e, hint=b"Check your manifest node id")
1984 raise error.Abort(e, hint=b"Check your manifest node id")
1985 manifest.read() # stores revisision in cache too
1985 manifest.read() # stores revisision in cache too
1986 return
1986 return
1987
1987
1988 cache = getcache()
1988 cache = getcache()
1989 if not len(cache):
1989 if not len(cache):
1990 ui.write(_(b'cache empty\n'))
1990 ui.write(_(b'cache empty\n'))
1991 else:
1991 else:
1992 ui.write(
1992 ui.write(
1993 _(
1993 _(
1994 b'cache contains %d manifest entries, in order of most to '
1994 b'cache contains %d manifest entries, in order of most to '
1995 b'least recent:\n'
1995 b'least recent:\n'
1996 )
1996 )
1997 % (len(cache),)
1997 % (len(cache),)
1998 )
1998 )
1999 totalsize = 0
1999 totalsize = 0
2000 for nodeid in cache:
2000 for nodeid in cache:
2001 # Use cache.get to not update the LRU order
2001 # Use cache.get to not update the LRU order
2002 data = cache.peek(nodeid)
2002 data = cache.peek(nodeid)
2003 size = len(data)
2003 size = len(data)
2004 totalsize += size + 24 # 20 bytes nodeid, 4 bytes size
2004 totalsize += size + 24 # 20 bytes nodeid, 4 bytes size
2005 ui.write(
2005 ui.write(
2006 _(b'id: %s, size %s\n') % (hex(nodeid), util.bytecount(size))
2006 _(b'id: %s, size %s\n') % (hex(nodeid), util.bytecount(size))
2007 )
2007 )
2008 ondisk = cache._opener.stat(b'manifestfulltextcache').st_size
2008 ondisk = cache._opener.stat(b'manifestfulltextcache').st_size
2009 ui.write(
2009 ui.write(
2010 _(b'total cache data size %s, on-disk %s\n')
2010 _(b'total cache data size %s, on-disk %s\n')
2011 % (util.bytecount(totalsize), util.bytecount(ondisk))
2011 % (util.bytecount(totalsize), util.bytecount(ondisk))
2012 )
2012 )
2013
2013
2014
2014
2015 @command(b'debugmergestate', [] + cmdutil.templateopts, b'')
2015 @command(b'debugmergestate', [] + cmdutil.templateopts, b'')
2016 def debugmergestate(ui, repo, *args, **opts):
2016 def debugmergestate(ui, repo, *args, **opts):
2017 """print merge state
2017 """print merge state
2018
2018
2019 Use --verbose to print out information about whether v1 or v2 merge state
2019 Use --verbose to print out information about whether v1 or v2 merge state
2020 was chosen."""
2020 was chosen."""
2021
2021
2022 if ui.verbose:
2022 if ui.verbose:
2023 ms = mergestatemod.mergestate(repo)
2023 ms = mergestatemod.mergestate(repo)
2024
2024
2025 # sort so that reasonable information is on top
2025 # sort so that reasonable information is on top
2026 v1records = ms._readrecordsv1()
2026 v1records = ms._readrecordsv1()
2027 v2records = ms._readrecordsv2()
2027 v2records = ms._readrecordsv2()
2028
2028
2029 if not v1records and not v2records:
2029 if not v1records and not v2records:
2030 pass
2030 pass
2031 elif not v2records:
2031 elif not v2records:
2032 ui.writenoi18n(b'no version 2 merge state\n')
2032 ui.writenoi18n(b'no version 2 merge state\n')
2033 elif ms._v1v2match(v1records, v2records):
2033 elif ms._v1v2match(v1records, v2records):
2034 ui.writenoi18n(b'v1 and v2 states match: using v2\n')
2034 ui.writenoi18n(b'v1 and v2 states match: using v2\n')
2035 else:
2035 else:
2036 ui.writenoi18n(b'v1 and v2 states mismatch: using v1\n')
2036 ui.writenoi18n(b'v1 and v2 states mismatch: using v1\n')
2037
2037
2038 opts = pycompat.byteskwargs(opts)
2038 opts = pycompat.byteskwargs(opts)
2039 if not opts[b'template']:
2039 if not opts[b'template']:
2040 opts[b'template'] = (
2040 opts[b'template'] = (
2041 b'{if(commits, "", "no merge state found\n")}'
2041 b'{if(commits, "", "no merge state found\n")}'
2042 b'{commits % "{name}{if(label, " ({label})")}: {node}\n"}'
2042 b'{commits % "{name}{if(label, " ({label})")}: {node}\n"}'
2043 b'{files % "file: {path} (state \\"{state}\\")\n'
2043 b'{files % "file: {path} (state \\"{state}\\")\n'
2044 b'{if(local_path, "'
2044 b'{if(local_path, "'
2045 b' local path: {local_path} (hash {local_key}, flags \\"{local_flags}\\")\n'
2045 b' local path: {local_path} (hash {local_key}, flags \\"{local_flags}\\")\n'
2046 b' ancestor path: {ancestor_path} (node {ancestor_node})\n'
2046 b' ancestor path: {ancestor_path} (node {ancestor_node})\n'
2047 b' other path: {other_path} (node {other_node})\n'
2047 b' other path: {other_path} (node {other_node})\n'
2048 b'")}'
2048 b'")}'
2049 b'{if(rename_side, "'
2049 b'{if(rename_side, "'
2050 b' rename side: {rename_side}\n'
2050 b' rename side: {rename_side}\n'
2051 b' renamed path: {renamed_path}\n'
2051 b' renamed path: {renamed_path}\n'
2052 b'")}'
2052 b'")}'
2053 b'{extras % " extra: {key} = {value}\n"}'
2053 b'{extras % " extra: {key} = {value}\n"}'
2054 b'"}'
2054 b'"}'
2055 b'{extras % "extra: {file} ({key} = {value})\n"}'
2055 b'{extras % "extra: {file} ({key} = {value})\n"}'
2056 )
2056 )
2057
2057
2058 ms = mergestatemod.mergestate.read(repo)
2058 ms = mergestatemod.mergestate.read(repo)
2059
2059
2060 fm = ui.formatter(b'debugmergestate', opts)
2060 fm = ui.formatter(b'debugmergestate', opts)
2061 fm.startitem()
2061 fm.startitem()
2062
2062
2063 fm_commits = fm.nested(b'commits')
2063 fm_commits = fm.nested(b'commits')
2064 if ms.active():
2064 if ms.active():
2065 for name, node, label_index in (
2065 for name, node, label_index in (
2066 (b'local', ms.local, 0),
2066 (b'local', ms.local, 0),
2067 (b'other', ms.other, 1),
2067 (b'other', ms.other, 1),
2068 ):
2068 ):
2069 fm_commits.startitem()
2069 fm_commits.startitem()
2070 fm_commits.data(name=name)
2070 fm_commits.data(name=name)
2071 fm_commits.data(node=hex(node))
2071 fm_commits.data(node=hex(node))
2072 if ms._labels and len(ms._labels) > label_index:
2072 if ms._labels and len(ms._labels) > label_index:
2073 fm_commits.data(label=ms._labels[label_index])
2073 fm_commits.data(label=ms._labels[label_index])
2074 fm_commits.end()
2074 fm_commits.end()
2075
2075
2076 fm_files = fm.nested(b'files')
2076 fm_files = fm.nested(b'files')
2077 if ms.active():
2077 if ms.active():
2078 for f in ms:
2078 for f in ms:
2079 fm_files.startitem()
2079 fm_files.startitem()
2080 fm_files.data(path=f)
2080 fm_files.data(path=f)
2081 state = ms._state[f]
2081 state = ms._state[f]
2082 fm_files.data(state=state[0])
2082 fm_files.data(state=state[0])
2083 if state[0] in (
2083 if state[0] in (
2084 mergestatemod.MERGE_RECORD_UNRESOLVED,
2084 mergestatemod.MERGE_RECORD_UNRESOLVED,
2085 mergestatemod.MERGE_RECORD_RESOLVED,
2085 mergestatemod.MERGE_RECORD_RESOLVED,
2086 ):
2086 ):
2087 fm_files.data(local_key=state[1])
2087 fm_files.data(local_key=state[1])
2088 fm_files.data(local_path=state[2])
2088 fm_files.data(local_path=state[2])
2089 fm_files.data(ancestor_path=state[3])
2089 fm_files.data(ancestor_path=state[3])
2090 fm_files.data(ancestor_node=state[4])
2090 fm_files.data(ancestor_node=state[4])
2091 fm_files.data(other_path=state[5])
2091 fm_files.data(other_path=state[5])
2092 fm_files.data(other_node=state[6])
2092 fm_files.data(other_node=state[6])
2093 fm_files.data(local_flags=state[7])
2093 fm_files.data(local_flags=state[7])
2094 elif state[0] in (
2094 elif state[0] in (
2095 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH,
2095 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH,
2096 mergestatemod.MERGE_RECORD_RESOLVED_PATH,
2096 mergestatemod.MERGE_RECORD_RESOLVED_PATH,
2097 ):
2097 ):
2098 fm_files.data(renamed_path=state[1])
2098 fm_files.data(renamed_path=state[1])
2099 fm_files.data(rename_side=state[2])
2099 fm_files.data(rename_side=state[2])
2100 fm_extras = fm_files.nested(b'extras')
2100 fm_extras = fm_files.nested(b'extras')
2101 for k, v in sorted(ms.extras(f).items()):
2101 for k, v in sorted(ms.extras(f).items()):
2102 fm_extras.startitem()
2102 fm_extras.startitem()
2103 fm_extras.data(key=k)
2103 fm_extras.data(key=k)
2104 fm_extras.data(value=v)
2104 fm_extras.data(value=v)
2105 fm_extras.end()
2105 fm_extras.end()
2106
2106
2107 fm_files.end()
2107 fm_files.end()
2108
2108
2109 fm_extras = fm.nested(b'extras')
2109 fm_extras = fm.nested(b'extras')
2110 for f, d in sorted(pycompat.iteritems(ms.allextras())):
2110 for f, d in sorted(pycompat.iteritems(ms.allextras())):
2111 if f in ms:
2111 if f in ms:
2112 # If file is in mergestate, we have already processed it's extras
2112 # If file is in mergestate, we have already processed it's extras
2113 continue
2113 continue
2114 for k, v in pycompat.iteritems(d):
2114 for k, v in pycompat.iteritems(d):
2115 fm_extras.startitem()
2115 fm_extras.startitem()
2116 fm_extras.data(file=f)
2116 fm_extras.data(file=f)
2117 fm_extras.data(key=k)
2117 fm_extras.data(key=k)
2118 fm_extras.data(value=v)
2118 fm_extras.data(value=v)
2119 fm_extras.end()
2119 fm_extras.end()
2120
2120
2121 fm.end()
2121 fm.end()
2122
2122
2123
2123
2124 @command(b'debugnamecomplete', [], _(b'NAME...'))
2124 @command(b'debugnamecomplete', [], _(b'NAME...'))
2125 def debugnamecomplete(ui, repo, *args):
2125 def debugnamecomplete(ui, repo, *args):
2126 '''complete "names" - tags, open branch names, bookmark names'''
2126 '''complete "names" - tags, open branch names, bookmark names'''
2127
2127
2128 names = set()
2128 names = set()
2129 # since we previously only listed open branches, we will handle that
2129 # since we previously only listed open branches, we will handle that
2130 # specially (after this for loop)
2130 # specially (after this for loop)
2131 for name, ns in pycompat.iteritems(repo.names):
2131 for name, ns in pycompat.iteritems(repo.names):
2132 if name != b'branches':
2132 if name != b'branches':
2133 names.update(ns.listnames(repo))
2133 names.update(ns.listnames(repo))
2134 names.update(
2134 names.update(
2135 tag
2135 tag
2136 for (tag, heads, tip, closed) in repo.branchmap().iterbranches()
2136 for (tag, heads, tip, closed) in repo.branchmap().iterbranches()
2137 if not closed
2137 if not closed
2138 )
2138 )
2139 completions = set()
2139 completions = set()
2140 if not args:
2140 if not args:
2141 args = [b'']
2141 args = [b'']
2142 for a in args:
2142 for a in args:
2143 completions.update(n for n in names if n.startswith(a))
2143 completions.update(n for n in names if n.startswith(a))
2144 ui.write(b'\n'.join(sorted(completions)))
2144 ui.write(b'\n'.join(sorted(completions)))
2145 ui.write(b'\n')
2145 ui.write(b'\n')
2146
2146
2147
2147
2148 @command(
2148 @command(
2149 b'debugnodemap',
2149 b'debugnodemap',
2150 [
2150 [
2151 (
2151 (
2152 b'',
2152 b'',
2153 b'dump-new',
2153 b'dump-new',
2154 False,
2154 False,
2155 _(b'write a (new) persistent binary nodemap on stdin'),
2155 _(b'write a (new) persistent binary nodemap on stdin'),
2156 ),
2156 ),
2157 (b'', b'dump-disk', False, _(b'dump on-disk data on stdin')),
2157 (b'', b'dump-disk', False, _(b'dump on-disk data on stdin')),
2158 (
2158 (
2159 b'',
2159 b'',
2160 b'check',
2160 b'check',
2161 False,
2161 False,
2162 _(b'check that the data on disk data are correct.'),
2162 _(b'check that the data on disk data are correct.'),
2163 ),
2163 ),
2164 (
2164 (
2165 b'',
2165 b'',
2166 b'metadata',
2166 b'metadata',
2167 False,
2167 False,
2168 _(b'display the on disk meta data for the nodemap'),
2168 _(b'display the on disk meta data for the nodemap'),
2169 ),
2169 ),
2170 ],
2170 ],
2171 )
2171 )
2172 def debugnodemap(ui, repo, **opts):
2172 def debugnodemap(ui, repo, **opts):
2173 """write and inspect on disk nodemap
2173 """write and inspect on disk nodemap
2174 """
2174 """
2175 if opts['dump_new']:
2175 if opts['dump_new']:
2176 unfi = repo.unfiltered()
2176 unfi = repo.unfiltered()
2177 cl = unfi.changelog
2177 cl = unfi.changelog
2178 if util.safehasattr(cl.index, "nodemap_data_all"):
2178 if util.safehasattr(cl.index, "nodemap_data_all"):
2179 data = cl.index.nodemap_data_all()
2179 data = cl.index.nodemap_data_all()
2180 else:
2180 else:
2181 data = nodemap.persistent_data(cl.index)
2181 data = nodemap.persistent_data(cl.index)
2182 ui.write(data)
2182 ui.write(data)
2183 elif opts['dump_disk']:
2183 elif opts['dump_disk']:
2184 unfi = repo.unfiltered()
2184 unfi = repo.unfiltered()
2185 cl = unfi.changelog
2185 cl = unfi.changelog
2186 nm_data = nodemap.persisted_data(cl)
2186 nm_data = nodemap.persisted_data(cl)
2187 if nm_data is not None:
2187 if nm_data is not None:
2188 docket, data = nm_data
2188 docket, data = nm_data
2189 ui.write(data[:])
2189 ui.write(data[:])
2190 elif opts['check']:
2190 elif opts['check']:
2191 unfi = repo.unfiltered()
2191 unfi = repo.unfiltered()
2192 cl = unfi.changelog
2192 cl = unfi.changelog
2193 nm_data = nodemap.persisted_data(cl)
2193 nm_data = nodemap.persisted_data(cl)
2194 if nm_data is not None:
2194 if nm_data is not None:
2195 docket, data = nm_data
2195 docket, data = nm_data
2196 return nodemap.check_data(ui, cl.index, data)
2196 return nodemap.check_data(ui, cl.index, data)
2197 elif opts['metadata']:
2197 elif opts['metadata']:
2198 unfi = repo.unfiltered()
2198 unfi = repo.unfiltered()
2199 cl = unfi.changelog
2199 cl = unfi.changelog
2200 nm_data = nodemap.persisted_data(cl)
2200 nm_data = nodemap.persisted_data(cl)
2201 if nm_data is not None:
2201 if nm_data is not None:
2202 docket, data = nm_data
2202 docket, data = nm_data
2203 ui.write((b"uid: %s\n") % docket.uid)
2203 ui.write((b"uid: %s\n") % docket.uid)
2204 ui.write((b"tip-rev: %d\n") % docket.tip_rev)
2204 ui.write((b"tip-rev: %d\n") % docket.tip_rev)
2205 ui.write((b"tip-node: %s\n") % hex(docket.tip_node))
2205 ui.write((b"tip-node: %s\n") % hex(docket.tip_node))
2206 ui.write((b"data-length: %d\n") % docket.data_length)
2206 ui.write((b"data-length: %d\n") % docket.data_length)
2207 ui.write((b"data-unused: %d\n") % docket.data_unused)
2207 ui.write((b"data-unused: %d\n") % docket.data_unused)
2208 unused_perc = docket.data_unused * 100.0 / docket.data_length
2208 unused_perc = docket.data_unused * 100.0 / docket.data_length
2209 ui.write((b"data-unused: %2.3f%%\n") % unused_perc)
2209 ui.write((b"data-unused: %2.3f%%\n") % unused_perc)
2210
2210
2211
2211
2212 @command(
2212 @command(
2213 b'debugobsolete',
2213 b'debugobsolete',
2214 [
2214 [
2215 (b'', b'flags', 0, _(b'markers flag')),
2215 (b'', b'flags', 0, _(b'markers flag')),
2216 (
2216 (
2217 b'',
2217 b'',
2218 b'record-parents',
2218 b'record-parents',
2219 False,
2219 False,
2220 _(b'record parent information for the precursor'),
2220 _(b'record parent information for the precursor'),
2221 ),
2221 ),
2222 (b'r', b'rev', [], _(b'display markers relevant to REV')),
2222 (b'r', b'rev', [], _(b'display markers relevant to REV')),
2223 (
2223 (
2224 b'',
2224 b'',
2225 b'exclusive',
2225 b'exclusive',
2226 False,
2226 False,
2227 _(b'restrict display to markers only relevant to REV'),
2227 _(b'restrict display to markers only relevant to REV'),
2228 ),
2228 ),
2229 (b'', b'index', False, _(b'display index of the marker')),
2229 (b'', b'index', False, _(b'display index of the marker')),
2230 (b'', b'delete', [], _(b'delete markers specified by indices')),
2230 (b'', b'delete', [], _(b'delete markers specified by indices')),
2231 ]
2231 ]
2232 + cmdutil.commitopts2
2232 + cmdutil.commitopts2
2233 + cmdutil.formatteropts,
2233 + cmdutil.formatteropts,
2234 _(b'[OBSOLETED [REPLACEMENT ...]]'),
2234 _(b'[OBSOLETED [REPLACEMENT ...]]'),
2235 )
2235 )
2236 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2236 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2237 """create arbitrary obsolete marker
2237 """create arbitrary obsolete marker
2238
2238
2239 With no arguments, displays the list of obsolescence markers."""
2239 With no arguments, displays the list of obsolescence markers."""
2240
2240
2241 opts = pycompat.byteskwargs(opts)
2241 opts = pycompat.byteskwargs(opts)
2242
2242
2243 def parsenodeid(s):
2243 def parsenodeid(s):
2244 try:
2244 try:
2245 # We do not use revsingle/revrange functions here to accept
2245 # We do not use revsingle/revrange functions here to accept
2246 # arbitrary node identifiers, possibly not present in the
2246 # arbitrary node identifiers, possibly not present in the
2247 # local repository.
2247 # local repository.
2248 n = bin(s)
2248 n = bin(s)
2249 if len(n) != len(nullid):
2249 if len(n) != len(nullid):
2250 raise TypeError()
2250 raise TypeError()
2251 return n
2251 return n
2252 except TypeError:
2252 except TypeError:
2253 raise error.Abort(
2253 raise error.Abort(
2254 b'changeset references must be full hexadecimal '
2254 b'changeset references must be full hexadecimal '
2255 b'node identifiers'
2255 b'node identifiers'
2256 )
2256 )
2257
2257
2258 if opts.get(b'delete'):
2258 if opts.get(b'delete'):
2259 indices = []
2259 indices = []
2260 for v in opts.get(b'delete'):
2260 for v in opts.get(b'delete'):
2261 try:
2261 try:
2262 indices.append(int(v))
2262 indices.append(int(v))
2263 except ValueError:
2263 except ValueError:
2264 raise error.Abort(
2264 raise error.Abort(
2265 _(b'invalid index value: %r') % v,
2265 _(b'invalid index value: %r') % v,
2266 hint=_(b'use integers for indices'),
2266 hint=_(b'use integers for indices'),
2267 )
2267 )
2268
2268
2269 if repo.currenttransaction():
2269 if repo.currenttransaction():
2270 raise error.Abort(
2270 raise error.Abort(
2271 _(b'cannot delete obsmarkers in the middle of transaction.')
2271 _(b'cannot delete obsmarkers in the middle of transaction.')
2272 )
2272 )
2273
2273
2274 with repo.lock():
2274 with repo.lock():
2275 n = repair.deleteobsmarkers(repo.obsstore, indices)
2275 n = repair.deleteobsmarkers(repo.obsstore, indices)
2276 ui.write(_(b'deleted %i obsolescence markers\n') % n)
2276 ui.write(_(b'deleted %i obsolescence markers\n') % n)
2277
2277
2278 return
2278 return
2279
2279
2280 if precursor is not None:
2280 if precursor is not None:
2281 if opts[b'rev']:
2281 if opts[b'rev']:
2282 raise error.Abort(b'cannot select revision when creating marker')
2282 raise error.Abort(b'cannot select revision when creating marker')
2283 metadata = {}
2283 metadata = {}
2284 metadata[b'user'] = encoding.fromlocal(opts[b'user'] or ui.username())
2284 metadata[b'user'] = encoding.fromlocal(opts[b'user'] or ui.username())
2285 succs = tuple(parsenodeid(succ) for succ in successors)
2285 succs = tuple(parsenodeid(succ) for succ in successors)
2286 l = repo.lock()
2286 l = repo.lock()
2287 try:
2287 try:
2288 tr = repo.transaction(b'debugobsolete')
2288 tr = repo.transaction(b'debugobsolete')
2289 try:
2289 try:
2290 date = opts.get(b'date')
2290 date = opts.get(b'date')
2291 if date:
2291 if date:
2292 date = dateutil.parsedate(date)
2292 date = dateutil.parsedate(date)
2293 else:
2293 else:
2294 date = None
2294 date = None
2295 prec = parsenodeid(precursor)
2295 prec = parsenodeid(precursor)
2296 parents = None
2296 parents = None
2297 if opts[b'record_parents']:
2297 if opts[b'record_parents']:
2298 if prec not in repo.unfiltered():
2298 if prec not in repo.unfiltered():
2299 raise error.Abort(
2299 raise error.Abort(
2300 b'cannot used --record-parents on '
2300 b'cannot used --record-parents on '
2301 b'unknown changesets'
2301 b'unknown changesets'
2302 )
2302 )
2303 parents = repo.unfiltered()[prec].parents()
2303 parents = repo.unfiltered()[prec].parents()
2304 parents = tuple(p.node() for p in parents)
2304 parents = tuple(p.node() for p in parents)
2305 repo.obsstore.create(
2305 repo.obsstore.create(
2306 tr,
2306 tr,
2307 prec,
2307 prec,
2308 succs,
2308 succs,
2309 opts[b'flags'],
2309 opts[b'flags'],
2310 parents=parents,
2310 parents=parents,
2311 date=date,
2311 date=date,
2312 metadata=metadata,
2312 metadata=metadata,
2313 ui=ui,
2313 ui=ui,
2314 )
2314 )
2315 tr.close()
2315 tr.close()
2316 except ValueError as exc:
2316 except ValueError as exc:
2317 raise error.Abort(
2317 raise error.Abort(
2318 _(b'bad obsmarker input: %s') % pycompat.bytestr(exc)
2318 _(b'bad obsmarker input: %s') % pycompat.bytestr(exc)
2319 )
2319 )
2320 finally:
2320 finally:
2321 tr.release()
2321 tr.release()
2322 finally:
2322 finally:
2323 l.release()
2323 l.release()
2324 else:
2324 else:
2325 if opts[b'rev']:
2325 if opts[b'rev']:
2326 revs = scmutil.revrange(repo, opts[b'rev'])
2326 revs = scmutil.revrange(repo, opts[b'rev'])
2327 nodes = [repo[r].node() for r in revs]
2327 nodes = [repo[r].node() for r in revs]
2328 markers = list(
2328 markers = list(
2329 obsutil.getmarkers(
2329 obsutil.getmarkers(
2330 repo, nodes=nodes, exclusive=opts[b'exclusive']
2330 repo, nodes=nodes, exclusive=opts[b'exclusive']
2331 )
2331 )
2332 )
2332 )
2333 markers.sort(key=lambda x: x._data)
2333 markers.sort(key=lambda x: x._data)
2334 else:
2334 else:
2335 markers = obsutil.getmarkers(repo)
2335 markers = obsutil.getmarkers(repo)
2336
2336
2337 markerstoiter = markers
2337 markerstoiter = markers
2338 isrelevant = lambda m: True
2338 isrelevant = lambda m: True
2339 if opts.get(b'rev') and opts.get(b'index'):
2339 if opts.get(b'rev') and opts.get(b'index'):
2340 markerstoiter = obsutil.getmarkers(repo)
2340 markerstoiter = obsutil.getmarkers(repo)
2341 markerset = set(markers)
2341 markerset = set(markers)
2342 isrelevant = lambda m: m in markerset
2342 isrelevant = lambda m: m in markerset
2343
2343
2344 fm = ui.formatter(b'debugobsolete', opts)
2344 fm = ui.formatter(b'debugobsolete', opts)
2345 for i, m in enumerate(markerstoiter):
2345 for i, m in enumerate(markerstoiter):
2346 if not isrelevant(m):
2346 if not isrelevant(m):
2347 # marker can be irrelevant when we're iterating over a set
2347 # marker can be irrelevant when we're iterating over a set
2348 # of markers (markerstoiter) which is bigger than the set
2348 # of markers (markerstoiter) which is bigger than the set
2349 # of markers we want to display (markers)
2349 # of markers we want to display (markers)
2350 # this can happen if both --index and --rev options are
2350 # this can happen if both --index and --rev options are
2351 # provided and thus we need to iterate over all of the markers
2351 # provided and thus we need to iterate over all of the markers
2352 # to get the correct indices, but only display the ones that
2352 # to get the correct indices, but only display the ones that
2353 # are relevant to --rev value
2353 # are relevant to --rev value
2354 continue
2354 continue
2355 fm.startitem()
2355 fm.startitem()
2356 ind = i if opts.get(b'index') else None
2356 ind = i if opts.get(b'index') else None
2357 cmdutil.showmarker(fm, m, index=ind)
2357 cmdutil.showmarker(fm, m, index=ind)
2358 fm.end()
2358 fm.end()
2359
2359
2360
2360
2361 @command(
2361 @command(
2362 b'debugp1copies',
2362 b'debugp1copies',
2363 [(b'r', b'rev', b'', _(b'revision to debug'), _(b'REV'))],
2363 [(b'r', b'rev', b'', _(b'revision to debug'), _(b'REV'))],
2364 _(b'[-r REV]'),
2364 _(b'[-r REV]'),
2365 )
2365 )
2366 def debugp1copies(ui, repo, **opts):
2366 def debugp1copies(ui, repo, **opts):
2367 """dump copy information compared to p1"""
2367 """dump copy information compared to p1"""
2368
2368
2369 opts = pycompat.byteskwargs(opts)
2369 opts = pycompat.byteskwargs(opts)
2370 ctx = scmutil.revsingle(repo, opts.get(b'rev'), default=None)
2370 ctx = scmutil.revsingle(repo, opts.get(b'rev'), default=None)
2371 for dst, src in ctx.p1copies().items():
2371 for dst, src in ctx.p1copies().items():
2372 ui.write(b'%s -> %s\n' % (src, dst))
2372 ui.write(b'%s -> %s\n' % (src, dst))
2373
2373
2374
2374
2375 @command(
2375 @command(
2376 b'debugp2copies',
2376 b'debugp2copies',
2377 [(b'r', b'rev', b'', _(b'revision to debug'), _(b'REV'))],
2377 [(b'r', b'rev', b'', _(b'revision to debug'), _(b'REV'))],
2378 _(b'[-r REV]'),
2378 _(b'[-r REV]'),
2379 )
2379 )
2380 def debugp1copies(ui, repo, **opts):
2380 def debugp1copies(ui, repo, **opts):
2381 """dump copy information compared to p2"""
2381 """dump copy information compared to p2"""
2382
2382
2383 opts = pycompat.byteskwargs(opts)
2383 opts = pycompat.byteskwargs(opts)
2384 ctx = scmutil.revsingle(repo, opts.get(b'rev'), default=None)
2384 ctx = scmutil.revsingle(repo, opts.get(b'rev'), default=None)
2385 for dst, src in ctx.p2copies().items():
2385 for dst, src in ctx.p2copies().items():
2386 ui.write(b'%s -> %s\n' % (src, dst))
2386 ui.write(b'%s -> %s\n' % (src, dst))
2387
2387
2388
2388
2389 @command(
2389 @command(
2390 b'debugpathcomplete',
2390 b'debugpathcomplete',
2391 [
2391 [
2392 (b'f', b'full', None, _(b'complete an entire path')),
2392 (b'f', b'full', None, _(b'complete an entire path')),
2393 (b'n', b'normal', None, _(b'show only normal files')),
2393 (b'n', b'normal', None, _(b'show only normal files')),
2394 (b'a', b'added', None, _(b'show only added files')),
2394 (b'a', b'added', None, _(b'show only added files')),
2395 (b'r', b'removed', None, _(b'show only removed files')),
2395 (b'r', b'removed', None, _(b'show only removed files')),
2396 ],
2396 ],
2397 _(b'FILESPEC...'),
2397 _(b'FILESPEC...'),
2398 )
2398 )
2399 def debugpathcomplete(ui, repo, *specs, **opts):
2399 def debugpathcomplete(ui, repo, *specs, **opts):
2400 '''complete part or all of a tracked path
2400 '''complete part or all of a tracked path
2401
2401
2402 This command supports shells that offer path name completion. It
2402 This command supports shells that offer path name completion. It
2403 currently completes only files already known to the dirstate.
2403 currently completes only files already known to the dirstate.
2404
2404
2405 Completion extends only to the next path segment unless
2405 Completion extends only to the next path segment unless
2406 --full is specified, in which case entire paths are used.'''
2406 --full is specified, in which case entire paths are used.'''
2407
2407
2408 def complete(path, acceptable):
2408 def complete(path, acceptable):
2409 dirstate = repo.dirstate
2409 dirstate = repo.dirstate
2410 spec = os.path.normpath(os.path.join(encoding.getcwd(), path))
2410 spec = os.path.normpath(os.path.join(encoding.getcwd(), path))
2411 rootdir = repo.root + pycompat.ossep
2411 rootdir = repo.root + pycompat.ossep
2412 if spec != repo.root and not spec.startswith(rootdir):
2412 if spec != repo.root and not spec.startswith(rootdir):
2413 return [], []
2413 return [], []
2414 if os.path.isdir(spec):
2414 if os.path.isdir(spec):
2415 spec += b'/'
2415 spec += b'/'
2416 spec = spec[len(rootdir) :]
2416 spec = spec[len(rootdir) :]
2417 fixpaths = pycompat.ossep != b'/'
2417 fixpaths = pycompat.ossep != b'/'
2418 if fixpaths:
2418 if fixpaths:
2419 spec = spec.replace(pycompat.ossep, b'/')
2419 spec = spec.replace(pycompat.ossep, b'/')
2420 speclen = len(spec)
2420 speclen = len(spec)
2421 fullpaths = opts['full']
2421 fullpaths = opts['full']
2422 files, dirs = set(), set()
2422 files, dirs = set(), set()
2423 adddir, addfile = dirs.add, files.add
2423 adddir, addfile = dirs.add, files.add
2424 for f, st in pycompat.iteritems(dirstate):
2424 for f, st in pycompat.iteritems(dirstate):
2425 if f.startswith(spec) and st[0] in acceptable:
2425 if f.startswith(spec) and st[0] in acceptable:
2426 if fixpaths:
2426 if fixpaths:
2427 f = f.replace(b'/', pycompat.ossep)
2427 f = f.replace(b'/', pycompat.ossep)
2428 if fullpaths:
2428 if fullpaths:
2429 addfile(f)
2429 addfile(f)
2430 continue
2430 continue
2431 s = f.find(pycompat.ossep, speclen)
2431 s = f.find(pycompat.ossep, speclen)
2432 if s >= 0:
2432 if s >= 0:
2433 adddir(f[:s])
2433 adddir(f[:s])
2434 else:
2434 else:
2435 addfile(f)
2435 addfile(f)
2436 return files, dirs
2436 return files, dirs
2437
2437
2438 acceptable = b''
2438 acceptable = b''
2439 if opts['normal']:
2439 if opts['normal']:
2440 acceptable += b'nm'
2440 acceptable += b'nm'
2441 if opts['added']:
2441 if opts['added']:
2442 acceptable += b'a'
2442 acceptable += b'a'
2443 if opts['removed']:
2443 if opts['removed']:
2444 acceptable += b'r'
2444 acceptable += b'r'
2445 cwd = repo.getcwd()
2445 cwd = repo.getcwd()
2446 if not specs:
2446 if not specs:
2447 specs = [b'.']
2447 specs = [b'.']
2448
2448
2449 files, dirs = set(), set()
2449 files, dirs = set(), set()
2450 for spec in specs:
2450 for spec in specs:
2451 f, d = complete(spec, acceptable or b'nmar')
2451 f, d = complete(spec, acceptable or b'nmar')
2452 files.update(f)
2452 files.update(f)
2453 dirs.update(d)
2453 dirs.update(d)
2454 files.update(dirs)
2454 files.update(dirs)
2455 ui.write(b'\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2455 ui.write(b'\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2456 ui.write(b'\n')
2456 ui.write(b'\n')
2457
2457
2458
2458
2459 @command(
2459 @command(
2460 b'debugpathcopies',
2460 b'debugpathcopies',
2461 cmdutil.walkopts,
2461 cmdutil.walkopts,
2462 b'hg debugpathcopies REV1 REV2 [FILE]',
2462 b'hg debugpathcopies REV1 REV2 [FILE]',
2463 inferrepo=True,
2463 inferrepo=True,
2464 )
2464 )
2465 def debugpathcopies(ui, repo, rev1, rev2, *pats, **opts):
2465 def debugpathcopies(ui, repo, rev1, rev2, *pats, **opts):
2466 """show copies between two revisions"""
2466 """show copies between two revisions"""
2467 ctx1 = scmutil.revsingle(repo, rev1)
2467 ctx1 = scmutil.revsingle(repo, rev1)
2468 ctx2 = scmutil.revsingle(repo, rev2)
2468 ctx2 = scmutil.revsingle(repo, rev2)
2469 m = scmutil.match(ctx1, pats, opts)
2469 m = scmutil.match(ctx1, pats, opts)
2470 for dst, src in sorted(copies.pathcopies(ctx1, ctx2, m).items()):
2470 for dst, src in sorted(copies.pathcopies(ctx1, ctx2, m).items()):
2471 ui.write(b'%s -> %s\n' % (src, dst))
2471 ui.write(b'%s -> %s\n' % (src, dst))
2472
2472
2473
2473
2474 @command(b'debugpeer', [], _(b'PATH'), norepo=True)
2474 @command(b'debugpeer', [], _(b'PATH'), norepo=True)
2475 def debugpeer(ui, path):
2475 def debugpeer(ui, path):
2476 """establish a connection to a peer repository"""
2476 """establish a connection to a peer repository"""
2477 # Always enable peer request logging. Requires --debug to display
2477 # Always enable peer request logging. Requires --debug to display
2478 # though.
2478 # though.
2479 overrides = {
2479 overrides = {
2480 (b'devel', b'debug.peer-request'): True,
2480 (b'devel', b'debug.peer-request'): True,
2481 }
2481 }
2482
2482
2483 with ui.configoverride(overrides):
2483 with ui.configoverride(overrides):
2484 peer = hg.peer(ui, {}, path)
2484 peer = hg.peer(ui, {}, path)
2485
2485
2486 local = peer.local() is not None
2486 local = peer.local() is not None
2487 canpush = peer.canpush()
2487 canpush = peer.canpush()
2488
2488
2489 ui.write(_(b'url: %s\n') % peer.url())
2489 ui.write(_(b'url: %s\n') % peer.url())
2490 ui.write(_(b'local: %s\n') % (_(b'yes') if local else _(b'no')))
2490 ui.write(_(b'local: %s\n') % (_(b'yes') if local else _(b'no')))
2491 ui.write(_(b'pushable: %s\n') % (_(b'yes') if canpush else _(b'no')))
2491 ui.write(_(b'pushable: %s\n') % (_(b'yes') if canpush else _(b'no')))
2492
2492
2493
2493
2494 @command(
2494 @command(
2495 b'debugpickmergetool',
2495 b'debugpickmergetool',
2496 [
2496 [
2497 (b'r', b'rev', b'', _(b'check for files in this revision'), _(b'REV')),
2497 (b'r', b'rev', b'', _(b'check for files in this revision'), _(b'REV')),
2498 (b'', b'changedelete', None, _(b'emulate merging change and delete')),
2498 (b'', b'changedelete', None, _(b'emulate merging change and delete')),
2499 ]
2499 ]
2500 + cmdutil.walkopts
2500 + cmdutil.walkopts
2501 + cmdutil.mergetoolopts,
2501 + cmdutil.mergetoolopts,
2502 _(b'[PATTERN]...'),
2502 _(b'[PATTERN]...'),
2503 inferrepo=True,
2503 inferrepo=True,
2504 )
2504 )
2505 def debugpickmergetool(ui, repo, *pats, **opts):
2505 def debugpickmergetool(ui, repo, *pats, **opts):
2506 """examine which merge tool is chosen for specified file
2506 """examine which merge tool is chosen for specified file
2507
2507
2508 As described in :hg:`help merge-tools`, Mercurial examines
2508 As described in :hg:`help merge-tools`, Mercurial examines
2509 configurations below in this order to decide which merge tool is
2509 configurations below in this order to decide which merge tool is
2510 chosen for specified file.
2510 chosen for specified file.
2511
2511
2512 1. ``--tool`` option
2512 1. ``--tool`` option
2513 2. ``HGMERGE`` environment variable
2513 2. ``HGMERGE`` environment variable
2514 3. configurations in ``merge-patterns`` section
2514 3. configurations in ``merge-patterns`` section
2515 4. configuration of ``ui.merge``
2515 4. configuration of ``ui.merge``
2516 5. configurations in ``merge-tools`` section
2516 5. configurations in ``merge-tools`` section
2517 6. ``hgmerge`` tool (for historical reason only)
2517 6. ``hgmerge`` tool (for historical reason only)
2518 7. default tool for fallback (``:merge`` or ``:prompt``)
2518 7. default tool for fallback (``:merge`` or ``:prompt``)
2519
2519
2520 This command writes out examination result in the style below::
2520 This command writes out examination result in the style below::
2521
2521
2522 FILE = MERGETOOL
2522 FILE = MERGETOOL
2523
2523
2524 By default, all files known in the first parent context of the
2524 By default, all files known in the first parent context of the
2525 working directory are examined. Use file patterns and/or -I/-X
2525 working directory are examined. Use file patterns and/or -I/-X
2526 options to limit target files. -r/--rev is also useful to examine
2526 options to limit target files. -r/--rev is also useful to examine
2527 files in another context without actual updating to it.
2527 files in another context without actual updating to it.
2528
2528
2529 With --debug, this command shows warning messages while matching
2529 With --debug, this command shows warning messages while matching
2530 against ``merge-patterns`` and so on, too. It is recommended to
2530 against ``merge-patterns`` and so on, too. It is recommended to
2531 use this option with explicit file patterns and/or -I/-X options,
2531 use this option with explicit file patterns and/or -I/-X options,
2532 because this option increases amount of output per file according
2532 because this option increases amount of output per file according
2533 to configurations in hgrc.
2533 to configurations in hgrc.
2534
2534
2535 With -v/--verbose, this command shows configurations below at
2535 With -v/--verbose, this command shows configurations below at
2536 first (only if specified).
2536 first (only if specified).
2537
2537
2538 - ``--tool`` option
2538 - ``--tool`` option
2539 - ``HGMERGE`` environment variable
2539 - ``HGMERGE`` environment variable
2540 - configuration of ``ui.merge``
2540 - configuration of ``ui.merge``
2541
2541
2542 If merge tool is chosen before matching against
2542 If merge tool is chosen before matching against
2543 ``merge-patterns``, this command can't show any helpful
2543 ``merge-patterns``, this command can't show any helpful
2544 information, even with --debug. In such case, information above is
2544 information, even with --debug. In such case, information above is
2545 useful to know why a merge tool is chosen.
2545 useful to know why a merge tool is chosen.
2546 """
2546 """
2547 opts = pycompat.byteskwargs(opts)
2547 opts = pycompat.byteskwargs(opts)
2548 overrides = {}
2548 overrides = {}
2549 if opts[b'tool']:
2549 if opts[b'tool']:
2550 overrides[(b'ui', b'forcemerge')] = opts[b'tool']
2550 overrides[(b'ui', b'forcemerge')] = opts[b'tool']
2551 ui.notenoi18n(b'with --tool %r\n' % (pycompat.bytestr(opts[b'tool'])))
2551 ui.notenoi18n(b'with --tool %r\n' % (pycompat.bytestr(opts[b'tool'])))
2552
2552
2553 with ui.configoverride(overrides, b'debugmergepatterns'):
2553 with ui.configoverride(overrides, b'debugmergepatterns'):
2554 hgmerge = encoding.environ.get(b"HGMERGE")
2554 hgmerge = encoding.environ.get(b"HGMERGE")
2555 if hgmerge is not None:
2555 if hgmerge is not None:
2556 ui.notenoi18n(b'with HGMERGE=%r\n' % (pycompat.bytestr(hgmerge)))
2556 ui.notenoi18n(b'with HGMERGE=%r\n' % (pycompat.bytestr(hgmerge)))
2557 uimerge = ui.config(b"ui", b"merge")
2557 uimerge = ui.config(b"ui", b"merge")
2558 if uimerge:
2558 if uimerge:
2559 ui.notenoi18n(b'with ui.merge=%r\n' % (pycompat.bytestr(uimerge)))
2559 ui.notenoi18n(b'with ui.merge=%r\n' % (pycompat.bytestr(uimerge)))
2560
2560
2561 ctx = scmutil.revsingle(repo, opts.get(b'rev'))
2561 ctx = scmutil.revsingle(repo, opts.get(b'rev'))
2562 m = scmutil.match(ctx, pats, opts)
2562 m = scmutil.match(ctx, pats, opts)
2563 changedelete = opts[b'changedelete']
2563 changedelete = opts[b'changedelete']
2564 for path in ctx.walk(m):
2564 for path in ctx.walk(m):
2565 fctx = ctx[path]
2565 fctx = ctx[path]
2566 try:
2566 try:
2567 if not ui.debugflag:
2567 if not ui.debugflag:
2568 ui.pushbuffer(error=True)
2568 ui.pushbuffer(error=True)
2569 tool, toolpath = filemerge._picktool(
2569 tool, toolpath = filemerge._picktool(
2570 repo,
2570 repo,
2571 ui,
2571 ui,
2572 path,
2572 path,
2573 fctx.isbinary(),
2573 fctx.isbinary(),
2574 b'l' in fctx.flags(),
2574 b'l' in fctx.flags(),
2575 changedelete,
2575 changedelete,
2576 )
2576 )
2577 finally:
2577 finally:
2578 if not ui.debugflag:
2578 if not ui.debugflag:
2579 ui.popbuffer()
2579 ui.popbuffer()
2580 ui.write(b'%s = %s\n' % (path, tool))
2580 ui.write(b'%s = %s\n' % (path, tool))
2581
2581
2582
2582
2583 @command(b'debugpushkey', [], _(b'REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
2583 @command(b'debugpushkey', [], _(b'REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
2584 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2584 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2585 '''access the pushkey key/value protocol
2585 '''access the pushkey key/value protocol
2586
2586
2587 With two args, list the keys in the given namespace.
2587 With two args, list the keys in the given namespace.
2588
2588
2589 With five args, set a key to new if it currently is set to old.
2589 With five args, set a key to new if it currently is set to old.
2590 Reports success or failure.
2590 Reports success or failure.
2591 '''
2591 '''
2592
2592
2593 target = hg.peer(ui, {}, repopath)
2593 target = hg.peer(ui, {}, repopath)
2594 if keyinfo:
2594 if keyinfo:
2595 key, old, new = keyinfo
2595 key, old, new = keyinfo
2596 with target.commandexecutor() as e:
2596 with target.commandexecutor() as e:
2597 r = e.callcommand(
2597 r = e.callcommand(
2598 b'pushkey',
2598 b'pushkey',
2599 {
2599 {
2600 b'namespace': namespace,
2600 b'namespace': namespace,
2601 b'key': key,
2601 b'key': key,
2602 b'old': old,
2602 b'old': old,
2603 b'new': new,
2603 b'new': new,
2604 },
2604 },
2605 ).result()
2605 ).result()
2606
2606
2607 ui.status(pycompat.bytestr(r) + b'\n')
2607 ui.status(pycompat.bytestr(r) + b'\n')
2608 return not r
2608 return not r
2609 else:
2609 else:
2610 for k, v in sorted(pycompat.iteritems(target.listkeys(namespace))):
2610 for k, v in sorted(pycompat.iteritems(target.listkeys(namespace))):
2611 ui.write(
2611 ui.write(
2612 b"%s\t%s\n" % (stringutil.escapestr(k), stringutil.escapestr(v))
2612 b"%s\t%s\n" % (stringutil.escapestr(k), stringutil.escapestr(v))
2613 )
2613 )
2614
2614
2615
2615
2616 @command(b'debugpvec', [], _(b'A B'))
2616 @command(b'debugpvec', [], _(b'A B'))
2617 def debugpvec(ui, repo, a, b=None):
2617 def debugpvec(ui, repo, a, b=None):
2618 ca = scmutil.revsingle(repo, a)
2618 ca = scmutil.revsingle(repo, a)
2619 cb = scmutil.revsingle(repo, b)
2619 cb = scmutil.revsingle(repo, b)
2620 pa = pvec.ctxpvec(ca)
2620 pa = pvec.ctxpvec(ca)
2621 pb = pvec.ctxpvec(cb)
2621 pb = pvec.ctxpvec(cb)
2622 if pa == pb:
2622 if pa == pb:
2623 rel = b"="
2623 rel = b"="
2624 elif pa > pb:
2624 elif pa > pb:
2625 rel = b">"
2625 rel = b">"
2626 elif pa < pb:
2626 elif pa < pb:
2627 rel = b"<"
2627 rel = b"<"
2628 elif pa | pb:
2628 elif pa | pb:
2629 rel = b"|"
2629 rel = b"|"
2630 ui.write(_(b"a: %s\n") % pa)
2630 ui.write(_(b"a: %s\n") % pa)
2631 ui.write(_(b"b: %s\n") % pb)
2631 ui.write(_(b"b: %s\n") % pb)
2632 ui.write(_(b"depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2632 ui.write(_(b"depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2633 ui.write(
2633 ui.write(
2634 _(b"delta: %d hdist: %d distance: %d relation: %s\n")
2634 _(b"delta: %d hdist: %d distance: %d relation: %s\n")
2635 % (
2635 % (
2636 abs(pa._depth - pb._depth),
2636 abs(pa._depth - pb._depth),
2637 pvec._hamming(pa._vec, pb._vec),
2637 pvec._hamming(pa._vec, pb._vec),
2638 pa.distance(pb),
2638 pa.distance(pb),
2639 rel,
2639 rel,
2640 )
2640 )
2641 )
2641 )
2642
2642
2643
2643
2644 @command(
2644 @command(
2645 b'debugrebuilddirstate|debugrebuildstate',
2645 b'debugrebuilddirstate|debugrebuildstate',
2646 [
2646 [
2647 (b'r', b'rev', b'', _(b'revision to rebuild to'), _(b'REV')),
2647 (b'r', b'rev', b'', _(b'revision to rebuild to'), _(b'REV')),
2648 (
2648 (
2649 b'',
2649 b'',
2650 b'minimal',
2650 b'minimal',
2651 None,
2651 None,
2652 _(
2652 _(
2653 b'only rebuild files that are inconsistent with '
2653 b'only rebuild files that are inconsistent with '
2654 b'the working copy parent'
2654 b'the working copy parent'
2655 ),
2655 ),
2656 ),
2656 ),
2657 ],
2657 ],
2658 _(b'[-r REV]'),
2658 _(b'[-r REV]'),
2659 )
2659 )
2660 def debugrebuilddirstate(ui, repo, rev, **opts):
2660 def debugrebuilddirstate(ui, repo, rev, **opts):
2661 """rebuild the dirstate as it would look like for the given revision
2661 """rebuild the dirstate as it would look like for the given revision
2662
2662
2663 If no revision is specified the first current parent will be used.
2663 If no revision is specified the first current parent will be used.
2664
2664
2665 The dirstate will be set to the files of the given revision.
2665 The dirstate will be set to the files of the given revision.
2666 The actual working directory content or existing dirstate
2666 The actual working directory content or existing dirstate
2667 information such as adds or removes is not considered.
2667 information such as adds or removes is not considered.
2668
2668
2669 ``minimal`` will only rebuild the dirstate status for files that claim to be
2669 ``minimal`` will only rebuild the dirstate status for files that claim to be
2670 tracked but are not in the parent manifest, or that exist in the parent
2670 tracked but are not in the parent manifest, or that exist in the parent
2671 manifest but are not in the dirstate. It will not change adds, removes, or
2671 manifest but are not in the dirstate. It will not change adds, removes, or
2672 modified files that are in the working copy parent.
2672 modified files that are in the working copy parent.
2673
2673
2674 One use of this command is to make the next :hg:`status` invocation
2674 One use of this command is to make the next :hg:`status` invocation
2675 check the actual file content.
2675 check the actual file content.
2676 """
2676 """
2677 ctx = scmutil.revsingle(repo, rev)
2677 ctx = scmutil.revsingle(repo, rev)
2678 with repo.wlock():
2678 with repo.wlock():
2679 dirstate = repo.dirstate
2679 dirstate = repo.dirstate
2680 changedfiles = None
2680 changedfiles = None
2681 # See command doc for what minimal does.
2681 # See command doc for what minimal does.
2682 if opts.get('minimal'):
2682 if opts.get('minimal'):
2683 manifestfiles = set(ctx.manifest().keys())
2683 manifestfiles = set(ctx.manifest().keys())
2684 dirstatefiles = set(dirstate)
2684 dirstatefiles = set(dirstate)
2685 manifestonly = manifestfiles - dirstatefiles
2685 manifestonly = manifestfiles - dirstatefiles
2686 dsonly = dirstatefiles - manifestfiles
2686 dsonly = dirstatefiles - manifestfiles
2687 dsnotadded = {f for f in dsonly if dirstate[f] != b'a'}
2687 dsnotadded = {f for f in dsonly if dirstate[f] != b'a'}
2688 changedfiles = manifestonly | dsnotadded
2688 changedfiles = manifestonly | dsnotadded
2689
2689
2690 dirstate.rebuild(ctx.node(), ctx.manifest(), changedfiles)
2690 dirstate.rebuild(ctx.node(), ctx.manifest(), changedfiles)
2691
2691
2692
2692
2693 @command(b'debugrebuildfncache', [], b'')
2693 @command(b'debugrebuildfncache', [], b'')
2694 def debugrebuildfncache(ui, repo):
2694 def debugrebuildfncache(ui, repo):
2695 """rebuild the fncache file"""
2695 """rebuild the fncache file"""
2696 repair.rebuildfncache(ui, repo)
2696 repair.rebuildfncache(ui, repo)
2697
2697
2698
2698
2699 @command(
2699 @command(
2700 b'debugrename',
2700 b'debugrename',
2701 [(b'r', b'rev', b'', _(b'revision to debug'), _(b'REV'))],
2701 [(b'r', b'rev', b'', _(b'revision to debug'), _(b'REV'))],
2702 _(b'[-r REV] [FILE]...'),
2702 _(b'[-r REV] [FILE]...'),
2703 )
2703 )
2704 def debugrename(ui, repo, *pats, **opts):
2704 def debugrename(ui, repo, *pats, **opts):
2705 """dump rename information"""
2705 """dump rename information"""
2706
2706
2707 opts = pycompat.byteskwargs(opts)
2707 opts = pycompat.byteskwargs(opts)
2708 ctx = scmutil.revsingle(repo, opts.get(b'rev'))
2708 ctx = scmutil.revsingle(repo, opts.get(b'rev'))
2709 m = scmutil.match(ctx, pats, opts)
2709 m = scmutil.match(ctx, pats, opts)
2710 for abs in ctx.walk(m):
2710 for abs in ctx.walk(m):
2711 fctx = ctx[abs]
2711 fctx = ctx[abs]
2712 o = fctx.filelog().renamed(fctx.filenode())
2712 o = fctx.filelog().renamed(fctx.filenode())
2713 rel = repo.pathto(abs)
2713 rel = repo.pathto(abs)
2714 if o:
2714 if o:
2715 ui.write(_(b"%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2715 ui.write(_(b"%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2716 else:
2716 else:
2717 ui.write(_(b"%s not renamed\n") % rel)
2717 ui.write(_(b"%s not renamed\n") % rel)
2718
2718
2719
2719
2720 @command(b'debugrequires|debugrequirements', [], b'')
2720 @command(b'debugrequires|debugrequirements', [], b'')
2721 def debugrequirements(ui, repo):
2721 def debugrequirements(ui, repo):
2722 """ print the current repo requirements """
2722 """ print the current repo requirements """
2723 for r in sorted(repo.requirements):
2723 for r in sorted(repo.requirements):
2724 ui.write(b"%s\n" % r)
2724 ui.write(b"%s\n" % r)
2725
2725
2726
2726
2727 @command(
2727 @command(
2728 b'debugrevlog',
2728 b'debugrevlog',
2729 cmdutil.debugrevlogopts + [(b'd', b'dump', False, _(b'dump index data'))],
2729 cmdutil.debugrevlogopts + [(b'd', b'dump', False, _(b'dump index data'))],
2730 _(b'-c|-m|FILE'),
2730 _(b'-c|-m|FILE'),
2731 optionalrepo=True,
2731 optionalrepo=True,
2732 )
2732 )
2733 def debugrevlog(ui, repo, file_=None, **opts):
2733 def debugrevlog(ui, repo, file_=None, **opts):
2734 """show data and statistics about a revlog"""
2734 """show data and statistics about a revlog"""
2735 opts = pycompat.byteskwargs(opts)
2735 opts = pycompat.byteskwargs(opts)
2736 r = cmdutil.openrevlog(repo, b'debugrevlog', file_, opts)
2736 r = cmdutil.openrevlog(repo, b'debugrevlog', file_, opts)
2737
2737
2738 if opts.get(b"dump"):
2738 if opts.get(b"dump"):
2739 numrevs = len(r)
2739 numrevs = len(r)
2740 ui.write(
2740 ui.write(
2741 (
2741 (
2742 b"# rev p1rev p2rev start end deltastart base p1 p2"
2742 b"# rev p1rev p2rev start end deltastart base p1 p2"
2743 b" rawsize totalsize compression heads chainlen\n"
2743 b" rawsize totalsize compression heads chainlen\n"
2744 )
2744 )
2745 )
2745 )
2746 ts = 0
2746 ts = 0
2747 heads = set()
2747 heads = set()
2748
2748
2749 for rev in pycompat.xrange(numrevs):
2749 for rev in pycompat.xrange(numrevs):
2750 dbase = r.deltaparent(rev)
2750 dbase = r.deltaparent(rev)
2751 if dbase == -1:
2751 if dbase == -1:
2752 dbase = rev
2752 dbase = rev
2753 cbase = r.chainbase(rev)
2753 cbase = r.chainbase(rev)
2754 clen = r.chainlen(rev)
2754 clen = r.chainlen(rev)
2755 p1, p2 = r.parentrevs(rev)
2755 p1, p2 = r.parentrevs(rev)
2756 rs = r.rawsize(rev)
2756 rs = r.rawsize(rev)
2757 ts = ts + rs
2757 ts = ts + rs
2758 heads -= set(r.parentrevs(rev))
2758 heads -= set(r.parentrevs(rev))
2759 heads.add(rev)
2759 heads.add(rev)
2760 try:
2760 try:
2761 compression = ts / r.end(rev)
2761 compression = ts / r.end(rev)
2762 except ZeroDivisionError:
2762 except ZeroDivisionError:
2763 compression = 0
2763 compression = 0
2764 ui.write(
2764 ui.write(
2765 b"%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d "
2765 b"%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d "
2766 b"%11d %5d %8d\n"
2766 b"%11d %5d %8d\n"
2767 % (
2767 % (
2768 rev,
2768 rev,
2769 p1,
2769 p1,
2770 p2,
2770 p2,
2771 r.start(rev),
2771 r.start(rev),
2772 r.end(rev),
2772 r.end(rev),
2773 r.start(dbase),
2773 r.start(dbase),
2774 r.start(cbase),
2774 r.start(cbase),
2775 r.start(p1),
2775 r.start(p1),
2776 r.start(p2),
2776 r.start(p2),
2777 rs,
2777 rs,
2778 ts,
2778 ts,
2779 compression,
2779 compression,
2780 len(heads),
2780 len(heads),
2781 clen,
2781 clen,
2782 )
2782 )
2783 )
2783 )
2784 return 0
2784 return 0
2785
2785
2786 v = r.version
2786 v = r.version
2787 format = v & 0xFFFF
2787 format = v & 0xFFFF
2788 flags = []
2788 flags = []
2789 gdelta = False
2789 gdelta = False
2790 if v & revlog.FLAG_INLINE_DATA:
2790 if v & revlog.FLAG_INLINE_DATA:
2791 flags.append(b'inline')
2791 flags.append(b'inline')
2792 if v & revlog.FLAG_GENERALDELTA:
2792 if v & revlog.FLAG_GENERALDELTA:
2793 gdelta = True
2793 gdelta = True
2794 flags.append(b'generaldelta')
2794 flags.append(b'generaldelta')
2795 if not flags:
2795 if not flags:
2796 flags = [b'(none)']
2796 flags = [b'(none)']
2797
2797
2798 ### tracks merge vs single parent
2798 ### tracks merge vs single parent
2799 nummerges = 0
2799 nummerges = 0
2800
2800
2801 ### tracks ways the "delta" are build
2801 ### tracks ways the "delta" are build
2802 # nodelta
2802 # nodelta
2803 numempty = 0
2803 numempty = 0
2804 numemptytext = 0
2804 numemptytext = 0
2805 numemptydelta = 0
2805 numemptydelta = 0
2806 # full file content
2806 # full file content
2807 numfull = 0
2807 numfull = 0
2808 # intermediate snapshot against a prior snapshot
2808 # intermediate snapshot against a prior snapshot
2809 numsemi = 0
2809 numsemi = 0
2810 # snapshot count per depth
2810 # snapshot count per depth
2811 numsnapdepth = collections.defaultdict(lambda: 0)
2811 numsnapdepth = collections.defaultdict(lambda: 0)
2812 # delta against previous revision
2812 # delta against previous revision
2813 numprev = 0
2813 numprev = 0
2814 # delta against first or second parent (not prev)
2814 # delta against first or second parent (not prev)
2815 nump1 = 0
2815 nump1 = 0
2816 nump2 = 0
2816 nump2 = 0
2817 # delta against neither prev nor parents
2817 # delta against neither prev nor parents
2818 numother = 0
2818 numother = 0
2819 # delta against prev that are also first or second parent
2819 # delta against prev that are also first or second parent
2820 # (details of `numprev`)
2820 # (details of `numprev`)
2821 nump1prev = 0
2821 nump1prev = 0
2822 nump2prev = 0
2822 nump2prev = 0
2823
2823
2824 # data about delta chain of each revs
2824 # data about delta chain of each revs
2825 chainlengths = []
2825 chainlengths = []
2826 chainbases = []
2826 chainbases = []
2827 chainspans = []
2827 chainspans = []
2828
2828
2829 # data about each revision
2829 # data about each revision
2830 datasize = [None, 0, 0]
2830 datasize = [None, 0, 0]
2831 fullsize = [None, 0, 0]
2831 fullsize = [None, 0, 0]
2832 semisize = [None, 0, 0]
2832 semisize = [None, 0, 0]
2833 # snapshot count per depth
2833 # snapshot count per depth
2834 snapsizedepth = collections.defaultdict(lambda: [None, 0, 0])
2834 snapsizedepth = collections.defaultdict(lambda: [None, 0, 0])
2835 deltasize = [None, 0, 0]
2835 deltasize = [None, 0, 0]
2836 chunktypecounts = {}
2836 chunktypecounts = {}
2837 chunktypesizes = {}
2837 chunktypesizes = {}
2838
2838
2839 def addsize(size, l):
2839 def addsize(size, l):
2840 if l[0] is None or size < l[0]:
2840 if l[0] is None or size < l[0]:
2841 l[0] = size
2841 l[0] = size
2842 if size > l[1]:
2842 if size > l[1]:
2843 l[1] = size
2843 l[1] = size
2844 l[2] += size
2844 l[2] += size
2845
2845
2846 numrevs = len(r)
2846 numrevs = len(r)
2847 for rev in pycompat.xrange(numrevs):
2847 for rev in pycompat.xrange(numrevs):
2848 p1, p2 = r.parentrevs(rev)
2848 p1, p2 = r.parentrevs(rev)
2849 delta = r.deltaparent(rev)
2849 delta = r.deltaparent(rev)
2850 if format > 0:
2850 if format > 0:
2851 addsize(r.rawsize(rev), datasize)
2851 addsize(r.rawsize(rev), datasize)
2852 if p2 != nullrev:
2852 if p2 != nullrev:
2853 nummerges += 1
2853 nummerges += 1
2854 size = r.length(rev)
2854 size = r.length(rev)
2855 if delta == nullrev:
2855 if delta == nullrev:
2856 chainlengths.append(0)
2856 chainlengths.append(0)
2857 chainbases.append(r.start(rev))
2857 chainbases.append(r.start(rev))
2858 chainspans.append(size)
2858 chainspans.append(size)
2859 if size == 0:
2859 if size == 0:
2860 numempty += 1
2860 numempty += 1
2861 numemptytext += 1
2861 numemptytext += 1
2862 else:
2862 else:
2863 numfull += 1
2863 numfull += 1
2864 numsnapdepth[0] += 1
2864 numsnapdepth[0] += 1
2865 addsize(size, fullsize)
2865 addsize(size, fullsize)
2866 addsize(size, snapsizedepth[0])
2866 addsize(size, snapsizedepth[0])
2867 else:
2867 else:
2868 chainlengths.append(chainlengths[delta] + 1)
2868 chainlengths.append(chainlengths[delta] + 1)
2869 baseaddr = chainbases[delta]
2869 baseaddr = chainbases[delta]
2870 revaddr = r.start(rev)
2870 revaddr = r.start(rev)
2871 chainbases.append(baseaddr)
2871 chainbases.append(baseaddr)
2872 chainspans.append((revaddr - baseaddr) + size)
2872 chainspans.append((revaddr - baseaddr) + size)
2873 if size == 0:
2873 if size == 0:
2874 numempty += 1
2874 numempty += 1
2875 numemptydelta += 1
2875 numemptydelta += 1
2876 elif r.issnapshot(rev):
2876 elif r.issnapshot(rev):
2877 addsize(size, semisize)
2877 addsize(size, semisize)
2878 numsemi += 1
2878 numsemi += 1
2879 depth = r.snapshotdepth(rev)
2879 depth = r.snapshotdepth(rev)
2880 numsnapdepth[depth] += 1
2880 numsnapdepth[depth] += 1
2881 addsize(size, snapsizedepth[depth])
2881 addsize(size, snapsizedepth[depth])
2882 else:
2882 else:
2883 addsize(size, deltasize)
2883 addsize(size, deltasize)
2884 if delta == rev - 1:
2884 if delta == rev - 1:
2885 numprev += 1
2885 numprev += 1
2886 if delta == p1:
2886 if delta == p1:
2887 nump1prev += 1
2887 nump1prev += 1
2888 elif delta == p2:
2888 elif delta == p2:
2889 nump2prev += 1
2889 nump2prev += 1
2890 elif delta == p1:
2890 elif delta == p1:
2891 nump1 += 1
2891 nump1 += 1
2892 elif delta == p2:
2892 elif delta == p2:
2893 nump2 += 1
2893 nump2 += 1
2894 elif delta != nullrev:
2894 elif delta != nullrev:
2895 numother += 1
2895 numother += 1
2896
2896
2897 # Obtain data on the raw chunks in the revlog.
2897 # Obtain data on the raw chunks in the revlog.
2898 if util.safehasattr(r, b'_getsegmentforrevs'):
2898 if util.safehasattr(r, b'_getsegmentforrevs'):
2899 segment = r._getsegmentforrevs(rev, rev)[1]
2899 segment = r._getsegmentforrevs(rev, rev)[1]
2900 else:
2900 else:
2901 segment = r._revlog._getsegmentforrevs(rev, rev)[1]
2901 segment = r._revlog._getsegmentforrevs(rev, rev)[1]
2902 if segment:
2902 if segment:
2903 chunktype = bytes(segment[0:1])
2903 chunktype = bytes(segment[0:1])
2904 else:
2904 else:
2905 chunktype = b'empty'
2905 chunktype = b'empty'
2906
2906
2907 if chunktype not in chunktypecounts:
2907 if chunktype not in chunktypecounts:
2908 chunktypecounts[chunktype] = 0
2908 chunktypecounts[chunktype] = 0
2909 chunktypesizes[chunktype] = 0
2909 chunktypesizes[chunktype] = 0
2910
2910
2911 chunktypecounts[chunktype] += 1
2911 chunktypecounts[chunktype] += 1
2912 chunktypesizes[chunktype] += size
2912 chunktypesizes[chunktype] += size
2913
2913
2914 # Adjust size min value for empty cases
2914 # Adjust size min value for empty cases
2915 for size in (datasize, fullsize, semisize, deltasize):
2915 for size in (datasize, fullsize, semisize, deltasize):
2916 if size[0] is None:
2916 if size[0] is None:
2917 size[0] = 0
2917 size[0] = 0
2918
2918
2919 numdeltas = numrevs - numfull - numempty - numsemi
2919 numdeltas = numrevs - numfull - numempty - numsemi
2920 numoprev = numprev - nump1prev - nump2prev
2920 numoprev = numprev - nump1prev - nump2prev
2921 totalrawsize = datasize[2]
2921 totalrawsize = datasize[2]
2922 datasize[2] /= numrevs
2922 datasize[2] /= numrevs
2923 fulltotal = fullsize[2]
2923 fulltotal = fullsize[2]
2924 if numfull == 0:
2924 if numfull == 0:
2925 fullsize[2] = 0
2925 fullsize[2] = 0
2926 else:
2926 else:
2927 fullsize[2] /= numfull
2927 fullsize[2] /= numfull
2928 semitotal = semisize[2]
2928 semitotal = semisize[2]
2929 snaptotal = {}
2929 snaptotal = {}
2930 if numsemi > 0:
2930 if numsemi > 0:
2931 semisize[2] /= numsemi
2931 semisize[2] /= numsemi
2932 for depth in snapsizedepth:
2932 for depth in snapsizedepth:
2933 snaptotal[depth] = snapsizedepth[depth][2]
2933 snaptotal[depth] = snapsizedepth[depth][2]
2934 snapsizedepth[depth][2] /= numsnapdepth[depth]
2934 snapsizedepth[depth][2] /= numsnapdepth[depth]
2935
2935
2936 deltatotal = deltasize[2]
2936 deltatotal = deltasize[2]
2937 if numdeltas > 0:
2937 if numdeltas > 0:
2938 deltasize[2] /= numdeltas
2938 deltasize[2] /= numdeltas
2939 totalsize = fulltotal + semitotal + deltatotal
2939 totalsize = fulltotal + semitotal + deltatotal
2940 avgchainlen = sum(chainlengths) / numrevs
2940 avgchainlen = sum(chainlengths) / numrevs
2941 maxchainlen = max(chainlengths)
2941 maxchainlen = max(chainlengths)
2942 maxchainspan = max(chainspans)
2942 maxchainspan = max(chainspans)
2943 compratio = 1
2943 compratio = 1
2944 if totalsize:
2944 if totalsize:
2945 compratio = totalrawsize / totalsize
2945 compratio = totalrawsize / totalsize
2946
2946
2947 basedfmtstr = b'%%%dd\n'
2947 basedfmtstr = b'%%%dd\n'
2948 basepcfmtstr = b'%%%dd %s(%%5.2f%%%%)\n'
2948 basepcfmtstr = b'%%%dd %s(%%5.2f%%%%)\n'
2949
2949
2950 def dfmtstr(max):
2950 def dfmtstr(max):
2951 return basedfmtstr % len(str(max))
2951 return basedfmtstr % len(str(max))
2952
2952
2953 def pcfmtstr(max, padding=0):
2953 def pcfmtstr(max, padding=0):
2954 return basepcfmtstr % (len(str(max)), b' ' * padding)
2954 return basepcfmtstr % (len(str(max)), b' ' * padding)
2955
2955
2956 def pcfmt(value, total):
2956 def pcfmt(value, total):
2957 if total:
2957 if total:
2958 return (value, 100 * float(value) / total)
2958 return (value, 100 * float(value) / total)
2959 else:
2959 else:
2960 return value, 100.0
2960 return value, 100.0
2961
2961
2962 ui.writenoi18n(b'format : %d\n' % format)
2962 ui.writenoi18n(b'format : %d\n' % format)
2963 ui.writenoi18n(b'flags : %s\n' % b', '.join(flags))
2963 ui.writenoi18n(b'flags : %s\n' % b', '.join(flags))
2964
2964
2965 ui.write(b'\n')
2965 ui.write(b'\n')
2966 fmt = pcfmtstr(totalsize)
2966 fmt = pcfmtstr(totalsize)
2967 fmt2 = dfmtstr(totalsize)
2967 fmt2 = dfmtstr(totalsize)
2968 ui.writenoi18n(b'revisions : ' + fmt2 % numrevs)
2968 ui.writenoi18n(b'revisions : ' + fmt2 % numrevs)
2969 ui.writenoi18n(b' merges : ' + fmt % pcfmt(nummerges, numrevs))
2969 ui.writenoi18n(b' merges : ' + fmt % pcfmt(nummerges, numrevs))
2970 ui.writenoi18n(
2970 ui.writenoi18n(
2971 b' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs)
2971 b' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs)
2972 )
2972 )
2973 ui.writenoi18n(b'revisions : ' + fmt2 % numrevs)
2973 ui.writenoi18n(b'revisions : ' + fmt2 % numrevs)
2974 ui.writenoi18n(b' empty : ' + fmt % pcfmt(numempty, numrevs))
2974 ui.writenoi18n(b' empty : ' + fmt % pcfmt(numempty, numrevs))
2975 ui.writenoi18n(
2975 ui.writenoi18n(
2976 b' text : '
2976 b' text : '
2977 + fmt % pcfmt(numemptytext, numemptytext + numemptydelta)
2977 + fmt % pcfmt(numemptytext, numemptytext + numemptydelta)
2978 )
2978 )
2979 ui.writenoi18n(
2979 ui.writenoi18n(
2980 b' delta : '
2980 b' delta : '
2981 + fmt % pcfmt(numemptydelta, numemptytext + numemptydelta)
2981 + fmt % pcfmt(numemptydelta, numemptytext + numemptydelta)
2982 )
2982 )
2983 ui.writenoi18n(
2983 ui.writenoi18n(
2984 b' snapshot : ' + fmt % pcfmt(numfull + numsemi, numrevs)
2984 b' snapshot : ' + fmt % pcfmt(numfull + numsemi, numrevs)
2985 )
2985 )
2986 for depth in sorted(numsnapdepth):
2986 for depth in sorted(numsnapdepth):
2987 ui.write(
2987 ui.write(
2988 (b' lvl-%-3d : ' % depth)
2988 (b' lvl-%-3d : ' % depth)
2989 + fmt % pcfmt(numsnapdepth[depth], numrevs)
2989 + fmt % pcfmt(numsnapdepth[depth], numrevs)
2990 )
2990 )
2991 ui.writenoi18n(b' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
2991 ui.writenoi18n(b' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
2992 ui.writenoi18n(b'revision size : ' + fmt2 % totalsize)
2992 ui.writenoi18n(b'revision size : ' + fmt2 % totalsize)
2993 ui.writenoi18n(
2993 ui.writenoi18n(
2994 b' snapshot : ' + fmt % pcfmt(fulltotal + semitotal, totalsize)
2994 b' snapshot : ' + fmt % pcfmt(fulltotal + semitotal, totalsize)
2995 )
2995 )
2996 for depth in sorted(numsnapdepth):
2996 for depth in sorted(numsnapdepth):
2997 ui.write(
2997 ui.write(
2998 (b' lvl-%-3d : ' % depth)
2998 (b' lvl-%-3d : ' % depth)
2999 + fmt % pcfmt(snaptotal[depth], totalsize)
2999 + fmt % pcfmt(snaptotal[depth], totalsize)
3000 )
3000 )
3001 ui.writenoi18n(b' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
3001 ui.writenoi18n(b' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
3002
3002
3003 def fmtchunktype(chunktype):
3003 def fmtchunktype(chunktype):
3004 if chunktype == b'empty':
3004 if chunktype == b'empty':
3005 return b' %s : ' % chunktype
3005 return b' %s : ' % chunktype
3006 elif chunktype in pycompat.bytestr(string.ascii_letters):
3006 elif chunktype in pycompat.bytestr(string.ascii_letters):
3007 return b' 0x%s (%s) : ' % (hex(chunktype), chunktype)
3007 return b' 0x%s (%s) : ' % (hex(chunktype), chunktype)
3008 else:
3008 else:
3009 return b' 0x%s : ' % hex(chunktype)
3009 return b' 0x%s : ' % hex(chunktype)
3010
3010
3011 ui.write(b'\n')
3011 ui.write(b'\n')
3012 ui.writenoi18n(b'chunks : ' + fmt2 % numrevs)
3012 ui.writenoi18n(b'chunks : ' + fmt2 % numrevs)
3013 for chunktype in sorted(chunktypecounts):
3013 for chunktype in sorted(chunktypecounts):
3014 ui.write(fmtchunktype(chunktype))
3014 ui.write(fmtchunktype(chunktype))
3015 ui.write(fmt % pcfmt(chunktypecounts[chunktype], numrevs))
3015 ui.write(fmt % pcfmt(chunktypecounts[chunktype], numrevs))
3016 ui.writenoi18n(b'chunks size : ' + fmt2 % totalsize)
3016 ui.writenoi18n(b'chunks size : ' + fmt2 % totalsize)
3017 for chunktype in sorted(chunktypecounts):
3017 for chunktype in sorted(chunktypecounts):
3018 ui.write(fmtchunktype(chunktype))
3018 ui.write(fmtchunktype(chunktype))
3019 ui.write(fmt % pcfmt(chunktypesizes[chunktype], totalsize))
3019 ui.write(fmt % pcfmt(chunktypesizes[chunktype], totalsize))
3020
3020
3021 ui.write(b'\n')
3021 ui.write(b'\n')
3022 fmt = dfmtstr(max(avgchainlen, maxchainlen, maxchainspan, compratio))
3022 fmt = dfmtstr(max(avgchainlen, maxchainlen, maxchainspan, compratio))
3023 ui.writenoi18n(b'avg chain length : ' + fmt % avgchainlen)
3023 ui.writenoi18n(b'avg chain length : ' + fmt % avgchainlen)
3024 ui.writenoi18n(b'max chain length : ' + fmt % maxchainlen)
3024 ui.writenoi18n(b'max chain length : ' + fmt % maxchainlen)
3025 ui.writenoi18n(b'max chain reach : ' + fmt % maxchainspan)
3025 ui.writenoi18n(b'max chain reach : ' + fmt % maxchainspan)
3026 ui.writenoi18n(b'compression ratio : ' + fmt % compratio)
3026 ui.writenoi18n(b'compression ratio : ' + fmt % compratio)
3027
3027
3028 if format > 0:
3028 if format > 0:
3029 ui.write(b'\n')
3029 ui.write(b'\n')
3030 ui.writenoi18n(
3030 ui.writenoi18n(
3031 b'uncompressed data size (min/max/avg) : %d / %d / %d\n'
3031 b'uncompressed data size (min/max/avg) : %d / %d / %d\n'
3032 % tuple(datasize)
3032 % tuple(datasize)
3033 )
3033 )
3034 ui.writenoi18n(
3034 ui.writenoi18n(
3035 b'full revision size (min/max/avg) : %d / %d / %d\n'
3035 b'full revision size (min/max/avg) : %d / %d / %d\n'
3036 % tuple(fullsize)
3036 % tuple(fullsize)
3037 )
3037 )
3038 ui.writenoi18n(
3038 ui.writenoi18n(
3039 b'inter-snapshot size (min/max/avg) : %d / %d / %d\n'
3039 b'inter-snapshot size (min/max/avg) : %d / %d / %d\n'
3040 % tuple(semisize)
3040 % tuple(semisize)
3041 )
3041 )
3042 for depth in sorted(snapsizedepth):
3042 for depth in sorted(snapsizedepth):
3043 if depth == 0:
3043 if depth == 0:
3044 continue
3044 continue
3045 ui.writenoi18n(
3045 ui.writenoi18n(
3046 b' level-%-3d (min/max/avg) : %d / %d / %d\n'
3046 b' level-%-3d (min/max/avg) : %d / %d / %d\n'
3047 % ((depth,) + tuple(snapsizedepth[depth]))
3047 % ((depth,) + tuple(snapsizedepth[depth]))
3048 )
3048 )
3049 ui.writenoi18n(
3049 ui.writenoi18n(
3050 b'delta size (min/max/avg) : %d / %d / %d\n'
3050 b'delta size (min/max/avg) : %d / %d / %d\n'
3051 % tuple(deltasize)
3051 % tuple(deltasize)
3052 )
3052 )
3053
3053
3054 if numdeltas > 0:
3054 if numdeltas > 0:
3055 ui.write(b'\n')
3055 ui.write(b'\n')
3056 fmt = pcfmtstr(numdeltas)
3056 fmt = pcfmtstr(numdeltas)
3057 fmt2 = pcfmtstr(numdeltas, 4)
3057 fmt2 = pcfmtstr(numdeltas, 4)
3058 ui.writenoi18n(
3058 ui.writenoi18n(
3059 b'deltas against prev : ' + fmt % pcfmt(numprev, numdeltas)
3059 b'deltas against prev : ' + fmt % pcfmt(numprev, numdeltas)
3060 )
3060 )
3061 if numprev > 0:
3061 if numprev > 0:
3062 ui.writenoi18n(
3062 ui.writenoi18n(
3063 b' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev)
3063 b' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev)
3064 )
3064 )
3065 ui.writenoi18n(
3065 ui.writenoi18n(
3066 b' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev)
3066 b' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev)
3067 )
3067 )
3068 ui.writenoi18n(
3068 ui.writenoi18n(
3069 b' other : ' + fmt2 % pcfmt(numoprev, numprev)
3069 b' other : ' + fmt2 % pcfmt(numoprev, numprev)
3070 )
3070 )
3071 if gdelta:
3071 if gdelta:
3072 ui.writenoi18n(
3072 ui.writenoi18n(
3073 b'deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas)
3073 b'deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas)
3074 )
3074 )
3075 ui.writenoi18n(
3075 ui.writenoi18n(
3076 b'deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas)
3076 b'deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas)
3077 )
3077 )
3078 ui.writenoi18n(
3078 ui.writenoi18n(
3079 b'deltas against other : ' + fmt % pcfmt(numother, numdeltas)
3079 b'deltas against other : ' + fmt % pcfmt(numother, numdeltas)
3080 )
3080 )
3081
3081
3082
3082
3083 @command(
3083 @command(
3084 b'debugrevlogindex',
3084 b'debugrevlogindex',
3085 cmdutil.debugrevlogopts
3085 cmdutil.debugrevlogopts
3086 + [(b'f', b'format', 0, _(b'revlog format'), _(b'FORMAT'))],
3086 + [(b'f', b'format', 0, _(b'revlog format'), _(b'FORMAT'))],
3087 _(b'[-f FORMAT] -c|-m|FILE'),
3087 _(b'[-f FORMAT] -c|-m|FILE'),
3088 optionalrepo=True,
3088 optionalrepo=True,
3089 )
3089 )
3090 def debugrevlogindex(ui, repo, file_=None, **opts):
3090 def debugrevlogindex(ui, repo, file_=None, **opts):
3091 """dump the contents of a revlog index"""
3091 """dump the contents of a revlog index"""
3092 opts = pycompat.byteskwargs(opts)
3092 opts = pycompat.byteskwargs(opts)
3093 r = cmdutil.openrevlog(repo, b'debugrevlogindex', file_, opts)
3093 r = cmdutil.openrevlog(repo, b'debugrevlogindex', file_, opts)
3094 format = opts.get(b'format', 0)
3094 format = opts.get(b'format', 0)
3095 if format not in (0, 1):
3095 if format not in (0, 1):
3096 raise error.Abort(_(b"unknown format %d") % format)
3096 raise error.Abort(_(b"unknown format %d") % format)
3097
3097
3098 if ui.debugflag:
3098 if ui.debugflag:
3099 shortfn = hex
3099 shortfn = hex
3100 else:
3100 else:
3101 shortfn = short
3101 shortfn = short
3102
3102
3103 # There might not be anything in r, so have a sane default
3103 # There might not be anything in r, so have a sane default
3104 idlen = 12
3104 idlen = 12
3105 for i in r:
3105 for i in r:
3106 idlen = len(shortfn(r.node(i)))
3106 idlen = len(shortfn(r.node(i)))
3107 break
3107 break
3108
3108
3109 if format == 0:
3109 if format == 0:
3110 if ui.verbose:
3110 if ui.verbose:
3111 ui.writenoi18n(
3111 ui.writenoi18n(
3112 b" rev offset length linkrev %s %s p2\n"
3112 b" rev offset length linkrev %s %s p2\n"
3113 % (b"nodeid".ljust(idlen), b"p1".ljust(idlen))
3113 % (b"nodeid".ljust(idlen), b"p1".ljust(idlen))
3114 )
3114 )
3115 else:
3115 else:
3116 ui.writenoi18n(
3116 ui.writenoi18n(
3117 b" rev linkrev %s %s p2\n"
3117 b" rev linkrev %s %s p2\n"
3118 % (b"nodeid".ljust(idlen), b"p1".ljust(idlen))
3118 % (b"nodeid".ljust(idlen), b"p1".ljust(idlen))
3119 )
3119 )
3120 elif format == 1:
3120 elif format == 1:
3121 if ui.verbose:
3121 if ui.verbose:
3122 ui.writenoi18n(
3122 ui.writenoi18n(
3123 (
3123 (
3124 b" rev flag offset length size link p1"
3124 b" rev flag offset length size link p1"
3125 b" p2 %s\n"
3125 b" p2 %s\n"
3126 )
3126 )
3127 % b"nodeid".rjust(idlen)
3127 % b"nodeid".rjust(idlen)
3128 )
3128 )
3129 else:
3129 else:
3130 ui.writenoi18n(
3130 ui.writenoi18n(
3131 b" rev flag size link p1 p2 %s\n"
3131 b" rev flag size link p1 p2 %s\n"
3132 % b"nodeid".rjust(idlen)
3132 % b"nodeid".rjust(idlen)
3133 )
3133 )
3134
3134
3135 for i in r:
3135 for i in r:
3136 node = r.node(i)
3136 node = r.node(i)
3137 if format == 0:
3137 if format == 0:
3138 try:
3138 try:
3139 pp = r.parents(node)
3139 pp = r.parents(node)
3140 except Exception:
3140 except Exception:
3141 pp = [nullid, nullid]
3141 pp = [nullid, nullid]
3142 if ui.verbose:
3142 if ui.verbose:
3143 ui.write(
3143 ui.write(
3144 b"% 6d % 9d % 7d % 7d %s %s %s\n"
3144 b"% 6d % 9d % 7d % 7d %s %s %s\n"
3145 % (
3145 % (
3146 i,
3146 i,
3147 r.start(i),
3147 r.start(i),
3148 r.length(i),
3148 r.length(i),
3149 r.linkrev(i),
3149 r.linkrev(i),
3150 shortfn(node),
3150 shortfn(node),
3151 shortfn(pp[0]),
3151 shortfn(pp[0]),
3152 shortfn(pp[1]),
3152 shortfn(pp[1]),
3153 )
3153 )
3154 )
3154 )
3155 else:
3155 else:
3156 ui.write(
3156 ui.write(
3157 b"% 6d % 7d %s %s %s\n"
3157 b"% 6d % 7d %s %s %s\n"
3158 % (
3158 % (
3159 i,
3159 i,
3160 r.linkrev(i),
3160 r.linkrev(i),
3161 shortfn(node),
3161 shortfn(node),
3162 shortfn(pp[0]),
3162 shortfn(pp[0]),
3163 shortfn(pp[1]),
3163 shortfn(pp[1]),
3164 )
3164 )
3165 )
3165 )
3166 elif format == 1:
3166 elif format == 1:
3167 pr = r.parentrevs(i)
3167 pr = r.parentrevs(i)
3168 if ui.verbose:
3168 if ui.verbose:
3169 ui.write(
3169 ui.write(
3170 b"% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d %s\n"
3170 b"% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d %s\n"
3171 % (
3171 % (
3172 i,
3172 i,
3173 r.flags(i),
3173 r.flags(i),
3174 r.start(i),
3174 r.start(i),
3175 r.length(i),
3175 r.length(i),
3176 r.rawsize(i),
3176 r.rawsize(i),
3177 r.linkrev(i),
3177 r.linkrev(i),
3178 pr[0],
3178 pr[0],
3179 pr[1],
3179 pr[1],
3180 shortfn(node),
3180 shortfn(node),
3181 )
3181 )
3182 )
3182 )
3183 else:
3183 else:
3184 ui.write(
3184 ui.write(
3185 b"% 6d %04x % 8d % 6d % 6d % 6d %s\n"
3185 b"% 6d %04x % 8d % 6d % 6d % 6d %s\n"
3186 % (
3186 % (
3187 i,
3187 i,
3188 r.flags(i),
3188 r.flags(i),
3189 r.rawsize(i),
3189 r.rawsize(i),
3190 r.linkrev(i),
3190 r.linkrev(i),
3191 pr[0],
3191 pr[0],
3192 pr[1],
3192 pr[1],
3193 shortfn(node),
3193 shortfn(node),
3194 )
3194 )
3195 )
3195 )
3196
3196
3197
3197
3198 @command(
3198 @command(
3199 b'debugrevspec',
3199 b'debugrevspec',
3200 [
3200 [
3201 (
3201 (
3202 b'',
3202 b'',
3203 b'optimize',
3203 b'optimize',
3204 None,
3204 None,
3205 _(b'print parsed tree after optimizing (DEPRECATED)'),
3205 _(b'print parsed tree after optimizing (DEPRECATED)'),
3206 ),
3206 ),
3207 (
3207 (
3208 b'',
3208 b'',
3209 b'show-revs',
3209 b'show-revs',
3210 True,
3210 True,
3211 _(b'print list of result revisions (default)'),
3211 _(b'print list of result revisions (default)'),
3212 ),
3212 ),
3213 (
3213 (
3214 b's',
3214 b's',
3215 b'show-set',
3215 b'show-set',
3216 None,
3216 None,
3217 _(b'print internal representation of result set'),
3217 _(b'print internal representation of result set'),
3218 ),
3218 ),
3219 (
3219 (
3220 b'p',
3220 b'p',
3221 b'show-stage',
3221 b'show-stage',
3222 [],
3222 [],
3223 _(b'print parsed tree at the given stage'),
3223 _(b'print parsed tree at the given stage'),
3224 _(b'NAME'),
3224 _(b'NAME'),
3225 ),
3225 ),
3226 (b'', b'no-optimized', False, _(b'evaluate tree without optimization')),
3226 (b'', b'no-optimized', False, _(b'evaluate tree without optimization')),
3227 (b'', b'verify-optimized', False, _(b'verify optimized result')),
3227 (b'', b'verify-optimized', False, _(b'verify optimized result')),
3228 ],
3228 ],
3229 b'REVSPEC',
3229 b'REVSPEC',
3230 )
3230 )
3231 def debugrevspec(ui, repo, expr, **opts):
3231 def debugrevspec(ui, repo, expr, **opts):
3232 """parse and apply a revision specification
3232 """parse and apply a revision specification
3233
3233
3234 Use -p/--show-stage option to print the parsed tree at the given stages.
3234 Use -p/--show-stage option to print the parsed tree at the given stages.
3235 Use -p all to print tree at every stage.
3235 Use -p all to print tree at every stage.
3236
3236
3237 Use --no-show-revs option with -s or -p to print only the set
3237 Use --no-show-revs option with -s or -p to print only the set
3238 representation or the parsed tree respectively.
3238 representation or the parsed tree respectively.
3239
3239
3240 Use --verify-optimized to compare the optimized result with the unoptimized
3240 Use --verify-optimized to compare the optimized result with the unoptimized
3241 one. Returns 1 if the optimized result differs.
3241 one. Returns 1 if the optimized result differs.
3242 """
3242 """
3243 opts = pycompat.byteskwargs(opts)
3243 opts = pycompat.byteskwargs(opts)
3244 aliases = ui.configitems(b'revsetalias')
3244 aliases = ui.configitems(b'revsetalias')
3245 stages = [
3245 stages = [
3246 (b'parsed', lambda tree: tree),
3246 (b'parsed', lambda tree: tree),
3247 (
3247 (
3248 b'expanded',
3248 b'expanded',
3249 lambda tree: revsetlang.expandaliases(tree, aliases, ui.warn),
3249 lambda tree: revsetlang.expandaliases(tree, aliases, ui.warn),
3250 ),
3250 ),
3251 (b'concatenated', revsetlang.foldconcat),
3251 (b'concatenated', revsetlang.foldconcat),
3252 (b'analyzed', revsetlang.analyze),
3252 (b'analyzed', revsetlang.analyze),
3253 (b'optimized', revsetlang.optimize),
3253 (b'optimized', revsetlang.optimize),
3254 ]
3254 ]
3255 if opts[b'no_optimized']:
3255 if opts[b'no_optimized']:
3256 stages = stages[:-1]
3256 stages = stages[:-1]
3257 if opts[b'verify_optimized'] and opts[b'no_optimized']:
3257 if opts[b'verify_optimized'] and opts[b'no_optimized']:
3258 raise error.Abort(
3258 raise error.Abort(
3259 _(b'cannot use --verify-optimized with --no-optimized')
3259 _(b'cannot use --verify-optimized with --no-optimized')
3260 )
3260 )
3261 stagenames = {n for n, f in stages}
3261 stagenames = {n for n, f in stages}
3262
3262
3263 showalways = set()
3263 showalways = set()
3264 showchanged = set()
3264 showchanged = set()
3265 if ui.verbose and not opts[b'show_stage']:
3265 if ui.verbose and not opts[b'show_stage']:
3266 # show parsed tree by --verbose (deprecated)
3266 # show parsed tree by --verbose (deprecated)
3267 showalways.add(b'parsed')
3267 showalways.add(b'parsed')
3268 showchanged.update([b'expanded', b'concatenated'])
3268 showchanged.update([b'expanded', b'concatenated'])
3269 if opts[b'optimize']:
3269 if opts[b'optimize']:
3270 showalways.add(b'optimized')
3270 showalways.add(b'optimized')
3271 if opts[b'show_stage'] and opts[b'optimize']:
3271 if opts[b'show_stage'] and opts[b'optimize']:
3272 raise error.Abort(_(b'cannot use --optimize with --show-stage'))
3272 raise error.Abort(_(b'cannot use --optimize with --show-stage'))
3273 if opts[b'show_stage'] == [b'all']:
3273 if opts[b'show_stage'] == [b'all']:
3274 showalways.update(stagenames)
3274 showalways.update(stagenames)
3275 else:
3275 else:
3276 for n in opts[b'show_stage']:
3276 for n in opts[b'show_stage']:
3277 if n not in stagenames:
3277 if n not in stagenames:
3278 raise error.Abort(_(b'invalid stage name: %s') % n)
3278 raise error.Abort(_(b'invalid stage name: %s') % n)
3279 showalways.update(opts[b'show_stage'])
3279 showalways.update(opts[b'show_stage'])
3280
3280
3281 treebystage = {}
3281 treebystage = {}
3282 printedtree = None
3282 printedtree = None
3283 tree = revsetlang.parse(expr, lookup=revset.lookupfn(repo))
3283 tree = revsetlang.parse(expr, lookup=revset.lookupfn(repo))
3284 for n, f in stages:
3284 for n, f in stages:
3285 treebystage[n] = tree = f(tree)
3285 treebystage[n] = tree = f(tree)
3286 if n in showalways or (n in showchanged and tree != printedtree):
3286 if n in showalways or (n in showchanged and tree != printedtree):
3287 if opts[b'show_stage'] or n != b'parsed':
3287 if opts[b'show_stage'] or n != b'parsed':
3288 ui.write(b"* %s:\n" % n)
3288 ui.write(b"* %s:\n" % n)
3289 ui.write(revsetlang.prettyformat(tree), b"\n")
3289 ui.write(revsetlang.prettyformat(tree), b"\n")
3290 printedtree = tree
3290 printedtree = tree
3291
3291
3292 if opts[b'verify_optimized']:
3292 if opts[b'verify_optimized']:
3293 arevs = revset.makematcher(treebystage[b'analyzed'])(repo)
3293 arevs = revset.makematcher(treebystage[b'analyzed'])(repo)
3294 brevs = revset.makematcher(treebystage[b'optimized'])(repo)
3294 brevs = revset.makematcher(treebystage[b'optimized'])(repo)
3295 if opts[b'show_set'] or (opts[b'show_set'] is None and ui.verbose):
3295 if opts[b'show_set'] or (opts[b'show_set'] is None and ui.verbose):
3296 ui.writenoi18n(
3296 ui.writenoi18n(
3297 b"* analyzed set:\n", stringutil.prettyrepr(arevs), b"\n"
3297 b"* analyzed set:\n", stringutil.prettyrepr(arevs), b"\n"
3298 )
3298 )
3299 ui.writenoi18n(
3299 ui.writenoi18n(
3300 b"* optimized set:\n", stringutil.prettyrepr(brevs), b"\n"
3300 b"* optimized set:\n", stringutil.prettyrepr(brevs), b"\n"
3301 )
3301 )
3302 arevs = list(arevs)
3302 arevs = list(arevs)
3303 brevs = list(brevs)
3303 brevs = list(brevs)
3304 if arevs == brevs:
3304 if arevs == brevs:
3305 return 0
3305 return 0
3306 ui.writenoi18n(b'--- analyzed\n', label=b'diff.file_a')
3306 ui.writenoi18n(b'--- analyzed\n', label=b'diff.file_a')
3307 ui.writenoi18n(b'+++ optimized\n', label=b'diff.file_b')
3307 ui.writenoi18n(b'+++ optimized\n', label=b'diff.file_b')
3308 sm = difflib.SequenceMatcher(None, arevs, brevs)
3308 sm = difflib.SequenceMatcher(None, arevs, brevs)
3309 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3309 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3310 if tag in ('delete', 'replace'):
3310 if tag in ('delete', 'replace'):
3311 for c in arevs[alo:ahi]:
3311 for c in arevs[alo:ahi]:
3312 ui.write(b'-%d\n' % c, label=b'diff.deleted')
3312 ui.write(b'-%d\n' % c, label=b'diff.deleted')
3313 if tag in ('insert', 'replace'):
3313 if tag in ('insert', 'replace'):
3314 for c in brevs[blo:bhi]:
3314 for c in brevs[blo:bhi]:
3315 ui.write(b'+%d\n' % c, label=b'diff.inserted')
3315 ui.write(b'+%d\n' % c, label=b'diff.inserted')
3316 if tag == 'equal':
3316 if tag == 'equal':
3317 for c in arevs[alo:ahi]:
3317 for c in arevs[alo:ahi]:
3318 ui.write(b' %d\n' % c)
3318 ui.write(b' %d\n' % c)
3319 return 1
3319 return 1
3320
3320
3321 func = revset.makematcher(tree)
3321 func = revset.makematcher(tree)
3322 revs = func(repo)
3322 revs = func(repo)
3323 if opts[b'show_set'] or (opts[b'show_set'] is None and ui.verbose):
3323 if opts[b'show_set'] or (opts[b'show_set'] is None and ui.verbose):
3324 ui.writenoi18n(b"* set:\n", stringutil.prettyrepr(revs), b"\n")
3324 ui.writenoi18n(b"* set:\n", stringutil.prettyrepr(revs), b"\n")
3325 if not opts[b'show_revs']:
3325 if not opts[b'show_revs']:
3326 return
3326 return
3327 for c in revs:
3327 for c in revs:
3328 ui.write(b"%d\n" % c)
3328 ui.write(b"%d\n" % c)
3329
3329
3330
3330
3331 @command(
3331 @command(
3332 b'debugserve',
3332 b'debugserve',
3333 [
3333 [
3334 (
3334 (
3335 b'',
3335 b'',
3336 b'sshstdio',
3336 b'sshstdio',
3337 False,
3337 False,
3338 _(b'run an SSH server bound to process handles'),
3338 _(b'run an SSH server bound to process handles'),
3339 ),
3339 ),
3340 (b'', b'logiofd', b'', _(b'file descriptor to log server I/O to')),
3340 (b'', b'logiofd', b'', _(b'file descriptor to log server I/O to')),
3341 (b'', b'logiofile', b'', _(b'file to log server I/O to')),
3341 (b'', b'logiofile', b'', _(b'file to log server I/O to')),
3342 ],
3342 ],
3343 b'',
3343 b'',
3344 )
3344 )
3345 def debugserve(ui, repo, **opts):
3345 def debugserve(ui, repo, **opts):
3346 """run a server with advanced settings
3346 """run a server with advanced settings
3347
3347
3348 This command is similar to :hg:`serve`. It exists partially as a
3348 This command is similar to :hg:`serve`. It exists partially as a
3349 workaround to the fact that ``hg serve --stdio`` must have specific
3349 workaround to the fact that ``hg serve --stdio`` must have specific
3350 arguments for security reasons.
3350 arguments for security reasons.
3351 """
3351 """
3352 opts = pycompat.byteskwargs(opts)
3352 opts = pycompat.byteskwargs(opts)
3353
3353
3354 if not opts[b'sshstdio']:
3354 if not opts[b'sshstdio']:
3355 raise error.Abort(_(b'only --sshstdio is currently supported'))
3355 raise error.Abort(_(b'only --sshstdio is currently supported'))
3356
3356
3357 logfh = None
3357 logfh = None
3358
3358
3359 if opts[b'logiofd'] and opts[b'logiofile']:
3359 if opts[b'logiofd'] and opts[b'logiofile']:
3360 raise error.Abort(_(b'cannot use both --logiofd and --logiofile'))
3360 raise error.Abort(_(b'cannot use both --logiofd and --logiofile'))
3361
3361
3362 if opts[b'logiofd']:
3362 if opts[b'logiofd']:
3363 # Ideally we would be line buffered. But line buffering in binary
3363 # Ideally we would be line buffered. But line buffering in binary
3364 # mode isn't supported and emits a warning in Python 3.8+. Disabling
3364 # mode isn't supported and emits a warning in Python 3.8+. Disabling
3365 # buffering could have performance impacts. But since this isn't
3365 # buffering could have performance impacts. But since this isn't
3366 # performance critical code, it should be fine.
3366 # performance critical code, it should be fine.
3367 try:
3367 try:
3368 logfh = os.fdopen(int(opts[b'logiofd']), 'ab', 0)
3368 logfh = os.fdopen(int(opts[b'logiofd']), 'ab', 0)
3369 except OSError as e:
3369 except OSError as e:
3370 if e.errno != errno.ESPIPE:
3370 if e.errno != errno.ESPIPE:
3371 raise
3371 raise
3372 # can't seek a pipe, so `ab` mode fails on py3
3372 # can't seek a pipe, so `ab` mode fails on py3
3373 logfh = os.fdopen(int(opts[b'logiofd']), 'wb', 0)
3373 logfh = os.fdopen(int(opts[b'logiofd']), 'wb', 0)
3374 elif opts[b'logiofile']:
3374 elif opts[b'logiofile']:
3375 logfh = open(opts[b'logiofile'], b'ab', 0)
3375 logfh = open(opts[b'logiofile'], b'ab', 0)
3376
3376
3377 s = wireprotoserver.sshserver(ui, repo, logfh=logfh)
3377 s = wireprotoserver.sshserver(ui, repo, logfh=logfh)
3378 s.serve_forever()
3378 s.serve_forever()
3379 sys.exit(0)
3379
3380
3380
3381
3381 @command(b'debugsetparents', [], _(b'REV1 [REV2]'))
3382 @command(b'debugsetparents', [], _(b'REV1 [REV2]'))
3382 def debugsetparents(ui, repo, rev1, rev2=None):
3383 def debugsetparents(ui, repo, rev1, rev2=None):
3383 """manually set the parents of the current working directory
3384 """manually set the parents of the current working directory
3384
3385
3385 This is useful for writing repository conversion tools, but should
3386 This is useful for writing repository conversion tools, but should
3386 be used with care. For example, neither the working directory nor the
3387 be used with care. For example, neither the working directory nor the
3387 dirstate is updated, so file status may be incorrect after running this
3388 dirstate is updated, so file status may be incorrect after running this
3388 command.
3389 command.
3389
3390
3390 Returns 0 on success.
3391 Returns 0 on success.
3391 """
3392 """
3392
3393
3393 node1 = scmutil.revsingle(repo, rev1).node()
3394 node1 = scmutil.revsingle(repo, rev1).node()
3394 node2 = scmutil.revsingle(repo, rev2, b'null').node()
3395 node2 = scmutil.revsingle(repo, rev2, b'null').node()
3395
3396
3396 with repo.wlock():
3397 with repo.wlock():
3397 repo.setparents(node1, node2)
3398 repo.setparents(node1, node2)
3398
3399
3399
3400
3400 @command(b'debugsidedata', cmdutil.debugrevlogopts, _(b'-c|-m|FILE REV'))
3401 @command(b'debugsidedata', cmdutil.debugrevlogopts, _(b'-c|-m|FILE REV'))
3401 def debugsidedata(ui, repo, file_, rev=None, **opts):
3402 def debugsidedata(ui, repo, file_, rev=None, **opts):
3402 """dump the side data for a cl/manifest/file revision
3403 """dump the side data for a cl/manifest/file revision
3403
3404
3404 Use --verbose to dump the sidedata content."""
3405 Use --verbose to dump the sidedata content."""
3405 opts = pycompat.byteskwargs(opts)
3406 opts = pycompat.byteskwargs(opts)
3406 if opts.get(b'changelog') or opts.get(b'manifest') or opts.get(b'dir'):
3407 if opts.get(b'changelog') or opts.get(b'manifest') or opts.get(b'dir'):
3407 if rev is not None:
3408 if rev is not None:
3408 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
3409 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
3409 file_, rev = None, file_
3410 file_, rev = None, file_
3410 elif rev is None:
3411 elif rev is None:
3411 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
3412 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
3412 r = cmdutil.openstorage(repo, b'debugdata', file_, opts)
3413 r = cmdutil.openstorage(repo, b'debugdata', file_, opts)
3413 r = getattr(r, '_revlog', r)
3414 r = getattr(r, '_revlog', r)
3414 try:
3415 try:
3415 sidedata = r.sidedata(r.lookup(rev))
3416 sidedata = r.sidedata(r.lookup(rev))
3416 except KeyError:
3417 except KeyError:
3417 raise error.Abort(_(b'invalid revision identifier %s') % rev)
3418 raise error.Abort(_(b'invalid revision identifier %s') % rev)
3418 if sidedata:
3419 if sidedata:
3419 sidedata = list(sidedata.items())
3420 sidedata = list(sidedata.items())
3420 sidedata.sort()
3421 sidedata.sort()
3421 ui.writenoi18n(b'%d sidedata entries\n' % len(sidedata))
3422 ui.writenoi18n(b'%d sidedata entries\n' % len(sidedata))
3422 for key, value in sidedata:
3423 for key, value in sidedata:
3423 ui.writenoi18n(b' entry-%04o size %d\n' % (key, len(value)))
3424 ui.writenoi18n(b' entry-%04o size %d\n' % (key, len(value)))
3424 if ui.verbose:
3425 if ui.verbose:
3425 ui.writenoi18n(b' %s\n' % stringutil.pprint(value))
3426 ui.writenoi18n(b' %s\n' % stringutil.pprint(value))
3426
3427
3427
3428
3428 @command(b'debugssl', [], b'[SOURCE]', optionalrepo=True)
3429 @command(b'debugssl', [], b'[SOURCE]', optionalrepo=True)
3429 def debugssl(ui, repo, source=None, **opts):
3430 def debugssl(ui, repo, source=None, **opts):
3430 '''test a secure connection to a server
3431 '''test a secure connection to a server
3431
3432
3432 This builds the certificate chain for the server on Windows, installing the
3433 This builds the certificate chain for the server on Windows, installing the
3433 missing intermediates and trusted root via Windows Update if necessary. It
3434 missing intermediates and trusted root via Windows Update if necessary. It
3434 does nothing on other platforms.
3435 does nothing on other platforms.
3435
3436
3436 If SOURCE is omitted, the 'default' path will be used. If a URL is given,
3437 If SOURCE is omitted, the 'default' path will be used. If a URL is given,
3437 that server is used. See :hg:`help urls` for more information.
3438 that server is used. See :hg:`help urls` for more information.
3438
3439
3439 If the update succeeds, retry the original operation. Otherwise, the cause
3440 If the update succeeds, retry the original operation. Otherwise, the cause
3440 of the SSL error is likely another issue.
3441 of the SSL error is likely another issue.
3441 '''
3442 '''
3442 if not pycompat.iswindows:
3443 if not pycompat.iswindows:
3443 raise error.Abort(
3444 raise error.Abort(
3444 _(b'certificate chain building is only possible on Windows')
3445 _(b'certificate chain building is only possible on Windows')
3445 )
3446 )
3446
3447
3447 if not source:
3448 if not source:
3448 if not repo:
3449 if not repo:
3449 raise error.Abort(
3450 raise error.Abort(
3450 _(
3451 _(
3451 b"there is no Mercurial repository here, and no "
3452 b"there is no Mercurial repository here, and no "
3452 b"server specified"
3453 b"server specified"
3453 )
3454 )
3454 )
3455 )
3455 source = b"default"
3456 source = b"default"
3456
3457
3457 source, branches = hg.parseurl(ui.expandpath(source))
3458 source, branches = hg.parseurl(ui.expandpath(source))
3458 url = util.url(source)
3459 url = util.url(source)
3459
3460
3460 defaultport = {b'https': 443, b'ssh': 22}
3461 defaultport = {b'https': 443, b'ssh': 22}
3461 if url.scheme in defaultport:
3462 if url.scheme in defaultport:
3462 try:
3463 try:
3463 addr = (url.host, int(url.port or defaultport[url.scheme]))
3464 addr = (url.host, int(url.port or defaultport[url.scheme]))
3464 except ValueError:
3465 except ValueError:
3465 raise error.Abort(_(b"malformed port number in URL"))
3466 raise error.Abort(_(b"malformed port number in URL"))
3466 else:
3467 else:
3467 raise error.Abort(_(b"only https and ssh connections are supported"))
3468 raise error.Abort(_(b"only https and ssh connections are supported"))
3468
3469
3469 from . import win32
3470 from . import win32
3470
3471
3471 s = ssl.wrap_socket(
3472 s = ssl.wrap_socket(
3472 socket.socket(),
3473 socket.socket(),
3473 ssl_version=ssl.PROTOCOL_TLS,
3474 ssl_version=ssl.PROTOCOL_TLS,
3474 cert_reqs=ssl.CERT_NONE,
3475 cert_reqs=ssl.CERT_NONE,
3475 ca_certs=None,
3476 ca_certs=None,
3476 )
3477 )
3477
3478
3478 try:
3479 try:
3479 s.connect(addr)
3480 s.connect(addr)
3480 cert = s.getpeercert(True)
3481 cert = s.getpeercert(True)
3481
3482
3482 ui.status(_(b'checking the certificate chain for %s\n') % url.host)
3483 ui.status(_(b'checking the certificate chain for %s\n') % url.host)
3483
3484
3484 complete = win32.checkcertificatechain(cert, build=False)
3485 complete = win32.checkcertificatechain(cert, build=False)
3485
3486
3486 if not complete:
3487 if not complete:
3487 ui.status(_(b'certificate chain is incomplete, updating... '))
3488 ui.status(_(b'certificate chain is incomplete, updating... '))
3488
3489
3489 if not win32.checkcertificatechain(cert):
3490 if not win32.checkcertificatechain(cert):
3490 ui.status(_(b'failed.\n'))
3491 ui.status(_(b'failed.\n'))
3491 else:
3492 else:
3492 ui.status(_(b'done.\n'))
3493 ui.status(_(b'done.\n'))
3493 else:
3494 else:
3494 ui.status(_(b'full certificate chain is available\n'))
3495 ui.status(_(b'full certificate chain is available\n'))
3495 finally:
3496 finally:
3496 s.close()
3497 s.close()
3497
3498
3498
3499
3499 @command(
3500 @command(
3500 b"debugbackupbundle",
3501 b"debugbackupbundle",
3501 [
3502 [
3502 (
3503 (
3503 b"",
3504 b"",
3504 b"recover",
3505 b"recover",
3505 b"",
3506 b"",
3506 b"brings the specified changeset back into the repository",
3507 b"brings the specified changeset back into the repository",
3507 )
3508 )
3508 ]
3509 ]
3509 + cmdutil.logopts,
3510 + cmdutil.logopts,
3510 _(b"hg debugbackupbundle [--recover HASH]"),
3511 _(b"hg debugbackupbundle [--recover HASH]"),
3511 )
3512 )
3512 def debugbackupbundle(ui, repo, *pats, **opts):
3513 def debugbackupbundle(ui, repo, *pats, **opts):
3513 """lists the changesets available in backup bundles
3514 """lists the changesets available in backup bundles
3514
3515
3515 Without any arguments, this command prints a list of the changesets in each
3516 Without any arguments, this command prints a list of the changesets in each
3516 backup bundle.
3517 backup bundle.
3517
3518
3518 --recover takes a changeset hash and unbundles the first bundle that
3519 --recover takes a changeset hash and unbundles the first bundle that
3519 contains that hash, which puts that changeset back in your repository.
3520 contains that hash, which puts that changeset back in your repository.
3520
3521
3521 --verbose will print the entire commit message and the bundle path for that
3522 --verbose will print the entire commit message and the bundle path for that
3522 backup.
3523 backup.
3523 """
3524 """
3524 backups = list(
3525 backups = list(
3525 filter(
3526 filter(
3526 os.path.isfile, glob.glob(repo.vfs.join(b"strip-backup") + b"/*.hg")
3527 os.path.isfile, glob.glob(repo.vfs.join(b"strip-backup") + b"/*.hg")
3527 )
3528 )
3528 )
3529 )
3529 backups.sort(key=lambda x: os.path.getmtime(x), reverse=True)
3530 backups.sort(key=lambda x: os.path.getmtime(x), reverse=True)
3530
3531
3531 opts = pycompat.byteskwargs(opts)
3532 opts = pycompat.byteskwargs(opts)
3532 opts[b"bundle"] = b""
3533 opts[b"bundle"] = b""
3533 opts[b"force"] = None
3534 opts[b"force"] = None
3534 limit = logcmdutil.getlimit(opts)
3535 limit = logcmdutil.getlimit(opts)
3535
3536
3536 def display(other, chlist, displayer):
3537 def display(other, chlist, displayer):
3537 if opts.get(b"newest_first"):
3538 if opts.get(b"newest_first"):
3538 chlist.reverse()
3539 chlist.reverse()
3539 count = 0
3540 count = 0
3540 for n in chlist:
3541 for n in chlist:
3541 if limit is not None and count >= limit:
3542 if limit is not None and count >= limit:
3542 break
3543 break
3543 parents = [True for p in other.changelog.parents(n) if p != nullid]
3544 parents = [True for p in other.changelog.parents(n) if p != nullid]
3544 if opts.get(b"no_merges") and len(parents) == 2:
3545 if opts.get(b"no_merges") and len(parents) == 2:
3545 continue
3546 continue
3546 count += 1
3547 count += 1
3547 displayer.show(other[n])
3548 displayer.show(other[n])
3548
3549
3549 recovernode = opts.get(b"recover")
3550 recovernode = opts.get(b"recover")
3550 if recovernode:
3551 if recovernode:
3551 if scmutil.isrevsymbol(repo, recovernode):
3552 if scmutil.isrevsymbol(repo, recovernode):
3552 ui.warn(_(b"%s already exists in the repo\n") % recovernode)
3553 ui.warn(_(b"%s already exists in the repo\n") % recovernode)
3553 return
3554 return
3554 elif backups:
3555 elif backups:
3555 msg = _(
3556 msg = _(
3556 b"Recover changesets using: hg debugbackupbundle --recover "
3557 b"Recover changesets using: hg debugbackupbundle --recover "
3557 b"<changeset hash>\n\nAvailable backup changesets:"
3558 b"<changeset hash>\n\nAvailable backup changesets:"
3558 )
3559 )
3559 ui.status(msg, label=b"status.removed")
3560 ui.status(msg, label=b"status.removed")
3560 else:
3561 else:
3561 ui.status(_(b"no backup changesets found\n"))
3562 ui.status(_(b"no backup changesets found\n"))
3562 return
3563 return
3563
3564
3564 for backup in backups:
3565 for backup in backups:
3565 # Much of this is copied from the hg incoming logic
3566 # Much of this is copied from the hg incoming logic
3566 source = ui.expandpath(os.path.relpath(backup, encoding.getcwd()))
3567 source = ui.expandpath(os.path.relpath(backup, encoding.getcwd()))
3567 source, branches = hg.parseurl(source, opts.get(b"branch"))
3568 source, branches = hg.parseurl(source, opts.get(b"branch"))
3568 try:
3569 try:
3569 other = hg.peer(repo, opts, source)
3570 other = hg.peer(repo, opts, source)
3570 except error.LookupError as ex:
3571 except error.LookupError as ex:
3571 msg = _(b"\nwarning: unable to open bundle %s") % source
3572 msg = _(b"\nwarning: unable to open bundle %s") % source
3572 hint = _(b"\n(missing parent rev %s)\n") % short(ex.name)
3573 hint = _(b"\n(missing parent rev %s)\n") % short(ex.name)
3573 ui.warn(msg, hint=hint)
3574 ui.warn(msg, hint=hint)
3574 continue
3575 continue
3575 revs, checkout = hg.addbranchrevs(
3576 revs, checkout = hg.addbranchrevs(
3576 repo, other, branches, opts.get(b"rev")
3577 repo, other, branches, opts.get(b"rev")
3577 )
3578 )
3578
3579
3579 if revs:
3580 if revs:
3580 revs = [other.lookup(rev) for rev in revs]
3581 revs = [other.lookup(rev) for rev in revs]
3581
3582
3582 quiet = ui.quiet
3583 quiet = ui.quiet
3583 try:
3584 try:
3584 ui.quiet = True
3585 ui.quiet = True
3585 other, chlist, cleanupfn = bundlerepo.getremotechanges(
3586 other, chlist, cleanupfn = bundlerepo.getremotechanges(
3586 ui, repo, other, revs, opts[b"bundle"], opts[b"force"]
3587 ui, repo, other, revs, opts[b"bundle"], opts[b"force"]
3587 )
3588 )
3588 except error.LookupError:
3589 except error.LookupError:
3589 continue
3590 continue
3590 finally:
3591 finally:
3591 ui.quiet = quiet
3592 ui.quiet = quiet
3592
3593
3593 try:
3594 try:
3594 if not chlist:
3595 if not chlist:
3595 continue
3596 continue
3596 if recovernode:
3597 if recovernode:
3597 with repo.lock(), repo.transaction(b"unbundle") as tr:
3598 with repo.lock(), repo.transaction(b"unbundle") as tr:
3598 if scmutil.isrevsymbol(other, recovernode):
3599 if scmutil.isrevsymbol(other, recovernode):
3599 ui.status(_(b"Unbundling %s\n") % (recovernode))
3600 ui.status(_(b"Unbundling %s\n") % (recovernode))
3600 f = hg.openpath(ui, source)
3601 f = hg.openpath(ui, source)
3601 gen = exchange.readbundle(ui, f, source)
3602 gen = exchange.readbundle(ui, f, source)
3602 if isinstance(gen, bundle2.unbundle20):
3603 if isinstance(gen, bundle2.unbundle20):
3603 bundle2.applybundle(
3604 bundle2.applybundle(
3604 repo,
3605 repo,
3605 gen,
3606 gen,
3606 tr,
3607 tr,
3607 source=b"unbundle",
3608 source=b"unbundle",
3608 url=b"bundle:" + source,
3609 url=b"bundle:" + source,
3609 )
3610 )
3610 else:
3611 else:
3611 gen.apply(repo, b"unbundle", b"bundle:" + source)
3612 gen.apply(repo, b"unbundle", b"bundle:" + source)
3612 break
3613 break
3613 else:
3614 else:
3614 backupdate = encoding.strtolocal(
3615 backupdate = encoding.strtolocal(
3615 time.strftime(
3616 time.strftime(
3616 "%a %H:%M, %Y-%m-%d",
3617 "%a %H:%M, %Y-%m-%d",
3617 time.localtime(os.path.getmtime(source)),
3618 time.localtime(os.path.getmtime(source)),
3618 )
3619 )
3619 )
3620 )
3620 ui.status(b"\n%s\n" % (backupdate.ljust(50)))
3621 ui.status(b"\n%s\n" % (backupdate.ljust(50)))
3621 if ui.verbose:
3622 if ui.verbose:
3622 ui.status(b"%s%s\n" % (b"bundle:".ljust(13), source))
3623 ui.status(b"%s%s\n" % (b"bundle:".ljust(13), source))
3623 else:
3624 else:
3624 opts[
3625 opts[
3625 b"template"
3626 b"template"
3626 ] = b"{label('status.modified', node|short)} {desc|firstline}\n"
3627 ] = b"{label('status.modified', node|short)} {desc|firstline}\n"
3627 displayer = logcmdutil.changesetdisplayer(
3628 displayer = logcmdutil.changesetdisplayer(
3628 ui, other, opts, False
3629 ui, other, opts, False
3629 )
3630 )
3630 display(other, chlist, displayer)
3631 display(other, chlist, displayer)
3631 displayer.close()
3632 displayer.close()
3632 finally:
3633 finally:
3633 cleanupfn()
3634 cleanupfn()
3634
3635
3635
3636
3636 @command(
3637 @command(
3637 b'debugsub',
3638 b'debugsub',
3638 [(b'r', b'rev', b'', _(b'revision to check'), _(b'REV'))],
3639 [(b'r', b'rev', b'', _(b'revision to check'), _(b'REV'))],
3639 _(b'[-r REV] [REV]'),
3640 _(b'[-r REV] [REV]'),
3640 )
3641 )
3641 def debugsub(ui, repo, rev=None):
3642 def debugsub(ui, repo, rev=None):
3642 ctx = scmutil.revsingle(repo, rev, None)
3643 ctx = scmutil.revsingle(repo, rev, None)
3643 for k, v in sorted(ctx.substate.items()):
3644 for k, v in sorted(ctx.substate.items()):
3644 ui.writenoi18n(b'path %s\n' % k)
3645 ui.writenoi18n(b'path %s\n' % k)
3645 ui.writenoi18n(b' source %s\n' % v[0])
3646 ui.writenoi18n(b' source %s\n' % v[0])
3646 ui.writenoi18n(b' revision %s\n' % v[1])
3647 ui.writenoi18n(b' revision %s\n' % v[1])
3647
3648
3648
3649
3649 @command(
3650 @command(
3650 b'debugsuccessorssets',
3651 b'debugsuccessorssets',
3651 [(b'', b'closest', False, _(b'return closest successors sets only'))],
3652 [(b'', b'closest', False, _(b'return closest successors sets only'))],
3652 _(b'[REV]'),
3653 _(b'[REV]'),
3653 )
3654 )
3654 def debugsuccessorssets(ui, repo, *revs, **opts):
3655 def debugsuccessorssets(ui, repo, *revs, **opts):
3655 """show set of successors for revision
3656 """show set of successors for revision
3656
3657
3657 A successors set of changeset A is a consistent group of revisions that
3658 A successors set of changeset A is a consistent group of revisions that
3658 succeed A. It contains non-obsolete changesets only unless closests
3659 succeed A. It contains non-obsolete changesets only unless closests
3659 successors set is set.
3660 successors set is set.
3660
3661
3661 In most cases a changeset A has a single successors set containing a single
3662 In most cases a changeset A has a single successors set containing a single
3662 successor (changeset A replaced by A').
3663 successor (changeset A replaced by A').
3663
3664
3664 A changeset that is made obsolete with no successors are called "pruned".
3665 A changeset that is made obsolete with no successors are called "pruned".
3665 Such changesets have no successors sets at all.
3666 Such changesets have no successors sets at all.
3666
3667
3667 A changeset that has been "split" will have a successors set containing
3668 A changeset that has been "split" will have a successors set containing
3668 more than one successor.
3669 more than one successor.
3669
3670
3670 A changeset that has been rewritten in multiple different ways is called
3671 A changeset that has been rewritten in multiple different ways is called
3671 "divergent". Such changesets have multiple successor sets (each of which
3672 "divergent". Such changesets have multiple successor sets (each of which
3672 may also be split, i.e. have multiple successors).
3673 may also be split, i.e. have multiple successors).
3673
3674
3674 Results are displayed as follows::
3675 Results are displayed as follows::
3675
3676
3676 <rev1>
3677 <rev1>
3677 <successors-1A>
3678 <successors-1A>
3678 <rev2>
3679 <rev2>
3679 <successors-2A>
3680 <successors-2A>
3680 <successors-2B1> <successors-2B2> <successors-2B3>
3681 <successors-2B1> <successors-2B2> <successors-2B3>
3681
3682
3682 Here rev2 has two possible (i.e. divergent) successors sets. The first
3683 Here rev2 has two possible (i.e. divergent) successors sets. The first
3683 holds one element, whereas the second holds three (i.e. the changeset has
3684 holds one element, whereas the second holds three (i.e. the changeset has
3684 been split).
3685 been split).
3685 """
3686 """
3686 # passed to successorssets caching computation from one call to another
3687 # passed to successorssets caching computation from one call to another
3687 cache = {}
3688 cache = {}
3688 ctx2str = bytes
3689 ctx2str = bytes
3689 node2str = short
3690 node2str = short
3690 for rev in scmutil.revrange(repo, revs):
3691 for rev in scmutil.revrange(repo, revs):
3691 ctx = repo[rev]
3692 ctx = repo[rev]
3692 ui.write(b'%s\n' % ctx2str(ctx))
3693 ui.write(b'%s\n' % ctx2str(ctx))
3693 for succsset in obsutil.successorssets(
3694 for succsset in obsutil.successorssets(
3694 repo, ctx.node(), closest=opts['closest'], cache=cache
3695 repo, ctx.node(), closest=opts['closest'], cache=cache
3695 ):
3696 ):
3696 if succsset:
3697 if succsset:
3697 ui.write(b' ')
3698 ui.write(b' ')
3698 ui.write(node2str(succsset[0]))
3699 ui.write(node2str(succsset[0]))
3699 for node in succsset[1:]:
3700 for node in succsset[1:]:
3700 ui.write(b' ')
3701 ui.write(b' ')
3701 ui.write(node2str(node))
3702 ui.write(node2str(node))
3702 ui.write(b'\n')
3703 ui.write(b'\n')
3703
3704
3704
3705
3705 @command(b'debugtagscache', [])
3706 @command(b'debugtagscache', [])
3706 def debugtagscache(ui, repo):
3707 def debugtagscache(ui, repo):
3707 """display the contents of .hg/cache/hgtagsfnodes1"""
3708 """display the contents of .hg/cache/hgtagsfnodes1"""
3708 cache = tagsmod.hgtagsfnodescache(repo.unfiltered())
3709 cache = tagsmod.hgtagsfnodescache(repo.unfiltered())
3709 for r in repo:
3710 for r in repo:
3710 node = repo[r].node()
3711 node = repo[r].node()
3711 tagsnode = cache.getfnode(node, computemissing=False)
3712 tagsnode = cache.getfnode(node, computemissing=False)
3712 tagsnodedisplay = hex(tagsnode) if tagsnode else b'missing/invalid'
3713 tagsnodedisplay = hex(tagsnode) if tagsnode else b'missing/invalid'
3713 ui.write(b'%d %s %s\n' % (r, hex(node), tagsnodedisplay))
3714 ui.write(b'%d %s %s\n' % (r, hex(node), tagsnodedisplay))
3714
3715
3715
3716
3716 @command(
3717 @command(
3717 b'debugtemplate',
3718 b'debugtemplate',
3718 [
3719 [
3719 (b'r', b'rev', [], _(b'apply template on changesets'), _(b'REV')),
3720 (b'r', b'rev', [], _(b'apply template on changesets'), _(b'REV')),
3720 (b'D', b'define', [], _(b'define template keyword'), _(b'KEY=VALUE')),
3721 (b'D', b'define', [], _(b'define template keyword'), _(b'KEY=VALUE')),
3721 ],
3722 ],
3722 _(b'[-r REV]... [-D KEY=VALUE]... TEMPLATE'),
3723 _(b'[-r REV]... [-D KEY=VALUE]... TEMPLATE'),
3723 optionalrepo=True,
3724 optionalrepo=True,
3724 )
3725 )
3725 def debugtemplate(ui, repo, tmpl, **opts):
3726 def debugtemplate(ui, repo, tmpl, **opts):
3726 """parse and apply a template
3727 """parse and apply a template
3727
3728
3728 If -r/--rev is given, the template is processed as a log template and
3729 If -r/--rev is given, the template is processed as a log template and
3729 applied to the given changesets. Otherwise, it is processed as a generic
3730 applied to the given changesets. Otherwise, it is processed as a generic
3730 template.
3731 template.
3731
3732
3732 Use --verbose to print the parsed tree.
3733 Use --verbose to print the parsed tree.
3733 """
3734 """
3734 revs = None
3735 revs = None
3735 if opts['rev']:
3736 if opts['rev']:
3736 if repo is None:
3737 if repo is None:
3737 raise error.RepoError(
3738 raise error.RepoError(
3738 _(b'there is no Mercurial repository here (.hg not found)')
3739 _(b'there is no Mercurial repository here (.hg not found)')
3739 )
3740 )
3740 revs = scmutil.revrange(repo, opts['rev'])
3741 revs = scmutil.revrange(repo, opts['rev'])
3741
3742
3742 props = {}
3743 props = {}
3743 for d in opts['define']:
3744 for d in opts['define']:
3744 try:
3745 try:
3745 k, v = (e.strip() for e in d.split(b'=', 1))
3746 k, v = (e.strip() for e in d.split(b'=', 1))
3746 if not k or k == b'ui':
3747 if not k or k == b'ui':
3747 raise ValueError
3748 raise ValueError
3748 props[k] = v
3749 props[k] = v
3749 except ValueError:
3750 except ValueError:
3750 raise error.Abort(_(b'malformed keyword definition: %s') % d)
3751 raise error.Abort(_(b'malformed keyword definition: %s') % d)
3751
3752
3752 if ui.verbose:
3753 if ui.verbose:
3753 aliases = ui.configitems(b'templatealias')
3754 aliases = ui.configitems(b'templatealias')
3754 tree = templater.parse(tmpl)
3755 tree = templater.parse(tmpl)
3755 ui.note(templater.prettyformat(tree), b'\n')
3756 ui.note(templater.prettyformat(tree), b'\n')
3756 newtree = templater.expandaliases(tree, aliases)
3757 newtree = templater.expandaliases(tree, aliases)
3757 if newtree != tree:
3758 if newtree != tree:
3758 ui.notenoi18n(
3759 ui.notenoi18n(
3759 b"* expanded:\n", templater.prettyformat(newtree), b'\n'
3760 b"* expanded:\n", templater.prettyformat(newtree), b'\n'
3760 )
3761 )
3761
3762
3762 if revs is None:
3763 if revs is None:
3763 tres = formatter.templateresources(ui, repo)
3764 tres = formatter.templateresources(ui, repo)
3764 t = formatter.maketemplater(ui, tmpl, resources=tres)
3765 t = formatter.maketemplater(ui, tmpl, resources=tres)
3765 if ui.verbose:
3766 if ui.verbose:
3766 kwds, funcs = t.symbolsuseddefault()
3767 kwds, funcs = t.symbolsuseddefault()
3767 ui.writenoi18n(b"* keywords: %s\n" % b', '.join(sorted(kwds)))
3768 ui.writenoi18n(b"* keywords: %s\n" % b', '.join(sorted(kwds)))
3768 ui.writenoi18n(b"* functions: %s\n" % b', '.join(sorted(funcs)))
3769 ui.writenoi18n(b"* functions: %s\n" % b', '.join(sorted(funcs)))
3769 ui.write(t.renderdefault(props))
3770 ui.write(t.renderdefault(props))
3770 else:
3771 else:
3771 displayer = logcmdutil.maketemplater(ui, repo, tmpl)
3772 displayer = logcmdutil.maketemplater(ui, repo, tmpl)
3772 if ui.verbose:
3773 if ui.verbose:
3773 kwds, funcs = displayer.t.symbolsuseddefault()
3774 kwds, funcs = displayer.t.symbolsuseddefault()
3774 ui.writenoi18n(b"* keywords: %s\n" % b', '.join(sorted(kwds)))
3775 ui.writenoi18n(b"* keywords: %s\n" % b', '.join(sorted(kwds)))
3775 ui.writenoi18n(b"* functions: %s\n" % b', '.join(sorted(funcs)))
3776 ui.writenoi18n(b"* functions: %s\n" % b', '.join(sorted(funcs)))
3776 for r in revs:
3777 for r in revs:
3777 displayer.show(repo[r], **pycompat.strkwargs(props))
3778 displayer.show(repo[r], **pycompat.strkwargs(props))
3778 displayer.close()
3779 displayer.close()
3779
3780
3780
3781
3781 @command(
3782 @command(
3782 b'debuguigetpass',
3783 b'debuguigetpass',
3783 [(b'p', b'prompt', b'', _(b'prompt text'), _(b'TEXT')),],
3784 [(b'p', b'prompt', b'', _(b'prompt text'), _(b'TEXT')),],
3784 _(b'[-p TEXT]'),
3785 _(b'[-p TEXT]'),
3785 norepo=True,
3786 norepo=True,
3786 )
3787 )
3787 def debuguigetpass(ui, prompt=b''):
3788 def debuguigetpass(ui, prompt=b''):
3788 """show prompt to type password"""
3789 """show prompt to type password"""
3789 r = ui.getpass(prompt)
3790 r = ui.getpass(prompt)
3790 ui.writenoi18n(b'response: %s\n' % r)
3791 ui.writenoi18n(b'response: %s\n' % r)
3791
3792
3792
3793
3793 @command(
3794 @command(
3794 b'debuguiprompt',
3795 b'debuguiprompt',
3795 [(b'p', b'prompt', b'', _(b'prompt text'), _(b'TEXT')),],
3796 [(b'p', b'prompt', b'', _(b'prompt text'), _(b'TEXT')),],
3796 _(b'[-p TEXT]'),
3797 _(b'[-p TEXT]'),
3797 norepo=True,
3798 norepo=True,
3798 )
3799 )
3799 def debuguiprompt(ui, prompt=b''):
3800 def debuguiprompt(ui, prompt=b''):
3800 """show plain prompt"""
3801 """show plain prompt"""
3801 r = ui.prompt(prompt)
3802 r = ui.prompt(prompt)
3802 ui.writenoi18n(b'response: %s\n' % r)
3803 ui.writenoi18n(b'response: %s\n' % r)
3803
3804
3804
3805
3805 @command(b'debugupdatecaches', [])
3806 @command(b'debugupdatecaches', [])
3806 def debugupdatecaches(ui, repo, *pats, **opts):
3807 def debugupdatecaches(ui, repo, *pats, **opts):
3807 """warm all known caches in the repository"""
3808 """warm all known caches in the repository"""
3808 with repo.wlock(), repo.lock():
3809 with repo.wlock(), repo.lock():
3809 repo.updatecaches(full=True)
3810 repo.updatecaches(full=True)
3810
3811
3811
3812
3812 @command(
3813 @command(
3813 b'debugupgraderepo',
3814 b'debugupgraderepo',
3814 [
3815 [
3815 (
3816 (
3816 b'o',
3817 b'o',
3817 b'optimize',
3818 b'optimize',
3818 [],
3819 [],
3819 _(b'extra optimization to perform'),
3820 _(b'extra optimization to perform'),
3820 _(b'NAME'),
3821 _(b'NAME'),
3821 ),
3822 ),
3822 (b'', b'run', False, _(b'performs an upgrade')),
3823 (b'', b'run', False, _(b'performs an upgrade')),
3823 (b'', b'backup', True, _(b'keep the old repository content around')),
3824 (b'', b'backup', True, _(b'keep the old repository content around')),
3824 (b'', b'changelog', None, _(b'select the changelog for upgrade')),
3825 (b'', b'changelog', None, _(b'select the changelog for upgrade')),
3825 (b'', b'manifest', None, _(b'select the manifest for upgrade')),
3826 (b'', b'manifest', None, _(b'select the manifest for upgrade')),
3826 ],
3827 ],
3827 )
3828 )
3828 def debugupgraderepo(ui, repo, run=False, optimize=None, backup=True, **opts):
3829 def debugupgraderepo(ui, repo, run=False, optimize=None, backup=True, **opts):
3829 """upgrade a repository to use different features
3830 """upgrade a repository to use different features
3830
3831
3831 If no arguments are specified, the repository is evaluated for upgrade
3832 If no arguments are specified, the repository is evaluated for upgrade
3832 and a list of problems and potential optimizations is printed.
3833 and a list of problems and potential optimizations is printed.
3833
3834
3834 With ``--run``, a repository upgrade is performed. Behavior of the upgrade
3835 With ``--run``, a repository upgrade is performed. Behavior of the upgrade
3835 can be influenced via additional arguments. More details will be provided
3836 can be influenced via additional arguments. More details will be provided
3836 by the command output when run without ``--run``.
3837 by the command output when run without ``--run``.
3837
3838
3838 During the upgrade, the repository will be locked and no writes will be
3839 During the upgrade, the repository will be locked and no writes will be
3839 allowed.
3840 allowed.
3840
3841
3841 At the end of the upgrade, the repository may not be readable while new
3842 At the end of the upgrade, the repository may not be readable while new
3842 repository data is swapped in. This window will be as long as it takes to
3843 repository data is swapped in. This window will be as long as it takes to
3843 rename some directories inside the ``.hg`` directory. On most machines, this
3844 rename some directories inside the ``.hg`` directory. On most machines, this
3844 should complete almost instantaneously and the chances of a consumer being
3845 should complete almost instantaneously and the chances of a consumer being
3845 unable to access the repository should be low.
3846 unable to access the repository should be low.
3846
3847
3847 By default, all revlog will be upgraded. You can restrict this using flag
3848 By default, all revlog will be upgraded. You can restrict this using flag
3848 such as `--manifest`:
3849 such as `--manifest`:
3849
3850
3850 * `--manifest`: only optimize the manifest
3851 * `--manifest`: only optimize the manifest
3851 * `--no-manifest`: optimize all revlog but the manifest
3852 * `--no-manifest`: optimize all revlog but the manifest
3852 * `--changelog`: optimize the changelog only
3853 * `--changelog`: optimize the changelog only
3853 * `--no-changelog --no-manifest`: optimize filelogs only
3854 * `--no-changelog --no-manifest`: optimize filelogs only
3854 """
3855 """
3855 return upgrade.upgraderepo(
3856 return upgrade.upgraderepo(
3856 ui, repo, run=run, optimize=optimize, backup=backup, **opts
3857 ui, repo, run=run, optimize=optimize, backup=backup, **opts
3857 )
3858 )
3858
3859
3859
3860
3860 @command(
3861 @command(
3861 b'debugwalk', cmdutil.walkopts, _(b'[OPTION]... [FILE]...'), inferrepo=True
3862 b'debugwalk', cmdutil.walkopts, _(b'[OPTION]... [FILE]...'), inferrepo=True
3862 )
3863 )
3863 def debugwalk(ui, repo, *pats, **opts):
3864 def debugwalk(ui, repo, *pats, **opts):
3864 """show how files match on given patterns"""
3865 """show how files match on given patterns"""
3865 opts = pycompat.byteskwargs(opts)
3866 opts = pycompat.byteskwargs(opts)
3866 m = scmutil.match(repo[None], pats, opts)
3867 m = scmutil.match(repo[None], pats, opts)
3867 if ui.verbose:
3868 if ui.verbose:
3868 ui.writenoi18n(b'* matcher:\n', stringutil.prettyrepr(m), b'\n')
3869 ui.writenoi18n(b'* matcher:\n', stringutil.prettyrepr(m), b'\n')
3869 items = list(repo[None].walk(m))
3870 items = list(repo[None].walk(m))
3870 if not items:
3871 if not items:
3871 return
3872 return
3872 f = lambda fn: fn
3873 f = lambda fn: fn
3873 if ui.configbool(b'ui', b'slash') and pycompat.ossep != b'/':
3874 if ui.configbool(b'ui', b'slash') and pycompat.ossep != b'/':
3874 f = lambda fn: util.normpath(fn)
3875 f = lambda fn: util.normpath(fn)
3875 fmt = b'f %%-%ds %%-%ds %%s' % (
3876 fmt = b'f %%-%ds %%-%ds %%s' % (
3876 max([len(abs) for abs in items]),
3877 max([len(abs) for abs in items]),
3877 max([len(repo.pathto(abs)) for abs in items]),
3878 max([len(repo.pathto(abs)) for abs in items]),
3878 )
3879 )
3879 for abs in items:
3880 for abs in items:
3880 line = fmt % (
3881 line = fmt % (
3881 abs,
3882 abs,
3882 f(repo.pathto(abs)),
3883 f(repo.pathto(abs)),
3883 m.exact(abs) and b'exact' or b'',
3884 m.exact(abs) and b'exact' or b'',
3884 )
3885 )
3885 ui.write(b"%s\n" % line.rstrip())
3886 ui.write(b"%s\n" % line.rstrip())
3886
3887
3887
3888
3888 @command(b'debugwhyunstable', [], _(b'REV'))
3889 @command(b'debugwhyunstable', [], _(b'REV'))
3889 def debugwhyunstable(ui, repo, rev):
3890 def debugwhyunstable(ui, repo, rev):
3890 """explain instabilities of a changeset"""
3891 """explain instabilities of a changeset"""
3891 for entry in obsutil.whyunstable(repo, scmutil.revsingle(repo, rev)):
3892 for entry in obsutil.whyunstable(repo, scmutil.revsingle(repo, rev)):
3892 dnodes = b''
3893 dnodes = b''
3893 if entry.get(b'divergentnodes'):
3894 if entry.get(b'divergentnodes'):
3894 dnodes = (
3895 dnodes = (
3895 b' '.join(
3896 b' '.join(
3896 b'%s (%s)' % (ctx.hex(), ctx.phasestr())
3897 b'%s (%s)' % (ctx.hex(), ctx.phasestr())
3897 for ctx in entry[b'divergentnodes']
3898 for ctx in entry[b'divergentnodes']
3898 )
3899 )
3899 + b' '
3900 + b' '
3900 )
3901 )
3901 ui.write(
3902 ui.write(
3902 b'%s: %s%s %s\n'
3903 b'%s: %s%s %s\n'
3903 % (entry[b'instability'], dnodes, entry[b'reason'], entry[b'node'])
3904 % (entry[b'instability'], dnodes, entry[b'reason'], entry[b'node'])
3904 )
3905 )
3905
3906
3906
3907
3907 @command(
3908 @command(
3908 b'debugwireargs',
3909 b'debugwireargs',
3909 [
3910 [
3910 (b'', b'three', b'', b'three'),
3911 (b'', b'three', b'', b'three'),
3911 (b'', b'four', b'', b'four'),
3912 (b'', b'four', b'', b'four'),
3912 (b'', b'five', b'', b'five'),
3913 (b'', b'five', b'', b'five'),
3913 ]
3914 ]
3914 + cmdutil.remoteopts,
3915 + cmdutil.remoteopts,
3915 _(b'REPO [OPTIONS]... [ONE [TWO]]'),
3916 _(b'REPO [OPTIONS]... [ONE [TWO]]'),
3916 norepo=True,
3917 norepo=True,
3917 )
3918 )
3918 def debugwireargs(ui, repopath, *vals, **opts):
3919 def debugwireargs(ui, repopath, *vals, **opts):
3919 opts = pycompat.byteskwargs(opts)
3920 opts = pycompat.byteskwargs(opts)
3920 repo = hg.peer(ui, opts, repopath)
3921 repo = hg.peer(ui, opts, repopath)
3921 for opt in cmdutil.remoteopts:
3922 for opt in cmdutil.remoteopts:
3922 del opts[opt[1]]
3923 del opts[opt[1]]
3923 args = {}
3924 args = {}
3924 for k, v in pycompat.iteritems(opts):
3925 for k, v in pycompat.iteritems(opts):
3925 if v:
3926 if v:
3926 args[k] = v
3927 args[k] = v
3927 args = pycompat.strkwargs(args)
3928 args = pycompat.strkwargs(args)
3928 # run twice to check that we don't mess up the stream for the next command
3929 # run twice to check that we don't mess up the stream for the next command
3929 res1 = repo.debugwireargs(*vals, **args)
3930 res1 = repo.debugwireargs(*vals, **args)
3930 res2 = repo.debugwireargs(*vals, **args)
3931 res2 = repo.debugwireargs(*vals, **args)
3931 ui.write(b"%s\n" % res1)
3932 ui.write(b"%s\n" % res1)
3932 if res1 != res2:
3933 if res1 != res2:
3933 ui.warn(b"%s\n" % res2)
3934 ui.warn(b"%s\n" % res2)
3934
3935
3935
3936
3936 def _parsewirelangblocks(fh):
3937 def _parsewirelangblocks(fh):
3937 activeaction = None
3938 activeaction = None
3938 blocklines = []
3939 blocklines = []
3939 lastindent = 0
3940 lastindent = 0
3940
3941
3941 for line in fh:
3942 for line in fh:
3942 line = line.rstrip()
3943 line = line.rstrip()
3943 if not line:
3944 if not line:
3944 continue
3945 continue
3945
3946
3946 if line.startswith(b'#'):
3947 if line.startswith(b'#'):
3947 continue
3948 continue
3948
3949
3949 if not line.startswith(b' '):
3950 if not line.startswith(b' '):
3950 # New block. Flush previous one.
3951 # New block. Flush previous one.
3951 if activeaction:
3952 if activeaction:
3952 yield activeaction, blocklines
3953 yield activeaction, blocklines
3953
3954
3954 activeaction = line
3955 activeaction = line
3955 blocklines = []
3956 blocklines = []
3956 lastindent = 0
3957 lastindent = 0
3957 continue
3958 continue
3958
3959
3959 # Else we start with an indent.
3960 # Else we start with an indent.
3960
3961
3961 if not activeaction:
3962 if not activeaction:
3962 raise error.Abort(_(b'indented line outside of block'))
3963 raise error.Abort(_(b'indented line outside of block'))
3963
3964
3964 indent = len(line) - len(line.lstrip())
3965 indent = len(line) - len(line.lstrip())
3965
3966
3966 # If this line is indented more than the last line, concatenate it.
3967 # If this line is indented more than the last line, concatenate it.
3967 if indent > lastindent and blocklines:
3968 if indent > lastindent and blocklines:
3968 blocklines[-1] += line.lstrip()
3969 blocklines[-1] += line.lstrip()
3969 else:
3970 else:
3970 blocklines.append(line)
3971 blocklines.append(line)
3971 lastindent = indent
3972 lastindent = indent
3972
3973
3973 # Flush last block.
3974 # Flush last block.
3974 if activeaction:
3975 if activeaction:
3975 yield activeaction, blocklines
3976 yield activeaction, blocklines
3976
3977
3977
3978
3978 @command(
3979 @command(
3979 b'debugwireproto',
3980 b'debugwireproto',
3980 [
3981 [
3981 (b'', b'localssh', False, _(b'start an SSH server for this repo')),
3982 (b'', b'localssh', False, _(b'start an SSH server for this repo')),
3982 (b'', b'peer', b'', _(b'construct a specific version of the peer')),
3983 (b'', b'peer', b'', _(b'construct a specific version of the peer')),
3983 (
3984 (
3984 b'',
3985 b'',
3985 b'noreadstderr',
3986 b'noreadstderr',
3986 False,
3987 False,
3987 _(b'do not read from stderr of the remote'),
3988 _(b'do not read from stderr of the remote'),
3988 ),
3989 ),
3989 (
3990 (
3990 b'',
3991 b'',
3991 b'nologhandshake',
3992 b'nologhandshake',
3992 False,
3993 False,
3993 _(b'do not log I/O related to the peer handshake'),
3994 _(b'do not log I/O related to the peer handshake'),
3994 ),
3995 ),
3995 ]
3996 ]
3996 + cmdutil.remoteopts,
3997 + cmdutil.remoteopts,
3997 _(b'[PATH]'),
3998 _(b'[PATH]'),
3998 optionalrepo=True,
3999 optionalrepo=True,
3999 )
4000 )
4000 def debugwireproto(ui, repo, path=None, **opts):
4001 def debugwireproto(ui, repo, path=None, **opts):
4001 """send wire protocol commands to a server
4002 """send wire protocol commands to a server
4002
4003
4003 This command can be used to issue wire protocol commands to remote
4004 This command can be used to issue wire protocol commands to remote
4004 peers and to debug the raw data being exchanged.
4005 peers and to debug the raw data being exchanged.
4005
4006
4006 ``--localssh`` will start an SSH server against the current repository
4007 ``--localssh`` will start an SSH server against the current repository
4007 and connect to that. By default, the connection will perform a handshake
4008 and connect to that. By default, the connection will perform a handshake
4008 and establish an appropriate peer instance.
4009 and establish an appropriate peer instance.
4009
4010
4010 ``--peer`` can be used to bypass the handshake protocol and construct a
4011 ``--peer`` can be used to bypass the handshake protocol and construct a
4011 peer instance using the specified class type. Valid values are ``raw``,
4012 peer instance using the specified class type. Valid values are ``raw``,
4012 ``http2``, ``ssh1``, and ``ssh2``. ``raw`` instances only allow sending
4013 ``http2``, ``ssh1``, and ``ssh2``. ``raw`` instances only allow sending
4013 raw data payloads and don't support higher-level command actions.
4014 raw data payloads and don't support higher-level command actions.
4014
4015
4015 ``--noreadstderr`` can be used to disable automatic reading from stderr
4016 ``--noreadstderr`` can be used to disable automatic reading from stderr
4016 of the peer (for SSH connections only). Disabling automatic reading of
4017 of the peer (for SSH connections only). Disabling automatic reading of
4017 stderr is useful for making output more deterministic.
4018 stderr is useful for making output more deterministic.
4018
4019
4019 Commands are issued via a mini language which is specified via stdin.
4020 Commands are issued via a mini language which is specified via stdin.
4020 The language consists of individual actions to perform. An action is
4021 The language consists of individual actions to perform. An action is
4021 defined by a block. A block is defined as a line with no leading
4022 defined by a block. A block is defined as a line with no leading
4022 space followed by 0 or more lines with leading space. Blocks are
4023 space followed by 0 or more lines with leading space. Blocks are
4023 effectively a high-level command with additional metadata.
4024 effectively a high-level command with additional metadata.
4024
4025
4025 Lines beginning with ``#`` are ignored.
4026 Lines beginning with ``#`` are ignored.
4026
4027
4027 The following sections denote available actions.
4028 The following sections denote available actions.
4028
4029
4029 raw
4030 raw
4030 ---
4031 ---
4031
4032
4032 Send raw data to the server.
4033 Send raw data to the server.
4033
4034
4034 The block payload contains the raw data to send as one atomic send
4035 The block payload contains the raw data to send as one atomic send
4035 operation. The data may not actually be delivered in a single system
4036 operation. The data may not actually be delivered in a single system
4036 call: it depends on the abilities of the transport being used.
4037 call: it depends on the abilities of the transport being used.
4037
4038
4038 Each line in the block is de-indented and concatenated. Then, that
4039 Each line in the block is de-indented and concatenated. Then, that
4039 value is evaluated as a Python b'' literal. This allows the use of
4040 value is evaluated as a Python b'' literal. This allows the use of
4040 backslash escaping, etc.
4041 backslash escaping, etc.
4041
4042
4042 raw+
4043 raw+
4043 ----
4044 ----
4044
4045
4045 Behaves like ``raw`` except flushes output afterwards.
4046 Behaves like ``raw`` except flushes output afterwards.
4046
4047
4047 command <X>
4048 command <X>
4048 -----------
4049 -----------
4049
4050
4050 Send a request to run a named command, whose name follows the ``command``
4051 Send a request to run a named command, whose name follows the ``command``
4051 string.
4052 string.
4052
4053
4053 Arguments to the command are defined as lines in this block. The format of
4054 Arguments to the command are defined as lines in this block. The format of
4054 each line is ``<key> <value>``. e.g.::
4055 each line is ``<key> <value>``. e.g.::
4055
4056
4056 command listkeys
4057 command listkeys
4057 namespace bookmarks
4058 namespace bookmarks
4058
4059
4059 If the value begins with ``eval:``, it will be interpreted as a Python
4060 If the value begins with ``eval:``, it will be interpreted as a Python
4060 literal expression. Otherwise values are interpreted as Python b'' literals.
4061 literal expression. Otherwise values are interpreted as Python b'' literals.
4061 This allows sending complex types and encoding special byte sequences via
4062 This allows sending complex types and encoding special byte sequences via
4062 backslash escaping.
4063 backslash escaping.
4063
4064
4064 The following arguments have special meaning:
4065 The following arguments have special meaning:
4065
4066
4066 ``PUSHFILE``
4067 ``PUSHFILE``
4067 When defined, the *push* mechanism of the peer will be used instead
4068 When defined, the *push* mechanism of the peer will be used instead
4068 of the static request-response mechanism and the content of the
4069 of the static request-response mechanism and the content of the
4069 file specified in the value of this argument will be sent as the
4070 file specified in the value of this argument will be sent as the
4070 command payload.
4071 command payload.
4071
4072
4072 This can be used to submit a local bundle file to the remote.
4073 This can be used to submit a local bundle file to the remote.
4073
4074
4074 batchbegin
4075 batchbegin
4075 ----------
4076 ----------
4076
4077
4077 Instruct the peer to begin a batched send.
4078 Instruct the peer to begin a batched send.
4078
4079
4079 All ``command`` blocks are queued for execution until the next
4080 All ``command`` blocks are queued for execution until the next
4080 ``batchsubmit`` block.
4081 ``batchsubmit`` block.
4081
4082
4082 batchsubmit
4083 batchsubmit
4083 -----------
4084 -----------
4084
4085
4085 Submit previously queued ``command`` blocks as a batch request.
4086 Submit previously queued ``command`` blocks as a batch request.
4086
4087
4087 This action MUST be paired with a ``batchbegin`` action.
4088 This action MUST be paired with a ``batchbegin`` action.
4088
4089
4089 httprequest <method> <path>
4090 httprequest <method> <path>
4090 ---------------------------
4091 ---------------------------
4091
4092
4092 (HTTP peer only)
4093 (HTTP peer only)
4093
4094
4094 Send an HTTP request to the peer.
4095 Send an HTTP request to the peer.
4095
4096
4096 The HTTP request line follows the ``httprequest`` action. e.g. ``GET /foo``.
4097 The HTTP request line follows the ``httprequest`` action. e.g. ``GET /foo``.
4097
4098
4098 Arguments of the form ``<key>: <value>`` are interpreted as HTTP request
4099 Arguments of the form ``<key>: <value>`` are interpreted as HTTP request
4099 headers to add to the request. e.g. ``Accept: foo``.
4100 headers to add to the request. e.g. ``Accept: foo``.
4100
4101
4101 The following arguments are special:
4102 The following arguments are special:
4102
4103
4103 ``BODYFILE``
4104 ``BODYFILE``
4104 The content of the file defined as the value to this argument will be
4105 The content of the file defined as the value to this argument will be
4105 transferred verbatim as the HTTP request body.
4106 transferred verbatim as the HTTP request body.
4106
4107
4107 ``frame <type> <flags> <payload>``
4108 ``frame <type> <flags> <payload>``
4108 Send a unified protocol frame as part of the request body.
4109 Send a unified protocol frame as part of the request body.
4109
4110
4110 All frames will be collected and sent as the body to the HTTP
4111 All frames will be collected and sent as the body to the HTTP
4111 request.
4112 request.
4112
4113
4113 close
4114 close
4114 -----
4115 -----
4115
4116
4116 Close the connection to the server.
4117 Close the connection to the server.
4117
4118
4118 flush
4119 flush
4119 -----
4120 -----
4120
4121
4121 Flush data written to the server.
4122 Flush data written to the server.
4122
4123
4123 readavailable
4124 readavailable
4124 -------------
4125 -------------
4125
4126
4126 Close the write end of the connection and read all available data from
4127 Close the write end of the connection and read all available data from
4127 the server.
4128 the server.
4128
4129
4129 If the connection to the server encompasses multiple pipes, we poll both
4130 If the connection to the server encompasses multiple pipes, we poll both
4130 pipes and read available data.
4131 pipes and read available data.
4131
4132
4132 readline
4133 readline
4133 --------
4134 --------
4134
4135
4135 Read a line of output from the server. If there are multiple output
4136 Read a line of output from the server. If there are multiple output
4136 pipes, reads only the main pipe.
4137 pipes, reads only the main pipe.
4137
4138
4138 ereadline
4139 ereadline
4139 ---------
4140 ---------
4140
4141
4141 Like ``readline``, but read from the stderr pipe, if available.
4142 Like ``readline``, but read from the stderr pipe, if available.
4142
4143
4143 read <X>
4144 read <X>
4144 --------
4145 --------
4145
4146
4146 ``read()`` N bytes from the server's main output pipe.
4147 ``read()`` N bytes from the server's main output pipe.
4147
4148
4148 eread <X>
4149 eread <X>
4149 ---------
4150 ---------
4150
4151
4151 ``read()`` N bytes from the server's stderr pipe, if available.
4152 ``read()`` N bytes from the server's stderr pipe, if available.
4152
4153
4153 Specifying Unified Frame-Based Protocol Frames
4154 Specifying Unified Frame-Based Protocol Frames
4154 ----------------------------------------------
4155 ----------------------------------------------
4155
4156
4156 It is possible to emit a *Unified Frame-Based Protocol* by using special
4157 It is possible to emit a *Unified Frame-Based Protocol* by using special
4157 syntax.
4158 syntax.
4158
4159
4159 A frame is composed as a type, flags, and payload. These can be parsed
4160 A frame is composed as a type, flags, and payload. These can be parsed
4160 from a string of the form:
4161 from a string of the form:
4161
4162
4162 <request-id> <stream-id> <stream-flags> <type> <flags> <payload>
4163 <request-id> <stream-id> <stream-flags> <type> <flags> <payload>
4163
4164
4164 ``request-id`` and ``stream-id`` are integers defining the request and
4165 ``request-id`` and ``stream-id`` are integers defining the request and
4165 stream identifiers.
4166 stream identifiers.
4166
4167
4167 ``type`` can be an integer value for the frame type or the string name
4168 ``type`` can be an integer value for the frame type or the string name
4168 of the type. The strings are defined in ``wireprotoframing.py``. e.g.
4169 of the type. The strings are defined in ``wireprotoframing.py``. e.g.
4169 ``command-name``.
4170 ``command-name``.
4170
4171
4171 ``stream-flags`` and ``flags`` are a ``|`` delimited list of flag
4172 ``stream-flags`` and ``flags`` are a ``|`` delimited list of flag
4172 components. Each component (and there can be just one) can be an integer
4173 components. Each component (and there can be just one) can be an integer
4173 or a flag name for stream flags or frame flags, respectively. Values are
4174 or a flag name for stream flags or frame flags, respectively. Values are
4174 resolved to integers and then bitwise OR'd together.
4175 resolved to integers and then bitwise OR'd together.
4175
4176
4176 ``payload`` represents the raw frame payload. If it begins with
4177 ``payload`` represents the raw frame payload. If it begins with
4177 ``cbor:``, the following string is evaluated as Python code and the
4178 ``cbor:``, the following string is evaluated as Python code and the
4178 resulting object is fed into a CBOR encoder. Otherwise it is interpreted
4179 resulting object is fed into a CBOR encoder. Otherwise it is interpreted
4179 as a Python byte string literal.
4180 as a Python byte string literal.
4180 """
4181 """
4181 opts = pycompat.byteskwargs(opts)
4182 opts = pycompat.byteskwargs(opts)
4182
4183
4183 if opts[b'localssh'] and not repo:
4184 if opts[b'localssh'] and not repo:
4184 raise error.Abort(_(b'--localssh requires a repository'))
4185 raise error.Abort(_(b'--localssh requires a repository'))
4185
4186
4186 if opts[b'peer'] and opts[b'peer'] not in (
4187 if opts[b'peer'] and opts[b'peer'] not in (
4187 b'raw',
4188 b'raw',
4188 b'http2',
4189 b'http2',
4189 b'ssh1',
4190 b'ssh1',
4190 b'ssh2',
4191 b'ssh2',
4191 ):
4192 ):
4192 raise error.Abort(
4193 raise error.Abort(
4193 _(b'invalid value for --peer'),
4194 _(b'invalid value for --peer'),
4194 hint=_(b'valid values are "raw", "ssh1", and "ssh2"'),
4195 hint=_(b'valid values are "raw", "ssh1", and "ssh2"'),
4195 )
4196 )
4196
4197
4197 if path and opts[b'localssh']:
4198 if path and opts[b'localssh']:
4198 raise error.Abort(_(b'cannot specify --localssh with an explicit path'))
4199 raise error.Abort(_(b'cannot specify --localssh with an explicit path'))
4199
4200
4200 if ui.interactive():
4201 if ui.interactive():
4201 ui.write(_(b'(waiting for commands on stdin)\n'))
4202 ui.write(_(b'(waiting for commands on stdin)\n'))
4202
4203
4203 blocks = list(_parsewirelangblocks(ui.fin))
4204 blocks = list(_parsewirelangblocks(ui.fin))
4204
4205
4205 proc = None
4206 proc = None
4206 stdin = None
4207 stdin = None
4207 stdout = None
4208 stdout = None
4208 stderr = None
4209 stderr = None
4209 opener = None
4210 opener = None
4210
4211
4211 if opts[b'localssh']:
4212 if opts[b'localssh']:
4212 # We start the SSH server in its own process so there is process
4213 # We start the SSH server in its own process so there is process
4213 # separation. This prevents a whole class of potential bugs around
4214 # separation. This prevents a whole class of potential bugs around
4214 # shared state from interfering with server operation.
4215 # shared state from interfering with server operation.
4215 args = procutil.hgcmd() + [
4216 args = procutil.hgcmd() + [
4216 b'-R',
4217 b'-R',
4217 repo.root,
4218 repo.root,
4218 b'debugserve',
4219 b'debugserve',
4219 b'--sshstdio',
4220 b'--sshstdio',
4220 ]
4221 ]
4221 proc = subprocess.Popen(
4222 proc = subprocess.Popen(
4222 pycompat.rapply(procutil.tonativestr, args),
4223 pycompat.rapply(procutil.tonativestr, args),
4223 stdin=subprocess.PIPE,
4224 stdin=subprocess.PIPE,
4224 stdout=subprocess.PIPE,
4225 stdout=subprocess.PIPE,
4225 stderr=subprocess.PIPE,
4226 stderr=subprocess.PIPE,
4226 bufsize=0,
4227 bufsize=0,
4227 )
4228 )
4228
4229
4229 stdin = proc.stdin
4230 stdin = proc.stdin
4230 stdout = proc.stdout
4231 stdout = proc.stdout
4231 stderr = proc.stderr
4232 stderr = proc.stderr
4232
4233
4233 # We turn the pipes into observers so we can log I/O.
4234 # We turn the pipes into observers so we can log I/O.
4234 if ui.verbose or opts[b'peer'] == b'raw':
4235 if ui.verbose or opts[b'peer'] == b'raw':
4235 stdin = util.makeloggingfileobject(
4236 stdin = util.makeloggingfileobject(
4236 ui, proc.stdin, b'i', logdata=True
4237 ui, proc.stdin, b'i', logdata=True
4237 )
4238 )
4238 stdout = util.makeloggingfileobject(
4239 stdout = util.makeloggingfileobject(
4239 ui, proc.stdout, b'o', logdata=True
4240 ui, proc.stdout, b'o', logdata=True
4240 )
4241 )
4241 stderr = util.makeloggingfileobject(
4242 stderr = util.makeloggingfileobject(
4242 ui, proc.stderr, b'e', logdata=True
4243 ui, proc.stderr, b'e', logdata=True
4243 )
4244 )
4244
4245
4245 # --localssh also implies the peer connection settings.
4246 # --localssh also implies the peer connection settings.
4246
4247
4247 url = b'ssh://localserver'
4248 url = b'ssh://localserver'
4248 autoreadstderr = not opts[b'noreadstderr']
4249 autoreadstderr = not opts[b'noreadstderr']
4249
4250
4250 if opts[b'peer'] == b'ssh1':
4251 if opts[b'peer'] == b'ssh1':
4251 ui.write(_(b'creating ssh peer for wire protocol version 1\n'))
4252 ui.write(_(b'creating ssh peer for wire protocol version 1\n'))
4252 peer = sshpeer.sshv1peer(
4253 peer = sshpeer.sshv1peer(
4253 ui,
4254 ui,
4254 url,
4255 url,
4255 proc,
4256 proc,
4256 stdin,
4257 stdin,
4257 stdout,
4258 stdout,
4258 stderr,
4259 stderr,
4259 None,
4260 None,
4260 autoreadstderr=autoreadstderr,
4261 autoreadstderr=autoreadstderr,
4261 )
4262 )
4262 elif opts[b'peer'] == b'ssh2':
4263 elif opts[b'peer'] == b'ssh2':
4263 ui.write(_(b'creating ssh peer for wire protocol version 2\n'))
4264 ui.write(_(b'creating ssh peer for wire protocol version 2\n'))
4264 peer = sshpeer.sshv2peer(
4265 peer = sshpeer.sshv2peer(
4265 ui,
4266 ui,
4266 url,
4267 url,
4267 proc,
4268 proc,
4268 stdin,
4269 stdin,
4269 stdout,
4270 stdout,
4270 stderr,
4271 stderr,
4271 None,
4272 None,
4272 autoreadstderr=autoreadstderr,
4273 autoreadstderr=autoreadstderr,
4273 )
4274 )
4274 elif opts[b'peer'] == b'raw':
4275 elif opts[b'peer'] == b'raw':
4275 ui.write(_(b'using raw connection to peer\n'))
4276 ui.write(_(b'using raw connection to peer\n'))
4276 peer = None
4277 peer = None
4277 else:
4278 else:
4278 ui.write(_(b'creating ssh peer from handshake results\n'))
4279 ui.write(_(b'creating ssh peer from handshake results\n'))
4279 peer = sshpeer.makepeer(
4280 peer = sshpeer.makepeer(
4280 ui,
4281 ui,
4281 url,
4282 url,
4282 proc,
4283 proc,
4283 stdin,
4284 stdin,
4284 stdout,
4285 stdout,
4285 stderr,
4286 stderr,
4286 autoreadstderr=autoreadstderr,
4287 autoreadstderr=autoreadstderr,
4287 )
4288 )
4288
4289
4289 elif path:
4290 elif path:
4290 # We bypass hg.peer() so we can proxy the sockets.
4291 # We bypass hg.peer() so we can proxy the sockets.
4291 # TODO consider not doing this because we skip
4292 # TODO consider not doing this because we skip
4292 # ``hg.wirepeersetupfuncs`` and potentially other useful functionality.
4293 # ``hg.wirepeersetupfuncs`` and potentially other useful functionality.
4293 u = util.url(path)
4294 u = util.url(path)
4294 if u.scheme != b'http':
4295 if u.scheme != b'http':
4295 raise error.Abort(_(b'only http:// paths are currently supported'))
4296 raise error.Abort(_(b'only http:// paths are currently supported'))
4296
4297
4297 url, authinfo = u.authinfo()
4298 url, authinfo = u.authinfo()
4298 openerargs = {
4299 openerargs = {
4299 'useragent': b'Mercurial debugwireproto',
4300 'useragent': b'Mercurial debugwireproto',
4300 }
4301 }
4301
4302
4302 # Turn pipes/sockets into observers so we can log I/O.
4303 # Turn pipes/sockets into observers so we can log I/O.
4303 if ui.verbose:
4304 if ui.verbose:
4304 openerargs.update(
4305 openerargs.update(
4305 {
4306 {
4306 'loggingfh': ui,
4307 'loggingfh': ui,
4307 'loggingname': b's',
4308 'loggingname': b's',
4308 'loggingopts': {'logdata': True, 'logdataapis': False,},
4309 'loggingopts': {'logdata': True, 'logdataapis': False,},
4309 }
4310 }
4310 )
4311 )
4311
4312
4312 if ui.debugflag:
4313 if ui.debugflag:
4313 openerargs['loggingopts']['logdataapis'] = True
4314 openerargs['loggingopts']['logdataapis'] = True
4314
4315
4315 # Don't send default headers when in raw mode. This allows us to
4316 # Don't send default headers when in raw mode. This allows us to
4316 # bypass most of the behavior of our URL handling code so we can
4317 # bypass most of the behavior of our URL handling code so we can
4317 # have near complete control over what's sent on the wire.
4318 # have near complete control over what's sent on the wire.
4318 if opts[b'peer'] == b'raw':
4319 if opts[b'peer'] == b'raw':
4319 openerargs['sendaccept'] = False
4320 openerargs['sendaccept'] = False
4320
4321
4321 opener = urlmod.opener(ui, authinfo, **openerargs)
4322 opener = urlmod.opener(ui, authinfo, **openerargs)
4322
4323
4323 if opts[b'peer'] == b'http2':
4324 if opts[b'peer'] == b'http2':
4324 ui.write(_(b'creating http peer for wire protocol version 2\n'))
4325 ui.write(_(b'creating http peer for wire protocol version 2\n'))
4325 # We go through makepeer() because we need an API descriptor for
4326 # We go through makepeer() because we need an API descriptor for
4326 # the peer instance to be useful.
4327 # the peer instance to be useful.
4327 with ui.configoverride(
4328 with ui.configoverride(
4328 {(b'experimental', b'httppeer.advertise-v2'): True}
4329 {(b'experimental', b'httppeer.advertise-v2'): True}
4329 ):
4330 ):
4330 if opts[b'nologhandshake']:
4331 if opts[b'nologhandshake']:
4331 ui.pushbuffer()
4332 ui.pushbuffer()
4332
4333
4333 peer = httppeer.makepeer(ui, path, opener=opener)
4334 peer = httppeer.makepeer(ui, path, opener=opener)
4334
4335
4335 if opts[b'nologhandshake']:
4336 if opts[b'nologhandshake']:
4336 ui.popbuffer()
4337 ui.popbuffer()
4337
4338
4338 if not isinstance(peer, httppeer.httpv2peer):
4339 if not isinstance(peer, httppeer.httpv2peer):
4339 raise error.Abort(
4340 raise error.Abort(
4340 _(
4341 _(
4341 b'could not instantiate HTTP peer for '
4342 b'could not instantiate HTTP peer for '
4342 b'wire protocol version 2'
4343 b'wire protocol version 2'
4343 ),
4344 ),
4344 hint=_(
4345 hint=_(
4345 b'the server may not have the feature '
4346 b'the server may not have the feature '
4346 b'enabled or is not allowing this '
4347 b'enabled or is not allowing this '
4347 b'client version'
4348 b'client version'
4348 ),
4349 ),
4349 )
4350 )
4350
4351
4351 elif opts[b'peer'] == b'raw':
4352 elif opts[b'peer'] == b'raw':
4352 ui.write(_(b'using raw connection to peer\n'))
4353 ui.write(_(b'using raw connection to peer\n'))
4353 peer = None
4354 peer = None
4354 elif opts[b'peer']:
4355 elif opts[b'peer']:
4355 raise error.Abort(
4356 raise error.Abort(
4356 _(b'--peer %s not supported with HTTP peers') % opts[b'peer']
4357 _(b'--peer %s not supported with HTTP peers') % opts[b'peer']
4357 )
4358 )
4358 else:
4359 else:
4359 peer = httppeer.makepeer(ui, path, opener=opener)
4360 peer = httppeer.makepeer(ui, path, opener=opener)
4360
4361
4361 # We /could/ populate stdin/stdout with sock.makefile()...
4362 # We /could/ populate stdin/stdout with sock.makefile()...
4362 else:
4363 else:
4363 raise error.Abort(_(b'unsupported connection configuration'))
4364 raise error.Abort(_(b'unsupported connection configuration'))
4364
4365
4365 batchedcommands = None
4366 batchedcommands = None
4366
4367
4367 # Now perform actions based on the parsed wire language instructions.
4368 # Now perform actions based on the parsed wire language instructions.
4368 for action, lines in blocks:
4369 for action, lines in blocks:
4369 if action in (b'raw', b'raw+'):
4370 if action in (b'raw', b'raw+'):
4370 if not stdin:
4371 if not stdin:
4371 raise error.Abort(_(b'cannot call raw/raw+ on this peer'))
4372 raise error.Abort(_(b'cannot call raw/raw+ on this peer'))
4372
4373
4373 # Concatenate the data together.
4374 # Concatenate the data together.
4374 data = b''.join(l.lstrip() for l in lines)
4375 data = b''.join(l.lstrip() for l in lines)
4375 data = stringutil.unescapestr(data)
4376 data = stringutil.unescapestr(data)
4376 stdin.write(data)
4377 stdin.write(data)
4377
4378
4378 if action == b'raw+':
4379 if action == b'raw+':
4379 stdin.flush()
4380 stdin.flush()
4380 elif action == b'flush':
4381 elif action == b'flush':
4381 if not stdin:
4382 if not stdin:
4382 raise error.Abort(_(b'cannot call flush on this peer'))
4383 raise error.Abort(_(b'cannot call flush on this peer'))
4383 stdin.flush()
4384 stdin.flush()
4384 elif action.startswith(b'command'):
4385 elif action.startswith(b'command'):
4385 if not peer:
4386 if not peer:
4386 raise error.Abort(
4387 raise error.Abort(
4387 _(
4388 _(
4388 b'cannot send commands unless peer instance '
4389 b'cannot send commands unless peer instance '
4389 b'is available'
4390 b'is available'
4390 )
4391 )
4391 )
4392 )
4392
4393
4393 command = action.split(b' ', 1)[1]
4394 command = action.split(b' ', 1)[1]
4394
4395
4395 args = {}
4396 args = {}
4396 for line in lines:
4397 for line in lines:
4397 # We need to allow empty values.
4398 # We need to allow empty values.
4398 fields = line.lstrip().split(b' ', 1)
4399 fields = line.lstrip().split(b' ', 1)
4399 if len(fields) == 1:
4400 if len(fields) == 1:
4400 key = fields[0]
4401 key = fields[0]
4401 value = b''
4402 value = b''
4402 else:
4403 else:
4403 key, value = fields
4404 key, value = fields
4404
4405
4405 if value.startswith(b'eval:'):
4406 if value.startswith(b'eval:'):
4406 value = stringutil.evalpythonliteral(value[5:])
4407 value = stringutil.evalpythonliteral(value[5:])
4407 else:
4408 else:
4408 value = stringutil.unescapestr(value)
4409 value = stringutil.unescapestr(value)
4409
4410
4410 args[key] = value
4411 args[key] = value
4411
4412
4412 if batchedcommands is not None:
4413 if batchedcommands is not None:
4413 batchedcommands.append((command, args))
4414 batchedcommands.append((command, args))
4414 continue
4415 continue
4415
4416
4416 ui.status(_(b'sending %s command\n') % command)
4417 ui.status(_(b'sending %s command\n') % command)
4417
4418
4418 if b'PUSHFILE' in args:
4419 if b'PUSHFILE' in args:
4419 with open(args[b'PUSHFILE'], 'rb') as fh:
4420 with open(args[b'PUSHFILE'], 'rb') as fh:
4420 del args[b'PUSHFILE']
4421 del args[b'PUSHFILE']
4421 res, output = peer._callpush(
4422 res, output = peer._callpush(
4422 command, fh, **pycompat.strkwargs(args)
4423 command, fh, **pycompat.strkwargs(args)
4423 )
4424 )
4424 ui.status(_(b'result: %s\n') % stringutil.escapestr(res))
4425 ui.status(_(b'result: %s\n') % stringutil.escapestr(res))
4425 ui.status(
4426 ui.status(
4426 _(b'remote output: %s\n') % stringutil.escapestr(output)
4427 _(b'remote output: %s\n') % stringutil.escapestr(output)
4427 )
4428 )
4428 else:
4429 else:
4429 with peer.commandexecutor() as e:
4430 with peer.commandexecutor() as e:
4430 res = e.callcommand(command, args).result()
4431 res = e.callcommand(command, args).result()
4431
4432
4432 if isinstance(res, wireprotov2peer.commandresponse):
4433 if isinstance(res, wireprotov2peer.commandresponse):
4433 val = res.objects()
4434 val = res.objects()
4434 ui.status(
4435 ui.status(
4435 _(b'response: %s\n')
4436 _(b'response: %s\n')
4436 % stringutil.pprint(val, bprefix=True, indent=2)
4437 % stringutil.pprint(val, bprefix=True, indent=2)
4437 )
4438 )
4438 else:
4439 else:
4439 ui.status(
4440 ui.status(
4440 _(b'response: %s\n')
4441 _(b'response: %s\n')
4441 % stringutil.pprint(res, bprefix=True, indent=2)
4442 % stringutil.pprint(res, bprefix=True, indent=2)
4442 )
4443 )
4443
4444
4444 elif action == b'batchbegin':
4445 elif action == b'batchbegin':
4445 if batchedcommands is not None:
4446 if batchedcommands is not None:
4446 raise error.Abort(_(b'nested batchbegin not allowed'))
4447 raise error.Abort(_(b'nested batchbegin not allowed'))
4447
4448
4448 batchedcommands = []
4449 batchedcommands = []
4449 elif action == b'batchsubmit':
4450 elif action == b'batchsubmit':
4450 # There is a batching API we could go through. But it would be
4451 # There is a batching API we could go through. But it would be
4451 # difficult to normalize requests into function calls. It is easier
4452 # difficult to normalize requests into function calls. It is easier
4452 # to bypass this layer and normalize to commands + args.
4453 # to bypass this layer and normalize to commands + args.
4453 ui.status(
4454 ui.status(
4454 _(b'sending batch with %d sub-commands\n')
4455 _(b'sending batch with %d sub-commands\n')
4455 % len(batchedcommands)
4456 % len(batchedcommands)
4456 )
4457 )
4457 assert peer is not None
4458 assert peer is not None
4458 for i, chunk in enumerate(peer._submitbatch(batchedcommands)):
4459 for i, chunk in enumerate(peer._submitbatch(batchedcommands)):
4459 ui.status(
4460 ui.status(
4460 _(b'response #%d: %s\n') % (i, stringutil.escapestr(chunk))
4461 _(b'response #%d: %s\n') % (i, stringutil.escapestr(chunk))
4461 )
4462 )
4462
4463
4463 batchedcommands = None
4464 batchedcommands = None
4464
4465
4465 elif action.startswith(b'httprequest '):
4466 elif action.startswith(b'httprequest '):
4466 if not opener:
4467 if not opener:
4467 raise error.Abort(
4468 raise error.Abort(
4468 _(b'cannot use httprequest without an HTTP peer')
4469 _(b'cannot use httprequest without an HTTP peer')
4469 )
4470 )
4470
4471
4471 request = action.split(b' ', 2)
4472 request = action.split(b' ', 2)
4472 if len(request) != 3:
4473 if len(request) != 3:
4473 raise error.Abort(
4474 raise error.Abort(
4474 _(
4475 _(
4475 b'invalid httprequest: expected format is '
4476 b'invalid httprequest: expected format is '
4476 b'"httprequest <method> <path>'
4477 b'"httprequest <method> <path>'
4477 )
4478 )
4478 )
4479 )
4479
4480
4480 method, httppath = request[1:]
4481 method, httppath = request[1:]
4481 headers = {}
4482 headers = {}
4482 body = None
4483 body = None
4483 frames = []
4484 frames = []
4484 for line in lines:
4485 for line in lines:
4485 line = line.lstrip()
4486 line = line.lstrip()
4486 m = re.match(b'^([a-zA-Z0-9_-]+): (.*)$', line)
4487 m = re.match(b'^([a-zA-Z0-9_-]+): (.*)$', line)
4487 if m:
4488 if m:
4488 # Headers need to use native strings.
4489 # Headers need to use native strings.
4489 key = pycompat.strurl(m.group(1))
4490 key = pycompat.strurl(m.group(1))
4490 value = pycompat.strurl(m.group(2))
4491 value = pycompat.strurl(m.group(2))
4491 headers[key] = value
4492 headers[key] = value
4492 continue
4493 continue
4493
4494
4494 if line.startswith(b'BODYFILE '):
4495 if line.startswith(b'BODYFILE '):
4495 with open(line.split(b' ', 1), b'rb') as fh:
4496 with open(line.split(b' ', 1), b'rb') as fh:
4496 body = fh.read()
4497 body = fh.read()
4497 elif line.startswith(b'frame '):
4498 elif line.startswith(b'frame '):
4498 frame = wireprotoframing.makeframefromhumanstring(
4499 frame = wireprotoframing.makeframefromhumanstring(
4499 line[len(b'frame ') :]
4500 line[len(b'frame ') :]
4500 )
4501 )
4501
4502
4502 frames.append(frame)
4503 frames.append(frame)
4503 else:
4504 else:
4504 raise error.Abort(
4505 raise error.Abort(
4505 _(b'unknown argument to httprequest: %s') % line
4506 _(b'unknown argument to httprequest: %s') % line
4506 )
4507 )
4507
4508
4508 url = path + httppath
4509 url = path + httppath
4509
4510
4510 if frames:
4511 if frames:
4511 body = b''.join(bytes(f) for f in frames)
4512 body = b''.join(bytes(f) for f in frames)
4512
4513
4513 req = urlmod.urlreq.request(pycompat.strurl(url), body, headers)
4514 req = urlmod.urlreq.request(pycompat.strurl(url), body, headers)
4514
4515
4515 # urllib.Request insists on using has_data() as a proxy for
4516 # urllib.Request insists on using has_data() as a proxy for
4516 # determining the request method. Override that to use our
4517 # determining the request method. Override that to use our
4517 # explicitly requested method.
4518 # explicitly requested method.
4518 req.get_method = lambda: pycompat.sysstr(method)
4519 req.get_method = lambda: pycompat.sysstr(method)
4519
4520
4520 try:
4521 try:
4521 res = opener.open(req)
4522 res = opener.open(req)
4522 body = res.read()
4523 body = res.read()
4523 except util.urlerr.urlerror as e:
4524 except util.urlerr.urlerror as e:
4524 # read() method must be called, but only exists in Python 2
4525 # read() method must be called, but only exists in Python 2
4525 getattr(e, 'read', lambda: None)()
4526 getattr(e, 'read', lambda: None)()
4526 continue
4527 continue
4527
4528
4528 ct = res.headers.get('Content-Type')
4529 ct = res.headers.get('Content-Type')
4529 if ct == 'application/mercurial-cbor':
4530 if ct == 'application/mercurial-cbor':
4530 ui.write(
4531 ui.write(
4531 _(b'cbor> %s\n')
4532 _(b'cbor> %s\n')
4532 % stringutil.pprint(
4533 % stringutil.pprint(
4533 cborutil.decodeall(body), bprefix=True, indent=2
4534 cborutil.decodeall(body), bprefix=True, indent=2
4534 )
4535 )
4535 )
4536 )
4536
4537
4537 elif action == b'close':
4538 elif action == b'close':
4538 assert peer is not None
4539 assert peer is not None
4539 peer.close()
4540 peer.close()
4540 elif action == b'readavailable':
4541 elif action == b'readavailable':
4541 if not stdout or not stderr:
4542 if not stdout or not stderr:
4542 raise error.Abort(
4543 raise error.Abort(
4543 _(b'readavailable not available on this peer')
4544 _(b'readavailable not available on this peer')
4544 )
4545 )
4545
4546
4546 stdin.close()
4547 stdin.close()
4547 stdout.read()
4548 stdout.read()
4548 stderr.read()
4549 stderr.read()
4549
4550
4550 elif action == b'readline':
4551 elif action == b'readline':
4551 if not stdout:
4552 if not stdout:
4552 raise error.Abort(_(b'readline not available on this peer'))
4553 raise error.Abort(_(b'readline not available on this peer'))
4553 stdout.readline()
4554 stdout.readline()
4554 elif action == b'ereadline':
4555 elif action == b'ereadline':
4555 if not stderr:
4556 if not stderr:
4556 raise error.Abort(_(b'ereadline not available on this peer'))
4557 raise error.Abort(_(b'ereadline not available on this peer'))
4557 stderr.readline()
4558 stderr.readline()
4558 elif action.startswith(b'read '):
4559 elif action.startswith(b'read '):
4559 count = int(action.split(b' ', 1)[1])
4560 count = int(action.split(b' ', 1)[1])
4560 if not stdout:
4561 if not stdout:
4561 raise error.Abort(_(b'read not available on this peer'))
4562 raise error.Abort(_(b'read not available on this peer'))
4562 stdout.read(count)
4563 stdout.read(count)
4563 elif action.startswith(b'eread '):
4564 elif action.startswith(b'eread '):
4564 count = int(action.split(b' ', 1)[1])
4565 count = int(action.split(b' ', 1)[1])
4565 if not stderr:
4566 if not stderr:
4566 raise error.Abort(_(b'eread not available on this peer'))
4567 raise error.Abort(_(b'eread not available on this peer'))
4567 stderr.read(count)
4568 stderr.read(count)
4568 else:
4569 else:
4569 raise error.Abort(_(b'unknown action: %s') % action)
4570 raise error.Abort(_(b'unknown action: %s') % action)
4570
4571
4571 if batchedcommands is not None:
4572 if batchedcommands is not None:
4572 raise error.Abort(_(b'unclosed "batchbegin" request'))
4573 raise error.Abort(_(b'unclosed "batchbegin" request'))
4573
4574
4574 if peer:
4575 if peer:
4575 peer.close()
4576 peer.close()
4576
4577
4577 if proc:
4578 if proc:
4578 proc.kill()
4579 proc.kill()
@@ -1,124 +1,126 b''
1 # hgweb/__init__.py - web interface to a mercurial repository
1 # hgweb/__init__.py - web interface to a mercurial repository
2 #
2 #
3 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
3 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
4 # Copyright 2005 Matt Mackall <mpm@selenic.com>
4 # Copyright 2005 Matt Mackall <mpm@selenic.com>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 from __future__ import absolute_import
9 from __future__ import absolute_import
10
10
11 import os
11 import os
12 import sys
12
13
13 from ..i18n import _
14 from ..i18n import _
14
15
15 from .. import (
16 from .. import (
16 error,
17 error,
17 pycompat,
18 pycompat,
18 )
19 )
19
20
20 from ..utils import procutil
21 from ..utils import procutil
21
22
22 from . import (
23 from . import (
23 hgweb_mod,
24 hgweb_mod,
24 hgwebdir_mod,
25 hgwebdir_mod,
25 server,
26 server,
26 )
27 )
27
28
28
29
29 def hgweb(config, name=None, baseui=None):
30 def hgweb(config, name=None, baseui=None):
30 '''create an hgweb wsgi object
31 '''create an hgweb wsgi object
31
32
32 config can be one of:
33 config can be one of:
33 - repo object (single repo view)
34 - repo object (single repo view)
34 - path to repo (single repo view)
35 - path to repo (single repo view)
35 - path to config file (multi-repo view)
36 - path to config file (multi-repo view)
36 - dict of virtual:real pairs (multi-repo view)
37 - dict of virtual:real pairs (multi-repo view)
37 - list of virtual:real tuples (multi-repo view)
38 - list of virtual:real tuples (multi-repo view)
38 '''
39 '''
39
40
40 if isinstance(config, pycompat.unicode):
41 if isinstance(config, pycompat.unicode):
41 raise error.ProgrammingError(
42 raise error.ProgrammingError(
42 b'Mercurial only supports encoded strings: %r' % config
43 b'Mercurial only supports encoded strings: %r' % config
43 )
44 )
44 if (
45 if (
45 (isinstance(config, bytes) and not os.path.isdir(config))
46 (isinstance(config, bytes) and not os.path.isdir(config))
46 or isinstance(config, dict)
47 or isinstance(config, dict)
47 or isinstance(config, list)
48 or isinstance(config, list)
48 ):
49 ):
49 # create a multi-dir interface
50 # create a multi-dir interface
50 return hgwebdir_mod.hgwebdir(config, baseui=baseui)
51 return hgwebdir_mod.hgwebdir(config, baseui=baseui)
51 return hgweb_mod.hgweb(config, name=name, baseui=baseui)
52 return hgweb_mod.hgweb(config, name=name, baseui=baseui)
52
53
53
54
54 def hgwebdir(config, baseui=None):
55 def hgwebdir(config, baseui=None):
55 return hgwebdir_mod.hgwebdir(config, baseui=baseui)
56 return hgwebdir_mod.hgwebdir(config, baseui=baseui)
56
57
57
58
58 class httpservice(object):
59 class httpservice(object):
59 def __init__(self, ui, app, opts):
60 def __init__(self, ui, app, opts):
60 self.ui = ui
61 self.ui = ui
61 self.app = app
62 self.app = app
62 self.opts = opts
63 self.opts = opts
63
64
64 def init(self):
65 def init(self):
65 procutil.setsignalhandler()
66 procutil.setsignalhandler()
66 self.httpd = server.create_server(self.ui, self.app)
67 self.httpd = server.create_server(self.ui, self.app)
67
68
68 if (
69 if (
69 self.opts[b'port']
70 self.opts[b'port']
70 and not self.ui.verbose
71 and not self.ui.verbose
71 and not self.opts[b'print_url']
72 and not self.opts[b'print_url']
72 ):
73 ):
73 return
74 return
74
75
75 if self.httpd.prefix:
76 if self.httpd.prefix:
76 prefix = self.httpd.prefix.strip(b'/') + b'/'
77 prefix = self.httpd.prefix.strip(b'/') + b'/'
77 else:
78 else:
78 prefix = b''
79 prefix = b''
79
80
80 port = ':%d' % self.httpd.port
81 port = ':%d' % self.httpd.port
81 if port == ':80':
82 if port == ':80':
82 port = ''
83 port = ''
83
84
84 bindaddr = self.httpd.addr
85 bindaddr = self.httpd.addr
85 if bindaddr == '0.0.0.0':
86 if bindaddr == '0.0.0.0':
86 bindaddr = '*'
87 bindaddr = '*'
87 elif ':' in bindaddr: # IPv6
88 elif ':' in bindaddr: # IPv6
88 bindaddr = '[%s]' % bindaddr
89 bindaddr = '[%s]' % bindaddr
89
90
90 fqaddr = self.httpd.fqaddr
91 fqaddr = self.httpd.fqaddr
91 if ':' in fqaddr:
92 if ':' in fqaddr:
92 fqaddr = '[%s]' % fqaddr
93 fqaddr = '[%s]' % fqaddr
93
94
94 url = b'http://%s%s/%s' % (
95 url = b'http://%s%s/%s' % (
95 pycompat.sysbytes(fqaddr),
96 pycompat.sysbytes(fqaddr),
96 pycompat.sysbytes(port),
97 pycompat.sysbytes(port),
97 prefix,
98 prefix,
98 )
99 )
99 if self.opts[b'print_url']:
100 if self.opts[b'print_url']:
100 self.ui.write(b'%s\n' % url)
101 self.ui.write(b'%s\n' % url)
101 else:
102 else:
102 if self.opts[b'port']:
103 if self.opts[b'port']:
103 write = self.ui.status
104 write = self.ui.status
104 else:
105 else:
105 write = self.ui.write
106 write = self.ui.write
106 write(
107 write(
107 _(b'listening at %s (bound to %s:%d)\n')
108 _(b'listening at %s (bound to %s:%d)\n')
108 % (url, pycompat.sysbytes(bindaddr), self.httpd.port)
109 % (url, pycompat.sysbytes(bindaddr), self.httpd.port)
109 )
110 )
110 self.ui.flush() # avoid buffering of status message
111 self.ui.flush() # avoid buffering of status message
111
112
112 def run(self):
113 def run(self):
113 self.httpd.serve_forever()
114 self.httpd.serve_forever()
115 sys.exit(0)
114
116
115
117
116 def createapp(baseui, repo, webconf):
118 def createapp(baseui, repo, webconf):
117 if webconf:
119 if webconf:
118 return hgwebdir_mod.hgwebdir(webconf, baseui=baseui)
120 return hgwebdir_mod.hgwebdir(webconf, baseui=baseui)
119 else:
121 else:
120 if not repo:
122 if not repo:
121 raise error.RepoError(
123 raise error.RepoError(
122 _(b"there is no Mercurial repository here (.hg not found)")
124 _(b"there is no Mercurial repository here (.hg not found)")
123 )
125 )
124 return hgweb_mod.hgweb(repo, baseui=baseui)
126 return hgweb_mod.hgweb(repo, baseui=baseui)
@@ -1,858 +1,856 b''
1 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
1 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
2 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
2 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 #
3 #
4 # This software may be used and distributed according to the terms of the
4 # This software may be used and distributed according to the terms of the
5 # GNU General Public License version 2 or any later version.
5 # GNU General Public License version 2 or any later version.
6
6
7 from __future__ import absolute_import
7 from __future__ import absolute_import
8
8
9 import contextlib
9 import contextlib
10 import struct
10 import struct
11 import sys
12 import threading
11 import threading
13
12
14 from .i18n import _
13 from .i18n import _
15 from . import (
14 from . import (
16 encoding,
15 encoding,
17 error,
16 error,
18 pycompat,
17 pycompat,
19 util,
18 util,
20 wireprototypes,
19 wireprototypes,
21 wireprotov1server,
20 wireprotov1server,
22 wireprotov2server,
21 wireprotov2server,
23 )
22 )
24 from .interfaces import util as interfaceutil
23 from .interfaces import util as interfaceutil
25 from .utils import (
24 from .utils import (
26 cborutil,
25 cborutil,
27 compression,
26 compression,
28 )
27 )
29
28
30 stringio = util.stringio
29 stringio = util.stringio
31
30
32 urlerr = util.urlerr
31 urlerr = util.urlerr
33 urlreq = util.urlreq
32 urlreq = util.urlreq
34
33
35 HTTP_OK = 200
34 HTTP_OK = 200
36
35
37 HGTYPE = b'application/mercurial-0.1'
36 HGTYPE = b'application/mercurial-0.1'
38 HGTYPE2 = b'application/mercurial-0.2'
37 HGTYPE2 = b'application/mercurial-0.2'
39 HGERRTYPE = b'application/hg-error'
38 HGERRTYPE = b'application/hg-error'
40
39
41 SSHV1 = wireprototypes.SSHV1
40 SSHV1 = wireprototypes.SSHV1
42 SSHV2 = wireprototypes.SSHV2
41 SSHV2 = wireprototypes.SSHV2
43
42
44
43
45 def decodevaluefromheaders(req, headerprefix):
44 def decodevaluefromheaders(req, headerprefix):
46 """Decode a long value from multiple HTTP request headers.
45 """Decode a long value from multiple HTTP request headers.
47
46
48 Returns the value as a bytes, not a str.
47 Returns the value as a bytes, not a str.
49 """
48 """
50 chunks = []
49 chunks = []
51 i = 1
50 i = 1
52 while True:
51 while True:
53 v = req.headers.get(b'%s-%d' % (headerprefix, i))
52 v = req.headers.get(b'%s-%d' % (headerprefix, i))
54 if v is None:
53 if v is None:
55 break
54 break
56 chunks.append(pycompat.bytesurl(v))
55 chunks.append(pycompat.bytesurl(v))
57 i += 1
56 i += 1
58
57
59 return b''.join(chunks)
58 return b''.join(chunks)
60
59
61
60
62 @interfaceutil.implementer(wireprototypes.baseprotocolhandler)
61 @interfaceutil.implementer(wireprototypes.baseprotocolhandler)
63 class httpv1protocolhandler(object):
62 class httpv1protocolhandler(object):
64 def __init__(self, req, ui, checkperm):
63 def __init__(self, req, ui, checkperm):
65 self._req = req
64 self._req = req
66 self._ui = ui
65 self._ui = ui
67 self._checkperm = checkperm
66 self._checkperm = checkperm
68 self._protocaps = None
67 self._protocaps = None
69
68
70 @property
69 @property
71 def name(self):
70 def name(self):
72 return b'http-v1'
71 return b'http-v1'
73
72
74 def getargs(self, args):
73 def getargs(self, args):
75 knownargs = self._args()
74 knownargs = self._args()
76 data = {}
75 data = {}
77 keys = args.split()
76 keys = args.split()
78 for k in keys:
77 for k in keys:
79 if k == b'*':
78 if k == b'*':
80 star = {}
79 star = {}
81 for key in knownargs.keys():
80 for key in knownargs.keys():
82 if key != b'cmd' and key not in keys:
81 if key != b'cmd' and key not in keys:
83 star[key] = knownargs[key][0]
82 star[key] = knownargs[key][0]
84 data[b'*'] = star
83 data[b'*'] = star
85 else:
84 else:
86 data[k] = knownargs[k][0]
85 data[k] = knownargs[k][0]
87 return [data[k] for k in keys]
86 return [data[k] for k in keys]
88
87
89 def _args(self):
88 def _args(self):
90 args = self._req.qsparams.asdictoflists()
89 args = self._req.qsparams.asdictoflists()
91 postlen = int(self._req.headers.get(b'X-HgArgs-Post', 0))
90 postlen = int(self._req.headers.get(b'X-HgArgs-Post', 0))
92 if postlen:
91 if postlen:
93 args.update(
92 args.update(
94 urlreq.parseqs(
93 urlreq.parseqs(
95 self._req.bodyfh.read(postlen), keep_blank_values=True
94 self._req.bodyfh.read(postlen), keep_blank_values=True
96 )
95 )
97 )
96 )
98 return args
97 return args
99
98
100 argvalue = decodevaluefromheaders(self._req, b'X-HgArg')
99 argvalue = decodevaluefromheaders(self._req, b'X-HgArg')
101 args.update(urlreq.parseqs(argvalue, keep_blank_values=True))
100 args.update(urlreq.parseqs(argvalue, keep_blank_values=True))
102 return args
101 return args
103
102
104 def getprotocaps(self):
103 def getprotocaps(self):
105 if self._protocaps is None:
104 if self._protocaps is None:
106 value = decodevaluefromheaders(self._req, b'X-HgProto')
105 value = decodevaluefromheaders(self._req, b'X-HgProto')
107 self._protocaps = set(value.split(b' '))
106 self._protocaps = set(value.split(b' '))
108 return self._protocaps
107 return self._protocaps
109
108
110 def getpayload(self):
109 def getpayload(self):
111 # Existing clients *always* send Content-Length.
110 # Existing clients *always* send Content-Length.
112 length = int(self._req.headers[b'Content-Length'])
111 length = int(self._req.headers[b'Content-Length'])
113
112
114 # If httppostargs is used, we need to read Content-Length
113 # If httppostargs is used, we need to read Content-Length
115 # minus the amount that was consumed by args.
114 # minus the amount that was consumed by args.
116 length -= int(self._req.headers.get(b'X-HgArgs-Post', 0))
115 length -= int(self._req.headers.get(b'X-HgArgs-Post', 0))
117 return util.filechunkiter(self._req.bodyfh, limit=length)
116 return util.filechunkiter(self._req.bodyfh, limit=length)
118
117
119 @contextlib.contextmanager
118 @contextlib.contextmanager
120 def mayberedirectstdio(self):
119 def mayberedirectstdio(self):
121 oldout = self._ui.fout
120 oldout = self._ui.fout
122 olderr = self._ui.ferr
121 olderr = self._ui.ferr
123
122
124 out = util.stringio()
123 out = util.stringio()
125
124
126 try:
125 try:
127 self._ui.fout = out
126 self._ui.fout = out
128 self._ui.ferr = out
127 self._ui.ferr = out
129 yield out
128 yield out
130 finally:
129 finally:
131 self._ui.fout = oldout
130 self._ui.fout = oldout
132 self._ui.ferr = olderr
131 self._ui.ferr = olderr
133
132
134 def client(self):
133 def client(self):
135 return b'remote:%s:%s:%s' % (
134 return b'remote:%s:%s:%s' % (
136 self._req.urlscheme,
135 self._req.urlscheme,
137 urlreq.quote(self._req.remotehost or b''),
136 urlreq.quote(self._req.remotehost or b''),
138 urlreq.quote(self._req.remoteuser or b''),
137 urlreq.quote(self._req.remoteuser or b''),
139 )
138 )
140
139
141 def addcapabilities(self, repo, caps):
140 def addcapabilities(self, repo, caps):
142 caps.append(b'batch')
141 caps.append(b'batch')
143
142
144 caps.append(
143 caps.append(
145 b'httpheader=%d' % repo.ui.configint(b'server', b'maxhttpheaderlen')
144 b'httpheader=%d' % repo.ui.configint(b'server', b'maxhttpheaderlen')
146 )
145 )
147 if repo.ui.configbool(b'experimental', b'httppostargs'):
146 if repo.ui.configbool(b'experimental', b'httppostargs'):
148 caps.append(b'httppostargs')
147 caps.append(b'httppostargs')
149
148
150 # FUTURE advertise 0.2rx once support is implemented
149 # FUTURE advertise 0.2rx once support is implemented
151 # FUTURE advertise minrx and mintx after consulting config option
150 # FUTURE advertise minrx and mintx after consulting config option
152 caps.append(b'httpmediatype=0.1rx,0.1tx,0.2tx')
151 caps.append(b'httpmediatype=0.1rx,0.1tx,0.2tx')
153
152
154 compengines = wireprototypes.supportedcompengines(
153 compengines = wireprototypes.supportedcompengines(
155 repo.ui, compression.SERVERROLE
154 repo.ui, compression.SERVERROLE
156 )
155 )
157 if compengines:
156 if compengines:
158 comptypes = b','.join(
157 comptypes = b','.join(
159 urlreq.quote(e.wireprotosupport().name) for e in compengines
158 urlreq.quote(e.wireprotosupport().name) for e in compengines
160 )
159 )
161 caps.append(b'compression=%s' % comptypes)
160 caps.append(b'compression=%s' % comptypes)
162
161
163 return caps
162 return caps
164
163
165 def checkperm(self, perm):
164 def checkperm(self, perm):
166 return self._checkperm(perm)
165 return self._checkperm(perm)
167
166
168
167
169 # This method exists mostly so that extensions like remotefilelog can
168 # This method exists mostly so that extensions like remotefilelog can
170 # disable a kludgey legacy method only over http. As of early 2018,
169 # disable a kludgey legacy method only over http. As of early 2018,
171 # there are no other known users, so with any luck we can discard this
170 # there are no other known users, so with any luck we can discard this
172 # hook if remotefilelog becomes a first-party extension.
171 # hook if remotefilelog becomes a first-party extension.
173 def iscmd(cmd):
172 def iscmd(cmd):
174 return cmd in wireprotov1server.commands
173 return cmd in wireprotov1server.commands
175
174
176
175
177 def handlewsgirequest(rctx, req, res, checkperm):
176 def handlewsgirequest(rctx, req, res, checkperm):
178 """Possibly process a wire protocol request.
177 """Possibly process a wire protocol request.
179
178
180 If the current request is a wire protocol request, the request is
179 If the current request is a wire protocol request, the request is
181 processed by this function.
180 processed by this function.
182
181
183 ``req`` is a ``parsedrequest`` instance.
182 ``req`` is a ``parsedrequest`` instance.
184 ``res`` is a ``wsgiresponse`` instance.
183 ``res`` is a ``wsgiresponse`` instance.
185
184
186 Returns a bool indicating if the request was serviced. If set, the caller
185 Returns a bool indicating if the request was serviced. If set, the caller
187 should stop processing the request, as a response has already been issued.
186 should stop processing the request, as a response has already been issued.
188 """
187 """
189 # Avoid cycle involving hg module.
188 # Avoid cycle involving hg module.
190 from .hgweb import common as hgwebcommon
189 from .hgweb import common as hgwebcommon
191
190
192 repo = rctx.repo
191 repo = rctx.repo
193
192
194 # HTTP version 1 wire protocol requests are denoted by a "cmd" query
193 # HTTP version 1 wire protocol requests are denoted by a "cmd" query
195 # string parameter. If it isn't present, this isn't a wire protocol
194 # string parameter. If it isn't present, this isn't a wire protocol
196 # request.
195 # request.
197 if b'cmd' not in req.qsparams:
196 if b'cmd' not in req.qsparams:
198 return False
197 return False
199
198
200 cmd = req.qsparams[b'cmd']
199 cmd = req.qsparams[b'cmd']
201
200
202 # The "cmd" request parameter is used by both the wire protocol and hgweb.
201 # The "cmd" request parameter is used by both the wire protocol and hgweb.
203 # While not all wire protocol commands are available for all transports,
202 # While not all wire protocol commands are available for all transports,
204 # if we see a "cmd" value that resembles a known wire protocol command, we
203 # if we see a "cmd" value that resembles a known wire protocol command, we
205 # route it to a protocol handler. This is better than routing possible
204 # route it to a protocol handler. This is better than routing possible
206 # wire protocol requests to hgweb because it prevents hgweb from using
205 # wire protocol requests to hgweb because it prevents hgweb from using
207 # known wire protocol commands and it is less confusing for machine
206 # known wire protocol commands and it is less confusing for machine
208 # clients.
207 # clients.
209 if not iscmd(cmd):
208 if not iscmd(cmd):
210 return False
209 return False
211
210
212 # The "cmd" query string argument is only valid on the root path of the
211 # The "cmd" query string argument is only valid on the root path of the
213 # repo. e.g. ``/?cmd=foo``, ``/repo?cmd=foo``. URL paths within the repo
212 # repo. e.g. ``/?cmd=foo``, ``/repo?cmd=foo``. URL paths within the repo
214 # like ``/blah?cmd=foo`` are not allowed. So don't recognize the request
213 # like ``/blah?cmd=foo`` are not allowed. So don't recognize the request
215 # in this case. We send an HTTP 404 for backwards compatibility reasons.
214 # in this case. We send an HTTP 404 for backwards compatibility reasons.
216 if req.dispatchpath:
215 if req.dispatchpath:
217 res.status = hgwebcommon.statusmessage(404)
216 res.status = hgwebcommon.statusmessage(404)
218 res.headers[b'Content-Type'] = HGTYPE
217 res.headers[b'Content-Type'] = HGTYPE
219 # TODO This is not a good response to issue for this request. This
218 # TODO This is not a good response to issue for this request. This
220 # is mostly for BC for now.
219 # is mostly for BC for now.
221 res.setbodybytes(b'0\n%s\n' % b'Not Found')
220 res.setbodybytes(b'0\n%s\n' % b'Not Found')
222 return True
221 return True
223
222
224 proto = httpv1protocolhandler(
223 proto = httpv1protocolhandler(
225 req, repo.ui, lambda perm: checkperm(rctx, req, perm)
224 req, repo.ui, lambda perm: checkperm(rctx, req, perm)
226 )
225 )
227
226
228 # The permissions checker should be the only thing that can raise an
227 # The permissions checker should be the only thing that can raise an
229 # ErrorResponse. It is kind of a layer violation to catch an hgweb
228 # ErrorResponse. It is kind of a layer violation to catch an hgweb
230 # exception here. So consider refactoring into a exception type that
229 # exception here. So consider refactoring into a exception type that
231 # is associated with the wire protocol.
230 # is associated with the wire protocol.
232 try:
231 try:
233 _callhttp(repo, req, res, proto, cmd)
232 _callhttp(repo, req, res, proto, cmd)
234 except hgwebcommon.ErrorResponse as e:
233 except hgwebcommon.ErrorResponse as e:
235 for k, v in e.headers:
234 for k, v in e.headers:
236 res.headers[k] = v
235 res.headers[k] = v
237 res.status = hgwebcommon.statusmessage(e.code, pycompat.bytestr(e))
236 res.status = hgwebcommon.statusmessage(e.code, pycompat.bytestr(e))
238 # TODO This response body assumes the failed command was
237 # TODO This response body assumes the failed command was
239 # "unbundle." That assumption is not always valid.
238 # "unbundle." That assumption is not always valid.
240 res.setbodybytes(b'0\n%s\n' % pycompat.bytestr(e))
239 res.setbodybytes(b'0\n%s\n' % pycompat.bytestr(e))
241
240
242 return True
241 return True
243
242
244
243
245 def _availableapis(repo):
244 def _availableapis(repo):
246 apis = set()
245 apis = set()
247
246
248 # Registered APIs are made available via config options of the name of
247 # Registered APIs are made available via config options of the name of
249 # the protocol.
248 # the protocol.
250 for k, v in API_HANDLERS.items():
249 for k, v in API_HANDLERS.items():
251 section, option = v[b'config']
250 section, option = v[b'config']
252 if repo.ui.configbool(section, option):
251 if repo.ui.configbool(section, option):
253 apis.add(k)
252 apis.add(k)
254
253
255 return apis
254 return apis
256
255
257
256
258 def handlewsgiapirequest(rctx, req, res, checkperm):
257 def handlewsgiapirequest(rctx, req, res, checkperm):
259 """Handle requests to /api/*."""
258 """Handle requests to /api/*."""
260 assert req.dispatchparts[0] == b'api'
259 assert req.dispatchparts[0] == b'api'
261
260
262 repo = rctx.repo
261 repo = rctx.repo
263
262
264 # This whole URL space is experimental for now. But we want to
263 # This whole URL space is experimental for now. But we want to
265 # reserve the URL space. So, 404 all URLs if the feature isn't enabled.
264 # reserve the URL space. So, 404 all URLs if the feature isn't enabled.
266 if not repo.ui.configbool(b'experimental', b'web.apiserver'):
265 if not repo.ui.configbool(b'experimental', b'web.apiserver'):
267 res.status = b'404 Not Found'
266 res.status = b'404 Not Found'
268 res.headers[b'Content-Type'] = b'text/plain'
267 res.headers[b'Content-Type'] = b'text/plain'
269 res.setbodybytes(_(b'Experimental API server endpoint not enabled'))
268 res.setbodybytes(_(b'Experimental API server endpoint not enabled'))
270 return
269 return
271
270
272 # The URL space is /api/<protocol>/*. The structure of URLs under varies
271 # The URL space is /api/<protocol>/*. The structure of URLs under varies
273 # by <protocol>.
272 # by <protocol>.
274
273
275 availableapis = _availableapis(repo)
274 availableapis = _availableapis(repo)
276
275
277 # Requests to /api/ list available APIs.
276 # Requests to /api/ list available APIs.
278 if req.dispatchparts == [b'api']:
277 if req.dispatchparts == [b'api']:
279 res.status = b'200 OK'
278 res.status = b'200 OK'
280 res.headers[b'Content-Type'] = b'text/plain'
279 res.headers[b'Content-Type'] = b'text/plain'
281 lines = [
280 lines = [
282 _(
281 _(
283 b'APIs can be accessed at /api/<name>, where <name> can be '
282 b'APIs can be accessed at /api/<name>, where <name> can be '
284 b'one of the following:\n'
283 b'one of the following:\n'
285 )
284 )
286 ]
285 ]
287 if availableapis:
286 if availableapis:
288 lines.extend(sorted(availableapis))
287 lines.extend(sorted(availableapis))
289 else:
288 else:
290 lines.append(_(b'(no available APIs)\n'))
289 lines.append(_(b'(no available APIs)\n'))
291 res.setbodybytes(b'\n'.join(lines))
290 res.setbodybytes(b'\n'.join(lines))
292 return
291 return
293
292
294 proto = req.dispatchparts[1]
293 proto = req.dispatchparts[1]
295
294
296 if proto not in API_HANDLERS:
295 if proto not in API_HANDLERS:
297 res.status = b'404 Not Found'
296 res.status = b'404 Not Found'
298 res.headers[b'Content-Type'] = b'text/plain'
297 res.headers[b'Content-Type'] = b'text/plain'
299 res.setbodybytes(
298 res.setbodybytes(
300 _(b'Unknown API: %s\nKnown APIs: %s')
299 _(b'Unknown API: %s\nKnown APIs: %s')
301 % (proto, b', '.join(sorted(availableapis)))
300 % (proto, b', '.join(sorted(availableapis)))
302 )
301 )
303 return
302 return
304
303
305 if proto not in availableapis:
304 if proto not in availableapis:
306 res.status = b'404 Not Found'
305 res.status = b'404 Not Found'
307 res.headers[b'Content-Type'] = b'text/plain'
306 res.headers[b'Content-Type'] = b'text/plain'
308 res.setbodybytes(_(b'API %s not enabled\n') % proto)
307 res.setbodybytes(_(b'API %s not enabled\n') % proto)
309 return
308 return
310
309
311 API_HANDLERS[proto][b'handler'](
310 API_HANDLERS[proto][b'handler'](
312 rctx, req, res, checkperm, req.dispatchparts[2:]
311 rctx, req, res, checkperm, req.dispatchparts[2:]
313 )
312 )
314
313
315
314
316 # Maps API name to metadata so custom API can be registered.
315 # Maps API name to metadata so custom API can be registered.
317 # Keys are:
316 # Keys are:
318 #
317 #
319 # config
318 # config
320 # Config option that controls whether service is enabled.
319 # Config option that controls whether service is enabled.
321 # handler
320 # handler
322 # Callable receiving (rctx, req, res, checkperm, urlparts) that is called
321 # Callable receiving (rctx, req, res, checkperm, urlparts) that is called
323 # when a request to this API is received.
322 # when a request to this API is received.
324 # apidescriptor
323 # apidescriptor
325 # Callable receiving (req, repo) that is called to obtain an API
324 # Callable receiving (req, repo) that is called to obtain an API
326 # descriptor for this service. The response must be serializable to CBOR.
325 # descriptor for this service. The response must be serializable to CBOR.
327 API_HANDLERS = {
326 API_HANDLERS = {
328 wireprotov2server.HTTP_WIREPROTO_V2: {
327 wireprotov2server.HTTP_WIREPROTO_V2: {
329 b'config': (b'experimental', b'web.api.http-v2'),
328 b'config': (b'experimental', b'web.api.http-v2'),
330 b'handler': wireprotov2server.handlehttpv2request,
329 b'handler': wireprotov2server.handlehttpv2request,
331 b'apidescriptor': wireprotov2server.httpv2apidescriptor,
330 b'apidescriptor': wireprotov2server.httpv2apidescriptor,
332 },
331 },
333 }
332 }
334
333
335
334
336 def _httpresponsetype(ui, proto, prefer_uncompressed):
335 def _httpresponsetype(ui, proto, prefer_uncompressed):
337 """Determine the appropriate response type and compression settings.
336 """Determine the appropriate response type and compression settings.
338
337
339 Returns a tuple of (mediatype, compengine, engineopts).
338 Returns a tuple of (mediatype, compengine, engineopts).
340 """
339 """
341 # Determine the response media type and compression engine based
340 # Determine the response media type and compression engine based
342 # on the request parameters.
341 # on the request parameters.
343
342
344 if b'0.2' in proto.getprotocaps():
343 if b'0.2' in proto.getprotocaps():
345 # All clients are expected to support uncompressed data.
344 # All clients are expected to support uncompressed data.
346 if prefer_uncompressed:
345 if prefer_uncompressed:
347 return HGTYPE2, compression._noopengine(), {}
346 return HGTYPE2, compression._noopengine(), {}
348
347
349 # Now find an agreed upon compression format.
348 # Now find an agreed upon compression format.
350 compformats = wireprotov1server.clientcompressionsupport(proto)
349 compformats = wireprotov1server.clientcompressionsupport(proto)
351 for engine in wireprototypes.supportedcompengines(
350 for engine in wireprototypes.supportedcompengines(
352 ui, compression.SERVERROLE
351 ui, compression.SERVERROLE
353 ):
352 ):
354 if engine.wireprotosupport().name in compformats:
353 if engine.wireprotosupport().name in compformats:
355 opts = {}
354 opts = {}
356 level = ui.configint(b'server', b'%slevel' % engine.name())
355 level = ui.configint(b'server', b'%slevel' % engine.name())
357 if level is not None:
356 if level is not None:
358 opts[b'level'] = level
357 opts[b'level'] = level
359
358
360 return HGTYPE2, engine, opts
359 return HGTYPE2, engine, opts
361
360
362 # No mutually supported compression format. Fall back to the
361 # No mutually supported compression format. Fall back to the
363 # legacy protocol.
362 # legacy protocol.
364
363
365 # Don't allow untrusted settings because disabling compression or
364 # Don't allow untrusted settings because disabling compression or
366 # setting a very high compression level could lead to flooding
365 # setting a very high compression level could lead to flooding
367 # the server's network or CPU.
366 # the server's network or CPU.
368 opts = {b'level': ui.configint(b'server', b'zliblevel')}
367 opts = {b'level': ui.configint(b'server', b'zliblevel')}
369 return HGTYPE, util.compengines[b'zlib'], opts
368 return HGTYPE, util.compengines[b'zlib'], opts
370
369
371
370
372 def processcapabilitieshandshake(repo, req, res, proto):
371 def processcapabilitieshandshake(repo, req, res, proto):
373 """Called during a ?cmd=capabilities request.
372 """Called during a ?cmd=capabilities request.
374
373
375 If the client is advertising support for a newer protocol, we send
374 If the client is advertising support for a newer protocol, we send
376 a CBOR response with information about available services. If no
375 a CBOR response with information about available services. If no
377 advertised services are available, we don't handle the request.
376 advertised services are available, we don't handle the request.
378 """
377 """
379 # Fall back to old behavior unless the API server is enabled.
378 # Fall back to old behavior unless the API server is enabled.
380 if not repo.ui.configbool(b'experimental', b'web.apiserver'):
379 if not repo.ui.configbool(b'experimental', b'web.apiserver'):
381 return False
380 return False
382
381
383 clientapis = decodevaluefromheaders(req, b'X-HgUpgrade')
382 clientapis = decodevaluefromheaders(req, b'X-HgUpgrade')
384 protocaps = decodevaluefromheaders(req, b'X-HgProto')
383 protocaps = decodevaluefromheaders(req, b'X-HgProto')
385 if not clientapis or not protocaps:
384 if not clientapis or not protocaps:
386 return False
385 return False
387
386
388 # We currently only support CBOR responses.
387 # We currently only support CBOR responses.
389 protocaps = set(protocaps.split(b' '))
388 protocaps = set(protocaps.split(b' '))
390 if b'cbor' not in protocaps:
389 if b'cbor' not in protocaps:
391 return False
390 return False
392
391
393 descriptors = {}
392 descriptors = {}
394
393
395 for api in sorted(set(clientapis.split()) & _availableapis(repo)):
394 for api in sorted(set(clientapis.split()) & _availableapis(repo)):
396 handler = API_HANDLERS[api]
395 handler = API_HANDLERS[api]
397
396
398 descriptorfn = handler.get(b'apidescriptor')
397 descriptorfn = handler.get(b'apidescriptor')
399 if not descriptorfn:
398 if not descriptorfn:
400 continue
399 continue
401
400
402 descriptors[api] = descriptorfn(req, repo)
401 descriptors[api] = descriptorfn(req, repo)
403
402
404 v1caps = wireprotov1server.dispatch(repo, proto, b'capabilities')
403 v1caps = wireprotov1server.dispatch(repo, proto, b'capabilities')
405 assert isinstance(v1caps, wireprototypes.bytesresponse)
404 assert isinstance(v1caps, wireprototypes.bytesresponse)
406
405
407 m = {
406 m = {
408 # TODO allow this to be configurable.
407 # TODO allow this to be configurable.
409 b'apibase': b'api/',
408 b'apibase': b'api/',
410 b'apis': descriptors,
409 b'apis': descriptors,
411 b'v1capabilities': v1caps.data,
410 b'v1capabilities': v1caps.data,
412 }
411 }
413
412
414 res.status = b'200 OK'
413 res.status = b'200 OK'
415 res.headers[b'Content-Type'] = b'application/mercurial-cbor'
414 res.headers[b'Content-Type'] = b'application/mercurial-cbor'
416 res.setbodybytes(b''.join(cborutil.streamencode(m)))
415 res.setbodybytes(b''.join(cborutil.streamencode(m)))
417
416
418 return True
417 return True
419
418
420
419
421 def _callhttp(repo, req, res, proto, cmd):
420 def _callhttp(repo, req, res, proto, cmd):
422 # Avoid cycle involving hg module.
421 # Avoid cycle involving hg module.
423 from .hgweb import common as hgwebcommon
422 from .hgweb import common as hgwebcommon
424
423
425 def genversion2(gen, engine, engineopts):
424 def genversion2(gen, engine, engineopts):
426 # application/mercurial-0.2 always sends a payload header
425 # application/mercurial-0.2 always sends a payload header
427 # identifying the compression engine.
426 # identifying the compression engine.
428 name = engine.wireprotosupport().name
427 name = engine.wireprotosupport().name
429 assert 0 < len(name) < 256
428 assert 0 < len(name) < 256
430 yield struct.pack(b'B', len(name))
429 yield struct.pack(b'B', len(name))
431 yield name
430 yield name
432
431
433 for chunk in gen:
432 for chunk in gen:
434 yield chunk
433 yield chunk
435
434
436 def setresponse(code, contenttype, bodybytes=None, bodygen=None):
435 def setresponse(code, contenttype, bodybytes=None, bodygen=None):
437 if code == HTTP_OK:
436 if code == HTTP_OK:
438 res.status = b'200 Script output follows'
437 res.status = b'200 Script output follows'
439 else:
438 else:
440 res.status = hgwebcommon.statusmessage(code)
439 res.status = hgwebcommon.statusmessage(code)
441
440
442 res.headers[b'Content-Type'] = contenttype
441 res.headers[b'Content-Type'] = contenttype
443
442
444 if bodybytes is not None:
443 if bodybytes is not None:
445 res.setbodybytes(bodybytes)
444 res.setbodybytes(bodybytes)
446 if bodygen is not None:
445 if bodygen is not None:
447 res.setbodygen(bodygen)
446 res.setbodygen(bodygen)
448
447
449 if not wireprotov1server.commands.commandavailable(cmd, proto):
448 if not wireprotov1server.commands.commandavailable(cmd, proto):
450 setresponse(
449 setresponse(
451 HTTP_OK,
450 HTTP_OK,
452 HGERRTYPE,
451 HGERRTYPE,
453 _(
452 _(
454 b'requested wire protocol command is not available over '
453 b'requested wire protocol command is not available over '
455 b'HTTP'
454 b'HTTP'
456 ),
455 ),
457 )
456 )
458 return
457 return
459
458
460 proto.checkperm(wireprotov1server.commands[cmd].permission)
459 proto.checkperm(wireprotov1server.commands[cmd].permission)
461
460
462 # Possibly handle a modern client wanting to switch protocols.
461 # Possibly handle a modern client wanting to switch protocols.
463 if cmd == b'capabilities' and processcapabilitieshandshake(
462 if cmd == b'capabilities' and processcapabilitieshandshake(
464 repo, req, res, proto
463 repo, req, res, proto
465 ):
464 ):
466
465
467 return
466 return
468
467
469 rsp = wireprotov1server.dispatch(repo, proto, cmd)
468 rsp = wireprotov1server.dispatch(repo, proto, cmd)
470
469
471 if isinstance(rsp, bytes):
470 if isinstance(rsp, bytes):
472 setresponse(HTTP_OK, HGTYPE, bodybytes=rsp)
471 setresponse(HTTP_OK, HGTYPE, bodybytes=rsp)
473 elif isinstance(rsp, wireprototypes.bytesresponse):
472 elif isinstance(rsp, wireprototypes.bytesresponse):
474 setresponse(HTTP_OK, HGTYPE, bodybytes=rsp.data)
473 setresponse(HTTP_OK, HGTYPE, bodybytes=rsp.data)
475 elif isinstance(rsp, wireprototypes.streamreslegacy):
474 elif isinstance(rsp, wireprototypes.streamreslegacy):
476 setresponse(HTTP_OK, HGTYPE, bodygen=rsp.gen)
475 setresponse(HTTP_OK, HGTYPE, bodygen=rsp.gen)
477 elif isinstance(rsp, wireprototypes.streamres):
476 elif isinstance(rsp, wireprototypes.streamres):
478 gen = rsp.gen
477 gen = rsp.gen
479
478
480 # This code for compression should not be streamres specific. It
479 # This code for compression should not be streamres specific. It
481 # is here because we only compress streamres at the moment.
480 # is here because we only compress streamres at the moment.
482 mediatype, engine, engineopts = _httpresponsetype(
481 mediatype, engine, engineopts = _httpresponsetype(
483 repo.ui, proto, rsp.prefer_uncompressed
482 repo.ui, proto, rsp.prefer_uncompressed
484 )
483 )
485 gen = engine.compressstream(gen, engineopts)
484 gen = engine.compressstream(gen, engineopts)
486
485
487 if mediatype == HGTYPE2:
486 if mediatype == HGTYPE2:
488 gen = genversion2(gen, engine, engineopts)
487 gen = genversion2(gen, engine, engineopts)
489
488
490 setresponse(HTTP_OK, mediatype, bodygen=gen)
489 setresponse(HTTP_OK, mediatype, bodygen=gen)
491 elif isinstance(rsp, wireprototypes.pushres):
490 elif isinstance(rsp, wireprototypes.pushres):
492 rsp = b'%d\n%s' % (rsp.res, rsp.output)
491 rsp = b'%d\n%s' % (rsp.res, rsp.output)
493 setresponse(HTTP_OK, HGTYPE, bodybytes=rsp)
492 setresponse(HTTP_OK, HGTYPE, bodybytes=rsp)
494 elif isinstance(rsp, wireprototypes.pusherr):
493 elif isinstance(rsp, wireprototypes.pusherr):
495 rsp = b'0\n%s\n' % rsp.res
494 rsp = b'0\n%s\n' % rsp.res
496 res.drain = True
495 res.drain = True
497 setresponse(HTTP_OK, HGTYPE, bodybytes=rsp)
496 setresponse(HTTP_OK, HGTYPE, bodybytes=rsp)
498 elif isinstance(rsp, wireprototypes.ooberror):
497 elif isinstance(rsp, wireprototypes.ooberror):
499 setresponse(HTTP_OK, HGERRTYPE, bodybytes=rsp.message)
498 setresponse(HTTP_OK, HGERRTYPE, bodybytes=rsp.message)
500 else:
499 else:
501 raise error.ProgrammingError(b'hgweb.protocol internal failure', rsp)
500 raise error.ProgrammingError(b'hgweb.protocol internal failure', rsp)
502
501
503
502
504 def _sshv1respondbytes(fout, value):
503 def _sshv1respondbytes(fout, value):
505 """Send a bytes response for protocol version 1."""
504 """Send a bytes response for protocol version 1."""
506 fout.write(b'%d\n' % len(value))
505 fout.write(b'%d\n' % len(value))
507 fout.write(value)
506 fout.write(value)
508 fout.flush()
507 fout.flush()
509
508
510
509
511 def _sshv1respondstream(fout, source):
510 def _sshv1respondstream(fout, source):
512 write = fout.write
511 write = fout.write
513 for chunk in source.gen:
512 for chunk in source.gen:
514 write(chunk)
513 write(chunk)
515 fout.flush()
514 fout.flush()
516
515
517
516
518 def _sshv1respondooberror(fout, ferr, rsp):
517 def _sshv1respondooberror(fout, ferr, rsp):
519 ferr.write(b'%s\n-\n' % rsp)
518 ferr.write(b'%s\n-\n' % rsp)
520 ferr.flush()
519 ferr.flush()
521 fout.write(b'\n')
520 fout.write(b'\n')
522 fout.flush()
521 fout.flush()
523
522
524
523
525 @interfaceutil.implementer(wireprototypes.baseprotocolhandler)
524 @interfaceutil.implementer(wireprototypes.baseprotocolhandler)
526 class sshv1protocolhandler(object):
525 class sshv1protocolhandler(object):
527 """Handler for requests services via version 1 of SSH protocol."""
526 """Handler for requests services via version 1 of SSH protocol."""
528
527
529 def __init__(self, ui, fin, fout):
528 def __init__(self, ui, fin, fout):
530 self._ui = ui
529 self._ui = ui
531 self._fin = fin
530 self._fin = fin
532 self._fout = fout
531 self._fout = fout
533 self._protocaps = set()
532 self._protocaps = set()
534
533
535 @property
534 @property
536 def name(self):
535 def name(self):
537 return wireprototypes.SSHV1
536 return wireprototypes.SSHV1
538
537
539 def getargs(self, args):
538 def getargs(self, args):
540 data = {}
539 data = {}
541 keys = args.split()
540 keys = args.split()
542 for n in pycompat.xrange(len(keys)):
541 for n in pycompat.xrange(len(keys)):
543 argline = self._fin.readline()[:-1]
542 argline = self._fin.readline()[:-1]
544 arg, l = argline.split()
543 arg, l = argline.split()
545 if arg not in keys:
544 if arg not in keys:
546 raise error.Abort(_(b"unexpected parameter %r") % arg)
545 raise error.Abort(_(b"unexpected parameter %r") % arg)
547 if arg == b'*':
546 if arg == b'*':
548 star = {}
547 star = {}
549 for k in pycompat.xrange(int(l)):
548 for k in pycompat.xrange(int(l)):
550 argline = self._fin.readline()[:-1]
549 argline = self._fin.readline()[:-1]
551 arg, l = argline.split()
550 arg, l = argline.split()
552 val = self._fin.read(int(l))
551 val = self._fin.read(int(l))
553 star[arg] = val
552 star[arg] = val
554 data[b'*'] = star
553 data[b'*'] = star
555 else:
554 else:
556 val = self._fin.read(int(l))
555 val = self._fin.read(int(l))
557 data[arg] = val
556 data[arg] = val
558 return [data[k] for k in keys]
557 return [data[k] for k in keys]
559
558
560 def getprotocaps(self):
559 def getprotocaps(self):
561 return self._protocaps
560 return self._protocaps
562
561
563 def getpayload(self):
562 def getpayload(self):
564 # We initially send an empty response. This tells the client it is
563 # We initially send an empty response. This tells the client it is
565 # OK to start sending data. If a client sees any other response, it
564 # OK to start sending data. If a client sees any other response, it
566 # interprets it as an error.
565 # interprets it as an error.
567 _sshv1respondbytes(self._fout, b'')
566 _sshv1respondbytes(self._fout, b'')
568
567
569 # The file is in the form:
568 # The file is in the form:
570 #
569 #
571 # <chunk size>\n<chunk>
570 # <chunk size>\n<chunk>
572 # ...
571 # ...
573 # 0\n
572 # 0\n
574 count = int(self._fin.readline())
573 count = int(self._fin.readline())
575 while count:
574 while count:
576 yield self._fin.read(count)
575 yield self._fin.read(count)
577 count = int(self._fin.readline())
576 count = int(self._fin.readline())
578
577
579 @contextlib.contextmanager
578 @contextlib.contextmanager
580 def mayberedirectstdio(self):
579 def mayberedirectstdio(self):
581 yield None
580 yield None
582
581
583 def client(self):
582 def client(self):
584 client = encoding.environ.get(b'SSH_CLIENT', b'').split(b' ', 1)[0]
583 client = encoding.environ.get(b'SSH_CLIENT', b'').split(b' ', 1)[0]
585 return b'remote:ssh:' + client
584 return b'remote:ssh:' + client
586
585
587 def addcapabilities(self, repo, caps):
586 def addcapabilities(self, repo, caps):
588 if self.name == wireprototypes.SSHV1:
587 if self.name == wireprototypes.SSHV1:
589 caps.append(b'protocaps')
588 caps.append(b'protocaps')
590 caps.append(b'batch')
589 caps.append(b'batch')
591 return caps
590 return caps
592
591
593 def checkperm(self, perm):
592 def checkperm(self, perm):
594 pass
593 pass
595
594
596
595
597 class sshv2protocolhandler(sshv1protocolhandler):
596 class sshv2protocolhandler(sshv1protocolhandler):
598 """Protocol handler for version 2 of the SSH protocol."""
597 """Protocol handler for version 2 of the SSH protocol."""
599
598
600 @property
599 @property
601 def name(self):
600 def name(self):
602 return wireprototypes.SSHV2
601 return wireprototypes.SSHV2
603
602
604 def addcapabilities(self, repo, caps):
603 def addcapabilities(self, repo, caps):
605 return caps
604 return caps
606
605
607
606
608 def _runsshserver(ui, repo, fin, fout, ev):
607 def _runsshserver(ui, repo, fin, fout, ev):
609 # This function operates like a state machine of sorts. The following
608 # This function operates like a state machine of sorts. The following
610 # states are defined:
609 # states are defined:
611 #
610 #
612 # protov1-serving
611 # protov1-serving
613 # Server is in protocol version 1 serving mode. Commands arrive on
612 # Server is in protocol version 1 serving mode. Commands arrive on
614 # new lines. These commands are processed in this state, one command
613 # new lines. These commands are processed in this state, one command
615 # after the other.
614 # after the other.
616 #
615 #
617 # protov2-serving
616 # protov2-serving
618 # Server is in protocol version 2 serving mode.
617 # Server is in protocol version 2 serving mode.
619 #
618 #
620 # upgrade-initial
619 # upgrade-initial
621 # The server is going to process an upgrade request.
620 # The server is going to process an upgrade request.
622 #
621 #
623 # upgrade-v2-filter-legacy-handshake
622 # upgrade-v2-filter-legacy-handshake
624 # The protocol is being upgraded to version 2. The server is expecting
623 # The protocol is being upgraded to version 2. The server is expecting
625 # the legacy handshake from version 1.
624 # the legacy handshake from version 1.
626 #
625 #
627 # upgrade-v2-finish
626 # upgrade-v2-finish
628 # The upgrade to version 2 of the protocol is imminent.
627 # The upgrade to version 2 of the protocol is imminent.
629 #
628 #
630 # shutdown
629 # shutdown
631 # The server is shutting down, possibly in reaction to a client event.
630 # The server is shutting down, possibly in reaction to a client event.
632 #
631 #
633 # And here are their transitions:
632 # And here are their transitions:
634 #
633 #
635 # protov1-serving -> shutdown
634 # protov1-serving -> shutdown
636 # When server receives an empty request or encounters another
635 # When server receives an empty request or encounters another
637 # error.
636 # error.
638 #
637 #
639 # protov1-serving -> upgrade-initial
638 # protov1-serving -> upgrade-initial
640 # An upgrade request line was seen.
639 # An upgrade request line was seen.
641 #
640 #
642 # upgrade-initial -> upgrade-v2-filter-legacy-handshake
641 # upgrade-initial -> upgrade-v2-filter-legacy-handshake
643 # Upgrade to version 2 in progress. Server is expecting to
642 # Upgrade to version 2 in progress. Server is expecting to
644 # process a legacy handshake.
643 # process a legacy handshake.
645 #
644 #
646 # upgrade-v2-filter-legacy-handshake -> shutdown
645 # upgrade-v2-filter-legacy-handshake -> shutdown
647 # Client did not fulfill upgrade handshake requirements.
646 # Client did not fulfill upgrade handshake requirements.
648 #
647 #
649 # upgrade-v2-filter-legacy-handshake -> upgrade-v2-finish
648 # upgrade-v2-filter-legacy-handshake -> upgrade-v2-finish
650 # Client fulfilled version 2 upgrade requirements. Finishing that
649 # Client fulfilled version 2 upgrade requirements. Finishing that
651 # upgrade.
650 # upgrade.
652 #
651 #
653 # upgrade-v2-finish -> protov2-serving
652 # upgrade-v2-finish -> protov2-serving
654 # Protocol upgrade to version 2 complete. Server can now speak protocol
653 # Protocol upgrade to version 2 complete. Server can now speak protocol
655 # version 2.
654 # version 2.
656 #
655 #
657 # protov2-serving -> protov1-serving
656 # protov2-serving -> protov1-serving
658 # Ths happens by default since protocol version 2 is the same as
657 # Ths happens by default since protocol version 2 is the same as
659 # version 1 except for the handshake.
658 # version 1 except for the handshake.
660
659
661 state = b'protov1-serving'
660 state = b'protov1-serving'
662 proto = sshv1protocolhandler(ui, fin, fout)
661 proto = sshv1protocolhandler(ui, fin, fout)
663 protoswitched = False
662 protoswitched = False
664
663
665 while not ev.is_set():
664 while not ev.is_set():
666 if state == b'protov1-serving':
665 if state == b'protov1-serving':
667 # Commands are issued on new lines.
666 # Commands are issued on new lines.
668 request = fin.readline()[:-1]
667 request = fin.readline()[:-1]
669
668
670 # Empty lines signal to terminate the connection.
669 # Empty lines signal to terminate the connection.
671 if not request:
670 if not request:
672 state = b'shutdown'
671 state = b'shutdown'
673 continue
672 continue
674
673
675 # It looks like a protocol upgrade request. Transition state to
674 # It looks like a protocol upgrade request. Transition state to
676 # handle it.
675 # handle it.
677 if request.startswith(b'upgrade '):
676 if request.startswith(b'upgrade '):
678 if protoswitched:
677 if protoswitched:
679 _sshv1respondooberror(
678 _sshv1respondooberror(
680 fout,
679 fout,
681 ui.ferr,
680 ui.ferr,
682 b'cannot upgrade protocols multiple times',
681 b'cannot upgrade protocols multiple times',
683 )
682 )
684 state = b'shutdown'
683 state = b'shutdown'
685 continue
684 continue
686
685
687 state = b'upgrade-initial'
686 state = b'upgrade-initial'
688 continue
687 continue
689
688
690 available = wireprotov1server.commands.commandavailable(
689 available = wireprotov1server.commands.commandavailable(
691 request, proto
690 request, proto
692 )
691 )
693
692
694 # This command isn't available. Send an empty response and go
693 # This command isn't available. Send an empty response and go
695 # back to waiting for a new command.
694 # back to waiting for a new command.
696 if not available:
695 if not available:
697 _sshv1respondbytes(fout, b'')
696 _sshv1respondbytes(fout, b'')
698 continue
697 continue
699
698
700 rsp = wireprotov1server.dispatch(repo, proto, request)
699 rsp = wireprotov1server.dispatch(repo, proto, request)
701 repo.ui.fout.flush()
700 repo.ui.fout.flush()
702 repo.ui.ferr.flush()
701 repo.ui.ferr.flush()
703
702
704 if isinstance(rsp, bytes):
703 if isinstance(rsp, bytes):
705 _sshv1respondbytes(fout, rsp)
704 _sshv1respondbytes(fout, rsp)
706 elif isinstance(rsp, wireprototypes.bytesresponse):
705 elif isinstance(rsp, wireprototypes.bytesresponse):
707 _sshv1respondbytes(fout, rsp.data)
706 _sshv1respondbytes(fout, rsp.data)
708 elif isinstance(rsp, wireprototypes.streamres):
707 elif isinstance(rsp, wireprototypes.streamres):
709 _sshv1respondstream(fout, rsp)
708 _sshv1respondstream(fout, rsp)
710 elif isinstance(rsp, wireprototypes.streamreslegacy):
709 elif isinstance(rsp, wireprototypes.streamreslegacy):
711 _sshv1respondstream(fout, rsp)
710 _sshv1respondstream(fout, rsp)
712 elif isinstance(rsp, wireprototypes.pushres):
711 elif isinstance(rsp, wireprototypes.pushres):
713 _sshv1respondbytes(fout, b'')
712 _sshv1respondbytes(fout, b'')
714 _sshv1respondbytes(fout, b'%d' % rsp.res)
713 _sshv1respondbytes(fout, b'%d' % rsp.res)
715 elif isinstance(rsp, wireprototypes.pusherr):
714 elif isinstance(rsp, wireprototypes.pusherr):
716 _sshv1respondbytes(fout, rsp.res)
715 _sshv1respondbytes(fout, rsp.res)
717 elif isinstance(rsp, wireprototypes.ooberror):
716 elif isinstance(rsp, wireprototypes.ooberror):
718 _sshv1respondooberror(fout, ui.ferr, rsp.message)
717 _sshv1respondooberror(fout, ui.ferr, rsp.message)
719 else:
718 else:
720 raise error.ProgrammingError(
719 raise error.ProgrammingError(
721 b'unhandled response type from '
720 b'unhandled response type from '
722 b'wire protocol command: %s' % rsp
721 b'wire protocol command: %s' % rsp
723 )
722 )
724
723
725 # For now, protocol version 2 serving just goes back to version 1.
724 # For now, protocol version 2 serving just goes back to version 1.
726 elif state == b'protov2-serving':
725 elif state == b'protov2-serving':
727 state = b'protov1-serving'
726 state = b'protov1-serving'
728 continue
727 continue
729
728
730 elif state == b'upgrade-initial':
729 elif state == b'upgrade-initial':
731 # We should never transition into this state if we've switched
730 # We should never transition into this state if we've switched
732 # protocols.
731 # protocols.
733 assert not protoswitched
732 assert not protoswitched
734 assert proto.name == wireprototypes.SSHV1
733 assert proto.name == wireprototypes.SSHV1
735
734
736 # Expected: upgrade <token> <capabilities>
735 # Expected: upgrade <token> <capabilities>
737 # If we get something else, the request is malformed. It could be
736 # If we get something else, the request is malformed. It could be
738 # from a future client that has altered the upgrade line content.
737 # from a future client that has altered the upgrade line content.
739 # We treat this as an unknown command.
738 # We treat this as an unknown command.
740 try:
739 try:
741 token, caps = request.split(b' ')[1:]
740 token, caps = request.split(b' ')[1:]
742 except ValueError:
741 except ValueError:
743 _sshv1respondbytes(fout, b'')
742 _sshv1respondbytes(fout, b'')
744 state = b'protov1-serving'
743 state = b'protov1-serving'
745 continue
744 continue
746
745
747 # Send empty response if we don't support upgrading protocols.
746 # Send empty response if we don't support upgrading protocols.
748 if not ui.configbool(b'experimental', b'sshserver.support-v2'):
747 if not ui.configbool(b'experimental', b'sshserver.support-v2'):
749 _sshv1respondbytes(fout, b'')
748 _sshv1respondbytes(fout, b'')
750 state = b'protov1-serving'
749 state = b'protov1-serving'
751 continue
750 continue
752
751
753 try:
752 try:
754 caps = urlreq.parseqs(caps)
753 caps = urlreq.parseqs(caps)
755 except ValueError:
754 except ValueError:
756 _sshv1respondbytes(fout, b'')
755 _sshv1respondbytes(fout, b'')
757 state = b'protov1-serving'
756 state = b'protov1-serving'
758 continue
757 continue
759
758
760 # We don't see an upgrade request to protocol version 2. Ignore
759 # We don't see an upgrade request to protocol version 2. Ignore
761 # the upgrade request.
760 # the upgrade request.
762 wantedprotos = caps.get(b'proto', [b''])[0]
761 wantedprotos = caps.get(b'proto', [b''])[0]
763 if SSHV2 not in wantedprotos:
762 if SSHV2 not in wantedprotos:
764 _sshv1respondbytes(fout, b'')
763 _sshv1respondbytes(fout, b'')
765 state = b'protov1-serving'
764 state = b'protov1-serving'
766 continue
765 continue
767
766
768 # It looks like we can honor this upgrade request to protocol 2.
767 # It looks like we can honor this upgrade request to protocol 2.
769 # Filter the rest of the handshake protocol request lines.
768 # Filter the rest of the handshake protocol request lines.
770 state = b'upgrade-v2-filter-legacy-handshake'
769 state = b'upgrade-v2-filter-legacy-handshake'
771 continue
770 continue
772
771
773 elif state == b'upgrade-v2-filter-legacy-handshake':
772 elif state == b'upgrade-v2-filter-legacy-handshake':
774 # Client should have sent legacy handshake after an ``upgrade``
773 # Client should have sent legacy handshake after an ``upgrade``
775 # request. Expected lines:
774 # request. Expected lines:
776 #
775 #
777 # hello
776 # hello
778 # between
777 # between
779 # pairs 81
778 # pairs 81
780 # 0000...-0000...
779 # 0000...-0000...
781
780
782 ok = True
781 ok = True
783 for line in (b'hello', b'between', b'pairs 81'):
782 for line in (b'hello', b'between', b'pairs 81'):
784 request = fin.readline()[:-1]
783 request = fin.readline()[:-1]
785
784
786 if request != line:
785 if request != line:
787 _sshv1respondooberror(
786 _sshv1respondooberror(
788 fout,
787 fout,
789 ui.ferr,
788 ui.ferr,
790 b'malformed handshake protocol: missing %s' % line,
789 b'malformed handshake protocol: missing %s' % line,
791 )
790 )
792 ok = False
791 ok = False
793 state = b'shutdown'
792 state = b'shutdown'
794 break
793 break
795
794
796 if not ok:
795 if not ok:
797 continue
796 continue
798
797
799 request = fin.read(81)
798 request = fin.read(81)
800 if request != b'%s-%s' % (b'0' * 40, b'0' * 40):
799 if request != b'%s-%s' % (b'0' * 40, b'0' * 40):
801 _sshv1respondooberror(
800 _sshv1respondooberror(
802 fout,
801 fout,
803 ui.ferr,
802 ui.ferr,
804 b'malformed handshake protocol: '
803 b'malformed handshake protocol: '
805 b'missing between argument value',
804 b'missing between argument value',
806 )
805 )
807 state = b'shutdown'
806 state = b'shutdown'
808 continue
807 continue
809
808
810 state = b'upgrade-v2-finish'
809 state = b'upgrade-v2-finish'
811 continue
810 continue
812
811
813 elif state == b'upgrade-v2-finish':
812 elif state == b'upgrade-v2-finish':
814 # Send the upgrade response.
813 # Send the upgrade response.
815 fout.write(b'upgraded %s %s\n' % (token, SSHV2))
814 fout.write(b'upgraded %s %s\n' % (token, SSHV2))
816 servercaps = wireprotov1server.capabilities(repo, proto)
815 servercaps = wireprotov1server.capabilities(repo, proto)
817 rsp = b'capabilities: %s' % servercaps.data
816 rsp = b'capabilities: %s' % servercaps.data
818 fout.write(b'%d\n%s\n' % (len(rsp), rsp))
817 fout.write(b'%d\n%s\n' % (len(rsp), rsp))
819 fout.flush()
818 fout.flush()
820
819
821 proto = sshv2protocolhandler(ui, fin, fout)
820 proto = sshv2protocolhandler(ui, fin, fout)
822 protoswitched = True
821 protoswitched = True
823
822
824 state = b'protov2-serving'
823 state = b'protov2-serving'
825 continue
824 continue
826
825
827 elif state == b'shutdown':
826 elif state == b'shutdown':
828 break
827 break
829
828
830 else:
829 else:
831 raise error.ProgrammingError(
830 raise error.ProgrammingError(
832 b'unhandled ssh server state: %s' % state
831 b'unhandled ssh server state: %s' % state
833 )
832 )
834
833
835
834
836 class sshserver(object):
835 class sshserver(object):
837 def __init__(self, ui, repo, logfh=None):
836 def __init__(self, ui, repo, logfh=None):
838 self._ui = ui
837 self._ui = ui
839 self._repo = repo
838 self._repo = repo
840 self._fin, self._fout = ui.protectfinout()
839 self._fin, self._fout = ui.protectfinout()
841
840
842 # Log write I/O to stdout and stderr if configured.
841 # Log write I/O to stdout and stderr if configured.
843 if logfh:
842 if logfh:
844 self._fout = util.makeloggingfileobject(
843 self._fout = util.makeloggingfileobject(
845 logfh, self._fout, b'o', logdata=True
844 logfh, self._fout, b'o', logdata=True
846 )
845 )
847 ui.ferr = util.makeloggingfileobject(
846 ui.ferr = util.makeloggingfileobject(
848 logfh, ui.ferr, b'e', logdata=True
847 logfh, ui.ferr, b'e', logdata=True
849 )
848 )
850
849
851 def serve_forever(self):
850 def serve_forever(self):
852 self.serveuntil(threading.Event())
851 self.serveuntil(threading.Event())
853 self._ui.restorefinout(self._fin, self._fout)
852 self._ui.restorefinout(self._fin, self._fout)
854 sys.exit(0)
855
853
856 def serveuntil(self, ev):
854 def serveuntil(self, ev):
857 """Serve until a threading.Event is set."""
855 """Serve until a threading.Event is set."""
858 _runsshserver(self._ui, self._repo, self._fin, self._fout, ev)
856 _runsshserver(self._ui, self._repo, self._fin, self._fout, ev)
General Comments 0
You need to be logged in to leave comments. Login now