##// END OF EJS Templates
path: pass `path` to `peer` in `hg pull`...
marmoute -
r50614:06083c5f default
parent child Browse files
Show More
@@ -1,7983 +1,7987 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005-2007 Olivia Mackall <olivia@selenic.com>
3 # Copyright 2005-2007 Olivia Mackall <olivia@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
8
9 import os
9 import os
10 import re
10 import re
11 import sys
11 import sys
12
12
13 from .i18n import _
13 from .i18n import _
14 from .node import (
14 from .node import (
15 hex,
15 hex,
16 nullrev,
16 nullrev,
17 short,
17 short,
18 wdirrev,
18 wdirrev,
19 )
19 )
20 from .pycompat import open
20 from .pycompat import open
21 from . import (
21 from . import (
22 archival,
22 archival,
23 bookmarks,
23 bookmarks,
24 bundle2,
24 bundle2,
25 bundlecaches,
25 bundlecaches,
26 changegroup,
26 changegroup,
27 cmdutil,
27 cmdutil,
28 copies,
28 copies,
29 debugcommands as debugcommandsmod,
29 debugcommands as debugcommandsmod,
30 destutil,
30 destutil,
31 dirstateguard,
31 dirstateguard,
32 discovery,
32 discovery,
33 encoding,
33 encoding,
34 error,
34 error,
35 exchange,
35 exchange,
36 extensions,
36 extensions,
37 filemerge,
37 filemerge,
38 formatter,
38 formatter,
39 graphmod,
39 graphmod,
40 grep as grepmod,
40 grep as grepmod,
41 hbisect,
41 hbisect,
42 help,
42 help,
43 hg,
43 hg,
44 logcmdutil,
44 logcmdutil,
45 merge as mergemod,
45 merge as mergemod,
46 mergestate as mergestatemod,
46 mergestate as mergestatemod,
47 narrowspec,
47 narrowspec,
48 obsolete,
48 obsolete,
49 obsutil,
49 obsutil,
50 patch,
50 patch,
51 phases,
51 phases,
52 pycompat,
52 pycompat,
53 rcutil,
53 rcutil,
54 registrar,
54 registrar,
55 requirements,
55 requirements,
56 revsetlang,
56 revsetlang,
57 rewriteutil,
57 rewriteutil,
58 scmutil,
58 scmutil,
59 server,
59 server,
60 shelve as shelvemod,
60 shelve as shelvemod,
61 state as statemod,
61 state as statemod,
62 streamclone,
62 streamclone,
63 tags as tagsmod,
63 tags as tagsmod,
64 ui as uimod,
64 ui as uimod,
65 util,
65 util,
66 verify as verifymod,
66 verify as verifymod,
67 vfs as vfsmod,
67 vfs as vfsmod,
68 wireprotoserver,
68 wireprotoserver,
69 )
69 )
70 from .utils import (
70 from .utils import (
71 dateutil,
71 dateutil,
72 stringutil,
72 stringutil,
73 urlutil,
73 urlutil,
74 )
74 )
75
75
76 table = {}
76 table = {}
77 table.update(debugcommandsmod.command._table)
77 table.update(debugcommandsmod.command._table)
78
78
79 command = registrar.command(table)
79 command = registrar.command(table)
80 INTENT_READONLY = registrar.INTENT_READONLY
80 INTENT_READONLY = registrar.INTENT_READONLY
81
81
82 # common command options
82 # common command options
83
83
84 globalopts = [
84 globalopts = [
85 (
85 (
86 b'R',
86 b'R',
87 b'repository',
87 b'repository',
88 b'',
88 b'',
89 _(b'repository root directory or name of overlay bundle file'),
89 _(b'repository root directory or name of overlay bundle file'),
90 _(b'REPO'),
90 _(b'REPO'),
91 ),
91 ),
92 (b'', b'cwd', b'', _(b'change working directory'), _(b'DIR')),
92 (b'', b'cwd', b'', _(b'change working directory'), _(b'DIR')),
93 (
93 (
94 b'y',
94 b'y',
95 b'noninteractive',
95 b'noninteractive',
96 None,
96 None,
97 _(
97 _(
98 b'do not prompt, automatically pick the first choice for all prompts'
98 b'do not prompt, automatically pick the first choice for all prompts'
99 ),
99 ),
100 ),
100 ),
101 (b'q', b'quiet', None, _(b'suppress output')),
101 (b'q', b'quiet', None, _(b'suppress output')),
102 (b'v', b'verbose', None, _(b'enable additional output')),
102 (b'v', b'verbose', None, _(b'enable additional output')),
103 (
103 (
104 b'',
104 b'',
105 b'color',
105 b'color',
106 b'',
106 b'',
107 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
107 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
108 # and should not be translated
108 # and should not be translated
109 _(b"when to colorize (boolean, always, auto, never, or debug)"),
109 _(b"when to colorize (boolean, always, auto, never, or debug)"),
110 _(b'TYPE'),
110 _(b'TYPE'),
111 ),
111 ),
112 (
112 (
113 b'',
113 b'',
114 b'config',
114 b'config',
115 [],
115 [],
116 _(b'set/override config option (use \'section.name=value\')'),
116 _(b'set/override config option (use \'section.name=value\')'),
117 _(b'CONFIG'),
117 _(b'CONFIG'),
118 ),
118 ),
119 (b'', b'debug', None, _(b'enable debugging output')),
119 (b'', b'debug', None, _(b'enable debugging output')),
120 (b'', b'debugger', None, _(b'start debugger')),
120 (b'', b'debugger', None, _(b'start debugger')),
121 (
121 (
122 b'',
122 b'',
123 b'encoding',
123 b'encoding',
124 encoding.encoding,
124 encoding.encoding,
125 _(b'set the charset encoding'),
125 _(b'set the charset encoding'),
126 _(b'ENCODE'),
126 _(b'ENCODE'),
127 ),
127 ),
128 (
128 (
129 b'',
129 b'',
130 b'encodingmode',
130 b'encodingmode',
131 encoding.encodingmode,
131 encoding.encodingmode,
132 _(b'set the charset encoding mode'),
132 _(b'set the charset encoding mode'),
133 _(b'MODE'),
133 _(b'MODE'),
134 ),
134 ),
135 (b'', b'traceback', None, _(b'always print a traceback on exception')),
135 (b'', b'traceback', None, _(b'always print a traceback on exception')),
136 (b'', b'time', None, _(b'time how long the command takes')),
136 (b'', b'time', None, _(b'time how long the command takes')),
137 (b'', b'profile', None, _(b'print command execution profile')),
137 (b'', b'profile', None, _(b'print command execution profile')),
138 (b'', b'version', None, _(b'output version information and exit')),
138 (b'', b'version', None, _(b'output version information and exit')),
139 (b'h', b'help', None, _(b'display help and exit')),
139 (b'h', b'help', None, _(b'display help and exit')),
140 (b'', b'hidden', False, _(b'consider hidden changesets')),
140 (b'', b'hidden', False, _(b'consider hidden changesets')),
141 (
141 (
142 b'',
142 b'',
143 b'pager',
143 b'pager',
144 b'auto',
144 b'auto',
145 _(b"when to paginate (boolean, always, auto, or never)"),
145 _(b"when to paginate (boolean, always, auto, or never)"),
146 _(b'TYPE'),
146 _(b'TYPE'),
147 ),
147 ),
148 ]
148 ]
149
149
150 dryrunopts = cmdutil.dryrunopts
150 dryrunopts = cmdutil.dryrunopts
151 remoteopts = cmdutil.remoteopts
151 remoteopts = cmdutil.remoteopts
152 walkopts = cmdutil.walkopts
152 walkopts = cmdutil.walkopts
153 commitopts = cmdutil.commitopts
153 commitopts = cmdutil.commitopts
154 commitopts2 = cmdutil.commitopts2
154 commitopts2 = cmdutil.commitopts2
155 commitopts3 = cmdutil.commitopts3
155 commitopts3 = cmdutil.commitopts3
156 formatteropts = cmdutil.formatteropts
156 formatteropts = cmdutil.formatteropts
157 templateopts = cmdutil.templateopts
157 templateopts = cmdutil.templateopts
158 logopts = cmdutil.logopts
158 logopts = cmdutil.logopts
159 diffopts = cmdutil.diffopts
159 diffopts = cmdutil.diffopts
160 diffwsopts = cmdutil.diffwsopts
160 diffwsopts = cmdutil.diffwsopts
161 diffopts2 = cmdutil.diffopts2
161 diffopts2 = cmdutil.diffopts2
162 mergetoolopts = cmdutil.mergetoolopts
162 mergetoolopts = cmdutil.mergetoolopts
163 similarityopts = cmdutil.similarityopts
163 similarityopts = cmdutil.similarityopts
164 subrepoopts = cmdutil.subrepoopts
164 subrepoopts = cmdutil.subrepoopts
165 debugrevlogopts = cmdutil.debugrevlogopts
165 debugrevlogopts = cmdutil.debugrevlogopts
166
166
167 # Commands start here, listed alphabetically
167 # Commands start here, listed alphabetically
168
168
169
169
170 @command(
170 @command(
171 b'abort',
171 b'abort',
172 dryrunopts,
172 dryrunopts,
173 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
173 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
174 helpbasic=True,
174 helpbasic=True,
175 )
175 )
176 def abort(ui, repo, **opts):
176 def abort(ui, repo, **opts):
177 """abort an unfinished operation (EXPERIMENTAL)
177 """abort an unfinished operation (EXPERIMENTAL)
178
178
179 Aborts a multistep operation like graft, histedit, rebase, merge,
179 Aborts a multistep operation like graft, histedit, rebase, merge,
180 and unshelve if they are in an unfinished state.
180 and unshelve if they are in an unfinished state.
181
181
182 use --dry-run/-n to dry run the command.
182 use --dry-run/-n to dry run the command.
183 """
183 """
184 dryrun = opts.get('dry_run')
184 dryrun = opts.get('dry_run')
185 abortstate = cmdutil.getunfinishedstate(repo)
185 abortstate = cmdutil.getunfinishedstate(repo)
186 if not abortstate:
186 if not abortstate:
187 raise error.StateError(_(b'no operation in progress'))
187 raise error.StateError(_(b'no operation in progress'))
188 if not abortstate.abortfunc:
188 if not abortstate.abortfunc:
189 raise error.InputError(
189 raise error.InputError(
190 (
190 (
191 _(b"%s in progress but does not support 'hg abort'")
191 _(b"%s in progress but does not support 'hg abort'")
192 % (abortstate._opname)
192 % (abortstate._opname)
193 ),
193 ),
194 hint=abortstate.hint(),
194 hint=abortstate.hint(),
195 )
195 )
196 if dryrun:
196 if dryrun:
197 ui.status(
197 ui.status(
198 _(b'%s in progress, will be aborted\n') % (abortstate._opname)
198 _(b'%s in progress, will be aborted\n') % (abortstate._opname)
199 )
199 )
200 return
200 return
201 return abortstate.abortfunc(ui, repo)
201 return abortstate.abortfunc(ui, repo)
202
202
203
203
204 @command(
204 @command(
205 b'add',
205 b'add',
206 walkopts + subrepoopts + dryrunopts,
206 walkopts + subrepoopts + dryrunopts,
207 _(b'[OPTION]... [FILE]...'),
207 _(b'[OPTION]... [FILE]...'),
208 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
208 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
209 helpbasic=True,
209 helpbasic=True,
210 inferrepo=True,
210 inferrepo=True,
211 )
211 )
212 def add(ui, repo, *pats, **opts):
212 def add(ui, repo, *pats, **opts):
213 """add the specified files on the next commit
213 """add the specified files on the next commit
214
214
215 Schedule files to be version controlled and added to the
215 Schedule files to be version controlled and added to the
216 repository.
216 repository.
217
217
218 The files will be added to the repository at the next commit. To
218 The files will be added to the repository at the next commit. To
219 undo an add before that, see :hg:`forget`.
219 undo an add before that, see :hg:`forget`.
220
220
221 If no names are given, add all files to the repository (except
221 If no names are given, add all files to the repository (except
222 files matching ``.hgignore``).
222 files matching ``.hgignore``).
223
223
224 .. container:: verbose
224 .. container:: verbose
225
225
226 Examples:
226 Examples:
227
227
228 - New (unknown) files are added
228 - New (unknown) files are added
229 automatically by :hg:`add`::
229 automatically by :hg:`add`::
230
230
231 $ ls
231 $ ls
232 foo.c
232 foo.c
233 $ hg status
233 $ hg status
234 ? foo.c
234 ? foo.c
235 $ hg add
235 $ hg add
236 adding foo.c
236 adding foo.c
237 $ hg status
237 $ hg status
238 A foo.c
238 A foo.c
239
239
240 - Specific files to be added can be specified::
240 - Specific files to be added can be specified::
241
241
242 $ ls
242 $ ls
243 bar.c foo.c
243 bar.c foo.c
244 $ hg status
244 $ hg status
245 ? bar.c
245 ? bar.c
246 ? foo.c
246 ? foo.c
247 $ hg add bar.c
247 $ hg add bar.c
248 $ hg status
248 $ hg status
249 A bar.c
249 A bar.c
250 ? foo.c
250 ? foo.c
251
251
252 Returns 0 if all files are successfully added.
252 Returns 0 if all files are successfully added.
253 """
253 """
254
254
255 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
255 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
256 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
256 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
257 rejected = cmdutil.add(ui, repo, m, b"", uipathfn, False, **opts)
257 rejected = cmdutil.add(ui, repo, m, b"", uipathfn, False, **opts)
258 return rejected and 1 or 0
258 return rejected and 1 or 0
259
259
260
260
261 @command(
261 @command(
262 b'addremove',
262 b'addremove',
263 similarityopts + subrepoopts + walkopts + dryrunopts,
263 similarityopts + subrepoopts + walkopts + dryrunopts,
264 _(b'[OPTION]... [FILE]...'),
264 _(b'[OPTION]... [FILE]...'),
265 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
265 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
266 inferrepo=True,
266 inferrepo=True,
267 )
267 )
268 def addremove(ui, repo, *pats, **opts):
268 def addremove(ui, repo, *pats, **opts):
269 """add all new files, delete all missing files
269 """add all new files, delete all missing files
270
270
271 Add all new files and remove all missing files from the
271 Add all new files and remove all missing files from the
272 repository.
272 repository.
273
273
274 Unless names are given, new files are ignored if they match any of
274 Unless names are given, new files are ignored if they match any of
275 the patterns in ``.hgignore``. As with add, these changes take
275 the patterns in ``.hgignore``. As with add, these changes take
276 effect at the next commit.
276 effect at the next commit.
277
277
278 Use the -s/--similarity option to detect renamed files. This
278 Use the -s/--similarity option to detect renamed files. This
279 option takes a percentage between 0 (disabled) and 100 (files must
279 option takes a percentage between 0 (disabled) and 100 (files must
280 be identical) as its parameter. With a parameter greater than 0,
280 be identical) as its parameter. With a parameter greater than 0,
281 this compares every removed file with every added file and records
281 this compares every removed file with every added file and records
282 those similar enough as renames. Detecting renamed files this way
282 those similar enough as renames. Detecting renamed files this way
283 can be expensive. After using this option, :hg:`status -C` can be
283 can be expensive. After using this option, :hg:`status -C` can be
284 used to check which files were identified as moved or renamed. If
284 used to check which files were identified as moved or renamed. If
285 not specified, -s/--similarity defaults to 100 and only renames of
285 not specified, -s/--similarity defaults to 100 and only renames of
286 identical files are detected.
286 identical files are detected.
287
287
288 .. container:: verbose
288 .. container:: verbose
289
289
290 Examples:
290 Examples:
291
291
292 - A number of files (bar.c and foo.c) are new,
292 - A number of files (bar.c and foo.c) are new,
293 while foobar.c has been removed (without using :hg:`remove`)
293 while foobar.c has been removed (without using :hg:`remove`)
294 from the repository::
294 from the repository::
295
295
296 $ ls
296 $ ls
297 bar.c foo.c
297 bar.c foo.c
298 $ hg status
298 $ hg status
299 ! foobar.c
299 ! foobar.c
300 ? bar.c
300 ? bar.c
301 ? foo.c
301 ? foo.c
302 $ hg addremove
302 $ hg addremove
303 adding bar.c
303 adding bar.c
304 adding foo.c
304 adding foo.c
305 removing foobar.c
305 removing foobar.c
306 $ hg status
306 $ hg status
307 A bar.c
307 A bar.c
308 A foo.c
308 A foo.c
309 R foobar.c
309 R foobar.c
310
310
311 - A file foobar.c was moved to foo.c without using :hg:`rename`.
311 - A file foobar.c was moved to foo.c without using :hg:`rename`.
312 Afterwards, it was edited slightly::
312 Afterwards, it was edited slightly::
313
313
314 $ ls
314 $ ls
315 foo.c
315 foo.c
316 $ hg status
316 $ hg status
317 ! foobar.c
317 ! foobar.c
318 ? foo.c
318 ? foo.c
319 $ hg addremove --similarity 90
319 $ hg addremove --similarity 90
320 removing foobar.c
320 removing foobar.c
321 adding foo.c
321 adding foo.c
322 recording removal of foobar.c as rename to foo.c (94% similar)
322 recording removal of foobar.c as rename to foo.c (94% similar)
323 $ hg status -C
323 $ hg status -C
324 A foo.c
324 A foo.c
325 foobar.c
325 foobar.c
326 R foobar.c
326 R foobar.c
327
327
328 Returns 0 if all files are successfully added.
328 Returns 0 if all files are successfully added.
329 """
329 """
330 opts = pycompat.byteskwargs(opts)
330 opts = pycompat.byteskwargs(opts)
331 if not opts.get(b'similarity'):
331 if not opts.get(b'similarity'):
332 opts[b'similarity'] = b'100'
332 opts[b'similarity'] = b'100'
333 matcher = scmutil.match(repo[None], pats, opts)
333 matcher = scmutil.match(repo[None], pats, opts)
334 relative = scmutil.anypats(pats, opts)
334 relative = scmutil.anypats(pats, opts)
335 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
335 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
336 return scmutil.addremove(repo, matcher, b"", uipathfn, opts)
336 return scmutil.addremove(repo, matcher, b"", uipathfn, opts)
337
337
338
338
339 @command(
339 @command(
340 b'annotate|blame',
340 b'annotate|blame',
341 [
341 [
342 (b'r', b'rev', b'', _(b'annotate the specified revision'), _(b'REV')),
342 (b'r', b'rev', b'', _(b'annotate the specified revision'), _(b'REV')),
343 (
343 (
344 b'',
344 b'',
345 b'follow',
345 b'follow',
346 None,
346 None,
347 _(b'follow copies/renames and list the filename (DEPRECATED)'),
347 _(b'follow copies/renames and list the filename (DEPRECATED)'),
348 ),
348 ),
349 (b'', b'no-follow', None, _(b"don't follow copies and renames")),
349 (b'', b'no-follow', None, _(b"don't follow copies and renames")),
350 (b'a', b'text', None, _(b'treat all files as text')),
350 (b'a', b'text', None, _(b'treat all files as text')),
351 (b'u', b'user', None, _(b'list the author (long with -v)')),
351 (b'u', b'user', None, _(b'list the author (long with -v)')),
352 (b'f', b'file', None, _(b'list the filename')),
352 (b'f', b'file', None, _(b'list the filename')),
353 (b'd', b'date', None, _(b'list the date (short with -q)')),
353 (b'd', b'date', None, _(b'list the date (short with -q)')),
354 (b'n', b'number', None, _(b'list the revision number (default)')),
354 (b'n', b'number', None, _(b'list the revision number (default)')),
355 (b'c', b'changeset', None, _(b'list the changeset')),
355 (b'c', b'changeset', None, _(b'list the changeset')),
356 (
356 (
357 b'l',
357 b'l',
358 b'line-number',
358 b'line-number',
359 None,
359 None,
360 _(b'show line number at the first appearance'),
360 _(b'show line number at the first appearance'),
361 ),
361 ),
362 (
362 (
363 b'',
363 b'',
364 b'skip',
364 b'skip',
365 [],
365 [],
366 _(b'revset to not display (EXPERIMENTAL)'),
366 _(b'revset to not display (EXPERIMENTAL)'),
367 _(b'REV'),
367 _(b'REV'),
368 ),
368 ),
369 ]
369 ]
370 + diffwsopts
370 + diffwsopts
371 + walkopts
371 + walkopts
372 + formatteropts,
372 + formatteropts,
373 _(b'[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
373 _(b'[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
374 helpcategory=command.CATEGORY_FILE_CONTENTS,
374 helpcategory=command.CATEGORY_FILE_CONTENTS,
375 helpbasic=True,
375 helpbasic=True,
376 inferrepo=True,
376 inferrepo=True,
377 )
377 )
378 def annotate(ui, repo, *pats, **opts):
378 def annotate(ui, repo, *pats, **opts):
379 """show changeset information by line for each file
379 """show changeset information by line for each file
380
380
381 List changes in files, showing the revision id responsible for
381 List changes in files, showing the revision id responsible for
382 each line.
382 each line.
383
383
384 This command is useful for discovering when a change was made and
384 This command is useful for discovering when a change was made and
385 by whom.
385 by whom.
386
386
387 If you include --file, --user, or --date, the revision number is
387 If you include --file, --user, or --date, the revision number is
388 suppressed unless you also include --number.
388 suppressed unless you also include --number.
389
389
390 Without the -a/--text option, annotate will avoid processing files
390 Without the -a/--text option, annotate will avoid processing files
391 it detects as binary. With -a, annotate will annotate the file
391 it detects as binary. With -a, annotate will annotate the file
392 anyway, although the results will probably be neither useful
392 anyway, although the results will probably be neither useful
393 nor desirable.
393 nor desirable.
394
394
395 .. container:: verbose
395 .. container:: verbose
396
396
397 Template:
397 Template:
398
398
399 The following keywords are supported in addition to the common template
399 The following keywords are supported in addition to the common template
400 keywords and functions. See also :hg:`help templates`.
400 keywords and functions. See also :hg:`help templates`.
401
401
402 :lines: List of lines with annotation data.
402 :lines: List of lines with annotation data.
403 :path: String. Repository-absolute path of the specified file.
403 :path: String. Repository-absolute path of the specified file.
404
404
405 And each entry of ``{lines}`` provides the following sub-keywords in
405 And each entry of ``{lines}`` provides the following sub-keywords in
406 addition to ``{date}``, ``{node}``, ``{rev}``, ``{user}``, etc.
406 addition to ``{date}``, ``{node}``, ``{rev}``, ``{user}``, etc.
407
407
408 :line: String. Line content.
408 :line: String. Line content.
409 :lineno: Integer. Line number at that revision.
409 :lineno: Integer. Line number at that revision.
410 :path: String. Repository-absolute path of the file at that revision.
410 :path: String. Repository-absolute path of the file at that revision.
411
411
412 See :hg:`help templates.operators` for the list expansion syntax.
412 See :hg:`help templates.operators` for the list expansion syntax.
413
413
414 Returns 0 on success.
414 Returns 0 on success.
415 """
415 """
416 opts = pycompat.byteskwargs(opts)
416 opts = pycompat.byteskwargs(opts)
417 if not pats:
417 if not pats:
418 raise error.InputError(
418 raise error.InputError(
419 _(b'at least one filename or pattern is required')
419 _(b'at least one filename or pattern is required')
420 )
420 )
421
421
422 if opts.get(b'follow'):
422 if opts.get(b'follow'):
423 # --follow is deprecated and now just an alias for -f/--file
423 # --follow is deprecated and now just an alias for -f/--file
424 # to mimic the behavior of Mercurial before version 1.5
424 # to mimic the behavior of Mercurial before version 1.5
425 opts[b'file'] = True
425 opts[b'file'] = True
426
426
427 if (
427 if (
428 not opts.get(b'user')
428 not opts.get(b'user')
429 and not opts.get(b'changeset')
429 and not opts.get(b'changeset')
430 and not opts.get(b'date')
430 and not opts.get(b'date')
431 and not opts.get(b'file')
431 and not opts.get(b'file')
432 ):
432 ):
433 opts[b'number'] = True
433 opts[b'number'] = True
434
434
435 linenumber = opts.get(b'line_number') is not None
435 linenumber = opts.get(b'line_number') is not None
436 if (
436 if (
437 linenumber
437 linenumber
438 and (not opts.get(b'changeset'))
438 and (not opts.get(b'changeset'))
439 and (not opts.get(b'number'))
439 and (not opts.get(b'number'))
440 ):
440 ):
441 raise error.InputError(_(b'at least one of -n/-c is required for -l'))
441 raise error.InputError(_(b'at least one of -n/-c is required for -l'))
442
442
443 rev = opts.get(b'rev')
443 rev = opts.get(b'rev')
444 if rev:
444 if rev:
445 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
445 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
446 ctx = logcmdutil.revsingle(repo, rev)
446 ctx = logcmdutil.revsingle(repo, rev)
447
447
448 ui.pager(b'annotate')
448 ui.pager(b'annotate')
449 rootfm = ui.formatter(b'annotate', opts)
449 rootfm = ui.formatter(b'annotate', opts)
450 if ui.debugflag:
450 if ui.debugflag:
451 shorthex = pycompat.identity
451 shorthex = pycompat.identity
452 else:
452 else:
453
453
454 def shorthex(h):
454 def shorthex(h):
455 return h[:12]
455 return h[:12]
456
456
457 if ui.quiet:
457 if ui.quiet:
458 datefunc = dateutil.shortdate
458 datefunc = dateutil.shortdate
459 else:
459 else:
460 datefunc = dateutil.datestr
460 datefunc = dateutil.datestr
461 if ctx.rev() is None:
461 if ctx.rev() is None:
462 if opts.get(b'changeset'):
462 if opts.get(b'changeset'):
463 # omit "+" suffix which is appended to node hex
463 # omit "+" suffix which is appended to node hex
464 def formatrev(rev):
464 def formatrev(rev):
465 if rev == wdirrev:
465 if rev == wdirrev:
466 return b'%d' % ctx.p1().rev()
466 return b'%d' % ctx.p1().rev()
467 else:
467 else:
468 return b'%d' % rev
468 return b'%d' % rev
469
469
470 else:
470 else:
471
471
472 def formatrev(rev):
472 def formatrev(rev):
473 if rev == wdirrev:
473 if rev == wdirrev:
474 return b'%d+' % ctx.p1().rev()
474 return b'%d+' % ctx.p1().rev()
475 else:
475 else:
476 return b'%d ' % rev
476 return b'%d ' % rev
477
477
478 def formathex(h):
478 def formathex(h):
479 if h == repo.nodeconstants.wdirhex:
479 if h == repo.nodeconstants.wdirhex:
480 return b'%s+' % shorthex(hex(ctx.p1().node()))
480 return b'%s+' % shorthex(hex(ctx.p1().node()))
481 else:
481 else:
482 return b'%s ' % shorthex(h)
482 return b'%s ' % shorthex(h)
483
483
484 else:
484 else:
485 formatrev = b'%d'.__mod__
485 formatrev = b'%d'.__mod__
486 formathex = shorthex
486 formathex = shorthex
487
487
488 opmap = [
488 opmap = [
489 (b'user', b' ', lambda x: x.fctx.user(), ui.shortuser),
489 (b'user', b' ', lambda x: x.fctx.user(), ui.shortuser),
490 (b'rev', b' ', lambda x: scmutil.intrev(x.fctx), formatrev),
490 (b'rev', b' ', lambda x: scmutil.intrev(x.fctx), formatrev),
491 (b'node', b' ', lambda x: hex(scmutil.binnode(x.fctx)), formathex),
491 (b'node', b' ', lambda x: hex(scmutil.binnode(x.fctx)), formathex),
492 (b'date', b' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
492 (b'date', b' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
493 (b'path', b' ', lambda x: x.fctx.path(), pycompat.bytestr),
493 (b'path', b' ', lambda x: x.fctx.path(), pycompat.bytestr),
494 (b'lineno', b':', lambda x: x.lineno, pycompat.bytestr),
494 (b'lineno', b':', lambda x: x.lineno, pycompat.bytestr),
495 ]
495 ]
496 opnamemap = {
496 opnamemap = {
497 b'rev': b'number',
497 b'rev': b'number',
498 b'node': b'changeset',
498 b'node': b'changeset',
499 b'path': b'file',
499 b'path': b'file',
500 b'lineno': b'line_number',
500 b'lineno': b'line_number',
501 }
501 }
502
502
503 if rootfm.isplain():
503 if rootfm.isplain():
504
504
505 def makefunc(get, fmt):
505 def makefunc(get, fmt):
506 return lambda x: fmt(get(x))
506 return lambda x: fmt(get(x))
507
507
508 else:
508 else:
509
509
510 def makefunc(get, fmt):
510 def makefunc(get, fmt):
511 return get
511 return get
512
512
513 datahint = rootfm.datahint()
513 datahint = rootfm.datahint()
514 funcmap = [
514 funcmap = [
515 (makefunc(get, fmt), sep)
515 (makefunc(get, fmt), sep)
516 for fn, sep, get, fmt in opmap
516 for fn, sep, get, fmt in opmap
517 if opts.get(opnamemap.get(fn, fn)) or fn in datahint
517 if opts.get(opnamemap.get(fn, fn)) or fn in datahint
518 ]
518 ]
519 funcmap[0] = (funcmap[0][0], b'') # no separator in front of first column
519 funcmap[0] = (funcmap[0][0], b'') # no separator in front of first column
520 fields = b' '.join(
520 fields = b' '.join(
521 fn
521 fn
522 for fn, sep, get, fmt in opmap
522 for fn, sep, get, fmt in opmap
523 if opts.get(opnamemap.get(fn, fn)) or fn in datahint
523 if opts.get(opnamemap.get(fn, fn)) or fn in datahint
524 )
524 )
525
525
526 def bad(x, y):
526 def bad(x, y):
527 raise error.InputError(b"%s: %s" % (x, y))
527 raise error.InputError(b"%s: %s" % (x, y))
528
528
529 m = scmutil.match(ctx, pats, opts, badfn=bad)
529 m = scmutil.match(ctx, pats, opts, badfn=bad)
530
530
531 follow = not opts.get(b'no_follow')
531 follow = not opts.get(b'no_follow')
532 diffopts = patch.difffeatureopts(
532 diffopts = patch.difffeatureopts(
533 ui, opts, section=b'annotate', whitespace=True
533 ui, opts, section=b'annotate', whitespace=True
534 )
534 )
535 skiprevs = opts.get(b'skip')
535 skiprevs = opts.get(b'skip')
536 if skiprevs:
536 if skiprevs:
537 skiprevs = logcmdutil.revrange(repo, skiprevs)
537 skiprevs = logcmdutil.revrange(repo, skiprevs)
538
538
539 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
539 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
540 for abs in ctx.walk(m):
540 for abs in ctx.walk(m):
541 fctx = ctx[abs]
541 fctx = ctx[abs]
542 rootfm.startitem()
542 rootfm.startitem()
543 rootfm.data(path=abs)
543 rootfm.data(path=abs)
544 if not opts.get(b'text') and fctx.isbinary():
544 if not opts.get(b'text') and fctx.isbinary():
545 rootfm.plain(_(b"%s: binary file\n") % uipathfn(abs))
545 rootfm.plain(_(b"%s: binary file\n") % uipathfn(abs))
546 continue
546 continue
547
547
548 fm = rootfm.nested(b'lines', tmpl=b'{rev}: {line}')
548 fm = rootfm.nested(b'lines', tmpl=b'{rev}: {line}')
549 lines = fctx.annotate(
549 lines = fctx.annotate(
550 follow=follow, skiprevs=skiprevs, diffopts=diffopts
550 follow=follow, skiprevs=skiprevs, diffopts=diffopts
551 )
551 )
552 if not lines:
552 if not lines:
553 fm.end()
553 fm.end()
554 continue
554 continue
555 formats = []
555 formats = []
556 pieces = []
556 pieces = []
557
557
558 for f, sep in funcmap:
558 for f, sep in funcmap:
559 l = [f(n) for n in lines]
559 l = [f(n) for n in lines]
560 if fm.isplain():
560 if fm.isplain():
561 sizes = [encoding.colwidth(x) for x in l]
561 sizes = [encoding.colwidth(x) for x in l]
562 ml = max(sizes)
562 ml = max(sizes)
563 formats.append([sep + b' ' * (ml - w) + b'%s' for w in sizes])
563 formats.append([sep + b' ' * (ml - w) + b'%s' for w in sizes])
564 else:
564 else:
565 formats.append([b'%s'] * len(l))
565 formats.append([b'%s'] * len(l))
566 pieces.append(l)
566 pieces.append(l)
567
567
568 for f, p, n in zip(zip(*formats), zip(*pieces), lines):
568 for f, p, n in zip(zip(*formats), zip(*pieces), lines):
569 fm.startitem()
569 fm.startitem()
570 fm.context(fctx=n.fctx)
570 fm.context(fctx=n.fctx)
571 fm.write(fields, b"".join(f), *p)
571 fm.write(fields, b"".join(f), *p)
572 if n.skip:
572 if n.skip:
573 fmt = b"* %s"
573 fmt = b"* %s"
574 else:
574 else:
575 fmt = b": %s"
575 fmt = b": %s"
576 fm.write(b'line', fmt, n.text)
576 fm.write(b'line', fmt, n.text)
577
577
578 if not lines[-1].text.endswith(b'\n'):
578 if not lines[-1].text.endswith(b'\n'):
579 fm.plain(b'\n')
579 fm.plain(b'\n')
580 fm.end()
580 fm.end()
581
581
582 rootfm.end()
582 rootfm.end()
583
583
584
584
585 @command(
585 @command(
586 b'archive',
586 b'archive',
587 [
587 [
588 (b'', b'no-decode', None, _(b'do not pass files through decoders')),
588 (b'', b'no-decode', None, _(b'do not pass files through decoders')),
589 (
589 (
590 b'p',
590 b'p',
591 b'prefix',
591 b'prefix',
592 b'',
592 b'',
593 _(b'directory prefix for files in archive'),
593 _(b'directory prefix for files in archive'),
594 _(b'PREFIX'),
594 _(b'PREFIX'),
595 ),
595 ),
596 (b'r', b'rev', b'', _(b'revision to distribute'), _(b'REV')),
596 (b'r', b'rev', b'', _(b'revision to distribute'), _(b'REV')),
597 (b't', b'type', b'', _(b'type of distribution to create'), _(b'TYPE')),
597 (b't', b'type', b'', _(b'type of distribution to create'), _(b'TYPE')),
598 ]
598 ]
599 + subrepoopts
599 + subrepoopts
600 + walkopts,
600 + walkopts,
601 _(b'[OPTION]... DEST'),
601 _(b'[OPTION]... DEST'),
602 helpcategory=command.CATEGORY_IMPORT_EXPORT,
602 helpcategory=command.CATEGORY_IMPORT_EXPORT,
603 )
603 )
604 def archive(ui, repo, dest, **opts):
604 def archive(ui, repo, dest, **opts):
605 """create an unversioned archive of a repository revision
605 """create an unversioned archive of a repository revision
606
606
607 By default, the revision used is the parent of the working
607 By default, the revision used is the parent of the working
608 directory; use -r/--rev to specify a different revision.
608 directory; use -r/--rev to specify a different revision.
609
609
610 The archive type is automatically detected based on file
610 The archive type is automatically detected based on file
611 extension (to override, use -t/--type).
611 extension (to override, use -t/--type).
612
612
613 .. container:: verbose
613 .. container:: verbose
614
614
615 Examples:
615 Examples:
616
616
617 - create a zip file containing the 1.0 release::
617 - create a zip file containing the 1.0 release::
618
618
619 hg archive -r 1.0 project-1.0.zip
619 hg archive -r 1.0 project-1.0.zip
620
620
621 - create a tarball excluding .hg files::
621 - create a tarball excluding .hg files::
622
622
623 hg archive project.tar.gz -X ".hg*"
623 hg archive project.tar.gz -X ".hg*"
624
624
625 Valid types are:
625 Valid types are:
626
626
627 :``files``: a directory full of files (default)
627 :``files``: a directory full of files (default)
628 :``tar``: tar archive, uncompressed
628 :``tar``: tar archive, uncompressed
629 :``tbz2``: tar archive, compressed using bzip2
629 :``tbz2``: tar archive, compressed using bzip2
630 :``tgz``: tar archive, compressed using gzip
630 :``tgz``: tar archive, compressed using gzip
631 :``txz``: tar archive, compressed using lzma (only in Python 3)
631 :``txz``: tar archive, compressed using lzma (only in Python 3)
632 :``uzip``: zip archive, uncompressed
632 :``uzip``: zip archive, uncompressed
633 :``zip``: zip archive, compressed using deflate
633 :``zip``: zip archive, compressed using deflate
634
634
635 The exact name of the destination archive or directory is given
635 The exact name of the destination archive or directory is given
636 using a format string; see :hg:`help export` for details.
636 using a format string; see :hg:`help export` for details.
637
637
638 Each member added to an archive file has a directory prefix
638 Each member added to an archive file has a directory prefix
639 prepended. Use -p/--prefix to specify a format string for the
639 prepended. Use -p/--prefix to specify a format string for the
640 prefix. The default is the basename of the archive, with suffixes
640 prefix. The default is the basename of the archive, with suffixes
641 removed.
641 removed.
642
642
643 Returns 0 on success.
643 Returns 0 on success.
644 """
644 """
645
645
646 opts = pycompat.byteskwargs(opts)
646 opts = pycompat.byteskwargs(opts)
647 rev = opts.get(b'rev')
647 rev = opts.get(b'rev')
648 if rev:
648 if rev:
649 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
649 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
650 ctx = logcmdutil.revsingle(repo, rev)
650 ctx = logcmdutil.revsingle(repo, rev)
651 if not ctx:
651 if not ctx:
652 raise error.InputError(
652 raise error.InputError(
653 _(b'no working directory: please specify a revision')
653 _(b'no working directory: please specify a revision')
654 )
654 )
655 node = ctx.node()
655 node = ctx.node()
656 dest = cmdutil.makefilename(ctx, dest)
656 dest = cmdutil.makefilename(ctx, dest)
657 if os.path.realpath(dest) == repo.root:
657 if os.path.realpath(dest) == repo.root:
658 raise error.InputError(_(b'repository root cannot be destination'))
658 raise error.InputError(_(b'repository root cannot be destination'))
659
659
660 kind = opts.get(b'type') or archival.guesskind(dest) or b'files'
660 kind = opts.get(b'type') or archival.guesskind(dest) or b'files'
661 prefix = opts.get(b'prefix')
661 prefix = opts.get(b'prefix')
662
662
663 if dest == b'-':
663 if dest == b'-':
664 if kind == b'files':
664 if kind == b'files':
665 raise error.InputError(_(b'cannot archive plain files to stdout'))
665 raise error.InputError(_(b'cannot archive plain files to stdout'))
666 dest = cmdutil.makefileobj(ctx, dest)
666 dest = cmdutil.makefileobj(ctx, dest)
667 if not prefix:
667 if not prefix:
668 prefix = os.path.basename(repo.root) + b'-%h'
668 prefix = os.path.basename(repo.root) + b'-%h'
669
669
670 prefix = cmdutil.makefilename(ctx, prefix)
670 prefix = cmdutil.makefilename(ctx, prefix)
671 match = scmutil.match(ctx, [], opts)
671 match = scmutil.match(ctx, [], opts)
672 archival.archive(
672 archival.archive(
673 repo,
673 repo,
674 dest,
674 dest,
675 node,
675 node,
676 kind,
676 kind,
677 not opts.get(b'no_decode'),
677 not opts.get(b'no_decode'),
678 match,
678 match,
679 prefix,
679 prefix,
680 subrepos=opts.get(b'subrepos'),
680 subrepos=opts.get(b'subrepos'),
681 )
681 )
682
682
683
683
684 @command(
684 @command(
685 b'backout',
685 b'backout',
686 [
686 [
687 (
687 (
688 b'',
688 b'',
689 b'merge',
689 b'merge',
690 None,
690 None,
691 _(b'merge with old dirstate parent after backout'),
691 _(b'merge with old dirstate parent after backout'),
692 ),
692 ),
693 (
693 (
694 b'',
694 b'',
695 b'commit',
695 b'commit',
696 None,
696 None,
697 _(b'commit if no conflicts were encountered (DEPRECATED)'),
697 _(b'commit if no conflicts were encountered (DEPRECATED)'),
698 ),
698 ),
699 (b'', b'no-commit', None, _(b'do not commit')),
699 (b'', b'no-commit', None, _(b'do not commit')),
700 (
700 (
701 b'',
701 b'',
702 b'parent',
702 b'parent',
703 b'',
703 b'',
704 _(b'parent to choose when backing out merge (DEPRECATED)'),
704 _(b'parent to choose when backing out merge (DEPRECATED)'),
705 _(b'REV'),
705 _(b'REV'),
706 ),
706 ),
707 (b'r', b'rev', b'', _(b'revision to backout'), _(b'REV')),
707 (b'r', b'rev', b'', _(b'revision to backout'), _(b'REV')),
708 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
708 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
709 ]
709 ]
710 + mergetoolopts
710 + mergetoolopts
711 + walkopts
711 + walkopts
712 + commitopts
712 + commitopts
713 + commitopts2,
713 + commitopts2,
714 _(b'[OPTION]... [-r] REV'),
714 _(b'[OPTION]... [-r] REV'),
715 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
715 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
716 )
716 )
717 def backout(ui, repo, node=None, rev=None, **opts):
717 def backout(ui, repo, node=None, rev=None, **opts):
718 """reverse effect of earlier changeset
718 """reverse effect of earlier changeset
719
719
720 Prepare a new changeset with the effect of REV undone in the
720 Prepare a new changeset with the effect of REV undone in the
721 current working directory. If no conflicts were encountered,
721 current working directory. If no conflicts were encountered,
722 it will be committed immediately.
722 it will be committed immediately.
723
723
724 If REV is the parent of the working directory, then this new changeset
724 If REV is the parent of the working directory, then this new changeset
725 is committed automatically (unless --no-commit is specified).
725 is committed automatically (unless --no-commit is specified).
726
726
727 .. note::
727 .. note::
728
728
729 :hg:`backout` cannot be used to fix either an unwanted or
729 :hg:`backout` cannot be used to fix either an unwanted or
730 incorrect merge.
730 incorrect merge.
731
731
732 .. container:: verbose
732 .. container:: verbose
733
733
734 Examples:
734 Examples:
735
735
736 - Reverse the effect of the parent of the working directory.
736 - Reverse the effect of the parent of the working directory.
737 This backout will be committed immediately::
737 This backout will be committed immediately::
738
738
739 hg backout -r .
739 hg backout -r .
740
740
741 - Reverse the effect of previous bad revision 23::
741 - Reverse the effect of previous bad revision 23::
742
742
743 hg backout -r 23
743 hg backout -r 23
744
744
745 - Reverse the effect of previous bad revision 23 and
745 - Reverse the effect of previous bad revision 23 and
746 leave changes uncommitted::
746 leave changes uncommitted::
747
747
748 hg backout -r 23 --no-commit
748 hg backout -r 23 --no-commit
749 hg commit -m "Backout revision 23"
749 hg commit -m "Backout revision 23"
750
750
751 By default, the pending changeset will have one parent,
751 By default, the pending changeset will have one parent,
752 maintaining a linear history. With --merge, the pending
752 maintaining a linear history. With --merge, the pending
753 changeset will instead have two parents: the old parent of the
753 changeset will instead have two parents: the old parent of the
754 working directory and a new child of REV that simply undoes REV.
754 working directory and a new child of REV that simply undoes REV.
755
755
756 Before version 1.7, the behavior without --merge was equivalent
756 Before version 1.7, the behavior without --merge was equivalent
757 to specifying --merge followed by :hg:`update --clean .` to
757 to specifying --merge followed by :hg:`update --clean .` to
758 cancel the merge and leave the child of REV as a head to be
758 cancel the merge and leave the child of REV as a head to be
759 merged separately.
759 merged separately.
760
760
761 See :hg:`help dates` for a list of formats valid for -d/--date.
761 See :hg:`help dates` for a list of formats valid for -d/--date.
762
762
763 See :hg:`help revert` for a way to restore files to the state
763 See :hg:`help revert` for a way to restore files to the state
764 of another revision.
764 of another revision.
765
765
766 Returns 0 on success, 1 if nothing to backout or there are unresolved
766 Returns 0 on success, 1 if nothing to backout or there are unresolved
767 files.
767 files.
768 """
768 """
769 with repo.wlock(), repo.lock():
769 with repo.wlock(), repo.lock():
770 return _dobackout(ui, repo, node, rev, **opts)
770 return _dobackout(ui, repo, node, rev, **opts)
771
771
772
772
773 def _dobackout(ui, repo, node=None, rev=None, **opts):
773 def _dobackout(ui, repo, node=None, rev=None, **opts):
774 cmdutil.check_incompatible_arguments(opts, 'no_commit', ['commit', 'merge'])
774 cmdutil.check_incompatible_arguments(opts, 'no_commit', ['commit', 'merge'])
775 opts = pycompat.byteskwargs(opts)
775 opts = pycompat.byteskwargs(opts)
776
776
777 if rev and node:
777 if rev and node:
778 raise error.InputError(_(b"please specify just one revision"))
778 raise error.InputError(_(b"please specify just one revision"))
779
779
780 if not rev:
780 if not rev:
781 rev = node
781 rev = node
782
782
783 if not rev:
783 if not rev:
784 raise error.InputError(_(b"please specify a revision to backout"))
784 raise error.InputError(_(b"please specify a revision to backout"))
785
785
786 date = opts.get(b'date')
786 date = opts.get(b'date')
787 if date:
787 if date:
788 opts[b'date'] = dateutil.parsedate(date)
788 opts[b'date'] = dateutil.parsedate(date)
789
789
790 cmdutil.checkunfinished(repo)
790 cmdutil.checkunfinished(repo)
791 cmdutil.bailifchanged(repo)
791 cmdutil.bailifchanged(repo)
792 ctx = logcmdutil.revsingle(repo, rev)
792 ctx = logcmdutil.revsingle(repo, rev)
793 node = ctx.node()
793 node = ctx.node()
794
794
795 op1, op2 = repo.dirstate.parents()
795 op1, op2 = repo.dirstate.parents()
796 if not repo.changelog.isancestor(node, op1):
796 if not repo.changelog.isancestor(node, op1):
797 raise error.InputError(
797 raise error.InputError(
798 _(b'cannot backout change that is not an ancestor')
798 _(b'cannot backout change that is not an ancestor')
799 )
799 )
800
800
801 p1, p2 = repo.changelog.parents(node)
801 p1, p2 = repo.changelog.parents(node)
802 if p1 == repo.nullid:
802 if p1 == repo.nullid:
803 raise error.InputError(_(b'cannot backout a change with no parents'))
803 raise error.InputError(_(b'cannot backout a change with no parents'))
804 if p2 != repo.nullid:
804 if p2 != repo.nullid:
805 if not opts.get(b'parent'):
805 if not opts.get(b'parent'):
806 raise error.InputError(_(b'cannot backout a merge changeset'))
806 raise error.InputError(_(b'cannot backout a merge changeset'))
807 p = repo.lookup(opts[b'parent'])
807 p = repo.lookup(opts[b'parent'])
808 if p not in (p1, p2):
808 if p not in (p1, p2):
809 raise error.InputError(
809 raise error.InputError(
810 _(b'%s is not a parent of %s') % (short(p), short(node))
810 _(b'%s is not a parent of %s') % (short(p), short(node))
811 )
811 )
812 parent = p
812 parent = p
813 else:
813 else:
814 if opts.get(b'parent'):
814 if opts.get(b'parent'):
815 raise error.InputError(
815 raise error.InputError(
816 _(b'cannot use --parent on non-merge changeset')
816 _(b'cannot use --parent on non-merge changeset')
817 )
817 )
818 parent = p1
818 parent = p1
819
819
820 # the backout should appear on the same branch
820 # the backout should appear on the same branch
821 branch = repo.dirstate.branch()
821 branch = repo.dirstate.branch()
822 bheads = repo.branchheads(branch)
822 bheads = repo.branchheads(branch)
823 rctx = scmutil.revsingle(repo, hex(parent))
823 rctx = scmutil.revsingle(repo, hex(parent))
824 if not opts.get(b'merge') and op1 != node:
824 if not opts.get(b'merge') and op1 != node:
825 with dirstateguard.dirstateguard(repo, b'backout'):
825 with dirstateguard.dirstateguard(repo, b'backout'):
826 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
826 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
827 with ui.configoverride(overrides, b'backout'):
827 with ui.configoverride(overrides, b'backout'):
828 stats = mergemod.back_out(ctx, parent=repo[parent])
828 stats = mergemod.back_out(ctx, parent=repo[parent])
829 repo.setparents(op1, op2)
829 repo.setparents(op1, op2)
830 hg._showstats(repo, stats)
830 hg._showstats(repo, stats)
831 if stats.unresolvedcount:
831 if stats.unresolvedcount:
832 repo.ui.status(
832 repo.ui.status(
833 _(b"use 'hg resolve' to retry unresolved file merges\n")
833 _(b"use 'hg resolve' to retry unresolved file merges\n")
834 )
834 )
835 return 1
835 return 1
836 else:
836 else:
837 hg.clean(repo, node, show_stats=False)
837 hg.clean(repo, node, show_stats=False)
838 repo.dirstate.setbranch(branch)
838 repo.dirstate.setbranch(branch)
839 cmdutil.revert(ui, repo, rctx)
839 cmdutil.revert(ui, repo, rctx)
840
840
841 if opts.get(b'no_commit'):
841 if opts.get(b'no_commit'):
842 msg = _(b"changeset %s backed out, don't forget to commit.\n")
842 msg = _(b"changeset %s backed out, don't forget to commit.\n")
843 ui.status(msg % short(node))
843 ui.status(msg % short(node))
844 return 0
844 return 0
845
845
846 def commitfunc(ui, repo, message, match, opts):
846 def commitfunc(ui, repo, message, match, opts):
847 editform = b'backout'
847 editform = b'backout'
848 e = cmdutil.getcommiteditor(
848 e = cmdutil.getcommiteditor(
849 editform=editform, **pycompat.strkwargs(opts)
849 editform=editform, **pycompat.strkwargs(opts)
850 )
850 )
851 if not message:
851 if not message:
852 # we don't translate commit messages
852 # we don't translate commit messages
853 message = b"Backed out changeset %s" % short(node)
853 message = b"Backed out changeset %s" % short(node)
854 e = cmdutil.getcommiteditor(edit=True, editform=editform)
854 e = cmdutil.getcommiteditor(edit=True, editform=editform)
855 return repo.commit(
855 return repo.commit(
856 message, opts.get(b'user'), opts.get(b'date'), match, editor=e
856 message, opts.get(b'user'), opts.get(b'date'), match, editor=e
857 )
857 )
858
858
859 # save to detect changes
859 # save to detect changes
860 tip = repo.changelog.tip()
860 tip = repo.changelog.tip()
861
861
862 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
862 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
863 if not newnode:
863 if not newnode:
864 ui.status(_(b"nothing changed\n"))
864 ui.status(_(b"nothing changed\n"))
865 return 1
865 return 1
866 cmdutil.commitstatus(repo, newnode, branch, bheads, tip)
866 cmdutil.commitstatus(repo, newnode, branch, bheads, tip)
867
867
868 def nice(node):
868 def nice(node):
869 return b'%d:%s' % (repo.changelog.rev(node), short(node))
869 return b'%d:%s' % (repo.changelog.rev(node), short(node))
870
870
871 ui.status(
871 ui.status(
872 _(b'changeset %s backs out changeset %s\n')
872 _(b'changeset %s backs out changeset %s\n')
873 % (nice(newnode), nice(node))
873 % (nice(newnode), nice(node))
874 )
874 )
875 if opts.get(b'merge') and op1 != node:
875 if opts.get(b'merge') and op1 != node:
876 hg.clean(repo, op1, show_stats=False)
876 hg.clean(repo, op1, show_stats=False)
877 ui.status(_(b'merging with changeset %s\n') % nice(newnode))
877 ui.status(_(b'merging with changeset %s\n') % nice(newnode))
878 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
878 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
879 with ui.configoverride(overrides, b'backout'):
879 with ui.configoverride(overrides, b'backout'):
880 return hg.merge(repo[b'tip'])
880 return hg.merge(repo[b'tip'])
881 return 0
881 return 0
882
882
883
883
884 @command(
884 @command(
885 b'bisect',
885 b'bisect',
886 [
886 [
887 (b'r', b'reset', False, _(b'reset bisect state')),
887 (b'r', b'reset', False, _(b'reset bisect state')),
888 (b'g', b'good', False, _(b'mark changeset good')),
888 (b'g', b'good', False, _(b'mark changeset good')),
889 (b'b', b'bad', False, _(b'mark changeset bad')),
889 (b'b', b'bad', False, _(b'mark changeset bad')),
890 (b's', b'skip', False, _(b'skip testing changeset')),
890 (b's', b'skip', False, _(b'skip testing changeset')),
891 (b'e', b'extend', False, _(b'extend the bisect range')),
891 (b'e', b'extend', False, _(b'extend the bisect range')),
892 (
892 (
893 b'c',
893 b'c',
894 b'command',
894 b'command',
895 b'',
895 b'',
896 _(b'use command to check changeset state'),
896 _(b'use command to check changeset state'),
897 _(b'CMD'),
897 _(b'CMD'),
898 ),
898 ),
899 (b'U', b'noupdate', False, _(b'do not update to target')),
899 (b'U', b'noupdate', False, _(b'do not update to target')),
900 ],
900 ],
901 _(b"[-gbsr] [-U] [-c CMD] [REV]"),
901 _(b"[-gbsr] [-U] [-c CMD] [REV]"),
902 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
902 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
903 )
903 )
904 def bisect(
904 def bisect(
905 ui,
905 ui,
906 repo,
906 repo,
907 positional_1=None,
907 positional_1=None,
908 positional_2=None,
908 positional_2=None,
909 command=None,
909 command=None,
910 reset=None,
910 reset=None,
911 good=None,
911 good=None,
912 bad=None,
912 bad=None,
913 skip=None,
913 skip=None,
914 extend=None,
914 extend=None,
915 noupdate=None,
915 noupdate=None,
916 ):
916 ):
917 """subdivision search of changesets
917 """subdivision search of changesets
918
918
919 This command helps to find changesets which introduce problems. To
919 This command helps to find changesets which introduce problems. To
920 use, mark the earliest changeset you know exhibits the problem as
920 use, mark the earliest changeset you know exhibits the problem as
921 bad, then mark the latest changeset which is free from the problem
921 bad, then mark the latest changeset which is free from the problem
922 as good. Bisect will update your working directory to a revision
922 as good. Bisect will update your working directory to a revision
923 for testing (unless the -U/--noupdate option is specified). Once
923 for testing (unless the -U/--noupdate option is specified). Once
924 you have performed tests, mark the working directory as good or
924 you have performed tests, mark the working directory as good or
925 bad, and bisect will either update to another candidate changeset
925 bad, and bisect will either update to another candidate changeset
926 or announce that it has found the bad revision.
926 or announce that it has found the bad revision.
927
927
928 As a shortcut, you can also use the revision argument to mark a
928 As a shortcut, you can also use the revision argument to mark a
929 revision as good or bad without checking it out first.
929 revision as good or bad without checking it out first.
930
930
931 If you supply a command, it will be used for automatic bisection.
931 If you supply a command, it will be used for automatic bisection.
932 The environment variable HG_NODE will contain the ID of the
932 The environment variable HG_NODE will contain the ID of the
933 changeset being tested. The exit status of the command will be
933 changeset being tested. The exit status of the command will be
934 used to mark revisions as good or bad: status 0 means good, 125
934 used to mark revisions as good or bad: status 0 means good, 125
935 means to skip the revision, 127 (command not found) will abort the
935 means to skip the revision, 127 (command not found) will abort the
936 bisection, and any other non-zero exit status means the revision
936 bisection, and any other non-zero exit status means the revision
937 is bad.
937 is bad.
938
938
939 .. container:: verbose
939 .. container:: verbose
940
940
941 Some examples:
941 Some examples:
942
942
943 - start a bisection with known bad revision 34, and good revision 12::
943 - start a bisection with known bad revision 34, and good revision 12::
944
944
945 hg bisect --bad 34
945 hg bisect --bad 34
946 hg bisect --good 12
946 hg bisect --good 12
947
947
948 - advance the current bisection by marking current revision as good or
948 - advance the current bisection by marking current revision as good or
949 bad::
949 bad::
950
950
951 hg bisect --good
951 hg bisect --good
952 hg bisect --bad
952 hg bisect --bad
953
953
954 - mark the current revision, or a known revision, to be skipped (e.g. if
954 - mark the current revision, or a known revision, to be skipped (e.g. if
955 that revision is not usable because of another issue)::
955 that revision is not usable because of another issue)::
956
956
957 hg bisect --skip
957 hg bisect --skip
958 hg bisect --skip 23
958 hg bisect --skip 23
959
959
960 - skip all revisions that do not touch directories ``foo`` or ``bar``::
960 - skip all revisions that do not touch directories ``foo`` or ``bar``::
961
961
962 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
962 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
963
963
964 - forget the current bisection::
964 - forget the current bisection::
965
965
966 hg bisect --reset
966 hg bisect --reset
967
967
968 - use 'make && make tests' to automatically find the first broken
968 - use 'make && make tests' to automatically find the first broken
969 revision::
969 revision::
970
970
971 hg bisect --reset
971 hg bisect --reset
972 hg bisect --bad 34
972 hg bisect --bad 34
973 hg bisect --good 12
973 hg bisect --good 12
974 hg bisect --command "make && make tests"
974 hg bisect --command "make && make tests"
975
975
976 - see all changesets whose states are already known in the current
976 - see all changesets whose states are already known in the current
977 bisection::
977 bisection::
978
978
979 hg log -r "bisect(pruned)"
979 hg log -r "bisect(pruned)"
980
980
981 - see the changeset currently being bisected (especially useful
981 - see the changeset currently being bisected (especially useful
982 if running with -U/--noupdate)::
982 if running with -U/--noupdate)::
983
983
984 hg log -r "bisect(current)"
984 hg log -r "bisect(current)"
985
985
986 - see all changesets that took part in the current bisection::
986 - see all changesets that took part in the current bisection::
987
987
988 hg log -r "bisect(range)"
988 hg log -r "bisect(range)"
989
989
990 - you can even get a nice graph::
990 - you can even get a nice graph::
991
991
992 hg log --graph -r "bisect(range)"
992 hg log --graph -r "bisect(range)"
993
993
994 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
994 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
995
995
996 Returns 0 on success.
996 Returns 0 on success.
997 """
997 """
998 rev = []
998 rev = []
999 # backward compatibility
999 # backward compatibility
1000 if positional_1 in (b"good", b"bad", b"reset", b"init"):
1000 if positional_1 in (b"good", b"bad", b"reset", b"init"):
1001 ui.warn(_(b"(use of 'hg bisect <cmd>' is deprecated)\n"))
1001 ui.warn(_(b"(use of 'hg bisect <cmd>' is deprecated)\n"))
1002 cmd = positional_1
1002 cmd = positional_1
1003 rev.append(positional_2)
1003 rev.append(positional_2)
1004 if cmd == b"good":
1004 if cmd == b"good":
1005 good = True
1005 good = True
1006 elif cmd == b"bad":
1006 elif cmd == b"bad":
1007 bad = True
1007 bad = True
1008 else:
1008 else:
1009 reset = True
1009 reset = True
1010 elif positional_2:
1010 elif positional_2:
1011 raise error.InputError(_(b'incompatible arguments'))
1011 raise error.InputError(_(b'incompatible arguments'))
1012 elif positional_1 is not None:
1012 elif positional_1 is not None:
1013 rev.append(positional_1)
1013 rev.append(positional_1)
1014
1014
1015 incompatibles = {
1015 incompatibles = {
1016 b'--bad': bad,
1016 b'--bad': bad,
1017 b'--command': bool(command),
1017 b'--command': bool(command),
1018 b'--extend': extend,
1018 b'--extend': extend,
1019 b'--good': good,
1019 b'--good': good,
1020 b'--reset': reset,
1020 b'--reset': reset,
1021 b'--skip': skip,
1021 b'--skip': skip,
1022 }
1022 }
1023
1023
1024 enabled = [x for x in incompatibles if incompatibles[x]]
1024 enabled = [x for x in incompatibles if incompatibles[x]]
1025
1025
1026 if len(enabled) > 1:
1026 if len(enabled) > 1:
1027 raise error.InputError(
1027 raise error.InputError(
1028 _(b'%s and %s are incompatible') % tuple(sorted(enabled)[0:2])
1028 _(b'%s and %s are incompatible') % tuple(sorted(enabled)[0:2])
1029 )
1029 )
1030
1030
1031 if reset:
1031 if reset:
1032 hbisect.resetstate(repo)
1032 hbisect.resetstate(repo)
1033 return
1033 return
1034
1034
1035 state = hbisect.load_state(repo)
1035 state = hbisect.load_state(repo)
1036
1036
1037 if rev:
1037 if rev:
1038 revs = logcmdutil.revrange(repo, rev)
1038 revs = logcmdutil.revrange(repo, rev)
1039 goodnodes = state[b'good']
1039 goodnodes = state[b'good']
1040 badnodes = state[b'bad']
1040 badnodes = state[b'bad']
1041 if goodnodes and badnodes:
1041 if goodnodes and badnodes:
1042 candidates = repo.revs(b'(%ln)::(%ln)', goodnodes, badnodes)
1042 candidates = repo.revs(b'(%ln)::(%ln)', goodnodes, badnodes)
1043 candidates += repo.revs(b'(%ln)::(%ln)', badnodes, goodnodes)
1043 candidates += repo.revs(b'(%ln)::(%ln)', badnodes, goodnodes)
1044 revs = candidates & revs
1044 revs = candidates & revs
1045 nodes = [repo.changelog.node(i) for i in revs]
1045 nodes = [repo.changelog.node(i) for i in revs]
1046 else:
1046 else:
1047 nodes = [repo.lookup(b'.')]
1047 nodes = [repo.lookup(b'.')]
1048
1048
1049 # update state
1049 # update state
1050 if good or bad or skip:
1050 if good or bad or skip:
1051 if good:
1051 if good:
1052 state[b'good'] += nodes
1052 state[b'good'] += nodes
1053 elif bad:
1053 elif bad:
1054 state[b'bad'] += nodes
1054 state[b'bad'] += nodes
1055 elif skip:
1055 elif skip:
1056 state[b'skip'] += nodes
1056 state[b'skip'] += nodes
1057 hbisect.save_state(repo, state)
1057 hbisect.save_state(repo, state)
1058 if not (state[b'good'] and state[b'bad']):
1058 if not (state[b'good'] and state[b'bad']):
1059 return
1059 return
1060
1060
1061 def mayupdate(repo, node, show_stats=True):
1061 def mayupdate(repo, node, show_stats=True):
1062 """common used update sequence"""
1062 """common used update sequence"""
1063 if noupdate:
1063 if noupdate:
1064 return
1064 return
1065 cmdutil.checkunfinished(repo)
1065 cmdutil.checkunfinished(repo)
1066 cmdutil.bailifchanged(repo)
1066 cmdutil.bailifchanged(repo)
1067 return hg.clean(repo, node, show_stats=show_stats)
1067 return hg.clean(repo, node, show_stats=show_stats)
1068
1068
1069 displayer = logcmdutil.changesetdisplayer(ui, repo, {})
1069 displayer = logcmdutil.changesetdisplayer(ui, repo, {})
1070
1070
1071 if command:
1071 if command:
1072 changesets = 1
1072 changesets = 1
1073 if noupdate:
1073 if noupdate:
1074 try:
1074 try:
1075 node = state[b'current'][0]
1075 node = state[b'current'][0]
1076 except LookupError:
1076 except LookupError:
1077 raise error.StateError(
1077 raise error.StateError(
1078 _(
1078 _(
1079 b'current bisect revision is unknown - '
1079 b'current bisect revision is unknown - '
1080 b'start a new bisect to fix'
1080 b'start a new bisect to fix'
1081 )
1081 )
1082 )
1082 )
1083 else:
1083 else:
1084 node, p2 = repo.dirstate.parents()
1084 node, p2 = repo.dirstate.parents()
1085 if p2 != repo.nullid:
1085 if p2 != repo.nullid:
1086 raise error.StateError(_(b'current bisect revision is a merge'))
1086 raise error.StateError(_(b'current bisect revision is a merge'))
1087 if rev:
1087 if rev:
1088 if not nodes:
1088 if not nodes:
1089 raise error.InputError(_(b'empty revision set'))
1089 raise error.InputError(_(b'empty revision set'))
1090 node = repo[nodes[-1]].node()
1090 node = repo[nodes[-1]].node()
1091 with hbisect.restore_state(repo, state, node):
1091 with hbisect.restore_state(repo, state, node):
1092 while changesets:
1092 while changesets:
1093 # update state
1093 # update state
1094 state[b'current'] = [node]
1094 state[b'current'] = [node]
1095 hbisect.save_state(repo, state)
1095 hbisect.save_state(repo, state)
1096 status = ui.system(
1096 status = ui.system(
1097 command,
1097 command,
1098 environ={b'HG_NODE': hex(node)},
1098 environ={b'HG_NODE': hex(node)},
1099 blockedtag=b'bisect_check',
1099 blockedtag=b'bisect_check',
1100 )
1100 )
1101 if status == 125:
1101 if status == 125:
1102 transition = b"skip"
1102 transition = b"skip"
1103 elif status == 0:
1103 elif status == 0:
1104 transition = b"good"
1104 transition = b"good"
1105 # status < 0 means process was killed
1105 # status < 0 means process was killed
1106 elif status == 127:
1106 elif status == 127:
1107 raise error.Abort(_(b"failed to execute %s") % command)
1107 raise error.Abort(_(b"failed to execute %s") % command)
1108 elif status < 0:
1108 elif status < 0:
1109 raise error.Abort(_(b"%s killed") % command)
1109 raise error.Abort(_(b"%s killed") % command)
1110 else:
1110 else:
1111 transition = b"bad"
1111 transition = b"bad"
1112 state[transition].append(node)
1112 state[transition].append(node)
1113 ctx = repo[node]
1113 ctx = repo[node]
1114 summary = cmdutil.format_changeset_summary(ui, ctx, b'bisect')
1114 summary = cmdutil.format_changeset_summary(ui, ctx, b'bisect')
1115 ui.status(_(b'changeset %s: %s\n') % (summary, transition))
1115 ui.status(_(b'changeset %s: %s\n') % (summary, transition))
1116 hbisect.checkstate(state)
1116 hbisect.checkstate(state)
1117 # bisect
1117 # bisect
1118 nodes, changesets, bgood = hbisect.bisect(repo, state)
1118 nodes, changesets, bgood = hbisect.bisect(repo, state)
1119 # update to next check
1119 # update to next check
1120 node = nodes[0]
1120 node = nodes[0]
1121 mayupdate(repo, node, show_stats=False)
1121 mayupdate(repo, node, show_stats=False)
1122 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
1122 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
1123 return
1123 return
1124
1124
1125 hbisect.checkstate(state)
1125 hbisect.checkstate(state)
1126
1126
1127 # actually bisect
1127 # actually bisect
1128 nodes, changesets, good = hbisect.bisect(repo, state)
1128 nodes, changesets, good = hbisect.bisect(repo, state)
1129 if extend:
1129 if extend:
1130 if not changesets:
1130 if not changesets:
1131 extendctx = hbisect.extendrange(repo, state, nodes, good)
1131 extendctx = hbisect.extendrange(repo, state, nodes, good)
1132 if extendctx is not None:
1132 if extendctx is not None:
1133 ui.write(
1133 ui.write(
1134 _(b"Extending search to changeset %s\n")
1134 _(b"Extending search to changeset %s\n")
1135 % cmdutil.format_changeset_summary(ui, extendctx, b'bisect')
1135 % cmdutil.format_changeset_summary(ui, extendctx, b'bisect')
1136 )
1136 )
1137 state[b'current'] = [extendctx.node()]
1137 state[b'current'] = [extendctx.node()]
1138 hbisect.save_state(repo, state)
1138 hbisect.save_state(repo, state)
1139 return mayupdate(repo, extendctx.node())
1139 return mayupdate(repo, extendctx.node())
1140 raise error.StateError(_(b"nothing to extend"))
1140 raise error.StateError(_(b"nothing to extend"))
1141
1141
1142 if changesets == 0:
1142 if changesets == 0:
1143 hbisect.printresult(ui, repo, state, displayer, nodes, good)
1143 hbisect.printresult(ui, repo, state, displayer, nodes, good)
1144 else:
1144 else:
1145 assert len(nodes) == 1 # only a single node can be tested next
1145 assert len(nodes) == 1 # only a single node can be tested next
1146 node = nodes[0]
1146 node = nodes[0]
1147 # compute the approximate number of remaining tests
1147 # compute the approximate number of remaining tests
1148 tests, size = 0, 2
1148 tests, size = 0, 2
1149 while size <= changesets:
1149 while size <= changesets:
1150 tests, size = tests + 1, size * 2
1150 tests, size = tests + 1, size * 2
1151 rev = repo.changelog.rev(node)
1151 rev = repo.changelog.rev(node)
1152 summary = cmdutil.format_changeset_summary(ui, repo[rev], b'bisect')
1152 summary = cmdutil.format_changeset_summary(ui, repo[rev], b'bisect')
1153 ui.write(
1153 ui.write(
1154 _(
1154 _(
1155 b"Testing changeset %s "
1155 b"Testing changeset %s "
1156 b"(%d changesets remaining, ~%d tests)\n"
1156 b"(%d changesets remaining, ~%d tests)\n"
1157 )
1157 )
1158 % (summary, changesets, tests)
1158 % (summary, changesets, tests)
1159 )
1159 )
1160 state[b'current'] = [node]
1160 state[b'current'] = [node]
1161 hbisect.save_state(repo, state)
1161 hbisect.save_state(repo, state)
1162 return mayupdate(repo, node)
1162 return mayupdate(repo, node)
1163
1163
1164
1164
1165 @command(
1165 @command(
1166 b'bookmarks|bookmark',
1166 b'bookmarks|bookmark',
1167 [
1167 [
1168 (b'f', b'force', False, _(b'force')),
1168 (b'f', b'force', False, _(b'force')),
1169 (b'r', b'rev', b'', _(b'revision for bookmark action'), _(b'REV')),
1169 (b'r', b'rev', b'', _(b'revision for bookmark action'), _(b'REV')),
1170 (b'd', b'delete', False, _(b'delete a given bookmark')),
1170 (b'd', b'delete', False, _(b'delete a given bookmark')),
1171 (b'm', b'rename', b'', _(b'rename a given bookmark'), _(b'OLD')),
1171 (b'm', b'rename', b'', _(b'rename a given bookmark'), _(b'OLD')),
1172 (b'i', b'inactive', False, _(b'mark a bookmark inactive')),
1172 (b'i', b'inactive', False, _(b'mark a bookmark inactive')),
1173 (b'l', b'list', False, _(b'list existing bookmarks')),
1173 (b'l', b'list', False, _(b'list existing bookmarks')),
1174 ]
1174 ]
1175 + formatteropts,
1175 + formatteropts,
1176 _(b'hg bookmarks [OPTIONS]... [NAME]...'),
1176 _(b'hg bookmarks [OPTIONS]... [NAME]...'),
1177 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1177 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1178 )
1178 )
1179 def bookmark(ui, repo, *names, **opts):
1179 def bookmark(ui, repo, *names, **opts):
1180 """create a new bookmark or list existing bookmarks
1180 """create a new bookmark or list existing bookmarks
1181
1181
1182 Bookmarks are labels on changesets to help track lines of development.
1182 Bookmarks are labels on changesets to help track lines of development.
1183 Bookmarks are unversioned and can be moved, renamed and deleted.
1183 Bookmarks are unversioned and can be moved, renamed and deleted.
1184 Deleting or moving a bookmark has no effect on the associated changesets.
1184 Deleting or moving a bookmark has no effect on the associated changesets.
1185
1185
1186 Creating or updating to a bookmark causes it to be marked as 'active'.
1186 Creating or updating to a bookmark causes it to be marked as 'active'.
1187 The active bookmark is indicated with a '*'.
1187 The active bookmark is indicated with a '*'.
1188 When a commit is made, the active bookmark will advance to the new commit.
1188 When a commit is made, the active bookmark will advance to the new commit.
1189 A plain :hg:`update` will also advance an active bookmark, if possible.
1189 A plain :hg:`update` will also advance an active bookmark, if possible.
1190 Updating away from a bookmark will cause it to be deactivated.
1190 Updating away from a bookmark will cause it to be deactivated.
1191
1191
1192 Bookmarks can be pushed and pulled between repositories (see
1192 Bookmarks can be pushed and pulled between repositories (see
1193 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
1193 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
1194 diverged, a new 'divergent bookmark' of the form 'name@path' will
1194 diverged, a new 'divergent bookmark' of the form 'name@path' will
1195 be created. Using :hg:`merge` will resolve the divergence.
1195 be created. Using :hg:`merge` will resolve the divergence.
1196
1196
1197 Specifying bookmark as '.' to -m/-d/-l options is equivalent to specifying
1197 Specifying bookmark as '.' to -m/-d/-l options is equivalent to specifying
1198 the active bookmark's name.
1198 the active bookmark's name.
1199
1199
1200 A bookmark named '@' has the special property that :hg:`clone` will
1200 A bookmark named '@' has the special property that :hg:`clone` will
1201 check it out by default if it exists.
1201 check it out by default if it exists.
1202
1202
1203 .. container:: verbose
1203 .. container:: verbose
1204
1204
1205 Template:
1205 Template:
1206
1206
1207 The following keywords are supported in addition to the common template
1207 The following keywords are supported in addition to the common template
1208 keywords and functions such as ``{bookmark}``. See also
1208 keywords and functions such as ``{bookmark}``. See also
1209 :hg:`help templates`.
1209 :hg:`help templates`.
1210
1210
1211 :active: Boolean. True if the bookmark is active.
1211 :active: Boolean. True if the bookmark is active.
1212
1212
1213 Examples:
1213 Examples:
1214
1214
1215 - create an active bookmark for a new line of development::
1215 - create an active bookmark for a new line of development::
1216
1216
1217 hg book new-feature
1217 hg book new-feature
1218
1218
1219 - create an inactive bookmark as a place marker::
1219 - create an inactive bookmark as a place marker::
1220
1220
1221 hg book -i reviewed
1221 hg book -i reviewed
1222
1222
1223 - create an inactive bookmark on another changeset::
1223 - create an inactive bookmark on another changeset::
1224
1224
1225 hg book -r .^ tested
1225 hg book -r .^ tested
1226
1226
1227 - rename bookmark turkey to dinner::
1227 - rename bookmark turkey to dinner::
1228
1228
1229 hg book -m turkey dinner
1229 hg book -m turkey dinner
1230
1230
1231 - move the '@' bookmark from another branch::
1231 - move the '@' bookmark from another branch::
1232
1232
1233 hg book -f @
1233 hg book -f @
1234
1234
1235 - print only the active bookmark name::
1235 - print only the active bookmark name::
1236
1236
1237 hg book -ql .
1237 hg book -ql .
1238 """
1238 """
1239 opts = pycompat.byteskwargs(opts)
1239 opts = pycompat.byteskwargs(opts)
1240 force = opts.get(b'force')
1240 force = opts.get(b'force')
1241 rev = opts.get(b'rev')
1241 rev = opts.get(b'rev')
1242 inactive = opts.get(b'inactive') # meaning add/rename to inactive bookmark
1242 inactive = opts.get(b'inactive') # meaning add/rename to inactive bookmark
1243
1243
1244 action = cmdutil.check_at_most_one_arg(opts, b'delete', b'rename', b'list')
1244 action = cmdutil.check_at_most_one_arg(opts, b'delete', b'rename', b'list')
1245 if action:
1245 if action:
1246 cmdutil.check_incompatible_arguments(opts, action, [b'rev'])
1246 cmdutil.check_incompatible_arguments(opts, action, [b'rev'])
1247 elif names or rev:
1247 elif names or rev:
1248 action = b'add'
1248 action = b'add'
1249 elif inactive:
1249 elif inactive:
1250 action = b'inactive' # meaning deactivate
1250 action = b'inactive' # meaning deactivate
1251 else:
1251 else:
1252 action = b'list'
1252 action = b'list'
1253
1253
1254 cmdutil.check_incompatible_arguments(
1254 cmdutil.check_incompatible_arguments(
1255 opts, b'inactive', [b'delete', b'list']
1255 opts, b'inactive', [b'delete', b'list']
1256 )
1256 )
1257 if not names and action in {b'add', b'delete'}:
1257 if not names and action in {b'add', b'delete'}:
1258 raise error.InputError(_(b"bookmark name required"))
1258 raise error.InputError(_(b"bookmark name required"))
1259
1259
1260 if action in {b'add', b'delete', b'rename', b'inactive'}:
1260 if action in {b'add', b'delete', b'rename', b'inactive'}:
1261 with repo.wlock(), repo.lock(), repo.transaction(b'bookmark') as tr:
1261 with repo.wlock(), repo.lock(), repo.transaction(b'bookmark') as tr:
1262 if action == b'delete':
1262 if action == b'delete':
1263 names = pycompat.maplist(repo._bookmarks.expandname, names)
1263 names = pycompat.maplist(repo._bookmarks.expandname, names)
1264 bookmarks.delete(repo, tr, names)
1264 bookmarks.delete(repo, tr, names)
1265 elif action == b'rename':
1265 elif action == b'rename':
1266 if not names:
1266 if not names:
1267 raise error.InputError(_(b"new bookmark name required"))
1267 raise error.InputError(_(b"new bookmark name required"))
1268 elif len(names) > 1:
1268 elif len(names) > 1:
1269 raise error.InputError(
1269 raise error.InputError(
1270 _(b"only one new bookmark name allowed")
1270 _(b"only one new bookmark name allowed")
1271 )
1271 )
1272 oldname = repo._bookmarks.expandname(opts[b'rename'])
1272 oldname = repo._bookmarks.expandname(opts[b'rename'])
1273 bookmarks.rename(repo, tr, oldname, names[0], force, inactive)
1273 bookmarks.rename(repo, tr, oldname, names[0], force, inactive)
1274 elif action == b'add':
1274 elif action == b'add':
1275 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
1275 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
1276 elif action == b'inactive':
1276 elif action == b'inactive':
1277 if len(repo._bookmarks) == 0:
1277 if len(repo._bookmarks) == 0:
1278 ui.status(_(b"no bookmarks set\n"))
1278 ui.status(_(b"no bookmarks set\n"))
1279 elif not repo._activebookmark:
1279 elif not repo._activebookmark:
1280 ui.status(_(b"no active bookmark\n"))
1280 ui.status(_(b"no active bookmark\n"))
1281 else:
1281 else:
1282 bookmarks.deactivate(repo)
1282 bookmarks.deactivate(repo)
1283 elif action == b'list':
1283 elif action == b'list':
1284 names = pycompat.maplist(repo._bookmarks.expandname, names)
1284 names = pycompat.maplist(repo._bookmarks.expandname, names)
1285 with ui.formatter(b'bookmarks', opts) as fm:
1285 with ui.formatter(b'bookmarks', opts) as fm:
1286 bookmarks.printbookmarks(ui, repo, fm, names)
1286 bookmarks.printbookmarks(ui, repo, fm, names)
1287 else:
1287 else:
1288 raise error.ProgrammingError(b'invalid action: %s' % action)
1288 raise error.ProgrammingError(b'invalid action: %s' % action)
1289
1289
1290
1290
1291 @command(
1291 @command(
1292 b'branch',
1292 b'branch',
1293 [
1293 [
1294 (
1294 (
1295 b'f',
1295 b'f',
1296 b'force',
1296 b'force',
1297 None,
1297 None,
1298 _(b'set branch name even if it shadows an existing branch'),
1298 _(b'set branch name even if it shadows an existing branch'),
1299 ),
1299 ),
1300 (b'C', b'clean', None, _(b'reset branch name to parent branch name')),
1300 (b'C', b'clean', None, _(b'reset branch name to parent branch name')),
1301 (
1301 (
1302 b'r',
1302 b'r',
1303 b'rev',
1303 b'rev',
1304 [],
1304 [],
1305 _(b'change branches of the given revs (EXPERIMENTAL)'),
1305 _(b'change branches of the given revs (EXPERIMENTAL)'),
1306 ),
1306 ),
1307 ],
1307 ],
1308 _(b'[-fC] [NAME]'),
1308 _(b'[-fC] [NAME]'),
1309 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1309 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1310 )
1310 )
1311 def branch(ui, repo, label=None, **opts):
1311 def branch(ui, repo, label=None, **opts):
1312 """set or show the current branch name
1312 """set or show the current branch name
1313
1313
1314 .. note::
1314 .. note::
1315
1315
1316 Branch names are permanent and global. Use :hg:`bookmark` to create a
1316 Branch names are permanent and global. Use :hg:`bookmark` to create a
1317 light-weight bookmark instead. See :hg:`help glossary` for more
1317 light-weight bookmark instead. See :hg:`help glossary` for more
1318 information about named branches and bookmarks.
1318 information about named branches and bookmarks.
1319
1319
1320 With no argument, show the current branch name. With one argument,
1320 With no argument, show the current branch name. With one argument,
1321 set the working directory branch name (the branch will not exist
1321 set the working directory branch name (the branch will not exist
1322 in the repository until the next commit). Standard practice
1322 in the repository until the next commit). Standard practice
1323 recommends that primary development take place on the 'default'
1323 recommends that primary development take place on the 'default'
1324 branch.
1324 branch.
1325
1325
1326 Unless -f/--force is specified, branch will not let you set a
1326 Unless -f/--force is specified, branch will not let you set a
1327 branch name that already exists.
1327 branch name that already exists.
1328
1328
1329 Use -C/--clean to reset the working directory branch to that of
1329 Use -C/--clean to reset the working directory branch to that of
1330 the parent of the working directory, negating a previous branch
1330 the parent of the working directory, negating a previous branch
1331 change.
1331 change.
1332
1332
1333 Use the command :hg:`update` to switch to an existing branch. Use
1333 Use the command :hg:`update` to switch to an existing branch. Use
1334 :hg:`commit --close-branch` to mark this branch head as closed.
1334 :hg:`commit --close-branch` to mark this branch head as closed.
1335 When all heads of a branch are closed, the branch will be
1335 When all heads of a branch are closed, the branch will be
1336 considered closed.
1336 considered closed.
1337
1337
1338 Returns 0 on success.
1338 Returns 0 on success.
1339 """
1339 """
1340 opts = pycompat.byteskwargs(opts)
1340 opts = pycompat.byteskwargs(opts)
1341 revs = opts.get(b'rev')
1341 revs = opts.get(b'rev')
1342 if label:
1342 if label:
1343 label = label.strip()
1343 label = label.strip()
1344
1344
1345 if not opts.get(b'clean') and not label:
1345 if not opts.get(b'clean') and not label:
1346 if revs:
1346 if revs:
1347 raise error.InputError(
1347 raise error.InputError(
1348 _(b"no branch name specified for the revisions")
1348 _(b"no branch name specified for the revisions")
1349 )
1349 )
1350 ui.write(b"%s\n" % repo.dirstate.branch())
1350 ui.write(b"%s\n" % repo.dirstate.branch())
1351 return
1351 return
1352
1352
1353 with repo.wlock():
1353 with repo.wlock():
1354 if opts.get(b'clean'):
1354 if opts.get(b'clean'):
1355 label = repo[b'.'].branch()
1355 label = repo[b'.'].branch()
1356 repo.dirstate.setbranch(label)
1356 repo.dirstate.setbranch(label)
1357 ui.status(_(b'reset working directory to branch %s\n') % label)
1357 ui.status(_(b'reset working directory to branch %s\n') % label)
1358 elif label:
1358 elif label:
1359
1359
1360 scmutil.checknewlabel(repo, label, b'branch')
1360 scmutil.checknewlabel(repo, label, b'branch')
1361 if revs:
1361 if revs:
1362 return cmdutil.changebranch(ui, repo, revs, label, opts)
1362 return cmdutil.changebranch(ui, repo, revs, label, opts)
1363
1363
1364 if not opts.get(b'force') and label in repo.branchmap():
1364 if not opts.get(b'force') and label in repo.branchmap():
1365 if label not in [p.branch() for p in repo[None].parents()]:
1365 if label not in [p.branch() for p in repo[None].parents()]:
1366 raise error.InputError(
1366 raise error.InputError(
1367 _(b'a branch of the same name already exists'),
1367 _(b'a branch of the same name already exists'),
1368 # i18n: "it" refers to an existing branch
1368 # i18n: "it" refers to an existing branch
1369 hint=_(b"use 'hg update' to switch to it"),
1369 hint=_(b"use 'hg update' to switch to it"),
1370 )
1370 )
1371
1371
1372 repo.dirstate.setbranch(label)
1372 repo.dirstate.setbranch(label)
1373 ui.status(_(b'marked working directory as branch %s\n') % label)
1373 ui.status(_(b'marked working directory as branch %s\n') % label)
1374
1374
1375 # find any open named branches aside from default
1375 # find any open named branches aside from default
1376 for n, h, t, c in repo.branchmap().iterbranches():
1376 for n, h, t, c in repo.branchmap().iterbranches():
1377 if n != b"default" and not c:
1377 if n != b"default" and not c:
1378 return 0
1378 return 0
1379 ui.status(
1379 ui.status(
1380 _(
1380 _(
1381 b'(branches are permanent and global, '
1381 b'(branches are permanent and global, '
1382 b'did you want a bookmark?)\n'
1382 b'did you want a bookmark?)\n'
1383 )
1383 )
1384 )
1384 )
1385
1385
1386
1386
1387 @command(
1387 @command(
1388 b'branches',
1388 b'branches',
1389 [
1389 [
1390 (
1390 (
1391 b'a',
1391 b'a',
1392 b'active',
1392 b'active',
1393 False,
1393 False,
1394 _(b'show only branches that have unmerged heads (DEPRECATED)'),
1394 _(b'show only branches that have unmerged heads (DEPRECATED)'),
1395 ),
1395 ),
1396 (b'c', b'closed', False, _(b'show normal and closed branches')),
1396 (b'c', b'closed', False, _(b'show normal and closed branches')),
1397 (b'r', b'rev', [], _(b'show branch name(s) of the given rev')),
1397 (b'r', b'rev', [], _(b'show branch name(s) of the given rev')),
1398 ]
1398 ]
1399 + formatteropts,
1399 + formatteropts,
1400 _(b'[-c]'),
1400 _(b'[-c]'),
1401 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1401 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1402 intents={INTENT_READONLY},
1402 intents={INTENT_READONLY},
1403 )
1403 )
1404 def branches(ui, repo, active=False, closed=False, **opts):
1404 def branches(ui, repo, active=False, closed=False, **opts):
1405 """list repository named branches
1405 """list repository named branches
1406
1406
1407 List the repository's named branches, indicating which ones are
1407 List the repository's named branches, indicating which ones are
1408 inactive. If -c/--closed is specified, also list branches which have
1408 inactive. If -c/--closed is specified, also list branches which have
1409 been marked closed (see :hg:`commit --close-branch`).
1409 been marked closed (see :hg:`commit --close-branch`).
1410
1410
1411 Use the command :hg:`update` to switch to an existing branch.
1411 Use the command :hg:`update` to switch to an existing branch.
1412
1412
1413 .. container:: verbose
1413 .. container:: verbose
1414
1414
1415 Template:
1415 Template:
1416
1416
1417 The following keywords are supported in addition to the common template
1417 The following keywords are supported in addition to the common template
1418 keywords and functions such as ``{branch}``. See also
1418 keywords and functions such as ``{branch}``. See also
1419 :hg:`help templates`.
1419 :hg:`help templates`.
1420
1420
1421 :active: Boolean. True if the branch is active.
1421 :active: Boolean. True if the branch is active.
1422 :closed: Boolean. True if the branch is closed.
1422 :closed: Boolean. True if the branch is closed.
1423 :current: Boolean. True if it is the current branch.
1423 :current: Boolean. True if it is the current branch.
1424
1424
1425 Returns 0.
1425 Returns 0.
1426 """
1426 """
1427
1427
1428 opts = pycompat.byteskwargs(opts)
1428 opts = pycompat.byteskwargs(opts)
1429 revs = opts.get(b'rev')
1429 revs = opts.get(b'rev')
1430 selectedbranches = None
1430 selectedbranches = None
1431 if revs:
1431 if revs:
1432 revs = logcmdutil.revrange(repo, revs)
1432 revs = logcmdutil.revrange(repo, revs)
1433 getbi = repo.revbranchcache().branchinfo
1433 getbi = repo.revbranchcache().branchinfo
1434 selectedbranches = {getbi(r)[0] for r in revs}
1434 selectedbranches = {getbi(r)[0] for r in revs}
1435
1435
1436 ui.pager(b'branches')
1436 ui.pager(b'branches')
1437 fm = ui.formatter(b'branches', opts)
1437 fm = ui.formatter(b'branches', opts)
1438 hexfunc = fm.hexfunc
1438 hexfunc = fm.hexfunc
1439
1439
1440 allheads = set(repo.heads())
1440 allheads = set(repo.heads())
1441 branches = []
1441 branches = []
1442 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1442 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1443 if selectedbranches is not None and tag not in selectedbranches:
1443 if selectedbranches is not None and tag not in selectedbranches:
1444 continue
1444 continue
1445 isactive = False
1445 isactive = False
1446 if not isclosed:
1446 if not isclosed:
1447 openheads = set(repo.branchmap().iteropen(heads))
1447 openheads = set(repo.branchmap().iteropen(heads))
1448 isactive = bool(openheads & allheads)
1448 isactive = bool(openheads & allheads)
1449 branches.append((tag, repo[tip], isactive, not isclosed))
1449 branches.append((tag, repo[tip], isactive, not isclosed))
1450 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]), reverse=True)
1450 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]), reverse=True)
1451
1451
1452 for tag, ctx, isactive, isopen in branches:
1452 for tag, ctx, isactive, isopen in branches:
1453 if active and not isactive:
1453 if active and not isactive:
1454 continue
1454 continue
1455 if isactive:
1455 if isactive:
1456 label = b'branches.active'
1456 label = b'branches.active'
1457 notice = b''
1457 notice = b''
1458 elif not isopen:
1458 elif not isopen:
1459 if not closed:
1459 if not closed:
1460 continue
1460 continue
1461 label = b'branches.closed'
1461 label = b'branches.closed'
1462 notice = _(b' (closed)')
1462 notice = _(b' (closed)')
1463 else:
1463 else:
1464 label = b'branches.inactive'
1464 label = b'branches.inactive'
1465 notice = _(b' (inactive)')
1465 notice = _(b' (inactive)')
1466 current = tag == repo.dirstate.branch()
1466 current = tag == repo.dirstate.branch()
1467 if current:
1467 if current:
1468 label = b'branches.current'
1468 label = b'branches.current'
1469
1469
1470 fm.startitem()
1470 fm.startitem()
1471 fm.write(b'branch', b'%s', tag, label=label)
1471 fm.write(b'branch', b'%s', tag, label=label)
1472 rev = ctx.rev()
1472 rev = ctx.rev()
1473 padsize = max(31 - len(b"%d" % rev) - encoding.colwidth(tag), 0)
1473 padsize = max(31 - len(b"%d" % rev) - encoding.colwidth(tag), 0)
1474 fmt = b' ' * padsize + b' %d:%s'
1474 fmt = b' ' * padsize + b' %d:%s'
1475 fm.condwrite(
1475 fm.condwrite(
1476 not ui.quiet,
1476 not ui.quiet,
1477 b'rev node',
1477 b'rev node',
1478 fmt,
1478 fmt,
1479 rev,
1479 rev,
1480 hexfunc(ctx.node()),
1480 hexfunc(ctx.node()),
1481 label=b'log.changeset changeset.%s' % ctx.phasestr(),
1481 label=b'log.changeset changeset.%s' % ctx.phasestr(),
1482 )
1482 )
1483 fm.context(ctx=ctx)
1483 fm.context(ctx=ctx)
1484 fm.data(active=isactive, closed=not isopen, current=current)
1484 fm.data(active=isactive, closed=not isopen, current=current)
1485 if not ui.quiet:
1485 if not ui.quiet:
1486 fm.plain(notice)
1486 fm.plain(notice)
1487 fm.plain(b'\n')
1487 fm.plain(b'\n')
1488 fm.end()
1488 fm.end()
1489
1489
1490
1490
1491 @command(
1491 @command(
1492 b'bundle',
1492 b'bundle',
1493 [
1493 [
1494 (
1494 (
1495 b'',
1495 b'',
1496 b'exact',
1496 b'exact',
1497 None,
1497 None,
1498 _(b'compute the base from the revision specified'),
1498 _(b'compute the base from the revision specified'),
1499 ),
1499 ),
1500 (
1500 (
1501 b'f',
1501 b'f',
1502 b'force',
1502 b'force',
1503 None,
1503 None,
1504 _(b'run even when the destination is unrelated'),
1504 _(b'run even when the destination is unrelated'),
1505 ),
1505 ),
1506 (
1506 (
1507 b'r',
1507 b'r',
1508 b'rev',
1508 b'rev',
1509 [],
1509 [],
1510 _(b'a changeset intended to be added to the destination'),
1510 _(b'a changeset intended to be added to the destination'),
1511 _(b'REV'),
1511 _(b'REV'),
1512 ),
1512 ),
1513 (
1513 (
1514 b'b',
1514 b'b',
1515 b'branch',
1515 b'branch',
1516 [],
1516 [],
1517 _(b'a specific branch you would like to bundle'),
1517 _(b'a specific branch you would like to bundle'),
1518 _(b'BRANCH'),
1518 _(b'BRANCH'),
1519 ),
1519 ),
1520 (
1520 (
1521 b'',
1521 b'',
1522 b'base',
1522 b'base',
1523 [],
1523 [],
1524 _(b'a base changeset assumed to be available at the destination'),
1524 _(b'a base changeset assumed to be available at the destination'),
1525 _(b'REV'),
1525 _(b'REV'),
1526 ),
1526 ),
1527 (b'a', b'all', None, _(b'bundle all changesets in the repository')),
1527 (b'a', b'all', None, _(b'bundle all changesets in the repository')),
1528 (
1528 (
1529 b't',
1529 b't',
1530 b'type',
1530 b'type',
1531 b'bzip2',
1531 b'bzip2',
1532 _(b'bundle compression type to use'),
1532 _(b'bundle compression type to use'),
1533 _(b'TYPE'),
1533 _(b'TYPE'),
1534 ),
1534 ),
1535 ]
1535 ]
1536 + remoteopts,
1536 + remoteopts,
1537 _(b'[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]...'),
1537 _(b'[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]...'),
1538 helpcategory=command.CATEGORY_IMPORT_EXPORT,
1538 helpcategory=command.CATEGORY_IMPORT_EXPORT,
1539 )
1539 )
1540 def bundle(ui, repo, fname, *dests, **opts):
1540 def bundle(ui, repo, fname, *dests, **opts):
1541 """create a bundle file
1541 """create a bundle file
1542
1542
1543 Generate a bundle file containing data to be transferred to another
1543 Generate a bundle file containing data to be transferred to another
1544 repository.
1544 repository.
1545
1545
1546 To create a bundle containing all changesets, use -a/--all
1546 To create a bundle containing all changesets, use -a/--all
1547 (or --base null). Otherwise, hg assumes the destination will have
1547 (or --base null). Otherwise, hg assumes the destination will have
1548 all the nodes you specify with --base parameters. Otherwise, hg
1548 all the nodes you specify with --base parameters. Otherwise, hg
1549 will assume the repository has all the nodes in destination, or
1549 will assume the repository has all the nodes in destination, or
1550 default-push/default if no destination is specified, where destination
1550 default-push/default if no destination is specified, where destination
1551 is the repositories you provide through DEST option.
1551 is the repositories you provide through DEST option.
1552
1552
1553 You can change bundle format with the -t/--type option. See
1553 You can change bundle format with the -t/--type option. See
1554 :hg:`help bundlespec` for documentation on this format. By default,
1554 :hg:`help bundlespec` for documentation on this format. By default,
1555 the most appropriate format is used and compression defaults to
1555 the most appropriate format is used and compression defaults to
1556 bzip2.
1556 bzip2.
1557
1557
1558 The bundle file can then be transferred using conventional means
1558 The bundle file can then be transferred using conventional means
1559 and applied to another repository with the unbundle or pull
1559 and applied to another repository with the unbundle or pull
1560 command. This is useful when direct push and pull are not
1560 command. This is useful when direct push and pull are not
1561 available or when exporting an entire repository is undesirable.
1561 available or when exporting an entire repository is undesirable.
1562
1562
1563 Applying bundles preserves all changeset contents including
1563 Applying bundles preserves all changeset contents including
1564 permissions, copy/rename information, and revision history.
1564 permissions, copy/rename information, and revision history.
1565
1565
1566 Returns 0 on success, 1 if no changes found.
1566 Returns 0 on success, 1 if no changes found.
1567 """
1567 """
1568 opts = pycompat.byteskwargs(opts)
1568 opts = pycompat.byteskwargs(opts)
1569
1569
1570 revs = None
1570 revs = None
1571 if b'rev' in opts:
1571 if b'rev' in opts:
1572 revstrings = opts[b'rev']
1572 revstrings = opts[b'rev']
1573 revs = logcmdutil.revrange(repo, revstrings)
1573 revs = logcmdutil.revrange(repo, revstrings)
1574 if revstrings and not revs:
1574 if revstrings and not revs:
1575 raise error.InputError(_(b'no commits to bundle'))
1575 raise error.InputError(_(b'no commits to bundle'))
1576
1576
1577 bundletype = opts.get(b'type', b'bzip2').lower()
1577 bundletype = opts.get(b'type', b'bzip2').lower()
1578 try:
1578 try:
1579 bundlespec = bundlecaches.parsebundlespec(
1579 bundlespec = bundlecaches.parsebundlespec(
1580 repo, bundletype, strict=False
1580 repo, bundletype, strict=False
1581 )
1581 )
1582 except error.UnsupportedBundleSpecification as e:
1582 except error.UnsupportedBundleSpecification as e:
1583 raise error.InputError(
1583 raise error.InputError(
1584 pycompat.bytestr(e),
1584 pycompat.bytestr(e),
1585 hint=_(b"see 'hg help bundlespec' for supported values for --type"),
1585 hint=_(b"see 'hg help bundlespec' for supported values for --type"),
1586 )
1586 )
1587 cgversion = bundlespec.params[b"cg.version"]
1587 cgversion = bundlespec.params[b"cg.version"]
1588
1588
1589 # Packed bundles are a pseudo bundle format for now.
1589 # Packed bundles are a pseudo bundle format for now.
1590 if cgversion == b's1':
1590 if cgversion == b's1':
1591 raise error.InputError(
1591 raise error.InputError(
1592 _(b'packed bundles cannot be produced by "hg bundle"'),
1592 _(b'packed bundles cannot be produced by "hg bundle"'),
1593 hint=_(b"use 'hg debugcreatestreamclonebundle'"),
1593 hint=_(b"use 'hg debugcreatestreamclonebundle'"),
1594 )
1594 )
1595
1595
1596 if opts.get(b'all'):
1596 if opts.get(b'all'):
1597 if dests:
1597 if dests:
1598 raise error.InputError(
1598 raise error.InputError(
1599 _(b"--all is incompatible with specifying destinations")
1599 _(b"--all is incompatible with specifying destinations")
1600 )
1600 )
1601 if opts.get(b'base'):
1601 if opts.get(b'base'):
1602 ui.warn(_(b"ignoring --base because --all was specified\n"))
1602 ui.warn(_(b"ignoring --base because --all was specified\n"))
1603 if opts.get(b'exact'):
1603 if opts.get(b'exact'):
1604 ui.warn(_(b"ignoring --exact because --all was specified\n"))
1604 ui.warn(_(b"ignoring --exact because --all was specified\n"))
1605 base = [nullrev]
1605 base = [nullrev]
1606 elif opts.get(b'exact'):
1606 elif opts.get(b'exact'):
1607 if dests:
1607 if dests:
1608 raise error.InputError(
1608 raise error.InputError(
1609 _(b"--exact is incompatible with specifying destinations")
1609 _(b"--exact is incompatible with specifying destinations")
1610 )
1610 )
1611 if opts.get(b'base'):
1611 if opts.get(b'base'):
1612 ui.warn(_(b"ignoring --base because --exact was specified\n"))
1612 ui.warn(_(b"ignoring --base because --exact was specified\n"))
1613 base = repo.revs(b'parents(%ld) - %ld', revs, revs)
1613 base = repo.revs(b'parents(%ld) - %ld', revs, revs)
1614 if not base:
1614 if not base:
1615 base = [nullrev]
1615 base = [nullrev]
1616 else:
1616 else:
1617 base = logcmdutil.revrange(repo, opts.get(b'base'))
1617 base = logcmdutil.revrange(repo, opts.get(b'base'))
1618 if cgversion not in changegroup.supportedoutgoingversions(repo):
1618 if cgversion not in changegroup.supportedoutgoingversions(repo):
1619 raise error.Abort(
1619 raise error.Abort(
1620 _(b"repository does not support bundle version %s") % cgversion
1620 _(b"repository does not support bundle version %s") % cgversion
1621 )
1621 )
1622
1622
1623 if base:
1623 if base:
1624 if dests:
1624 if dests:
1625 raise error.InputError(
1625 raise error.InputError(
1626 _(b"--base is incompatible with specifying destinations")
1626 _(b"--base is incompatible with specifying destinations")
1627 )
1627 )
1628 cl = repo.changelog
1628 cl = repo.changelog
1629 common = [cl.node(rev) for rev in base]
1629 common = [cl.node(rev) for rev in base]
1630 heads = [cl.node(r) for r in revs] if revs else None
1630 heads = [cl.node(r) for r in revs] if revs else None
1631 outgoing = discovery.outgoing(repo, common, heads)
1631 outgoing = discovery.outgoing(repo, common, heads)
1632 missing = outgoing.missing
1632 missing = outgoing.missing
1633 excluded = outgoing.excluded
1633 excluded = outgoing.excluded
1634 else:
1634 else:
1635 missing = set()
1635 missing = set()
1636 excluded = set()
1636 excluded = set()
1637 for path in urlutil.get_push_paths(repo, ui, dests):
1637 for path in urlutil.get_push_paths(repo, ui, dests):
1638 other = hg.peer(repo, opts, path)
1638 other = hg.peer(repo, opts, path)
1639 if revs is not None:
1639 if revs is not None:
1640 hex_revs = [repo[r].hex() for r in revs]
1640 hex_revs = [repo[r].hex() for r in revs]
1641 else:
1641 else:
1642 hex_revs = None
1642 hex_revs = None
1643 branches = (path.branch, [])
1643 branches = (path.branch, [])
1644 head_revs, checkout = hg.addbranchrevs(
1644 head_revs, checkout = hg.addbranchrevs(
1645 repo, repo, branches, hex_revs
1645 repo, repo, branches, hex_revs
1646 )
1646 )
1647 heads = (
1647 heads = (
1648 head_revs
1648 head_revs
1649 and pycompat.maplist(repo.lookup, head_revs)
1649 and pycompat.maplist(repo.lookup, head_revs)
1650 or head_revs
1650 or head_revs
1651 )
1651 )
1652 outgoing = discovery.findcommonoutgoing(
1652 outgoing = discovery.findcommonoutgoing(
1653 repo,
1653 repo,
1654 other,
1654 other,
1655 onlyheads=heads,
1655 onlyheads=heads,
1656 force=opts.get(b'force'),
1656 force=opts.get(b'force'),
1657 portable=True,
1657 portable=True,
1658 )
1658 )
1659 missing.update(outgoing.missing)
1659 missing.update(outgoing.missing)
1660 excluded.update(outgoing.excluded)
1660 excluded.update(outgoing.excluded)
1661
1661
1662 if not missing:
1662 if not missing:
1663 scmutil.nochangesfound(ui, repo, not base and excluded)
1663 scmutil.nochangesfound(ui, repo, not base and excluded)
1664 return 1
1664 return 1
1665
1665
1666 if heads:
1666 if heads:
1667 outgoing = discovery.outgoing(
1667 outgoing = discovery.outgoing(
1668 repo, missingroots=missing, ancestorsof=heads
1668 repo, missingroots=missing, ancestorsof=heads
1669 )
1669 )
1670 else:
1670 else:
1671 outgoing = discovery.outgoing(repo, missingroots=missing)
1671 outgoing = discovery.outgoing(repo, missingroots=missing)
1672 outgoing.excluded = sorted(excluded)
1672 outgoing.excluded = sorted(excluded)
1673
1673
1674 if cgversion == b'01': # bundle1
1674 if cgversion == b'01': # bundle1
1675 bversion = b'HG10' + bundlespec.wirecompression
1675 bversion = b'HG10' + bundlespec.wirecompression
1676 bcompression = None
1676 bcompression = None
1677 elif cgversion in (b'02', b'03'):
1677 elif cgversion in (b'02', b'03'):
1678 bversion = b'HG20'
1678 bversion = b'HG20'
1679 bcompression = bundlespec.wirecompression
1679 bcompression = bundlespec.wirecompression
1680 else:
1680 else:
1681 raise error.ProgrammingError(
1681 raise error.ProgrammingError(
1682 b'bundle: unexpected changegroup version %s' % cgversion
1682 b'bundle: unexpected changegroup version %s' % cgversion
1683 )
1683 )
1684
1684
1685 # TODO compression options should be derived from bundlespec parsing.
1685 # TODO compression options should be derived from bundlespec parsing.
1686 # This is a temporary hack to allow adjusting bundle compression
1686 # This is a temporary hack to allow adjusting bundle compression
1687 # level without a) formalizing the bundlespec changes to declare it
1687 # level without a) formalizing the bundlespec changes to declare it
1688 # b) introducing a command flag.
1688 # b) introducing a command flag.
1689 compopts = {}
1689 compopts = {}
1690 complevel = ui.configint(
1690 complevel = ui.configint(
1691 b'experimental', b'bundlecomplevel.' + bundlespec.compression
1691 b'experimental', b'bundlecomplevel.' + bundlespec.compression
1692 )
1692 )
1693 if complevel is None:
1693 if complevel is None:
1694 complevel = ui.configint(b'experimental', b'bundlecomplevel')
1694 complevel = ui.configint(b'experimental', b'bundlecomplevel')
1695 if complevel is not None:
1695 if complevel is not None:
1696 compopts[b'level'] = complevel
1696 compopts[b'level'] = complevel
1697
1697
1698 compthreads = ui.configint(
1698 compthreads = ui.configint(
1699 b'experimental', b'bundlecompthreads.' + bundlespec.compression
1699 b'experimental', b'bundlecompthreads.' + bundlespec.compression
1700 )
1700 )
1701 if compthreads is None:
1701 if compthreads is None:
1702 compthreads = ui.configint(b'experimental', b'bundlecompthreads')
1702 compthreads = ui.configint(b'experimental', b'bundlecompthreads')
1703 if compthreads is not None:
1703 if compthreads is not None:
1704 compopts[b'threads'] = compthreads
1704 compopts[b'threads'] = compthreads
1705
1705
1706 # Bundling of obsmarker and phases is optional as not all clients
1706 # Bundling of obsmarker and phases is optional as not all clients
1707 # support the necessary features.
1707 # support the necessary features.
1708 cfg = ui.configbool
1708 cfg = ui.configbool
1709 obsolescence_cfg = cfg(b'experimental', b'evolution.bundle-obsmarker')
1709 obsolescence_cfg = cfg(b'experimental', b'evolution.bundle-obsmarker')
1710 bundlespec.set_param(b'obsolescence', obsolescence_cfg, overwrite=False)
1710 bundlespec.set_param(b'obsolescence', obsolescence_cfg, overwrite=False)
1711 obs_mand_cfg = cfg(b'experimental', b'evolution.bundle-obsmarker:mandatory')
1711 obs_mand_cfg = cfg(b'experimental', b'evolution.bundle-obsmarker:mandatory')
1712 bundlespec.set_param(
1712 bundlespec.set_param(
1713 b'obsolescence-mandatory', obs_mand_cfg, overwrite=False
1713 b'obsolescence-mandatory', obs_mand_cfg, overwrite=False
1714 )
1714 )
1715 phases_cfg = cfg(b'experimental', b'bundle-phases')
1715 phases_cfg = cfg(b'experimental', b'bundle-phases')
1716 bundlespec.set_param(b'phases', phases_cfg, overwrite=False)
1716 bundlespec.set_param(b'phases', phases_cfg, overwrite=False)
1717
1717
1718 bundle2.writenewbundle(
1718 bundle2.writenewbundle(
1719 ui,
1719 ui,
1720 repo,
1720 repo,
1721 b'bundle',
1721 b'bundle',
1722 fname,
1722 fname,
1723 bversion,
1723 bversion,
1724 outgoing,
1724 outgoing,
1725 bundlespec.params,
1725 bundlespec.params,
1726 compression=bcompression,
1726 compression=bcompression,
1727 compopts=compopts,
1727 compopts=compopts,
1728 )
1728 )
1729
1729
1730
1730
1731 @command(
1731 @command(
1732 b'cat',
1732 b'cat',
1733 [
1733 [
1734 (
1734 (
1735 b'o',
1735 b'o',
1736 b'output',
1736 b'output',
1737 b'',
1737 b'',
1738 _(b'print output to file with formatted name'),
1738 _(b'print output to file with formatted name'),
1739 _(b'FORMAT'),
1739 _(b'FORMAT'),
1740 ),
1740 ),
1741 (b'r', b'rev', b'', _(b'print the given revision'), _(b'REV')),
1741 (b'r', b'rev', b'', _(b'print the given revision'), _(b'REV')),
1742 (b'', b'decode', None, _(b'apply any matching decode filter')),
1742 (b'', b'decode', None, _(b'apply any matching decode filter')),
1743 ]
1743 ]
1744 + walkopts
1744 + walkopts
1745 + formatteropts,
1745 + formatteropts,
1746 _(b'[OPTION]... FILE...'),
1746 _(b'[OPTION]... FILE...'),
1747 helpcategory=command.CATEGORY_FILE_CONTENTS,
1747 helpcategory=command.CATEGORY_FILE_CONTENTS,
1748 inferrepo=True,
1748 inferrepo=True,
1749 intents={INTENT_READONLY},
1749 intents={INTENT_READONLY},
1750 )
1750 )
1751 def cat(ui, repo, file1, *pats, **opts):
1751 def cat(ui, repo, file1, *pats, **opts):
1752 """output the current or given revision of files
1752 """output the current or given revision of files
1753
1753
1754 Print the specified files as they were at the given revision. If
1754 Print the specified files as they were at the given revision. If
1755 no revision is given, the parent of the working directory is used.
1755 no revision is given, the parent of the working directory is used.
1756
1756
1757 Output may be to a file, in which case the name of the file is
1757 Output may be to a file, in which case the name of the file is
1758 given using a template string. See :hg:`help templates`. In addition
1758 given using a template string. See :hg:`help templates`. In addition
1759 to the common template keywords, the following formatting rules are
1759 to the common template keywords, the following formatting rules are
1760 supported:
1760 supported:
1761
1761
1762 :``%%``: literal "%" character
1762 :``%%``: literal "%" character
1763 :``%s``: basename of file being printed
1763 :``%s``: basename of file being printed
1764 :``%d``: dirname of file being printed, or '.' if in repository root
1764 :``%d``: dirname of file being printed, or '.' if in repository root
1765 :``%p``: root-relative path name of file being printed
1765 :``%p``: root-relative path name of file being printed
1766 :``%H``: changeset hash (40 hexadecimal digits)
1766 :``%H``: changeset hash (40 hexadecimal digits)
1767 :``%R``: changeset revision number
1767 :``%R``: changeset revision number
1768 :``%h``: short-form changeset hash (12 hexadecimal digits)
1768 :``%h``: short-form changeset hash (12 hexadecimal digits)
1769 :``%r``: zero-padded changeset revision number
1769 :``%r``: zero-padded changeset revision number
1770 :``%b``: basename of the exporting repository
1770 :``%b``: basename of the exporting repository
1771 :``\\``: literal "\\" character
1771 :``\\``: literal "\\" character
1772
1772
1773 .. container:: verbose
1773 .. container:: verbose
1774
1774
1775 Template:
1775 Template:
1776
1776
1777 The following keywords are supported in addition to the common template
1777 The following keywords are supported in addition to the common template
1778 keywords and functions. See also :hg:`help templates`.
1778 keywords and functions. See also :hg:`help templates`.
1779
1779
1780 :data: String. File content.
1780 :data: String. File content.
1781 :path: String. Repository-absolute path of the file.
1781 :path: String. Repository-absolute path of the file.
1782
1782
1783 Returns 0 on success.
1783 Returns 0 on success.
1784 """
1784 """
1785 opts = pycompat.byteskwargs(opts)
1785 opts = pycompat.byteskwargs(opts)
1786 rev = opts.get(b'rev')
1786 rev = opts.get(b'rev')
1787 if rev:
1787 if rev:
1788 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
1788 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
1789 ctx = logcmdutil.revsingle(repo, rev)
1789 ctx = logcmdutil.revsingle(repo, rev)
1790 m = scmutil.match(ctx, (file1,) + pats, opts)
1790 m = scmutil.match(ctx, (file1,) + pats, opts)
1791 fntemplate = opts.pop(b'output', b'')
1791 fntemplate = opts.pop(b'output', b'')
1792 if cmdutil.isstdiofilename(fntemplate):
1792 if cmdutil.isstdiofilename(fntemplate):
1793 fntemplate = b''
1793 fntemplate = b''
1794
1794
1795 if fntemplate:
1795 if fntemplate:
1796 fm = formatter.nullformatter(ui, b'cat', opts)
1796 fm = formatter.nullformatter(ui, b'cat', opts)
1797 else:
1797 else:
1798 ui.pager(b'cat')
1798 ui.pager(b'cat')
1799 fm = ui.formatter(b'cat', opts)
1799 fm = ui.formatter(b'cat', opts)
1800 with fm:
1800 with fm:
1801 return cmdutil.cat(
1801 return cmdutil.cat(
1802 ui, repo, ctx, m, fm, fntemplate, b'', **pycompat.strkwargs(opts)
1802 ui, repo, ctx, m, fm, fntemplate, b'', **pycompat.strkwargs(opts)
1803 )
1803 )
1804
1804
1805
1805
1806 @command(
1806 @command(
1807 b'clone',
1807 b'clone',
1808 [
1808 [
1809 (
1809 (
1810 b'U',
1810 b'U',
1811 b'noupdate',
1811 b'noupdate',
1812 None,
1812 None,
1813 _(
1813 _(
1814 b'the clone will include an empty working '
1814 b'the clone will include an empty working '
1815 b'directory (only a repository)'
1815 b'directory (only a repository)'
1816 ),
1816 ),
1817 ),
1817 ),
1818 (
1818 (
1819 b'u',
1819 b'u',
1820 b'updaterev',
1820 b'updaterev',
1821 b'',
1821 b'',
1822 _(b'revision, tag, or branch to check out'),
1822 _(b'revision, tag, or branch to check out'),
1823 _(b'REV'),
1823 _(b'REV'),
1824 ),
1824 ),
1825 (
1825 (
1826 b'r',
1826 b'r',
1827 b'rev',
1827 b'rev',
1828 [],
1828 [],
1829 _(
1829 _(
1830 b'do not clone everything, but include this changeset'
1830 b'do not clone everything, but include this changeset'
1831 b' and its ancestors'
1831 b' and its ancestors'
1832 ),
1832 ),
1833 _(b'REV'),
1833 _(b'REV'),
1834 ),
1834 ),
1835 (
1835 (
1836 b'b',
1836 b'b',
1837 b'branch',
1837 b'branch',
1838 [],
1838 [],
1839 _(
1839 _(
1840 b'do not clone everything, but include this branch\'s'
1840 b'do not clone everything, but include this branch\'s'
1841 b' changesets and their ancestors'
1841 b' changesets and their ancestors'
1842 ),
1842 ),
1843 _(b'BRANCH'),
1843 _(b'BRANCH'),
1844 ),
1844 ),
1845 (b'', b'pull', None, _(b'use pull protocol to copy metadata')),
1845 (b'', b'pull', None, _(b'use pull protocol to copy metadata')),
1846 (b'', b'uncompressed', None, _(b'an alias to --stream (DEPRECATED)')),
1846 (b'', b'uncompressed', None, _(b'an alias to --stream (DEPRECATED)')),
1847 (b'', b'stream', None, _(b'clone with minimal data processing')),
1847 (b'', b'stream', None, _(b'clone with minimal data processing')),
1848 ]
1848 ]
1849 + remoteopts,
1849 + remoteopts,
1850 _(b'[OPTION]... SOURCE [DEST]'),
1850 _(b'[OPTION]... SOURCE [DEST]'),
1851 helpcategory=command.CATEGORY_REPO_CREATION,
1851 helpcategory=command.CATEGORY_REPO_CREATION,
1852 helpbasic=True,
1852 helpbasic=True,
1853 norepo=True,
1853 norepo=True,
1854 )
1854 )
1855 def clone(ui, source, dest=None, **opts):
1855 def clone(ui, source, dest=None, **opts):
1856 """make a copy of an existing repository
1856 """make a copy of an existing repository
1857
1857
1858 Create a copy of an existing repository in a new directory.
1858 Create a copy of an existing repository in a new directory.
1859
1859
1860 If no destination directory name is specified, it defaults to the
1860 If no destination directory name is specified, it defaults to the
1861 basename of the source.
1861 basename of the source.
1862
1862
1863 The location of the source is added to the new repository's
1863 The location of the source is added to the new repository's
1864 ``.hg/hgrc`` file, as the default to be used for future pulls.
1864 ``.hg/hgrc`` file, as the default to be used for future pulls.
1865
1865
1866 Only local paths and ``ssh://`` URLs are supported as
1866 Only local paths and ``ssh://`` URLs are supported as
1867 destinations. For ``ssh://`` destinations, no working directory or
1867 destinations. For ``ssh://`` destinations, no working directory or
1868 ``.hg/hgrc`` will be created on the remote side.
1868 ``.hg/hgrc`` will be created on the remote side.
1869
1869
1870 If the source repository has a bookmark called '@' set, that
1870 If the source repository has a bookmark called '@' set, that
1871 revision will be checked out in the new repository by default.
1871 revision will be checked out in the new repository by default.
1872
1872
1873 To check out a particular version, use -u/--update, or
1873 To check out a particular version, use -u/--update, or
1874 -U/--noupdate to create a clone with no working directory.
1874 -U/--noupdate to create a clone with no working directory.
1875
1875
1876 To pull only a subset of changesets, specify one or more revisions
1876 To pull only a subset of changesets, specify one or more revisions
1877 identifiers with -r/--rev or branches with -b/--branch. The
1877 identifiers with -r/--rev or branches with -b/--branch. The
1878 resulting clone will contain only the specified changesets and
1878 resulting clone will contain only the specified changesets and
1879 their ancestors. These options (or 'clone src#rev dest') imply
1879 their ancestors. These options (or 'clone src#rev dest') imply
1880 --pull, even for local source repositories.
1880 --pull, even for local source repositories.
1881
1881
1882 In normal clone mode, the remote normalizes repository data into a common
1882 In normal clone mode, the remote normalizes repository data into a common
1883 exchange format and the receiving end translates this data into its local
1883 exchange format and the receiving end translates this data into its local
1884 storage format. --stream activates a different clone mode that essentially
1884 storage format. --stream activates a different clone mode that essentially
1885 copies repository files from the remote with minimal data processing. This
1885 copies repository files from the remote with minimal data processing. This
1886 significantly reduces the CPU cost of a clone both remotely and locally.
1886 significantly reduces the CPU cost of a clone both remotely and locally.
1887 However, it often increases the transferred data size by 30-40%. This can
1887 However, it often increases the transferred data size by 30-40%. This can
1888 result in substantially faster clones where I/O throughput is plentiful,
1888 result in substantially faster clones where I/O throughput is plentiful,
1889 especially for larger repositories. A side-effect of --stream clones is
1889 especially for larger repositories. A side-effect of --stream clones is
1890 that storage settings and requirements on the remote are applied locally:
1890 that storage settings and requirements on the remote are applied locally:
1891 a modern client may inherit legacy or inefficient storage used by the
1891 a modern client may inherit legacy or inefficient storage used by the
1892 remote or a legacy Mercurial client may not be able to clone from a
1892 remote or a legacy Mercurial client may not be able to clone from a
1893 modern Mercurial remote.
1893 modern Mercurial remote.
1894
1894
1895 .. note::
1895 .. note::
1896
1896
1897 Specifying a tag will include the tagged changeset but not the
1897 Specifying a tag will include the tagged changeset but not the
1898 changeset containing the tag.
1898 changeset containing the tag.
1899
1899
1900 .. container:: verbose
1900 .. container:: verbose
1901
1901
1902 For efficiency, hardlinks are used for cloning whenever the
1902 For efficiency, hardlinks are used for cloning whenever the
1903 source and destination are on the same filesystem (note this
1903 source and destination are on the same filesystem (note this
1904 applies only to the repository data, not to the working
1904 applies only to the repository data, not to the working
1905 directory). Some filesystems, such as AFS, implement hardlinking
1905 directory). Some filesystems, such as AFS, implement hardlinking
1906 incorrectly, but do not report errors. In these cases, use the
1906 incorrectly, but do not report errors. In these cases, use the
1907 --pull option to avoid hardlinking.
1907 --pull option to avoid hardlinking.
1908
1908
1909 Mercurial will update the working directory to the first applicable
1909 Mercurial will update the working directory to the first applicable
1910 revision from this list:
1910 revision from this list:
1911
1911
1912 a) null if -U or the source repository has no changesets
1912 a) null if -U or the source repository has no changesets
1913 b) if -u . and the source repository is local, the first parent of
1913 b) if -u . and the source repository is local, the first parent of
1914 the source repository's working directory
1914 the source repository's working directory
1915 c) the changeset specified with -u (if a branch name, this means the
1915 c) the changeset specified with -u (if a branch name, this means the
1916 latest head of that branch)
1916 latest head of that branch)
1917 d) the changeset specified with -r
1917 d) the changeset specified with -r
1918 e) the tipmost head specified with -b
1918 e) the tipmost head specified with -b
1919 f) the tipmost head specified with the url#branch source syntax
1919 f) the tipmost head specified with the url#branch source syntax
1920 g) the revision marked with the '@' bookmark, if present
1920 g) the revision marked with the '@' bookmark, if present
1921 h) the tipmost head of the default branch
1921 h) the tipmost head of the default branch
1922 i) tip
1922 i) tip
1923
1923
1924 When cloning from servers that support it, Mercurial may fetch
1924 When cloning from servers that support it, Mercurial may fetch
1925 pre-generated data from a server-advertised URL or inline from the
1925 pre-generated data from a server-advertised URL or inline from the
1926 same stream. When this is done, hooks operating on incoming changesets
1926 same stream. When this is done, hooks operating on incoming changesets
1927 and changegroups may fire more than once, once for each pre-generated
1927 and changegroups may fire more than once, once for each pre-generated
1928 bundle and as well as for any additional remaining data. In addition,
1928 bundle and as well as for any additional remaining data. In addition,
1929 if an error occurs, the repository may be rolled back to a partial
1929 if an error occurs, the repository may be rolled back to a partial
1930 clone. This behavior may change in future releases.
1930 clone. This behavior may change in future releases.
1931 See :hg:`help -e clonebundles` for more.
1931 See :hg:`help -e clonebundles` for more.
1932
1932
1933 Examples:
1933 Examples:
1934
1934
1935 - clone a remote repository to a new directory named hg/::
1935 - clone a remote repository to a new directory named hg/::
1936
1936
1937 hg clone https://www.mercurial-scm.org/repo/hg/
1937 hg clone https://www.mercurial-scm.org/repo/hg/
1938
1938
1939 - create a lightweight local clone::
1939 - create a lightweight local clone::
1940
1940
1941 hg clone project/ project-feature/
1941 hg clone project/ project-feature/
1942
1942
1943 - clone from an absolute path on an ssh server (note double-slash)::
1943 - clone from an absolute path on an ssh server (note double-slash)::
1944
1944
1945 hg clone ssh://user@server//home/projects/alpha/
1945 hg clone ssh://user@server//home/projects/alpha/
1946
1946
1947 - do a streaming clone while checking out a specified version::
1947 - do a streaming clone while checking out a specified version::
1948
1948
1949 hg clone --stream http://server/repo -u 1.5
1949 hg clone --stream http://server/repo -u 1.5
1950
1950
1951 - create a repository without changesets after a particular revision::
1951 - create a repository without changesets after a particular revision::
1952
1952
1953 hg clone -r 04e544 experimental/ good/
1953 hg clone -r 04e544 experimental/ good/
1954
1954
1955 - clone (and track) a particular named branch::
1955 - clone (and track) a particular named branch::
1956
1956
1957 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1957 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1958
1958
1959 See :hg:`help urls` for details on specifying URLs.
1959 See :hg:`help urls` for details on specifying URLs.
1960
1960
1961 Returns 0 on success.
1961 Returns 0 on success.
1962 """
1962 """
1963 opts = pycompat.byteskwargs(opts)
1963 opts = pycompat.byteskwargs(opts)
1964 cmdutil.check_at_most_one_arg(opts, b'noupdate', b'updaterev')
1964 cmdutil.check_at_most_one_arg(opts, b'noupdate', b'updaterev')
1965
1965
1966 # --include/--exclude can come from narrow or sparse.
1966 # --include/--exclude can come from narrow or sparse.
1967 includepats, excludepats = None, None
1967 includepats, excludepats = None, None
1968
1968
1969 # hg.clone() differentiates between None and an empty set. So make sure
1969 # hg.clone() differentiates between None and an empty set. So make sure
1970 # patterns are sets if narrow is requested without patterns.
1970 # patterns are sets if narrow is requested without patterns.
1971 if opts.get(b'narrow'):
1971 if opts.get(b'narrow'):
1972 includepats = set()
1972 includepats = set()
1973 excludepats = set()
1973 excludepats = set()
1974
1974
1975 if opts.get(b'include'):
1975 if opts.get(b'include'):
1976 includepats = narrowspec.parsepatterns(opts.get(b'include'))
1976 includepats = narrowspec.parsepatterns(opts.get(b'include'))
1977 if opts.get(b'exclude'):
1977 if opts.get(b'exclude'):
1978 excludepats = narrowspec.parsepatterns(opts.get(b'exclude'))
1978 excludepats = narrowspec.parsepatterns(opts.get(b'exclude'))
1979
1979
1980 r = hg.clone(
1980 r = hg.clone(
1981 ui,
1981 ui,
1982 opts,
1982 opts,
1983 source,
1983 source,
1984 dest,
1984 dest,
1985 pull=opts.get(b'pull'),
1985 pull=opts.get(b'pull'),
1986 stream=opts.get(b'stream') or opts.get(b'uncompressed'),
1986 stream=opts.get(b'stream') or opts.get(b'uncompressed'),
1987 revs=opts.get(b'rev'),
1987 revs=opts.get(b'rev'),
1988 update=opts.get(b'updaterev') or not opts.get(b'noupdate'),
1988 update=opts.get(b'updaterev') or not opts.get(b'noupdate'),
1989 branch=opts.get(b'branch'),
1989 branch=opts.get(b'branch'),
1990 shareopts=opts.get(b'shareopts'),
1990 shareopts=opts.get(b'shareopts'),
1991 storeincludepats=includepats,
1991 storeincludepats=includepats,
1992 storeexcludepats=excludepats,
1992 storeexcludepats=excludepats,
1993 depth=opts.get(b'depth') or None,
1993 depth=opts.get(b'depth') or None,
1994 )
1994 )
1995
1995
1996 return r is None
1996 return r is None
1997
1997
1998
1998
1999 @command(
1999 @command(
2000 b'commit|ci',
2000 b'commit|ci',
2001 [
2001 [
2002 (
2002 (
2003 b'A',
2003 b'A',
2004 b'addremove',
2004 b'addremove',
2005 None,
2005 None,
2006 _(b'mark new/missing files as added/removed before committing'),
2006 _(b'mark new/missing files as added/removed before committing'),
2007 ),
2007 ),
2008 (b'', b'close-branch', None, _(b'mark a branch head as closed')),
2008 (b'', b'close-branch', None, _(b'mark a branch head as closed')),
2009 (b'', b'amend', None, _(b'amend the parent of the working directory')),
2009 (b'', b'amend', None, _(b'amend the parent of the working directory')),
2010 (b's', b'secret', None, _(b'use the secret phase for committing')),
2010 (b's', b'secret', None, _(b'use the secret phase for committing')),
2011 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
2011 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
2012 (
2012 (
2013 b'',
2013 b'',
2014 b'force-close-branch',
2014 b'force-close-branch',
2015 None,
2015 None,
2016 _(b'forcibly close branch from a non-head changeset (ADVANCED)'),
2016 _(b'forcibly close branch from a non-head changeset (ADVANCED)'),
2017 ),
2017 ),
2018 (b'i', b'interactive', None, _(b'use interactive mode')),
2018 (b'i', b'interactive', None, _(b'use interactive mode')),
2019 ]
2019 ]
2020 + walkopts
2020 + walkopts
2021 + commitopts
2021 + commitopts
2022 + commitopts2
2022 + commitopts2
2023 + subrepoopts,
2023 + subrepoopts,
2024 _(b'[OPTION]... [FILE]...'),
2024 _(b'[OPTION]... [FILE]...'),
2025 helpcategory=command.CATEGORY_COMMITTING,
2025 helpcategory=command.CATEGORY_COMMITTING,
2026 helpbasic=True,
2026 helpbasic=True,
2027 inferrepo=True,
2027 inferrepo=True,
2028 )
2028 )
2029 def commit(ui, repo, *pats, **opts):
2029 def commit(ui, repo, *pats, **opts):
2030 """commit the specified files or all outstanding changes
2030 """commit the specified files or all outstanding changes
2031
2031
2032 Commit changes to the given files into the repository. Unlike a
2032 Commit changes to the given files into the repository. Unlike a
2033 centralized SCM, this operation is a local operation. See
2033 centralized SCM, this operation is a local operation. See
2034 :hg:`push` for a way to actively distribute your changes.
2034 :hg:`push` for a way to actively distribute your changes.
2035
2035
2036 If a list of files is omitted, all changes reported by :hg:`status`
2036 If a list of files is omitted, all changes reported by :hg:`status`
2037 will be committed.
2037 will be committed.
2038
2038
2039 If you are committing the result of a merge, do not provide any
2039 If you are committing the result of a merge, do not provide any
2040 filenames or -I/-X filters.
2040 filenames or -I/-X filters.
2041
2041
2042 If no commit message is specified, Mercurial starts your
2042 If no commit message is specified, Mercurial starts your
2043 configured editor where you can enter a message. In case your
2043 configured editor where you can enter a message. In case your
2044 commit fails, you will find a backup of your message in
2044 commit fails, you will find a backup of your message in
2045 ``.hg/last-message.txt``.
2045 ``.hg/last-message.txt``.
2046
2046
2047 The --close-branch flag can be used to mark the current branch
2047 The --close-branch flag can be used to mark the current branch
2048 head closed. When all heads of a branch are closed, the branch
2048 head closed. When all heads of a branch are closed, the branch
2049 will be considered closed and no longer listed.
2049 will be considered closed and no longer listed.
2050
2050
2051 The --amend flag can be used to amend the parent of the
2051 The --amend flag can be used to amend the parent of the
2052 working directory with a new commit that contains the changes
2052 working directory with a new commit that contains the changes
2053 in the parent in addition to those currently reported by :hg:`status`,
2053 in the parent in addition to those currently reported by :hg:`status`,
2054 if there are any. The old commit is stored in a backup bundle in
2054 if there are any. The old commit is stored in a backup bundle in
2055 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
2055 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
2056 on how to restore it).
2056 on how to restore it).
2057
2057
2058 Message, user and date are taken from the amended commit unless
2058 Message, user and date are taken from the amended commit unless
2059 specified. When a message isn't specified on the command line,
2059 specified. When a message isn't specified on the command line,
2060 the editor will open with the message of the amended commit.
2060 the editor will open with the message of the amended commit.
2061
2061
2062 It is not possible to amend public changesets (see :hg:`help phases`)
2062 It is not possible to amend public changesets (see :hg:`help phases`)
2063 or changesets that have children.
2063 or changesets that have children.
2064
2064
2065 See :hg:`help dates` for a list of formats valid for -d/--date.
2065 See :hg:`help dates` for a list of formats valid for -d/--date.
2066
2066
2067 Returns 0 on success, 1 if nothing changed.
2067 Returns 0 on success, 1 if nothing changed.
2068
2068
2069 .. container:: verbose
2069 .. container:: verbose
2070
2070
2071 Examples:
2071 Examples:
2072
2072
2073 - commit all files ending in .py::
2073 - commit all files ending in .py::
2074
2074
2075 hg commit --include "set:**.py"
2075 hg commit --include "set:**.py"
2076
2076
2077 - commit all non-binary files::
2077 - commit all non-binary files::
2078
2078
2079 hg commit --exclude "set:binary()"
2079 hg commit --exclude "set:binary()"
2080
2080
2081 - amend the current commit and set the date to now::
2081 - amend the current commit and set the date to now::
2082
2082
2083 hg commit --amend --date now
2083 hg commit --amend --date now
2084 """
2084 """
2085 with repo.wlock(), repo.lock():
2085 with repo.wlock(), repo.lock():
2086 return _docommit(ui, repo, *pats, **opts)
2086 return _docommit(ui, repo, *pats, **opts)
2087
2087
2088
2088
2089 def _docommit(ui, repo, *pats, **opts):
2089 def _docommit(ui, repo, *pats, **opts):
2090 if opts.get('interactive'):
2090 if opts.get('interactive'):
2091 opts.pop('interactive')
2091 opts.pop('interactive')
2092 ret = cmdutil.dorecord(
2092 ret = cmdutil.dorecord(
2093 ui, repo, commit, None, False, cmdutil.recordfilter, *pats, **opts
2093 ui, repo, commit, None, False, cmdutil.recordfilter, *pats, **opts
2094 )
2094 )
2095 # ret can be 0 (no changes to record) or the value returned by
2095 # ret can be 0 (no changes to record) or the value returned by
2096 # commit(), 1 if nothing changed or None on success.
2096 # commit(), 1 if nothing changed or None on success.
2097 return 1 if ret == 0 else ret
2097 return 1 if ret == 0 else ret
2098
2098
2099 if opts.get('subrepos'):
2099 if opts.get('subrepos'):
2100 cmdutil.check_incompatible_arguments(opts, 'subrepos', ['amend'])
2100 cmdutil.check_incompatible_arguments(opts, 'subrepos', ['amend'])
2101 # Let --subrepos on the command line override config setting.
2101 # Let --subrepos on the command line override config setting.
2102 ui.setconfig(b'ui', b'commitsubrepos', True, b'commit')
2102 ui.setconfig(b'ui', b'commitsubrepos', True, b'commit')
2103
2103
2104 cmdutil.checkunfinished(repo, commit=True)
2104 cmdutil.checkunfinished(repo, commit=True)
2105
2105
2106 branch = repo[None].branch()
2106 branch = repo[None].branch()
2107 bheads = repo.branchheads(branch)
2107 bheads = repo.branchheads(branch)
2108 tip = repo.changelog.tip()
2108 tip = repo.changelog.tip()
2109
2109
2110 extra = {}
2110 extra = {}
2111 if opts.get('close_branch') or opts.get('force_close_branch'):
2111 if opts.get('close_branch') or opts.get('force_close_branch'):
2112 extra[b'close'] = b'1'
2112 extra[b'close'] = b'1'
2113
2113
2114 if repo[b'.'].closesbranch():
2114 if repo[b'.'].closesbranch():
2115 # Not ideal, but let us do an extra status early to prevent early
2115 # Not ideal, but let us do an extra status early to prevent early
2116 # bail out.
2116 # bail out.
2117 matcher = scmutil.match(
2117 matcher = scmutil.match(
2118 repo[None], pats, pycompat.byteskwargs(opts)
2118 repo[None], pats, pycompat.byteskwargs(opts)
2119 )
2119 )
2120 s = repo.status(match=matcher)
2120 s = repo.status(match=matcher)
2121 if s.modified or s.added or s.removed:
2121 if s.modified or s.added or s.removed:
2122 bheads = repo.branchheads(branch, closed=True)
2122 bheads = repo.branchheads(branch, closed=True)
2123 else:
2123 else:
2124 msg = _(b'current revision is already a branch closing head')
2124 msg = _(b'current revision is already a branch closing head')
2125 raise error.InputError(msg)
2125 raise error.InputError(msg)
2126
2126
2127 if not bheads:
2127 if not bheads:
2128 raise error.InputError(
2128 raise error.InputError(
2129 _(b'branch "%s" has no heads to close') % branch
2129 _(b'branch "%s" has no heads to close') % branch
2130 )
2130 )
2131 elif (
2131 elif (
2132 branch == repo[b'.'].branch()
2132 branch == repo[b'.'].branch()
2133 and repo[b'.'].node() not in bheads
2133 and repo[b'.'].node() not in bheads
2134 and not opts.get('force_close_branch')
2134 and not opts.get('force_close_branch')
2135 ):
2135 ):
2136 hint = _(
2136 hint = _(
2137 b'use --force-close-branch to close branch from a non-head'
2137 b'use --force-close-branch to close branch from a non-head'
2138 b' changeset'
2138 b' changeset'
2139 )
2139 )
2140 raise error.InputError(_(b'can only close branch heads'), hint=hint)
2140 raise error.InputError(_(b'can only close branch heads'), hint=hint)
2141 elif opts.get('amend'):
2141 elif opts.get('amend'):
2142 if (
2142 if (
2143 repo[b'.'].p1().branch() != branch
2143 repo[b'.'].p1().branch() != branch
2144 and repo[b'.'].p2().branch() != branch
2144 and repo[b'.'].p2().branch() != branch
2145 ):
2145 ):
2146 raise error.InputError(_(b'can only close branch heads'))
2146 raise error.InputError(_(b'can only close branch heads'))
2147
2147
2148 if opts.get('amend'):
2148 if opts.get('amend'):
2149 if ui.configbool(b'ui', b'commitsubrepos'):
2149 if ui.configbool(b'ui', b'commitsubrepos'):
2150 raise error.InputError(
2150 raise error.InputError(
2151 _(b'cannot amend with ui.commitsubrepos enabled')
2151 _(b'cannot amend with ui.commitsubrepos enabled')
2152 )
2152 )
2153
2153
2154 old = repo[b'.']
2154 old = repo[b'.']
2155 rewriteutil.precheck(repo, [old.rev()], b'amend')
2155 rewriteutil.precheck(repo, [old.rev()], b'amend')
2156
2156
2157 # Currently histedit gets confused if an amend happens while histedit
2157 # Currently histedit gets confused if an amend happens while histedit
2158 # is in progress. Since we have a checkunfinished command, we are
2158 # is in progress. Since we have a checkunfinished command, we are
2159 # temporarily honoring it.
2159 # temporarily honoring it.
2160 #
2160 #
2161 # Note: eventually this guard will be removed. Please do not expect
2161 # Note: eventually this guard will be removed. Please do not expect
2162 # this behavior to remain.
2162 # this behavior to remain.
2163 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
2163 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
2164 cmdutil.checkunfinished(repo)
2164 cmdutil.checkunfinished(repo)
2165
2165
2166 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
2166 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
2167 opts = pycompat.byteskwargs(opts)
2167 opts = pycompat.byteskwargs(opts)
2168 if node == old.node():
2168 if node == old.node():
2169 ui.status(_(b"nothing changed\n"))
2169 ui.status(_(b"nothing changed\n"))
2170 return 1
2170 return 1
2171 else:
2171 else:
2172
2172
2173 def commitfunc(ui, repo, message, match, opts):
2173 def commitfunc(ui, repo, message, match, opts):
2174 overrides = {}
2174 overrides = {}
2175 if opts.get(b'secret'):
2175 if opts.get(b'secret'):
2176 overrides[(b'phases', b'new-commit')] = b'secret'
2176 overrides[(b'phases', b'new-commit')] = b'secret'
2177
2177
2178 baseui = repo.baseui
2178 baseui = repo.baseui
2179 with baseui.configoverride(overrides, b'commit'):
2179 with baseui.configoverride(overrides, b'commit'):
2180 with ui.configoverride(overrides, b'commit'):
2180 with ui.configoverride(overrides, b'commit'):
2181 editform = cmdutil.mergeeditform(
2181 editform = cmdutil.mergeeditform(
2182 repo[None], b'commit.normal'
2182 repo[None], b'commit.normal'
2183 )
2183 )
2184 editor = cmdutil.getcommiteditor(
2184 editor = cmdutil.getcommiteditor(
2185 editform=editform, **pycompat.strkwargs(opts)
2185 editform=editform, **pycompat.strkwargs(opts)
2186 )
2186 )
2187 return repo.commit(
2187 return repo.commit(
2188 message,
2188 message,
2189 opts.get(b'user'),
2189 opts.get(b'user'),
2190 opts.get(b'date'),
2190 opts.get(b'date'),
2191 match,
2191 match,
2192 editor=editor,
2192 editor=editor,
2193 extra=extra,
2193 extra=extra,
2194 )
2194 )
2195
2195
2196 opts = pycompat.byteskwargs(opts)
2196 opts = pycompat.byteskwargs(opts)
2197 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
2197 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
2198
2198
2199 if not node:
2199 if not node:
2200 stat = cmdutil.postcommitstatus(repo, pats, opts)
2200 stat = cmdutil.postcommitstatus(repo, pats, opts)
2201 if stat.deleted:
2201 if stat.deleted:
2202 ui.status(
2202 ui.status(
2203 _(
2203 _(
2204 b"nothing changed (%d missing files, see "
2204 b"nothing changed (%d missing files, see "
2205 b"'hg status')\n"
2205 b"'hg status')\n"
2206 )
2206 )
2207 % len(stat.deleted)
2207 % len(stat.deleted)
2208 )
2208 )
2209 else:
2209 else:
2210 ui.status(_(b"nothing changed\n"))
2210 ui.status(_(b"nothing changed\n"))
2211 return 1
2211 return 1
2212
2212
2213 cmdutil.commitstatus(repo, node, branch, bheads, tip, opts)
2213 cmdutil.commitstatus(repo, node, branch, bheads, tip, opts)
2214
2214
2215 if not ui.quiet and ui.configbool(b'commands', b'commit.post-status'):
2215 if not ui.quiet and ui.configbool(b'commands', b'commit.post-status'):
2216 status(
2216 status(
2217 ui,
2217 ui,
2218 repo,
2218 repo,
2219 modified=True,
2219 modified=True,
2220 added=True,
2220 added=True,
2221 removed=True,
2221 removed=True,
2222 deleted=True,
2222 deleted=True,
2223 unknown=True,
2223 unknown=True,
2224 subrepos=opts.get(b'subrepos'),
2224 subrepos=opts.get(b'subrepos'),
2225 )
2225 )
2226
2226
2227
2227
2228 @command(
2228 @command(
2229 b'config|showconfig|debugconfig',
2229 b'config|showconfig|debugconfig',
2230 [
2230 [
2231 (b'u', b'untrusted', None, _(b'show untrusted configuration options')),
2231 (b'u', b'untrusted', None, _(b'show untrusted configuration options')),
2232 # This is experimental because we need
2232 # This is experimental because we need
2233 # * reasonable behavior around aliases,
2233 # * reasonable behavior around aliases,
2234 # * decide if we display [debug] [experimental] and [devel] section par
2234 # * decide if we display [debug] [experimental] and [devel] section par
2235 # default
2235 # default
2236 # * some way to display "generic" config entry (the one matching
2236 # * some way to display "generic" config entry (the one matching
2237 # regexp,
2237 # regexp,
2238 # * proper display of the different value type
2238 # * proper display of the different value type
2239 # * a better way to handle <DYNAMIC> values (and variable types),
2239 # * a better way to handle <DYNAMIC> values (and variable types),
2240 # * maybe some type information ?
2240 # * maybe some type information ?
2241 (
2241 (
2242 b'',
2242 b'',
2243 b'exp-all-known',
2243 b'exp-all-known',
2244 None,
2244 None,
2245 _(b'show all known config option (EXPERIMENTAL)'),
2245 _(b'show all known config option (EXPERIMENTAL)'),
2246 ),
2246 ),
2247 (b'e', b'edit', None, _(b'edit user config')),
2247 (b'e', b'edit', None, _(b'edit user config')),
2248 (b'l', b'local', None, _(b'edit repository config')),
2248 (b'l', b'local', None, _(b'edit repository config')),
2249 (b'', b'source', None, _(b'show source of configuration value')),
2249 (b'', b'source', None, _(b'show source of configuration value')),
2250 (
2250 (
2251 b'',
2251 b'',
2252 b'shared',
2252 b'shared',
2253 None,
2253 None,
2254 _(b'edit shared source repository config (EXPERIMENTAL)'),
2254 _(b'edit shared source repository config (EXPERIMENTAL)'),
2255 ),
2255 ),
2256 (b'', b'non-shared', None, _(b'edit non shared config (EXPERIMENTAL)')),
2256 (b'', b'non-shared', None, _(b'edit non shared config (EXPERIMENTAL)')),
2257 (b'g', b'global', None, _(b'edit global config')),
2257 (b'g', b'global', None, _(b'edit global config')),
2258 ]
2258 ]
2259 + formatteropts,
2259 + formatteropts,
2260 _(b'[-u] [NAME]...'),
2260 _(b'[-u] [NAME]...'),
2261 helpcategory=command.CATEGORY_HELP,
2261 helpcategory=command.CATEGORY_HELP,
2262 optionalrepo=True,
2262 optionalrepo=True,
2263 intents={INTENT_READONLY},
2263 intents={INTENT_READONLY},
2264 )
2264 )
2265 def config(ui, repo, *values, **opts):
2265 def config(ui, repo, *values, **opts):
2266 """show combined config settings from all hgrc files
2266 """show combined config settings from all hgrc files
2267
2267
2268 With no arguments, print names and values of all config items.
2268 With no arguments, print names and values of all config items.
2269
2269
2270 With one argument of the form section.name, print just the value
2270 With one argument of the form section.name, print just the value
2271 of that config item.
2271 of that config item.
2272
2272
2273 With multiple arguments, print names and values of all config
2273 With multiple arguments, print names and values of all config
2274 items with matching section names or section.names.
2274 items with matching section names or section.names.
2275
2275
2276 With --edit, start an editor on the user-level config file. With
2276 With --edit, start an editor on the user-level config file. With
2277 --global, edit the system-wide config file. With --local, edit the
2277 --global, edit the system-wide config file. With --local, edit the
2278 repository-level config file.
2278 repository-level config file.
2279
2279
2280 With --source, the source (filename and line number) is printed
2280 With --source, the source (filename and line number) is printed
2281 for each config item.
2281 for each config item.
2282
2282
2283 See :hg:`help config` for more information about config files.
2283 See :hg:`help config` for more information about config files.
2284
2284
2285 .. container:: verbose
2285 .. container:: verbose
2286
2286
2287 --non-shared flag is used to edit `.hg/hgrc-not-shared` config file.
2287 --non-shared flag is used to edit `.hg/hgrc-not-shared` config file.
2288 This file is not shared across shares when in share-safe mode.
2288 This file is not shared across shares when in share-safe mode.
2289
2289
2290 Template:
2290 Template:
2291
2291
2292 The following keywords are supported. See also :hg:`help templates`.
2292 The following keywords are supported. See also :hg:`help templates`.
2293
2293
2294 :name: String. Config name.
2294 :name: String. Config name.
2295 :source: String. Filename and line number where the item is defined.
2295 :source: String. Filename and line number where the item is defined.
2296 :value: String. Config value.
2296 :value: String. Config value.
2297
2297
2298 The --shared flag can be used to edit the config file of shared source
2298 The --shared flag can be used to edit the config file of shared source
2299 repository. It only works when you have shared using the experimental
2299 repository. It only works when you have shared using the experimental
2300 share safe feature.
2300 share safe feature.
2301
2301
2302 Returns 0 on success, 1 if NAME does not exist.
2302 Returns 0 on success, 1 if NAME does not exist.
2303
2303
2304 """
2304 """
2305
2305
2306 opts = pycompat.byteskwargs(opts)
2306 opts = pycompat.byteskwargs(opts)
2307 editopts = (b'edit', b'local', b'global', b'shared', b'non_shared')
2307 editopts = (b'edit', b'local', b'global', b'shared', b'non_shared')
2308 if any(opts.get(o) for o in editopts):
2308 if any(opts.get(o) for o in editopts):
2309 cmdutil.check_at_most_one_arg(opts, *editopts[1:])
2309 cmdutil.check_at_most_one_arg(opts, *editopts[1:])
2310 if opts.get(b'local'):
2310 if opts.get(b'local'):
2311 if not repo:
2311 if not repo:
2312 raise error.InputError(
2312 raise error.InputError(
2313 _(b"can't use --local outside a repository")
2313 _(b"can't use --local outside a repository")
2314 )
2314 )
2315 paths = [repo.vfs.join(b'hgrc')]
2315 paths = [repo.vfs.join(b'hgrc')]
2316 elif opts.get(b'global'):
2316 elif opts.get(b'global'):
2317 paths = rcutil.systemrcpath()
2317 paths = rcutil.systemrcpath()
2318 elif opts.get(b'shared'):
2318 elif opts.get(b'shared'):
2319 if not repo.shared():
2319 if not repo.shared():
2320 raise error.InputError(
2320 raise error.InputError(
2321 _(b"repository is not shared; can't use --shared")
2321 _(b"repository is not shared; can't use --shared")
2322 )
2322 )
2323 if requirements.SHARESAFE_REQUIREMENT not in repo.requirements:
2323 if requirements.SHARESAFE_REQUIREMENT not in repo.requirements:
2324 raise error.InputError(
2324 raise error.InputError(
2325 _(
2325 _(
2326 b"share safe feature not enabled; "
2326 b"share safe feature not enabled; "
2327 b"unable to edit shared source repository config"
2327 b"unable to edit shared source repository config"
2328 )
2328 )
2329 )
2329 )
2330 paths = [vfsmod.vfs(repo.sharedpath).join(b'hgrc')]
2330 paths = [vfsmod.vfs(repo.sharedpath).join(b'hgrc')]
2331 elif opts.get(b'non_shared'):
2331 elif opts.get(b'non_shared'):
2332 paths = [repo.vfs.join(b'hgrc-not-shared')]
2332 paths = [repo.vfs.join(b'hgrc-not-shared')]
2333 else:
2333 else:
2334 paths = rcutil.userrcpath()
2334 paths = rcutil.userrcpath()
2335
2335
2336 for f in paths:
2336 for f in paths:
2337 if os.path.exists(f):
2337 if os.path.exists(f):
2338 break
2338 break
2339 else:
2339 else:
2340 if opts.get(b'global'):
2340 if opts.get(b'global'):
2341 samplehgrc = uimod.samplehgrcs[b'global']
2341 samplehgrc = uimod.samplehgrcs[b'global']
2342 elif opts.get(b'local'):
2342 elif opts.get(b'local'):
2343 samplehgrc = uimod.samplehgrcs[b'local']
2343 samplehgrc = uimod.samplehgrcs[b'local']
2344 else:
2344 else:
2345 samplehgrc = uimod.samplehgrcs[b'user']
2345 samplehgrc = uimod.samplehgrcs[b'user']
2346
2346
2347 f = paths[0]
2347 f = paths[0]
2348 fp = open(f, b"wb")
2348 fp = open(f, b"wb")
2349 fp.write(util.tonativeeol(samplehgrc))
2349 fp.write(util.tonativeeol(samplehgrc))
2350 fp.close()
2350 fp.close()
2351
2351
2352 editor = ui.geteditor()
2352 editor = ui.geteditor()
2353 ui.system(
2353 ui.system(
2354 b"%s \"%s\"" % (editor, f),
2354 b"%s \"%s\"" % (editor, f),
2355 onerr=error.InputError,
2355 onerr=error.InputError,
2356 errprefix=_(b"edit failed"),
2356 errprefix=_(b"edit failed"),
2357 blockedtag=b'config_edit',
2357 blockedtag=b'config_edit',
2358 )
2358 )
2359 return
2359 return
2360 ui.pager(b'config')
2360 ui.pager(b'config')
2361 fm = ui.formatter(b'config', opts)
2361 fm = ui.formatter(b'config', opts)
2362 for t, f in rcutil.rccomponents():
2362 for t, f in rcutil.rccomponents():
2363 if t == b'path':
2363 if t == b'path':
2364 ui.debug(b'read config from: %s\n' % f)
2364 ui.debug(b'read config from: %s\n' % f)
2365 elif t == b'resource':
2365 elif t == b'resource':
2366 ui.debug(b'read config from: resource:%s.%s\n' % (f[0], f[1]))
2366 ui.debug(b'read config from: resource:%s.%s\n' % (f[0], f[1]))
2367 elif t == b'items':
2367 elif t == b'items':
2368 # Don't print anything for 'items'.
2368 # Don't print anything for 'items'.
2369 pass
2369 pass
2370 else:
2370 else:
2371 raise error.ProgrammingError(b'unknown rctype: %s' % t)
2371 raise error.ProgrammingError(b'unknown rctype: %s' % t)
2372 untrusted = bool(opts.get(b'untrusted'))
2372 untrusted = bool(opts.get(b'untrusted'))
2373
2373
2374 selsections = selentries = []
2374 selsections = selentries = []
2375 if values:
2375 if values:
2376 selsections = [v for v in values if b'.' not in v]
2376 selsections = [v for v in values if b'.' not in v]
2377 selentries = [v for v in values if b'.' in v]
2377 selentries = [v for v in values if b'.' in v]
2378 uniquesel = len(selentries) == 1 and not selsections
2378 uniquesel = len(selentries) == 1 and not selsections
2379 selsections = set(selsections)
2379 selsections = set(selsections)
2380 selentries = set(selentries)
2380 selentries = set(selentries)
2381
2381
2382 matched = False
2382 matched = False
2383 all_known = opts[b'exp_all_known']
2383 all_known = opts[b'exp_all_known']
2384 show_source = ui.debugflag or opts.get(b'source')
2384 show_source = ui.debugflag or opts.get(b'source')
2385 entries = ui.walkconfig(untrusted=untrusted, all_known=all_known)
2385 entries = ui.walkconfig(untrusted=untrusted, all_known=all_known)
2386 for section, name, value in entries:
2386 for section, name, value in entries:
2387 source = ui.configsource(section, name, untrusted)
2387 source = ui.configsource(section, name, untrusted)
2388 value = pycompat.bytestr(value)
2388 value = pycompat.bytestr(value)
2389 defaultvalue = ui.configdefault(section, name)
2389 defaultvalue = ui.configdefault(section, name)
2390 if fm.isplain():
2390 if fm.isplain():
2391 source = source or b'none'
2391 source = source or b'none'
2392 value = value.replace(b'\n', b'\\n')
2392 value = value.replace(b'\n', b'\\n')
2393 entryname = section + b'.' + name
2393 entryname = section + b'.' + name
2394 if values and not (section in selsections or entryname in selentries):
2394 if values and not (section in selsections or entryname in selentries):
2395 continue
2395 continue
2396 fm.startitem()
2396 fm.startitem()
2397 fm.condwrite(show_source, b'source', b'%s: ', source)
2397 fm.condwrite(show_source, b'source', b'%s: ', source)
2398 if uniquesel:
2398 if uniquesel:
2399 fm.data(name=entryname)
2399 fm.data(name=entryname)
2400 fm.write(b'value', b'%s\n', value)
2400 fm.write(b'value', b'%s\n', value)
2401 else:
2401 else:
2402 fm.write(b'name value', b'%s=%s\n', entryname, value)
2402 fm.write(b'name value', b'%s=%s\n', entryname, value)
2403 if formatter.isprintable(defaultvalue):
2403 if formatter.isprintable(defaultvalue):
2404 fm.data(defaultvalue=defaultvalue)
2404 fm.data(defaultvalue=defaultvalue)
2405 elif isinstance(defaultvalue, list) and all(
2405 elif isinstance(defaultvalue, list) and all(
2406 formatter.isprintable(e) for e in defaultvalue
2406 formatter.isprintable(e) for e in defaultvalue
2407 ):
2407 ):
2408 fm.data(defaultvalue=fm.formatlist(defaultvalue, name=b'value'))
2408 fm.data(defaultvalue=fm.formatlist(defaultvalue, name=b'value'))
2409 # TODO: no idea how to process unsupported defaultvalue types
2409 # TODO: no idea how to process unsupported defaultvalue types
2410 matched = True
2410 matched = True
2411 fm.end()
2411 fm.end()
2412 if matched:
2412 if matched:
2413 return 0
2413 return 0
2414 return 1
2414 return 1
2415
2415
2416
2416
2417 @command(
2417 @command(
2418 b'continue',
2418 b'continue',
2419 dryrunopts,
2419 dryrunopts,
2420 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
2420 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
2421 helpbasic=True,
2421 helpbasic=True,
2422 )
2422 )
2423 def continuecmd(ui, repo, **opts):
2423 def continuecmd(ui, repo, **opts):
2424 """resumes an interrupted operation (EXPERIMENTAL)
2424 """resumes an interrupted operation (EXPERIMENTAL)
2425
2425
2426 Finishes a multistep operation like graft, histedit, rebase, merge,
2426 Finishes a multistep operation like graft, histedit, rebase, merge,
2427 and unshelve if they are in an interrupted state.
2427 and unshelve if they are in an interrupted state.
2428
2428
2429 use --dry-run/-n to dry run the command.
2429 use --dry-run/-n to dry run the command.
2430 """
2430 """
2431 dryrun = opts.get('dry_run')
2431 dryrun = opts.get('dry_run')
2432 contstate = cmdutil.getunfinishedstate(repo)
2432 contstate = cmdutil.getunfinishedstate(repo)
2433 if not contstate:
2433 if not contstate:
2434 raise error.StateError(_(b'no operation in progress'))
2434 raise error.StateError(_(b'no operation in progress'))
2435 if not contstate.continuefunc:
2435 if not contstate.continuefunc:
2436 raise error.StateError(
2436 raise error.StateError(
2437 (
2437 (
2438 _(b"%s in progress but does not support 'hg continue'")
2438 _(b"%s in progress but does not support 'hg continue'")
2439 % (contstate._opname)
2439 % (contstate._opname)
2440 ),
2440 ),
2441 hint=contstate.continuemsg(),
2441 hint=contstate.continuemsg(),
2442 )
2442 )
2443 if dryrun:
2443 if dryrun:
2444 ui.status(_(b'%s in progress, will be resumed\n') % (contstate._opname))
2444 ui.status(_(b'%s in progress, will be resumed\n') % (contstate._opname))
2445 return
2445 return
2446 return contstate.continuefunc(ui, repo)
2446 return contstate.continuefunc(ui, repo)
2447
2447
2448
2448
2449 @command(
2449 @command(
2450 b'copy|cp',
2450 b'copy|cp',
2451 [
2451 [
2452 (b'', b'forget', None, _(b'unmark a destination file as copied')),
2452 (b'', b'forget', None, _(b'unmark a destination file as copied')),
2453 (b'A', b'after', None, _(b'record a copy that has already occurred')),
2453 (b'A', b'after', None, _(b'record a copy that has already occurred')),
2454 (
2454 (
2455 b'',
2455 b'',
2456 b'at-rev',
2456 b'at-rev',
2457 b'',
2457 b'',
2458 _(b'(un)mark copies in the given revision (EXPERIMENTAL)'),
2458 _(b'(un)mark copies in the given revision (EXPERIMENTAL)'),
2459 _(b'REV'),
2459 _(b'REV'),
2460 ),
2460 ),
2461 (
2461 (
2462 b'f',
2462 b'f',
2463 b'force',
2463 b'force',
2464 None,
2464 None,
2465 _(b'forcibly copy over an existing managed file'),
2465 _(b'forcibly copy over an existing managed file'),
2466 ),
2466 ),
2467 ]
2467 ]
2468 + walkopts
2468 + walkopts
2469 + dryrunopts,
2469 + dryrunopts,
2470 _(b'[OPTION]... (SOURCE... DEST | --forget DEST...)'),
2470 _(b'[OPTION]... (SOURCE... DEST | --forget DEST...)'),
2471 helpcategory=command.CATEGORY_FILE_CONTENTS,
2471 helpcategory=command.CATEGORY_FILE_CONTENTS,
2472 )
2472 )
2473 def copy(ui, repo, *pats, **opts):
2473 def copy(ui, repo, *pats, **opts):
2474 """mark files as copied for the next commit
2474 """mark files as copied for the next commit
2475
2475
2476 Mark dest as having copies of source files. If dest is a
2476 Mark dest as having copies of source files. If dest is a
2477 directory, copies are put in that directory. If dest is a file,
2477 directory, copies are put in that directory. If dest is a file,
2478 the source must be a single file.
2478 the source must be a single file.
2479
2479
2480 By default, this command copies the contents of files as they
2480 By default, this command copies the contents of files as they
2481 exist in the working directory. If invoked with -A/--after, the
2481 exist in the working directory. If invoked with -A/--after, the
2482 operation is recorded, but no copying is performed.
2482 operation is recorded, but no copying is performed.
2483
2483
2484 To undo marking a destination file as copied, use --forget. With that
2484 To undo marking a destination file as copied, use --forget. With that
2485 option, all given (positional) arguments are unmarked as copies. The
2485 option, all given (positional) arguments are unmarked as copies. The
2486 destination file(s) will be left in place (still tracked). Note that
2486 destination file(s) will be left in place (still tracked). Note that
2487 :hg:`copy --forget` behaves the same way as :hg:`rename --forget`.
2487 :hg:`copy --forget` behaves the same way as :hg:`rename --forget`.
2488
2488
2489 This command takes effect with the next commit by default.
2489 This command takes effect with the next commit by default.
2490
2490
2491 Returns 0 on success, 1 if errors are encountered.
2491 Returns 0 on success, 1 if errors are encountered.
2492 """
2492 """
2493 opts = pycompat.byteskwargs(opts)
2493 opts = pycompat.byteskwargs(opts)
2494 with repo.wlock():
2494 with repo.wlock():
2495 return cmdutil.copy(ui, repo, pats, opts)
2495 return cmdutil.copy(ui, repo, pats, opts)
2496
2496
2497
2497
2498 @command(
2498 @command(
2499 b'debugcommands',
2499 b'debugcommands',
2500 [],
2500 [],
2501 _(b'[COMMAND]'),
2501 _(b'[COMMAND]'),
2502 helpcategory=command.CATEGORY_HELP,
2502 helpcategory=command.CATEGORY_HELP,
2503 norepo=True,
2503 norepo=True,
2504 )
2504 )
2505 def debugcommands(ui, cmd=b'', *args):
2505 def debugcommands(ui, cmd=b'', *args):
2506 """list all available commands and options"""
2506 """list all available commands and options"""
2507 for cmd, vals in sorted(table.items()):
2507 for cmd, vals in sorted(table.items()):
2508 cmd = cmd.split(b'|')[0]
2508 cmd = cmd.split(b'|')[0]
2509 opts = b', '.join([i[1] for i in vals[1]])
2509 opts = b', '.join([i[1] for i in vals[1]])
2510 ui.write(b'%s: %s\n' % (cmd, opts))
2510 ui.write(b'%s: %s\n' % (cmd, opts))
2511
2511
2512
2512
2513 @command(
2513 @command(
2514 b'debugcomplete',
2514 b'debugcomplete',
2515 [(b'o', b'options', None, _(b'show the command options'))],
2515 [(b'o', b'options', None, _(b'show the command options'))],
2516 _(b'[-o] CMD'),
2516 _(b'[-o] CMD'),
2517 helpcategory=command.CATEGORY_HELP,
2517 helpcategory=command.CATEGORY_HELP,
2518 norepo=True,
2518 norepo=True,
2519 )
2519 )
2520 def debugcomplete(ui, cmd=b'', **opts):
2520 def debugcomplete(ui, cmd=b'', **opts):
2521 """returns the completion list associated with the given command"""
2521 """returns the completion list associated with the given command"""
2522
2522
2523 if opts.get('options'):
2523 if opts.get('options'):
2524 options = []
2524 options = []
2525 otables = [globalopts]
2525 otables = [globalopts]
2526 if cmd:
2526 if cmd:
2527 aliases, entry = cmdutil.findcmd(cmd, table, False)
2527 aliases, entry = cmdutil.findcmd(cmd, table, False)
2528 otables.append(entry[1])
2528 otables.append(entry[1])
2529 for t in otables:
2529 for t in otables:
2530 for o in t:
2530 for o in t:
2531 if b"(DEPRECATED)" in o[3]:
2531 if b"(DEPRECATED)" in o[3]:
2532 continue
2532 continue
2533 if o[0]:
2533 if o[0]:
2534 options.append(b'-%s' % o[0])
2534 options.append(b'-%s' % o[0])
2535 options.append(b'--%s' % o[1])
2535 options.append(b'--%s' % o[1])
2536 ui.write(b"%s\n" % b"\n".join(options))
2536 ui.write(b"%s\n" % b"\n".join(options))
2537 return
2537 return
2538
2538
2539 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
2539 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
2540 if ui.verbose:
2540 if ui.verbose:
2541 cmdlist = [b' '.join(c[0]) for c in cmdlist.values()]
2541 cmdlist = [b' '.join(c[0]) for c in cmdlist.values()]
2542 ui.write(b"%s\n" % b"\n".join(sorted(cmdlist)))
2542 ui.write(b"%s\n" % b"\n".join(sorted(cmdlist)))
2543
2543
2544
2544
2545 @command(
2545 @command(
2546 b'diff',
2546 b'diff',
2547 [
2547 [
2548 (b'r', b'rev', [], _(b'revision (DEPRECATED)'), _(b'REV')),
2548 (b'r', b'rev', [], _(b'revision (DEPRECATED)'), _(b'REV')),
2549 (b'', b'from', b'', _(b'revision to diff from'), _(b'REV1')),
2549 (b'', b'from', b'', _(b'revision to diff from'), _(b'REV1')),
2550 (b'', b'to', b'', _(b'revision to diff to'), _(b'REV2')),
2550 (b'', b'to', b'', _(b'revision to diff to'), _(b'REV2')),
2551 (b'c', b'change', b'', _(b'change made by revision'), _(b'REV')),
2551 (b'c', b'change', b'', _(b'change made by revision'), _(b'REV')),
2552 ]
2552 ]
2553 + diffopts
2553 + diffopts
2554 + diffopts2
2554 + diffopts2
2555 + walkopts
2555 + walkopts
2556 + subrepoopts,
2556 + subrepoopts,
2557 _(b'[OPTION]... ([-c REV] | [--from REV1] [--to REV2]) [FILE]...'),
2557 _(b'[OPTION]... ([-c REV] | [--from REV1] [--to REV2]) [FILE]...'),
2558 helpcategory=command.CATEGORY_FILE_CONTENTS,
2558 helpcategory=command.CATEGORY_FILE_CONTENTS,
2559 helpbasic=True,
2559 helpbasic=True,
2560 inferrepo=True,
2560 inferrepo=True,
2561 intents={INTENT_READONLY},
2561 intents={INTENT_READONLY},
2562 )
2562 )
2563 def diff(ui, repo, *pats, **opts):
2563 def diff(ui, repo, *pats, **opts):
2564 """diff repository (or selected files)
2564 """diff repository (or selected files)
2565
2565
2566 Show differences between revisions for the specified files.
2566 Show differences between revisions for the specified files.
2567
2567
2568 Differences between files are shown using the unified diff format.
2568 Differences between files are shown using the unified diff format.
2569
2569
2570 .. note::
2570 .. note::
2571
2571
2572 :hg:`diff` may generate unexpected results for merges, as it will
2572 :hg:`diff` may generate unexpected results for merges, as it will
2573 default to comparing against the working directory's first
2573 default to comparing against the working directory's first
2574 parent changeset if no revisions are specified. To diff against the
2574 parent changeset if no revisions are specified. To diff against the
2575 conflict regions, you can use `--config diff.merge=yes`.
2575 conflict regions, you can use `--config diff.merge=yes`.
2576
2576
2577 By default, the working directory files are compared to its first parent. To
2577 By default, the working directory files are compared to its first parent. To
2578 see the differences from another revision, use --from. To see the difference
2578 see the differences from another revision, use --from. To see the difference
2579 to another revision, use --to. For example, :hg:`diff --from .^` will show
2579 to another revision, use --to. For example, :hg:`diff --from .^` will show
2580 the differences from the working copy's grandparent to the working copy,
2580 the differences from the working copy's grandparent to the working copy,
2581 :hg:`diff --to .` will show the diff from the working copy to its parent
2581 :hg:`diff --to .` will show the diff from the working copy to its parent
2582 (i.e. the reverse of the default), and :hg:`diff --from 1.0 --to 1.2` will
2582 (i.e. the reverse of the default), and :hg:`diff --from 1.0 --to 1.2` will
2583 show the diff between those two revisions.
2583 show the diff between those two revisions.
2584
2584
2585 Alternatively you can specify -c/--change with a revision to see the changes
2585 Alternatively you can specify -c/--change with a revision to see the changes
2586 in that changeset relative to its first parent (i.e. :hg:`diff -c 42` is
2586 in that changeset relative to its first parent (i.e. :hg:`diff -c 42` is
2587 equivalent to :hg:`diff --from 42^ --to 42`)
2587 equivalent to :hg:`diff --from 42^ --to 42`)
2588
2588
2589 Without the -a/--text option, diff will avoid generating diffs of
2589 Without the -a/--text option, diff will avoid generating diffs of
2590 files it detects as binary. With -a, diff will generate a diff
2590 files it detects as binary. With -a, diff will generate a diff
2591 anyway, probably with undesirable results.
2591 anyway, probably with undesirable results.
2592
2592
2593 Use the -g/--git option to generate diffs in the git extended diff
2593 Use the -g/--git option to generate diffs in the git extended diff
2594 format. For more information, read :hg:`help diffs`.
2594 format. For more information, read :hg:`help diffs`.
2595
2595
2596 .. container:: verbose
2596 .. container:: verbose
2597
2597
2598 Examples:
2598 Examples:
2599
2599
2600 - compare a file in the current working directory to its parent::
2600 - compare a file in the current working directory to its parent::
2601
2601
2602 hg diff foo.c
2602 hg diff foo.c
2603
2603
2604 - compare two historical versions of a directory, with rename info::
2604 - compare two historical versions of a directory, with rename info::
2605
2605
2606 hg diff --git --from 1.0 --to 1.2 lib/
2606 hg diff --git --from 1.0 --to 1.2 lib/
2607
2607
2608 - get change stats relative to the last change on some date::
2608 - get change stats relative to the last change on some date::
2609
2609
2610 hg diff --stat --from "date('may 2')"
2610 hg diff --stat --from "date('may 2')"
2611
2611
2612 - diff all newly-added files that contain a keyword::
2612 - diff all newly-added files that contain a keyword::
2613
2613
2614 hg diff "set:added() and grep(GNU)"
2614 hg diff "set:added() and grep(GNU)"
2615
2615
2616 - compare a revision and its parents::
2616 - compare a revision and its parents::
2617
2617
2618 hg diff -c 9353 # compare against first parent
2618 hg diff -c 9353 # compare against first parent
2619 hg diff --from 9353^ --to 9353 # same using revset syntax
2619 hg diff --from 9353^ --to 9353 # same using revset syntax
2620 hg diff --from 9353^2 --to 9353 # compare against the second parent
2620 hg diff --from 9353^2 --to 9353 # compare against the second parent
2621
2621
2622 Returns 0 on success.
2622 Returns 0 on success.
2623 """
2623 """
2624
2624
2625 cmdutil.check_at_most_one_arg(opts, 'rev', 'change')
2625 cmdutil.check_at_most_one_arg(opts, 'rev', 'change')
2626 opts = pycompat.byteskwargs(opts)
2626 opts = pycompat.byteskwargs(opts)
2627 revs = opts.get(b'rev')
2627 revs = opts.get(b'rev')
2628 change = opts.get(b'change')
2628 change = opts.get(b'change')
2629 from_rev = opts.get(b'from')
2629 from_rev = opts.get(b'from')
2630 to_rev = opts.get(b'to')
2630 to_rev = opts.get(b'to')
2631 stat = opts.get(b'stat')
2631 stat = opts.get(b'stat')
2632 reverse = opts.get(b'reverse')
2632 reverse = opts.get(b'reverse')
2633
2633
2634 cmdutil.check_incompatible_arguments(opts, b'from', [b'rev', b'change'])
2634 cmdutil.check_incompatible_arguments(opts, b'from', [b'rev', b'change'])
2635 cmdutil.check_incompatible_arguments(opts, b'to', [b'rev', b'change'])
2635 cmdutil.check_incompatible_arguments(opts, b'to', [b'rev', b'change'])
2636 if change:
2636 if change:
2637 repo = scmutil.unhidehashlikerevs(repo, [change], b'nowarn')
2637 repo = scmutil.unhidehashlikerevs(repo, [change], b'nowarn')
2638 ctx2 = logcmdutil.revsingle(repo, change, None)
2638 ctx2 = logcmdutil.revsingle(repo, change, None)
2639 ctx1 = logcmdutil.diff_parent(ctx2)
2639 ctx1 = logcmdutil.diff_parent(ctx2)
2640 elif from_rev or to_rev:
2640 elif from_rev or to_rev:
2641 repo = scmutil.unhidehashlikerevs(
2641 repo = scmutil.unhidehashlikerevs(
2642 repo, [from_rev] + [to_rev], b'nowarn'
2642 repo, [from_rev] + [to_rev], b'nowarn'
2643 )
2643 )
2644 ctx1 = logcmdutil.revsingle(repo, from_rev, None)
2644 ctx1 = logcmdutil.revsingle(repo, from_rev, None)
2645 ctx2 = logcmdutil.revsingle(repo, to_rev, None)
2645 ctx2 = logcmdutil.revsingle(repo, to_rev, None)
2646 else:
2646 else:
2647 repo = scmutil.unhidehashlikerevs(repo, revs, b'nowarn')
2647 repo = scmutil.unhidehashlikerevs(repo, revs, b'nowarn')
2648 ctx1, ctx2 = logcmdutil.revpair(repo, revs)
2648 ctx1, ctx2 = logcmdutil.revpair(repo, revs)
2649
2649
2650 if reverse:
2650 if reverse:
2651 ctxleft = ctx2
2651 ctxleft = ctx2
2652 ctxright = ctx1
2652 ctxright = ctx1
2653 else:
2653 else:
2654 ctxleft = ctx1
2654 ctxleft = ctx1
2655 ctxright = ctx2
2655 ctxright = ctx2
2656
2656
2657 diffopts = patch.diffallopts(ui, opts)
2657 diffopts = patch.diffallopts(ui, opts)
2658 m = scmutil.match(ctx2, pats, opts)
2658 m = scmutil.match(ctx2, pats, opts)
2659 m = repo.narrowmatch(m)
2659 m = repo.narrowmatch(m)
2660 ui.pager(b'diff')
2660 ui.pager(b'diff')
2661 logcmdutil.diffordiffstat(
2661 logcmdutil.diffordiffstat(
2662 ui,
2662 ui,
2663 repo,
2663 repo,
2664 diffopts,
2664 diffopts,
2665 ctxleft,
2665 ctxleft,
2666 ctxright,
2666 ctxright,
2667 m,
2667 m,
2668 stat=stat,
2668 stat=stat,
2669 listsubrepos=opts.get(b'subrepos'),
2669 listsubrepos=opts.get(b'subrepos'),
2670 root=opts.get(b'root'),
2670 root=opts.get(b'root'),
2671 )
2671 )
2672
2672
2673
2673
2674 @command(
2674 @command(
2675 b'export',
2675 b'export',
2676 [
2676 [
2677 (
2677 (
2678 b'B',
2678 b'B',
2679 b'bookmark',
2679 b'bookmark',
2680 b'',
2680 b'',
2681 _(b'export changes only reachable by given bookmark'),
2681 _(b'export changes only reachable by given bookmark'),
2682 _(b'BOOKMARK'),
2682 _(b'BOOKMARK'),
2683 ),
2683 ),
2684 (
2684 (
2685 b'o',
2685 b'o',
2686 b'output',
2686 b'output',
2687 b'',
2687 b'',
2688 _(b'print output to file with formatted name'),
2688 _(b'print output to file with formatted name'),
2689 _(b'FORMAT'),
2689 _(b'FORMAT'),
2690 ),
2690 ),
2691 (b'', b'switch-parent', None, _(b'diff against the second parent')),
2691 (b'', b'switch-parent', None, _(b'diff against the second parent')),
2692 (b'r', b'rev', [], _(b'revisions to export'), _(b'REV')),
2692 (b'r', b'rev', [], _(b'revisions to export'), _(b'REV')),
2693 ]
2693 ]
2694 + diffopts
2694 + diffopts
2695 + formatteropts,
2695 + formatteropts,
2696 _(b'[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'),
2696 _(b'[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'),
2697 helpcategory=command.CATEGORY_IMPORT_EXPORT,
2697 helpcategory=command.CATEGORY_IMPORT_EXPORT,
2698 helpbasic=True,
2698 helpbasic=True,
2699 intents={INTENT_READONLY},
2699 intents={INTENT_READONLY},
2700 )
2700 )
2701 def export(ui, repo, *changesets, **opts):
2701 def export(ui, repo, *changesets, **opts):
2702 """dump the header and diffs for one or more changesets
2702 """dump the header and diffs for one or more changesets
2703
2703
2704 Print the changeset header and diffs for one or more revisions.
2704 Print the changeset header and diffs for one or more revisions.
2705 If no revision is given, the parent of the working directory is used.
2705 If no revision is given, the parent of the working directory is used.
2706
2706
2707 The information shown in the changeset header is: author, date,
2707 The information shown in the changeset header is: author, date,
2708 branch name (if non-default), changeset hash, parent(s) and commit
2708 branch name (if non-default), changeset hash, parent(s) and commit
2709 comment.
2709 comment.
2710
2710
2711 .. note::
2711 .. note::
2712
2712
2713 :hg:`export` may generate unexpected diff output for merge
2713 :hg:`export` may generate unexpected diff output for merge
2714 changesets, as it will compare the merge changeset against its
2714 changesets, as it will compare the merge changeset against its
2715 first parent only.
2715 first parent only.
2716
2716
2717 Output may be to a file, in which case the name of the file is
2717 Output may be to a file, in which case the name of the file is
2718 given using a template string. See :hg:`help templates`. In addition
2718 given using a template string. See :hg:`help templates`. In addition
2719 to the common template keywords, the following formatting rules are
2719 to the common template keywords, the following formatting rules are
2720 supported:
2720 supported:
2721
2721
2722 :``%%``: literal "%" character
2722 :``%%``: literal "%" character
2723 :``%H``: changeset hash (40 hexadecimal digits)
2723 :``%H``: changeset hash (40 hexadecimal digits)
2724 :``%N``: number of patches being generated
2724 :``%N``: number of patches being generated
2725 :``%R``: changeset revision number
2725 :``%R``: changeset revision number
2726 :``%b``: basename of the exporting repository
2726 :``%b``: basename of the exporting repository
2727 :``%h``: short-form changeset hash (12 hexadecimal digits)
2727 :``%h``: short-form changeset hash (12 hexadecimal digits)
2728 :``%m``: first line of the commit message (only alphanumeric characters)
2728 :``%m``: first line of the commit message (only alphanumeric characters)
2729 :``%n``: zero-padded sequence number, starting at 1
2729 :``%n``: zero-padded sequence number, starting at 1
2730 :``%r``: zero-padded changeset revision number
2730 :``%r``: zero-padded changeset revision number
2731 :``\\``: literal "\\" character
2731 :``\\``: literal "\\" character
2732
2732
2733 Without the -a/--text option, export will avoid generating diffs
2733 Without the -a/--text option, export will avoid generating diffs
2734 of files it detects as binary. With -a, export will generate a
2734 of files it detects as binary. With -a, export will generate a
2735 diff anyway, probably with undesirable results.
2735 diff anyway, probably with undesirable results.
2736
2736
2737 With -B/--bookmark changesets reachable by the given bookmark are
2737 With -B/--bookmark changesets reachable by the given bookmark are
2738 selected.
2738 selected.
2739
2739
2740 Use the -g/--git option to generate diffs in the git extended diff
2740 Use the -g/--git option to generate diffs in the git extended diff
2741 format. See :hg:`help diffs` for more information.
2741 format. See :hg:`help diffs` for more information.
2742
2742
2743 With the --switch-parent option, the diff will be against the
2743 With the --switch-parent option, the diff will be against the
2744 second parent. It can be useful to review a merge.
2744 second parent. It can be useful to review a merge.
2745
2745
2746 .. container:: verbose
2746 .. container:: verbose
2747
2747
2748 Template:
2748 Template:
2749
2749
2750 The following keywords are supported in addition to the common template
2750 The following keywords are supported in addition to the common template
2751 keywords and functions. See also :hg:`help templates`.
2751 keywords and functions. See also :hg:`help templates`.
2752
2752
2753 :diff: String. Diff content.
2753 :diff: String. Diff content.
2754 :parents: List of strings. Parent nodes of the changeset.
2754 :parents: List of strings. Parent nodes of the changeset.
2755
2755
2756 Examples:
2756 Examples:
2757
2757
2758 - use export and import to transplant a bugfix to the current
2758 - use export and import to transplant a bugfix to the current
2759 branch::
2759 branch::
2760
2760
2761 hg export -r 9353 | hg import -
2761 hg export -r 9353 | hg import -
2762
2762
2763 - export all the changesets between two revisions to a file with
2763 - export all the changesets between two revisions to a file with
2764 rename information::
2764 rename information::
2765
2765
2766 hg export --git -r 123:150 > changes.txt
2766 hg export --git -r 123:150 > changes.txt
2767
2767
2768 - split outgoing changes into a series of patches with
2768 - split outgoing changes into a series of patches with
2769 descriptive names::
2769 descriptive names::
2770
2770
2771 hg export -r "outgoing()" -o "%n-%m.patch"
2771 hg export -r "outgoing()" -o "%n-%m.patch"
2772
2772
2773 Returns 0 on success.
2773 Returns 0 on success.
2774 """
2774 """
2775 opts = pycompat.byteskwargs(opts)
2775 opts = pycompat.byteskwargs(opts)
2776 bookmark = opts.get(b'bookmark')
2776 bookmark = opts.get(b'bookmark')
2777 changesets += tuple(opts.get(b'rev', []))
2777 changesets += tuple(opts.get(b'rev', []))
2778
2778
2779 cmdutil.check_at_most_one_arg(opts, b'rev', b'bookmark')
2779 cmdutil.check_at_most_one_arg(opts, b'rev', b'bookmark')
2780
2780
2781 if bookmark:
2781 if bookmark:
2782 if bookmark not in repo._bookmarks:
2782 if bookmark not in repo._bookmarks:
2783 raise error.InputError(_(b"bookmark '%s' not found") % bookmark)
2783 raise error.InputError(_(b"bookmark '%s' not found") % bookmark)
2784
2784
2785 revs = scmutil.bookmarkrevs(repo, bookmark)
2785 revs = scmutil.bookmarkrevs(repo, bookmark)
2786 else:
2786 else:
2787 if not changesets:
2787 if not changesets:
2788 changesets = [b'.']
2788 changesets = [b'.']
2789
2789
2790 repo = scmutil.unhidehashlikerevs(repo, changesets, b'nowarn')
2790 repo = scmutil.unhidehashlikerevs(repo, changesets, b'nowarn')
2791 revs = logcmdutil.revrange(repo, changesets)
2791 revs = logcmdutil.revrange(repo, changesets)
2792
2792
2793 if not revs:
2793 if not revs:
2794 raise error.InputError(_(b"export requires at least one changeset"))
2794 raise error.InputError(_(b"export requires at least one changeset"))
2795 if len(revs) > 1:
2795 if len(revs) > 1:
2796 ui.note(_(b'exporting patches:\n'))
2796 ui.note(_(b'exporting patches:\n'))
2797 else:
2797 else:
2798 ui.note(_(b'exporting patch:\n'))
2798 ui.note(_(b'exporting patch:\n'))
2799
2799
2800 fntemplate = opts.get(b'output')
2800 fntemplate = opts.get(b'output')
2801 if cmdutil.isstdiofilename(fntemplate):
2801 if cmdutil.isstdiofilename(fntemplate):
2802 fntemplate = b''
2802 fntemplate = b''
2803
2803
2804 if fntemplate:
2804 if fntemplate:
2805 fm = formatter.nullformatter(ui, b'export', opts)
2805 fm = formatter.nullformatter(ui, b'export', opts)
2806 else:
2806 else:
2807 ui.pager(b'export')
2807 ui.pager(b'export')
2808 fm = ui.formatter(b'export', opts)
2808 fm = ui.formatter(b'export', opts)
2809 with fm:
2809 with fm:
2810 cmdutil.export(
2810 cmdutil.export(
2811 repo,
2811 repo,
2812 revs,
2812 revs,
2813 fm,
2813 fm,
2814 fntemplate=fntemplate,
2814 fntemplate=fntemplate,
2815 switch_parent=opts.get(b'switch_parent'),
2815 switch_parent=opts.get(b'switch_parent'),
2816 opts=patch.diffallopts(ui, opts),
2816 opts=patch.diffallopts(ui, opts),
2817 )
2817 )
2818
2818
2819
2819
2820 @command(
2820 @command(
2821 b'files',
2821 b'files',
2822 [
2822 [
2823 (
2823 (
2824 b'r',
2824 b'r',
2825 b'rev',
2825 b'rev',
2826 b'',
2826 b'',
2827 _(b'search the repository as it is in REV'),
2827 _(b'search the repository as it is in REV'),
2828 _(b'REV'),
2828 _(b'REV'),
2829 ),
2829 ),
2830 (
2830 (
2831 b'0',
2831 b'0',
2832 b'print0',
2832 b'print0',
2833 None,
2833 None,
2834 _(b'end filenames with NUL, for use with xargs'),
2834 _(b'end filenames with NUL, for use with xargs'),
2835 ),
2835 ),
2836 ]
2836 ]
2837 + walkopts
2837 + walkopts
2838 + formatteropts
2838 + formatteropts
2839 + subrepoopts,
2839 + subrepoopts,
2840 _(b'[OPTION]... [FILE]...'),
2840 _(b'[OPTION]... [FILE]...'),
2841 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2841 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2842 intents={INTENT_READONLY},
2842 intents={INTENT_READONLY},
2843 )
2843 )
2844 def files(ui, repo, *pats, **opts):
2844 def files(ui, repo, *pats, **opts):
2845 """list tracked files
2845 """list tracked files
2846
2846
2847 Print files under Mercurial control in the working directory or
2847 Print files under Mercurial control in the working directory or
2848 specified revision for given files (excluding removed files).
2848 specified revision for given files (excluding removed files).
2849 Files can be specified as filenames or filesets.
2849 Files can be specified as filenames or filesets.
2850
2850
2851 If no files are given to match, this command prints the names
2851 If no files are given to match, this command prints the names
2852 of all files under Mercurial control.
2852 of all files under Mercurial control.
2853
2853
2854 .. container:: verbose
2854 .. container:: verbose
2855
2855
2856 Template:
2856 Template:
2857
2857
2858 The following keywords are supported in addition to the common template
2858 The following keywords are supported in addition to the common template
2859 keywords and functions. See also :hg:`help templates`.
2859 keywords and functions. See also :hg:`help templates`.
2860
2860
2861 :flags: String. Character denoting file's symlink and executable bits.
2861 :flags: String. Character denoting file's symlink and executable bits.
2862 :path: String. Repository-absolute path of the file.
2862 :path: String. Repository-absolute path of the file.
2863 :size: Integer. Size of the file in bytes.
2863 :size: Integer. Size of the file in bytes.
2864
2864
2865 Examples:
2865 Examples:
2866
2866
2867 - list all files under the current directory::
2867 - list all files under the current directory::
2868
2868
2869 hg files .
2869 hg files .
2870
2870
2871 - shows sizes and flags for current revision::
2871 - shows sizes and flags for current revision::
2872
2872
2873 hg files -vr .
2873 hg files -vr .
2874
2874
2875 - list all files named README::
2875 - list all files named README::
2876
2876
2877 hg files -I "**/README"
2877 hg files -I "**/README"
2878
2878
2879 - list all binary files::
2879 - list all binary files::
2880
2880
2881 hg files "set:binary()"
2881 hg files "set:binary()"
2882
2882
2883 - find files containing a regular expression::
2883 - find files containing a regular expression::
2884
2884
2885 hg files "set:grep('bob')"
2885 hg files "set:grep('bob')"
2886
2886
2887 - search tracked file contents with xargs and grep::
2887 - search tracked file contents with xargs and grep::
2888
2888
2889 hg files -0 | xargs -0 grep foo
2889 hg files -0 | xargs -0 grep foo
2890
2890
2891 See :hg:`help patterns` and :hg:`help filesets` for more information
2891 See :hg:`help patterns` and :hg:`help filesets` for more information
2892 on specifying file patterns.
2892 on specifying file patterns.
2893
2893
2894 Returns 0 if a match is found, 1 otherwise.
2894 Returns 0 if a match is found, 1 otherwise.
2895
2895
2896 """
2896 """
2897
2897
2898 opts = pycompat.byteskwargs(opts)
2898 opts = pycompat.byteskwargs(opts)
2899 rev = opts.get(b'rev')
2899 rev = opts.get(b'rev')
2900 if rev:
2900 if rev:
2901 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
2901 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
2902 ctx = logcmdutil.revsingle(repo, rev, None)
2902 ctx = logcmdutil.revsingle(repo, rev, None)
2903
2903
2904 end = b'\n'
2904 end = b'\n'
2905 if opts.get(b'print0'):
2905 if opts.get(b'print0'):
2906 end = b'\0'
2906 end = b'\0'
2907 fmt = b'%s' + end
2907 fmt = b'%s' + end
2908
2908
2909 m = scmutil.match(ctx, pats, opts)
2909 m = scmutil.match(ctx, pats, opts)
2910 ui.pager(b'files')
2910 ui.pager(b'files')
2911 uipathfn = scmutil.getuipathfn(ctx.repo(), legacyrelativevalue=True)
2911 uipathfn = scmutil.getuipathfn(ctx.repo(), legacyrelativevalue=True)
2912 with ui.formatter(b'files', opts) as fm:
2912 with ui.formatter(b'files', opts) as fm:
2913 return cmdutil.files(
2913 return cmdutil.files(
2914 ui, ctx, m, uipathfn, fm, fmt, opts.get(b'subrepos')
2914 ui, ctx, m, uipathfn, fm, fmt, opts.get(b'subrepos')
2915 )
2915 )
2916
2916
2917
2917
2918 @command(
2918 @command(
2919 b'forget',
2919 b'forget',
2920 [
2920 [
2921 (b'i', b'interactive', None, _(b'use interactive mode')),
2921 (b'i', b'interactive', None, _(b'use interactive mode')),
2922 ]
2922 ]
2923 + walkopts
2923 + walkopts
2924 + dryrunopts,
2924 + dryrunopts,
2925 _(b'[OPTION]... FILE...'),
2925 _(b'[OPTION]... FILE...'),
2926 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2926 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2927 helpbasic=True,
2927 helpbasic=True,
2928 inferrepo=True,
2928 inferrepo=True,
2929 )
2929 )
2930 def forget(ui, repo, *pats, **opts):
2930 def forget(ui, repo, *pats, **opts):
2931 """forget the specified files on the next commit
2931 """forget the specified files on the next commit
2932
2932
2933 Mark the specified files so they will no longer be tracked
2933 Mark the specified files so they will no longer be tracked
2934 after the next commit.
2934 after the next commit.
2935
2935
2936 This only removes files from the current branch, not from the
2936 This only removes files from the current branch, not from the
2937 entire project history, and it does not delete them from the
2937 entire project history, and it does not delete them from the
2938 working directory.
2938 working directory.
2939
2939
2940 To delete the file from the working directory, see :hg:`remove`.
2940 To delete the file from the working directory, see :hg:`remove`.
2941
2941
2942 To undo a forget before the next commit, see :hg:`add`.
2942 To undo a forget before the next commit, see :hg:`add`.
2943
2943
2944 .. container:: verbose
2944 .. container:: verbose
2945
2945
2946 Examples:
2946 Examples:
2947
2947
2948 - forget newly-added binary files::
2948 - forget newly-added binary files::
2949
2949
2950 hg forget "set:added() and binary()"
2950 hg forget "set:added() and binary()"
2951
2951
2952 - forget files that would be excluded by .hgignore::
2952 - forget files that would be excluded by .hgignore::
2953
2953
2954 hg forget "set:hgignore()"
2954 hg forget "set:hgignore()"
2955
2955
2956 Returns 0 on success.
2956 Returns 0 on success.
2957 """
2957 """
2958
2958
2959 opts = pycompat.byteskwargs(opts)
2959 opts = pycompat.byteskwargs(opts)
2960 if not pats:
2960 if not pats:
2961 raise error.InputError(_(b'no files specified'))
2961 raise error.InputError(_(b'no files specified'))
2962
2962
2963 m = scmutil.match(repo[None], pats, opts)
2963 m = scmutil.match(repo[None], pats, opts)
2964 dryrun, interactive = opts.get(b'dry_run'), opts.get(b'interactive')
2964 dryrun, interactive = opts.get(b'dry_run'), opts.get(b'interactive')
2965 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
2965 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
2966 rejected = cmdutil.forget(
2966 rejected = cmdutil.forget(
2967 ui,
2967 ui,
2968 repo,
2968 repo,
2969 m,
2969 m,
2970 prefix=b"",
2970 prefix=b"",
2971 uipathfn=uipathfn,
2971 uipathfn=uipathfn,
2972 explicitonly=False,
2972 explicitonly=False,
2973 dryrun=dryrun,
2973 dryrun=dryrun,
2974 interactive=interactive,
2974 interactive=interactive,
2975 )[0]
2975 )[0]
2976 return rejected and 1 or 0
2976 return rejected and 1 or 0
2977
2977
2978
2978
2979 @command(
2979 @command(
2980 b'graft',
2980 b'graft',
2981 [
2981 [
2982 (b'r', b'rev', [], _(b'revisions to graft'), _(b'REV')),
2982 (b'r', b'rev', [], _(b'revisions to graft'), _(b'REV')),
2983 (
2983 (
2984 b'',
2984 b'',
2985 b'base',
2985 b'base',
2986 b'',
2986 b'',
2987 _(b'base revision when doing the graft merge (ADVANCED)'),
2987 _(b'base revision when doing the graft merge (ADVANCED)'),
2988 _(b'REV'),
2988 _(b'REV'),
2989 ),
2989 ),
2990 (b'c', b'continue', False, _(b'resume interrupted graft')),
2990 (b'c', b'continue', False, _(b'resume interrupted graft')),
2991 (b'', b'stop', False, _(b'stop interrupted graft')),
2991 (b'', b'stop', False, _(b'stop interrupted graft')),
2992 (b'', b'abort', False, _(b'abort interrupted graft')),
2992 (b'', b'abort', False, _(b'abort interrupted graft')),
2993 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
2993 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
2994 (b'', b'log', None, _(b'append graft info to log message')),
2994 (b'', b'log', None, _(b'append graft info to log message')),
2995 (
2995 (
2996 b'',
2996 b'',
2997 b'no-commit',
2997 b'no-commit',
2998 None,
2998 None,
2999 _(b"don't commit, just apply the changes in working directory"),
2999 _(b"don't commit, just apply the changes in working directory"),
3000 ),
3000 ),
3001 (b'f', b'force', False, _(b'force graft')),
3001 (b'f', b'force', False, _(b'force graft')),
3002 (
3002 (
3003 b'D',
3003 b'D',
3004 b'currentdate',
3004 b'currentdate',
3005 False,
3005 False,
3006 _(b'record the current date as commit date'),
3006 _(b'record the current date as commit date'),
3007 ),
3007 ),
3008 (
3008 (
3009 b'U',
3009 b'U',
3010 b'currentuser',
3010 b'currentuser',
3011 False,
3011 False,
3012 _(b'record the current user as committer'),
3012 _(b'record the current user as committer'),
3013 ),
3013 ),
3014 ]
3014 ]
3015 + commitopts2
3015 + commitopts2
3016 + mergetoolopts
3016 + mergetoolopts
3017 + dryrunopts,
3017 + dryrunopts,
3018 _(b'[OPTION]... [-r REV]... REV...'),
3018 _(b'[OPTION]... [-r REV]... REV...'),
3019 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
3019 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
3020 )
3020 )
3021 def graft(ui, repo, *revs, **opts):
3021 def graft(ui, repo, *revs, **opts):
3022 """copy changes from other branches onto the current branch
3022 """copy changes from other branches onto the current branch
3023
3023
3024 This command uses Mercurial's merge logic to copy individual
3024 This command uses Mercurial's merge logic to copy individual
3025 changes from other branches without merging branches in the
3025 changes from other branches without merging branches in the
3026 history graph. This is sometimes known as 'backporting' or
3026 history graph. This is sometimes known as 'backporting' or
3027 'cherry-picking'. By default, graft will copy user, date, and
3027 'cherry-picking'. By default, graft will copy user, date, and
3028 description from the source changesets.
3028 description from the source changesets.
3029
3029
3030 Changesets that are ancestors of the current revision, that have
3030 Changesets that are ancestors of the current revision, that have
3031 already been grafted, or that are merges will be skipped.
3031 already been grafted, or that are merges will be skipped.
3032
3032
3033 If --log is specified, log messages will have a comment appended
3033 If --log is specified, log messages will have a comment appended
3034 of the form::
3034 of the form::
3035
3035
3036 (grafted from CHANGESETHASH)
3036 (grafted from CHANGESETHASH)
3037
3037
3038 If --force is specified, revisions will be grafted even if they
3038 If --force is specified, revisions will be grafted even if they
3039 are already ancestors of, or have been grafted to, the destination.
3039 are already ancestors of, or have been grafted to, the destination.
3040 This is useful when the revisions have since been backed out.
3040 This is useful when the revisions have since been backed out.
3041
3041
3042 If a graft merge results in conflicts, the graft process is
3042 If a graft merge results in conflicts, the graft process is
3043 interrupted so that the current merge can be manually resolved.
3043 interrupted so that the current merge can be manually resolved.
3044 Once all conflicts are addressed, the graft process can be
3044 Once all conflicts are addressed, the graft process can be
3045 continued with the -c/--continue option.
3045 continued with the -c/--continue option.
3046
3046
3047 The -c/--continue option reapplies all the earlier options.
3047 The -c/--continue option reapplies all the earlier options.
3048
3048
3049 .. container:: verbose
3049 .. container:: verbose
3050
3050
3051 The --base option exposes more of how graft internally uses merge with a
3051 The --base option exposes more of how graft internally uses merge with a
3052 custom base revision. --base can be used to specify another ancestor than
3052 custom base revision. --base can be used to specify another ancestor than
3053 the first and only parent.
3053 the first and only parent.
3054
3054
3055 The command::
3055 The command::
3056
3056
3057 hg graft -r 345 --base 234
3057 hg graft -r 345 --base 234
3058
3058
3059 is thus pretty much the same as::
3059 is thus pretty much the same as::
3060
3060
3061 hg diff --from 234 --to 345 | hg import
3061 hg diff --from 234 --to 345 | hg import
3062
3062
3063 but using merge to resolve conflicts and track moved files.
3063 but using merge to resolve conflicts and track moved files.
3064
3064
3065 The result of a merge can thus be backported as a single commit by
3065 The result of a merge can thus be backported as a single commit by
3066 specifying one of the merge parents as base, and thus effectively
3066 specifying one of the merge parents as base, and thus effectively
3067 grafting the changes from the other side.
3067 grafting the changes from the other side.
3068
3068
3069 It is also possible to collapse multiple changesets and clean up history
3069 It is also possible to collapse multiple changesets and clean up history
3070 by specifying another ancestor as base, much like rebase --collapse
3070 by specifying another ancestor as base, much like rebase --collapse
3071 --keep.
3071 --keep.
3072
3072
3073 The commit message can be tweaked after the fact using commit --amend .
3073 The commit message can be tweaked after the fact using commit --amend .
3074
3074
3075 For using non-ancestors as the base to backout changes, see the backout
3075 For using non-ancestors as the base to backout changes, see the backout
3076 command and the hidden --parent option.
3076 command and the hidden --parent option.
3077
3077
3078 .. container:: verbose
3078 .. container:: verbose
3079
3079
3080 Examples:
3080 Examples:
3081
3081
3082 - copy a single change to the stable branch and edit its description::
3082 - copy a single change to the stable branch and edit its description::
3083
3083
3084 hg update stable
3084 hg update stable
3085 hg graft --edit 9393
3085 hg graft --edit 9393
3086
3086
3087 - graft a range of changesets with one exception, updating dates::
3087 - graft a range of changesets with one exception, updating dates::
3088
3088
3089 hg graft -D "2085::2093 and not 2091"
3089 hg graft -D "2085::2093 and not 2091"
3090
3090
3091 - continue a graft after resolving conflicts::
3091 - continue a graft after resolving conflicts::
3092
3092
3093 hg graft -c
3093 hg graft -c
3094
3094
3095 - show the source of a grafted changeset::
3095 - show the source of a grafted changeset::
3096
3096
3097 hg log --debug -r .
3097 hg log --debug -r .
3098
3098
3099 - show revisions sorted by date::
3099 - show revisions sorted by date::
3100
3100
3101 hg log -r "sort(all(), date)"
3101 hg log -r "sort(all(), date)"
3102
3102
3103 - backport the result of a merge as a single commit::
3103 - backport the result of a merge as a single commit::
3104
3104
3105 hg graft -r 123 --base 123^
3105 hg graft -r 123 --base 123^
3106
3106
3107 - land a feature branch as one changeset::
3107 - land a feature branch as one changeset::
3108
3108
3109 hg up -cr default
3109 hg up -cr default
3110 hg graft -r featureX --base "ancestor('featureX', 'default')"
3110 hg graft -r featureX --base "ancestor('featureX', 'default')"
3111
3111
3112 See :hg:`help revisions` for more about specifying revisions.
3112 See :hg:`help revisions` for more about specifying revisions.
3113
3113
3114 Returns 0 on successful completion, 1 if there are unresolved files.
3114 Returns 0 on successful completion, 1 if there are unresolved files.
3115 """
3115 """
3116 with repo.wlock():
3116 with repo.wlock():
3117 return _dograft(ui, repo, *revs, **opts)
3117 return _dograft(ui, repo, *revs, **opts)
3118
3118
3119
3119
3120 def _dograft(ui, repo, *revs, **opts):
3120 def _dograft(ui, repo, *revs, **opts):
3121 if revs and opts.get('rev'):
3121 if revs and opts.get('rev'):
3122 ui.warn(
3122 ui.warn(
3123 _(
3123 _(
3124 b'warning: inconsistent use of --rev might give unexpected '
3124 b'warning: inconsistent use of --rev might give unexpected '
3125 b'revision ordering!\n'
3125 b'revision ordering!\n'
3126 )
3126 )
3127 )
3127 )
3128
3128
3129 revs = list(revs)
3129 revs = list(revs)
3130 revs.extend(opts.get('rev'))
3130 revs.extend(opts.get('rev'))
3131 # a dict of data to be stored in state file
3131 # a dict of data to be stored in state file
3132 statedata = {}
3132 statedata = {}
3133 # list of new nodes created by ongoing graft
3133 # list of new nodes created by ongoing graft
3134 statedata[b'newnodes'] = []
3134 statedata[b'newnodes'] = []
3135
3135
3136 cmdutil.resolve_commit_options(ui, opts)
3136 cmdutil.resolve_commit_options(ui, opts)
3137
3137
3138 editor = cmdutil.getcommiteditor(editform=b'graft', **opts)
3138 editor = cmdutil.getcommiteditor(editform=b'graft', **opts)
3139
3139
3140 cmdutil.check_at_most_one_arg(opts, 'abort', 'stop', 'continue')
3140 cmdutil.check_at_most_one_arg(opts, 'abort', 'stop', 'continue')
3141
3141
3142 cont = False
3142 cont = False
3143 if opts.get('no_commit'):
3143 if opts.get('no_commit'):
3144 cmdutil.check_incompatible_arguments(
3144 cmdutil.check_incompatible_arguments(
3145 opts,
3145 opts,
3146 'no_commit',
3146 'no_commit',
3147 ['edit', 'currentuser', 'currentdate', 'log'],
3147 ['edit', 'currentuser', 'currentdate', 'log'],
3148 )
3148 )
3149
3149
3150 graftstate = statemod.cmdstate(repo, b'graftstate')
3150 graftstate = statemod.cmdstate(repo, b'graftstate')
3151
3151
3152 if opts.get('stop'):
3152 if opts.get('stop'):
3153 cmdutil.check_incompatible_arguments(
3153 cmdutil.check_incompatible_arguments(
3154 opts,
3154 opts,
3155 'stop',
3155 'stop',
3156 [
3156 [
3157 'edit',
3157 'edit',
3158 'log',
3158 'log',
3159 'user',
3159 'user',
3160 'date',
3160 'date',
3161 'currentdate',
3161 'currentdate',
3162 'currentuser',
3162 'currentuser',
3163 'rev',
3163 'rev',
3164 ],
3164 ],
3165 )
3165 )
3166 return _stopgraft(ui, repo, graftstate)
3166 return _stopgraft(ui, repo, graftstate)
3167 elif opts.get('abort'):
3167 elif opts.get('abort'):
3168 cmdutil.check_incompatible_arguments(
3168 cmdutil.check_incompatible_arguments(
3169 opts,
3169 opts,
3170 'abort',
3170 'abort',
3171 [
3171 [
3172 'edit',
3172 'edit',
3173 'log',
3173 'log',
3174 'user',
3174 'user',
3175 'date',
3175 'date',
3176 'currentdate',
3176 'currentdate',
3177 'currentuser',
3177 'currentuser',
3178 'rev',
3178 'rev',
3179 ],
3179 ],
3180 )
3180 )
3181 return cmdutil.abortgraft(ui, repo, graftstate)
3181 return cmdutil.abortgraft(ui, repo, graftstate)
3182 elif opts.get('continue'):
3182 elif opts.get('continue'):
3183 cont = True
3183 cont = True
3184 if revs:
3184 if revs:
3185 raise error.InputError(_(b"can't specify --continue and revisions"))
3185 raise error.InputError(_(b"can't specify --continue and revisions"))
3186 # read in unfinished revisions
3186 # read in unfinished revisions
3187 if graftstate.exists():
3187 if graftstate.exists():
3188 statedata = cmdutil.readgraftstate(repo, graftstate)
3188 statedata = cmdutil.readgraftstate(repo, graftstate)
3189 if statedata.get(b'date'):
3189 if statedata.get(b'date'):
3190 opts['date'] = statedata[b'date']
3190 opts['date'] = statedata[b'date']
3191 if statedata.get(b'user'):
3191 if statedata.get(b'user'):
3192 opts['user'] = statedata[b'user']
3192 opts['user'] = statedata[b'user']
3193 if statedata.get(b'log'):
3193 if statedata.get(b'log'):
3194 opts['log'] = True
3194 opts['log'] = True
3195 if statedata.get(b'no_commit'):
3195 if statedata.get(b'no_commit'):
3196 opts['no_commit'] = statedata.get(b'no_commit')
3196 opts['no_commit'] = statedata.get(b'no_commit')
3197 if statedata.get(b'base'):
3197 if statedata.get(b'base'):
3198 opts['base'] = statedata.get(b'base')
3198 opts['base'] = statedata.get(b'base')
3199 nodes = statedata[b'nodes']
3199 nodes = statedata[b'nodes']
3200 revs = [repo[node].rev() for node in nodes]
3200 revs = [repo[node].rev() for node in nodes]
3201 else:
3201 else:
3202 cmdutil.wrongtooltocontinue(repo, _(b'graft'))
3202 cmdutil.wrongtooltocontinue(repo, _(b'graft'))
3203 else:
3203 else:
3204 if not revs:
3204 if not revs:
3205 raise error.InputError(_(b'no revisions specified'))
3205 raise error.InputError(_(b'no revisions specified'))
3206 cmdutil.checkunfinished(repo)
3206 cmdutil.checkunfinished(repo)
3207 cmdutil.bailifchanged(repo)
3207 cmdutil.bailifchanged(repo)
3208 revs = logcmdutil.revrange(repo, revs)
3208 revs = logcmdutil.revrange(repo, revs)
3209
3209
3210 skipped = set()
3210 skipped = set()
3211 basectx = None
3211 basectx = None
3212 if opts.get('base'):
3212 if opts.get('base'):
3213 basectx = logcmdutil.revsingle(repo, opts['base'], None)
3213 basectx = logcmdutil.revsingle(repo, opts['base'], None)
3214 if basectx is None:
3214 if basectx is None:
3215 # check for merges
3215 # check for merges
3216 for rev in repo.revs(b'%ld and merge()', revs):
3216 for rev in repo.revs(b'%ld and merge()', revs):
3217 ui.warn(_(b'skipping ungraftable merge revision %d\n') % rev)
3217 ui.warn(_(b'skipping ungraftable merge revision %d\n') % rev)
3218 skipped.add(rev)
3218 skipped.add(rev)
3219 revs = [r for r in revs if r not in skipped]
3219 revs = [r for r in revs if r not in skipped]
3220 if not revs:
3220 if not revs:
3221 return -1
3221 return -1
3222 if basectx is not None and len(revs) != 1:
3222 if basectx is not None and len(revs) != 1:
3223 raise error.InputError(_(b'only one revision allowed with --base '))
3223 raise error.InputError(_(b'only one revision allowed with --base '))
3224
3224
3225 # Don't check in the --continue case, in effect retaining --force across
3225 # Don't check in the --continue case, in effect retaining --force across
3226 # --continues. That's because without --force, any revisions we decided to
3226 # --continues. That's because without --force, any revisions we decided to
3227 # skip would have been filtered out here, so they wouldn't have made their
3227 # skip would have been filtered out here, so they wouldn't have made their
3228 # way to the graftstate. With --force, any revisions we would have otherwise
3228 # way to the graftstate. With --force, any revisions we would have otherwise
3229 # skipped would not have been filtered out, and if they hadn't been applied
3229 # skipped would not have been filtered out, and if they hadn't been applied
3230 # already, they'd have been in the graftstate.
3230 # already, they'd have been in the graftstate.
3231 if not (cont or opts.get('force')) and basectx is None:
3231 if not (cont or opts.get('force')) and basectx is None:
3232 # check for ancestors of dest branch
3232 # check for ancestors of dest branch
3233 ancestors = repo.revs(b'%ld & (::.)', revs)
3233 ancestors = repo.revs(b'%ld & (::.)', revs)
3234 for rev in ancestors:
3234 for rev in ancestors:
3235 ui.warn(_(b'skipping ancestor revision %d:%s\n') % (rev, repo[rev]))
3235 ui.warn(_(b'skipping ancestor revision %d:%s\n') % (rev, repo[rev]))
3236
3236
3237 revs = [r for r in revs if r not in ancestors]
3237 revs = [r for r in revs if r not in ancestors]
3238
3238
3239 if not revs:
3239 if not revs:
3240 return -1
3240 return -1
3241
3241
3242 # analyze revs for earlier grafts
3242 # analyze revs for earlier grafts
3243 ids = {}
3243 ids = {}
3244 for ctx in repo.set(b"%ld", revs):
3244 for ctx in repo.set(b"%ld", revs):
3245 ids[ctx.hex()] = ctx.rev()
3245 ids[ctx.hex()] = ctx.rev()
3246 n = ctx.extra().get(b'source')
3246 n = ctx.extra().get(b'source')
3247 if n:
3247 if n:
3248 ids[n] = ctx.rev()
3248 ids[n] = ctx.rev()
3249
3249
3250 # check ancestors for earlier grafts
3250 # check ancestors for earlier grafts
3251 ui.debug(b'scanning for duplicate grafts\n')
3251 ui.debug(b'scanning for duplicate grafts\n')
3252
3252
3253 # The only changesets we can be sure doesn't contain grafts of any
3253 # The only changesets we can be sure doesn't contain grafts of any
3254 # revs, are the ones that are common ancestors of *all* revs:
3254 # revs, are the ones that are common ancestors of *all* revs:
3255 for rev in repo.revs(b'only(%d,ancestor(%ld))', repo[b'.'].rev(), revs):
3255 for rev in repo.revs(b'only(%d,ancestor(%ld))', repo[b'.'].rev(), revs):
3256 ctx = repo[rev]
3256 ctx = repo[rev]
3257 n = ctx.extra().get(b'source')
3257 n = ctx.extra().get(b'source')
3258 if n in ids:
3258 if n in ids:
3259 try:
3259 try:
3260 r = repo[n].rev()
3260 r = repo[n].rev()
3261 except error.RepoLookupError:
3261 except error.RepoLookupError:
3262 r = None
3262 r = None
3263 if r in revs:
3263 if r in revs:
3264 ui.warn(
3264 ui.warn(
3265 _(
3265 _(
3266 b'skipping revision %d:%s '
3266 b'skipping revision %d:%s '
3267 b'(already grafted to %d:%s)\n'
3267 b'(already grafted to %d:%s)\n'
3268 )
3268 )
3269 % (r, repo[r], rev, ctx)
3269 % (r, repo[r], rev, ctx)
3270 )
3270 )
3271 revs.remove(r)
3271 revs.remove(r)
3272 elif ids[n] in revs:
3272 elif ids[n] in revs:
3273 if r is None:
3273 if r is None:
3274 ui.warn(
3274 ui.warn(
3275 _(
3275 _(
3276 b'skipping already grafted revision %d:%s '
3276 b'skipping already grafted revision %d:%s '
3277 b'(%d:%s also has unknown origin %s)\n'
3277 b'(%d:%s also has unknown origin %s)\n'
3278 )
3278 )
3279 % (ids[n], repo[ids[n]], rev, ctx, n[:12])
3279 % (ids[n], repo[ids[n]], rev, ctx, n[:12])
3280 )
3280 )
3281 else:
3281 else:
3282 ui.warn(
3282 ui.warn(
3283 _(
3283 _(
3284 b'skipping already grafted revision %d:%s '
3284 b'skipping already grafted revision %d:%s '
3285 b'(%d:%s also has origin %d:%s)\n'
3285 b'(%d:%s also has origin %d:%s)\n'
3286 )
3286 )
3287 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12])
3287 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12])
3288 )
3288 )
3289 revs.remove(ids[n])
3289 revs.remove(ids[n])
3290 elif ctx.hex() in ids:
3290 elif ctx.hex() in ids:
3291 r = ids[ctx.hex()]
3291 r = ids[ctx.hex()]
3292 if r in revs:
3292 if r in revs:
3293 ui.warn(
3293 ui.warn(
3294 _(
3294 _(
3295 b'skipping already grafted revision %d:%s '
3295 b'skipping already grafted revision %d:%s '
3296 b'(was grafted from %d:%s)\n'
3296 b'(was grafted from %d:%s)\n'
3297 )
3297 )
3298 % (r, repo[r], rev, ctx)
3298 % (r, repo[r], rev, ctx)
3299 )
3299 )
3300 revs.remove(r)
3300 revs.remove(r)
3301 if not revs:
3301 if not revs:
3302 return -1
3302 return -1
3303
3303
3304 if opts.get('no_commit'):
3304 if opts.get('no_commit'):
3305 statedata[b'no_commit'] = True
3305 statedata[b'no_commit'] = True
3306 if opts.get('base'):
3306 if opts.get('base'):
3307 statedata[b'base'] = opts['base']
3307 statedata[b'base'] = opts['base']
3308 for pos, ctx in enumerate(repo.set(b"%ld", revs)):
3308 for pos, ctx in enumerate(repo.set(b"%ld", revs)):
3309 desc = b'%d:%s "%s"' % (
3309 desc = b'%d:%s "%s"' % (
3310 ctx.rev(),
3310 ctx.rev(),
3311 ctx,
3311 ctx,
3312 ctx.description().split(b'\n', 1)[0],
3312 ctx.description().split(b'\n', 1)[0],
3313 )
3313 )
3314 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
3314 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
3315 if names:
3315 if names:
3316 desc += b' (%s)' % b' '.join(names)
3316 desc += b' (%s)' % b' '.join(names)
3317 ui.status(_(b'grafting %s\n') % desc)
3317 ui.status(_(b'grafting %s\n') % desc)
3318 if opts.get('dry_run'):
3318 if opts.get('dry_run'):
3319 continue
3319 continue
3320
3320
3321 source = ctx.extra().get(b'source')
3321 source = ctx.extra().get(b'source')
3322 extra = {}
3322 extra = {}
3323 if source:
3323 if source:
3324 extra[b'source'] = source
3324 extra[b'source'] = source
3325 extra[b'intermediate-source'] = ctx.hex()
3325 extra[b'intermediate-source'] = ctx.hex()
3326 else:
3326 else:
3327 extra[b'source'] = ctx.hex()
3327 extra[b'source'] = ctx.hex()
3328 user = ctx.user()
3328 user = ctx.user()
3329 if opts.get('user'):
3329 if opts.get('user'):
3330 user = opts['user']
3330 user = opts['user']
3331 statedata[b'user'] = user
3331 statedata[b'user'] = user
3332 date = ctx.date()
3332 date = ctx.date()
3333 if opts.get('date'):
3333 if opts.get('date'):
3334 date = opts['date']
3334 date = opts['date']
3335 statedata[b'date'] = date
3335 statedata[b'date'] = date
3336 message = ctx.description()
3336 message = ctx.description()
3337 if opts.get('log'):
3337 if opts.get('log'):
3338 message += b'\n(grafted from %s)' % ctx.hex()
3338 message += b'\n(grafted from %s)' % ctx.hex()
3339 statedata[b'log'] = True
3339 statedata[b'log'] = True
3340
3340
3341 # we don't merge the first commit when continuing
3341 # we don't merge the first commit when continuing
3342 if not cont:
3342 if not cont:
3343 # perform the graft merge with p1(rev) as 'ancestor'
3343 # perform the graft merge with p1(rev) as 'ancestor'
3344 overrides = {(b'ui', b'forcemerge'): opts.get('tool', b'')}
3344 overrides = {(b'ui', b'forcemerge'): opts.get('tool', b'')}
3345 base = ctx.p1() if basectx is None else basectx
3345 base = ctx.p1() if basectx is None else basectx
3346 with ui.configoverride(overrides, b'graft'):
3346 with ui.configoverride(overrides, b'graft'):
3347 stats = mergemod.graft(
3347 stats = mergemod.graft(
3348 repo, ctx, base, [b'local', b'graft', b'parent of graft']
3348 repo, ctx, base, [b'local', b'graft', b'parent of graft']
3349 )
3349 )
3350 # report any conflicts
3350 # report any conflicts
3351 if stats.unresolvedcount > 0:
3351 if stats.unresolvedcount > 0:
3352 # write out state for --continue
3352 # write out state for --continue
3353 nodes = [repo[rev].hex() for rev in revs[pos:]]
3353 nodes = [repo[rev].hex() for rev in revs[pos:]]
3354 statedata[b'nodes'] = nodes
3354 statedata[b'nodes'] = nodes
3355 stateversion = 1
3355 stateversion = 1
3356 graftstate.save(stateversion, statedata)
3356 graftstate.save(stateversion, statedata)
3357 ui.error(_(b"abort: unresolved conflicts, can't continue\n"))
3357 ui.error(_(b"abort: unresolved conflicts, can't continue\n"))
3358 ui.error(_(b"(use 'hg resolve' and 'hg graft --continue')\n"))
3358 ui.error(_(b"(use 'hg resolve' and 'hg graft --continue')\n"))
3359 return 1
3359 return 1
3360 else:
3360 else:
3361 cont = False
3361 cont = False
3362
3362
3363 # commit if --no-commit is false
3363 # commit if --no-commit is false
3364 if not opts.get('no_commit'):
3364 if not opts.get('no_commit'):
3365 node = repo.commit(
3365 node = repo.commit(
3366 text=message, user=user, date=date, extra=extra, editor=editor
3366 text=message, user=user, date=date, extra=extra, editor=editor
3367 )
3367 )
3368 if node is None:
3368 if node is None:
3369 ui.warn(
3369 ui.warn(
3370 _(b'note: graft of %d:%s created no changes to commit\n')
3370 _(b'note: graft of %d:%s created no changes to commit\n')
3371 % (ctx.rev(), ctx)
3371 % (ctx.rev(), ctx)
3372 )
3372 )
3373 # checking that newnodes exist because old state files won't have it
3373 # checking that newnodes exist because old state files won't have it
3374 elif statedata.get(b'newnodes') is not None:
3374 elif statedata.get(b'newnodes') is not None:
3375 nn = statedata[b'newnodes']
3375 nn = statedata[b'newnodes']
3376 assert isinstance(nn, list) # list of bytes
3376 assert isinstance(nn, list) # list of bytes
3377 nn.append(node)
3377 nn.append(node)
3378
3378
3379 # remove state when we complete successfully
3379 # remove state when we complete successfully
3380 if not opts.get('dry_run'):
3380 if not opts.get('dry_run'):
3381 graftstate.delete()
3381 graftstate.delete()
3382
3382
3383 return 0
3383 return 0
3384
3384
3385
3385
3386 def _stopgraft(ui, repo, graftstate):
3386 def _stopgraft(ui, repo, graftstate):
3387 """stop the interrupted graft"""
3387 """stop the interrupted graft"""
3388 if not graftstate.exists():
3388 if not graftstate.exists():
3389 raise error.StateError(_(b"no interrupted graft found"))
3389 raise error.StateError(_(b"no interrupted graft found"))
3390 pctx = repo[b'.']
3390 pctx = repo[b'.']
3391 mergemod.clean_update(pctx)
3391 mergemod.clean_update(pctx)
3392 graftstate.delete()
3392 graftstate.delete()
3393 ui.status(_(b"stopped the interrupted graft\n"))
3393 ui.status(_(b"stopped the interrupted graft\n"))
3394 ui.status(_(b"working directory is now at %s\n") % pctx.hex()[:12])
3394 ui.status(_(b"working directory is now at %s\n") % pctx.hex()[:12])
3395 return 0
3395 return 0
3396
3396
3397
3397
3398 statemod.addunfinished(
3398 statemod.addunfinished(
3399 b'graft',
3399 b'graft',
3400 fname=b'graftstate',
3400 fname=b'graftstate',
3401 clearable=True,
3401 clearable=True,
3402 stopflag=True,
3402 stopflag=True,
3403 continueflag=True,
3403 continueflag=True,
3404 abortfunc=cmdutil.hgabortgraft,
3404 abortfunc=cmdutil.hgabortgraft,
3405 cmdhint=_(b"use 'hg graft --continue' or 'hg graft --stop' to stop"),
3405 cmdhint=_(b"use 'hg graft --continue' or 'hg graft --stop' to stop"),
3406 )
3406 )
3407
3407
3408
3408
3409 @command(
3409 @command(
3410 b'grep',
3410 b'grep',
3411 [
3411 [
3412 (b'0', b'print0', None, _(b'end fields with NUL')),
3412 (b'0', b'print0', None, _(b'end fields with NUL')),
3413 (b'', b'all', None, _(b'an alias to --diff (DEPRECATED)')),
3413 (b'', b'all', None, _(b'an alias to --diff (DEPRECATED)')),
3414 (
3414 (
3415 b'',
3415 b'',
3416 b'diff',
3416 b'diff',
3417 None,
3417 None,
3418 _(
3418 _(
3419 b'search revision differences for when the pattern was added '
3419 b'search revision differences for when the pattern was added '
3420 b'or removed'
3420 b'or removed'
3421 ),
3421 ),
3422 ),
3422 ),
3423 (b'a', b'text', None, _(b'treat all files as text')),
3423 (b'a', b'text', None, _(b'treat all files as text')),
3424 (
3424 (
3425 b'f',
3425 b'f',
3426 b'follow',
3426 b'follow',
3427 None,
3427 None,
3428 _(
3428 _(
3429 b'follow changeset history,'
3429 b'follow changeset history,'
3430 b' or file history across copies and renames'
3430 b' or file history across copies and renames'
3431 ),
3431 ),
3432 ),
3432 ),
3433 (b'i', b'ignore-case', None, _(b'ignore case when matching')),
3433 (b'i', b'ignore-case', None, _(b'ignore case when matching')),
3434 (
3434 (
3435 b'l',
3435 b'l',
3436 b'files-with-matches',
3436 b'files-with-matches',
3437 None,
3437 None,
3438 _(b'print only filenames and revisions that match'),
3438 _(b'print only filenames and revisions that match'),
3439 ),
3439 ),
3440 (b'n', b'line-number', None, _(b'print matching line numbers')),
3440 (b'n', b'line-number', None, _(b'print matching line numbers')),
3441 (
3441 (
3442 b'r',
3442 b'r',
3443 b'rev',
3443 b'rev',
3444 [],
3444 [],
3445 _(b'search files changed within revision range'),
3445 _(b'search files changed within revision range'),
3446 _(b'REV'),
3446 _(b'REV'),
3447 ),
3447 ),
3448 (
3448 (
3449 b'',
3449 b'',
3450 b'all-files',
3450 b'all-files',
3451 None,
3451 None,
3452 _(
3452 _(
3453 b'include all files in the changeset while grepping (DEPRECATED)'
3453 b'include all files in the changeset while grepping (DEPRECATED)'
3454 ),
3454 ),
3455 ),
3455 ),
3456 (b'u', b'user', None, _(b'list the author (long with -v)')),
3456 (b'u', b'user', None, _(b'list the author (long with -v)')),
3457 (b'd', b'date', None, _(b'list the date (short with -q)')),
3457 (b'd', b'date', None, _(b'list the date (short with -q)')),
3458 ]
3458 ]
3459 + formatteropts
3459 + formatteropts
3460 + walkopts,
3460 + walkopts,
3461 _(b'[--diff] [OPTION]... PATTERN [FILE]...'),
3461 _(b'[--diff] [OPTION]... PATTERN [FILE]...'),
3462 helpcategory=command.CATEGORY_FILE_CONTENTS,
3462 helpcategory=command.CATEGORY_FILE_CONTENTS,
3463 inferrepo=True,
3463 inferrepo=True,
3464 intents={INTENT_READONLY},
3464 intents={INTENT_READONLY},
3465 )
3465 )
3466 def grep(ui, repo, pattern, *pats, **opts):
3466 def grep(ui, repo, pattern, *pats, **opts):
3467 """search for a pattern in specified files
3467 """search for a pattern in specified files
3468
3468
3469 Search the working directory or revision history for a regular
3469 Search the working directory or revision history for a regular
3470 expression in the specified files for the entire repository.
3470 expression in the specified files for the entire repository.
3471
3471
3472 By default, grep searches the repository files in the working
3472 By default, grep searches the repository files in the working
3473 directory and prints the files where it finds a match. To specify
3473 directory and prints the files where it finds a match. To specify
3474 historical revisions instead of the working directory, use the
3474 historical revisions instead of the working directory, use the
3475 --rev flag.
3475 --rev flag.
3476
3476
3477 To search instead historical revision differences that contains a
3477 To search instead historical revision differences that contains a
3478 change in match status ("-" for a match that becomes a non-match,
3478 change in match status ("-" for a match that becomes a non-match,
3479 or "+" for a non-match that becomes a match), use the --diff flag.
3479 or "+" for a non-match that becomes a match), use the --diff flag.
3480
3480
3481 PATTERN can be any Python (roughly Perl-compatible) regular
3481 PATTERN can be any Python (roughly Perl-compatible) regular
3482 expression.
3482 expression.
3483
3483
3484 If no FILEs are specified and the --rev flag isn't supplied, all
3484 If no FILEs are specified and the --rev flag isn't supplied, all
3485 files in the working directory are searched. When using the --rev
3485 files in the working directory are searched. When using the --rev
3486 flag and specifying FILEs, use the --follow argument to also
3486 flag and specifying FILEs, use the --follow argument to also
3487 follow the specified FILEs across renames and copies.
3487 follow the specified FILEs across renames and copies.
3488
3488
3489 .. container:: verbose
3489 .. container:: verbose
3490
3490
3491 Template:
3491 Template:
3492
3492
3493 The following keywords are supported in addition to the common template
3493 The following keywords are supported in addition to the common template
3494 keywords and functions. See also :hg:`help templates`.
3494 keywords and functions. See also :hg:`help templates`.
3495
3495
3496 :change: String. Character denoting insertion ``+`` or removal ``-``.
3496 :change: String. Character denoting insertion ``+`` or removal ``-``.
3497 Available if ``--diff`` is specified.
3497 Available if ``--diff`` is specified.
3498 :lineno: Integer. Line number of the match.
3498 :lineno: Integer. Line number of the match.
3499 :path: String. Repository-absolute path of the file.
3499 :path: String. Repository-absolute path of the file.
3500 :texts: List of text chunks.
3500 :texts: List of text chunks.
3501
3501
3502 And each entry of ``{texts}`` provides the following sub-keywords.
3502 And each entry of ``{texts}`` provides the following sub-keywords.
3503
3503
3504 :matched: Boolean. True if the chunk matches the specified pattern.
3504 :matched: Boolean. True if the chunk matches the specified pattern.
3505 :text: String. Chunk content.
3505 :text: String. Chunk content.
3506
3506
3507 See :hg:`help templates.operators` for the list expansion syntax.
3507 See :hg:`help templates.operators` for the list expansion syntax.
3508
3508
3509 Returns 0 if a match is found, 1 otherwise.
3509 Returns 0 if a match is found, 1 otherwise.
3510
3510
3511 """
3511 """
3512 cmdutil.check_incompatible_arguments(opts, 'all_files', ['all', 'diff'])
3512 cmdutil.check_incompatible_arguments(opts, 'all_files', ['all', 'diff'])
3513 opts = pycompat.byteskwargs(opts)
3513 opts = pycompat.byteskwargs(opts)
3514 diff = opts.get(b'all') or opts.get(b'diff')
3514 diff = opts.get(b'all') or opts.get(b'diff')
3515 follow = opts.get(b'follow')
3515 follow = opts.get(b'follow')
3516 if opts.get(b'all_files') is None and not diff:
3516 if opts.get(b'all_files') is None and not diff:
3517 opts[b'all_files'] = True
3517 opts[b'all_files'] = True
3518 plaingrep = (
3518 plaingrep = (
3519 opts.get(b'all_files')
3519 opts.get(b'all_files')
3520 and not opts.get(b'rev')
3520 and not opts.get(b'rev')
3521 and not opts.get(b'follow')
3521 and not opts.get(b'follow')
3522 )
3522 )
3523 all_files = opts.get(b'all_files')
3523 all_files = opts.get(b'all_files')
3524 if plaingrep:
3524 if plaingrep:
3525 opts[b'rev'] = [b'wdir()']
3525 opts[b'rev'] = [b'wdir()']
3526
3526
3527 reflags = re.M
3527 reflags = re.M
3528 if opts.get(b'ignore_case'):
3528 if opts.get(b'ignore_case'):
3529 reflags |= re.I
3529 reflags |= re.I
3530 try:
3530 try:
3531 regexp = util.re.compile(pattern, reflags)
3531 regexp = util.re.compile(pattern, reflags)
3532 except re.error as inst:
3532 except re.error as inst:
3533 ui.warn(
3533 ui.warn(
3534 _(b"grep: invalid match pattern: %s\n")
3534 _(b"grep: invalid match pattern: %s\n")
3535 % stringutil.forcebytestr(inst)
3535 % stringutil.forcebytestr(inst)
3536 )
3536 )
3537 return 1
3537 return 1
3538 sep, eol = b':', b'\n'
3538 sep, eol = b':', b'\n'
3539 if opts.get(b'print0'):
3539 if opts.get(b'print0'):
3540 sep = eol = b'\0'
3540 sep = eol = b'\0'
3541
3541
3542 searcher = grepmod.grepsearcher(
3542 searcher = grepmod.grepsearcher(
3543 ui, repo, regexp, all_files=all_files, diff=diff, follow=follow
3543 ui, repo, regexp, all_files=all_files, diff=diff, follow=follow
3544 )
3544 )
3545
3545
3546 getfile = searcher._getfile
3546 getfile = searcher._getfile
3547
3547
3548 uipathfn = scmutil.getuipathfn(repo)
3548 uipathfn = scmutil.getuipathfn(repo)
3549
3549
3550 def display(fm, fn, ctx, pstates, states):
3550 def display(fm, fn, ctx, pstates, states):
3551 rev = scmutil.intrev(ctx)
3551 rev = scmutil.intrev(ctx)
3552 if fm.isplain():
3552 if fm.isplain():
3553 formatuser = ui.shortuser
3553 formatuser = ui.shortuser
3554 else:
3554 else:
3555 formatuser = pycompat.bytestr
3555 formatuser = pycompat.bytestr
3556 if ui.quiet:
3556 if ui.quiet:
3557 datefmt = b'%Y-%m-%d'
3557 datefmt = b'%Y-%m-%d'
3558 else:
3558 else:
3559 datefmt = b'%a %b %d %H:%M:%S %Y %1%2'
3559 datefmt = b'%a %b %d %H:%M:%S %Y %1%2'
3560 found = False
3560 found = False
3561
3561
3562 @util.cachefunc
3562 @util.cachefunc
3563 def binary():
3563 def binary():
3564 flog = getfile(fn)
3564 flog = getfile(fn)
3565 try:
3565 try:
3566 return stringutil.binary(flog.read(ctx.filenode(fn)))
3566 return stringutil.binary(flog.read(ctx.filenode(fn)))
3567 except error.WdirUnsupported:
3567 except error.WdirUnsupported:
3568 return ctx[fn].isbinary()
3568 return ctx[fn].isbinary()
3569
3569
3570 fieldnamemap = {b'linenumber': b'lineno'}
3570 fieldnamemap = {b'linenumber': b'lineno'}
3571 if diff:
3571 if diff:
3572 iter = grepmod.difflinestates(pstates, states)
3572 iter = grepmod.difflinestates(pstates, states)
3573 else:
3573 else:
3574 iter = [(b'', l) for l in states]
3574 iter = [(b'', l) for l in states]
3575 for change, l in iter:
3575 for change, l in iter:
3576 fm.startitem()
3576 fm.startitem()
3577 fm.context(ctx=ctx)
3577 fm.context(ctx=ctx)
3578 fm.data(node=fm.hexfunc(scmutil.binnode(ctx)), path=fn)
3578 fm.data(node=fm.hexfunc(scmutil.binnode(ctx)), path=fn)
3579 fm.plain(uipathfn(fn), label=b'grep.filename')
3579 fm.plain(uipathfn(fn), label=b'grep.filename')
3580
3580
3581 cols = [
3581 cols = [
3582 (b'rev', b'%d', rev, not plaingrep, b''),
3582 (b'rev', b'%d', rev, not plaingrep, b''),
3583 (
3583 (
3584 b'linenumber',
3584 b'linenumber',
3585 b'%d',
3585 b'%d',
3586 l.linenum,
3586 l.linenum,
3587 opts.get(b'line_number'),
3587 opts.get(b'line_number'),
3588 b'',
3588 b'',
3589 ),
3589 ),
3590 ]
3590 ]
3591 if diff:
3591 if diff:
3592 cols.append(
3592 cols.append(
3593 (
3593 (
3594 b'change',
3594 b'change',
3595 b'%s',
3595 b'%s',
3596 change,
3596 change,
3597 True,
3597 True,
3598 b'grep.inserted '
3598 b'grep.inserted '
3599 if change == b'+'
3599 if change == b'+'
3600 else b'grep.deleted ',
3600 else b'grep.deleted ',
3601 )
3601 )
3602 )
3602 )
3603 cols.extend(
3603 cols.extend(
3604 [
3604 [
3605 (
3605 (
3606 b'user',
3606 b'user',
3607 b'%s',
3607 b'%s',
3608 formatuser(ctx.user()),
3608 formatuser(ctx.user()),
3609 opts.get(b'user'),
3609 opts.get(b'user'),
3610 b'',
3610 b'',
3611 ),
3611 ),
3612 (
3612 (
3613 b'date',
3613 b'date',
3614 b'%s',
3614 b'%s',
3615 fm.formatdate(ctx.date(), datefmt),
3615 fm.formatdate(ctx.date(), datefmt),
3616 opts.get(b'date'),
3616 opts.get(b'date'),
3617 b'',
3617 b'',
3618 ),
3618 ),
3619 ]
3619 ]
3620 )
3620 )
3621 for name, fmt, data, cond, extra_label in cols:
3621 for name, fmt, data, cond, extra_label in cols:
3622 if cond:
3622 if cond:
3623 fm.plain(sep, label=b'grep.sep')
3623 fm.plain(sep, label=b'grep.sep')
3624 field = fieldnamemap.get(name, name)
3624 field = fieldnamemap.get(name, name)
3625 label = extra_label + (b'grep.%s' % name)
3625 label = extra_label + (b'grep.%s' % name)
3626 fm.condwrite(cond, field, fmt, data, label=label)
3626 fm.condwrite(cond, field, fmt, data, label=label)
3627 if not opts.get(b'files_with_matches'):
3627 if not opts.get(b'files_with_matches'):
3628 fm.plain(sep, label=b'grep.sep')
3628 fm.plain(sep, label=b'grep.sep')
3629 if not opts.get(b'text') and binary():
3629 if not opts.get(b'text') and binary():
3630 fm.plain(_(b" Binary file matches"))
3630 fm.plain(_(b" Binary file matches"))
3631 else:
3631 else:
3632 displaymatches(fm.nested(b'texts', tmpl=b'{text}'), l)
3632 displaymatches(fm.nested(b'texts', tmpl=b'{text}'), l)
3633 fm.plain(eol)
3633 fm.plain(eol)
3634 found = True
3634 found = True
3635 if opts.get(b'files_with_matches'):
3635 if opts.get(b'files_with_matches'):
3636 break
3636 break
3637 return found
3637 return found
3638
3638
3639 def displaymatches(fm, l):
3639 def displaymatches(fm, l):
3640 p = 0
3640 p = 0
3641 for s, e in l.findpos(regexp):
3641 for s, e in l.findpos(regexp):
3642 if p < s:
3642 if p < s:
3643 fm.startitem()
3643 fm.startitem()
3644 fm.write(b'text', b'%s', l.line[p:s])
3644 fm.write(b'text', b'%s', l.line[p:s])
3645 fm.data(matched=False)
3645 fm.data(matched=False)
3646 fm.startitem()
3646 fm.startitem()
3647 fm.write(b'text', b'%s', l.line[s:e], label=b'grep.match')
3647 fm.write(b'text', b'%s', l.line[s:e], label=b'grep.match')
3648 fm.data(matched=True)
3648 fm.data(matched=True)
3649 p = e
3649 p = e
3650 if p < len(l.line):
3650 if p < len(l.line):
3651 fm.startitem()
3651 fm.startitem()
3652 fm.write(b'text', b'%s', l.line[p:])
3652 fm.write(b'text', b'%s', l.line[p:])
3653 fm.data(matched=False)
3653 fm.data(matched=False)
3654 fm.end()
3654 fm.end()
3655
3655
3656 found = False
3656 found = False
3657
3657
3658 wopts = logcmdutil.walkopts(
3658 wopts = logcmdutil.walkopts(
3659 pats=pats,
3659 pats=pats,
3660 opts=opts,
3660 opts=opts,
3661 revspec=opts[b'rev'],
3661 revspec=opts[b'rev'],
3662 include_pats=opts[b'include'],
3662 include_pats=opts[b'include'],
3663 exclude_pats=opts[b'exclude'],
3663 exclude_pats=opts[b'exclude'],
3664 follow=follow,
3664 follow=follow,
3665 force_changelog_traversal=all_files,
3665 force_changelog_traversal=all_files,
3666 filter_revisions_by_pats=not all_files,
3666 filter_revisions_by_pats=not all_files,
3667 )
3667 )
3668 revs, makefilematcher = logcmdutil.makewalker(repo, wopts)
3668 revs, makefilematcher = logcmdutil.makewalker(repo, wopts)
3669
3669
3670 ui.pager(b'grep')
3670 ui.pager(b'grep')
3671 fm = ui.formatter(b'grep', opts)
3671 fm = ui.formatter(b'grep', opts)
3672 for fn, ctx, pstates, states in searcher.searchfiles(revs, makefilematcher):
3672 for fn, ctx, pstates, states in searcher.searchfiles(revs, makefilematcher):
3673 r = display(fm, fn, ctx, pstates, states)
3673 r = display(fm, fn, ctx, pstates, states)
3674 found = found or r
3674 found = found or r
3675 if r and not diff and not all_files:
3675 if r and not diff and not all_files:
3676 searcher.skipfile(fn, ctx.rev())
3676 searcher.skipfile(fn, ctx.rev())
3677 fm.end()
3677 fm.end()
3678
3678
3679 return not found
3679 return not found
3680
3680
3681
3681
3682 @command(
3682 @command(
3683 b'heads',
3683 b'heads',
3684 [
3684 [
3685 (
3685 (
3686 b'r',
3686 b'r',
3687 b'rev',
3687 b'rev',
3688 b'',
3688 b'',
3689 _(b'show only heads which are descendants of STARTREV'),
3689 _(b'show only heads which are descendants of STARTREV'),
3690 _(b'STARTREV'),
3690 _(b'STARTREV'),
3691 ),
3691 ),
3692 (b't', b'topo', False, _(b'show topological heads only')),
3692 (b't', b'topo', False, _(b'show topological heads only')),
3693 (
3693 (
3694 b'a',
3694 b'a',
3695 b'active',
3695 b'active',
3696 False,
3696 False,
3697 _(b'show active branchheads only (DEPRECATED)'),
3697 _(b'show active branchheads only (DEPRECATED)'),
3698 ),
3698 ),
3699 (b'c', b'closed', False, _(b'show normal and closed branch heads')),
3699 (b'c', b'closed', False, _(b'show normal and closed branch heads')),
3700 ]
3700 ]
3701 + templateopts,
3701 + templateopts,
3702 _(b'[-ct] [-r STARTREV] [REV]...'),
3702 _(b'[-ct] [-r STARTREV] [REV]...'),
3703 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3703 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3704 intents={INTENT_READONLY},
3704 intents={INTENT_READONLY},
3705 )
3705 )
3706 def heads(ui, repo, *branchrevs, **opts):
3706 def heads(ui, repo, *branchrevs, **opts):
3707 """show branch heads
3707 """show branch heads
3708
3708
3709 With no arguments, show all open branch heads in the repository.
3709 With no arguments, show all open branch heads in the repository.
3710 Branch heads are changesets that have no descendants on the
3710 Branch heads are changesets that have no descendants on the
3711 same branch. They are where development generally takes place and
3711 same branch. They are where development generally takes place and
3712 are the usual targets for update and merge operations.
3712 are the usual targets for update and merge operations.
3713
3713
3714 If one or more REVs are given, only open branch heads on the
3714 If one or more REVs are given, only open branch heads on the
3715 branches associated with the specified changesets are shown. This
3715 branches associated with the specified changesets are shown. This
3716 means that you can use :hg:`heads .` to see the heads on the
3716 means that you can use :hg:`heads .` to see the heads on the
3717 currently checked-out branch.
3717 currently checked-out branch.
3718
3718
3719 If -c/--closed is specified, also show branch heads marked closed
3719 If -c/--closed is specified, also show branch heads marked closed
3720 (see :hg:`commit --close-branch`).
3720 (see :hg:`commit --close-branch`).
3721
3721
3722 If STARTREV is specified, only those heads that are descendants of
3722 If STARTREV is specified, only those heads that are descendants of
3723 STARTREV will be displayed.
3723 STARTREV will be displayed.
3724
3724
3725 If -t/--topo is specified, named branch mechanics will be ignored and only
3725 If -t/--topo is specified, named branch mechanics will be ignored and only
3726 topological heads (changesets with no children) will be shown.
3726 topological heads (changesets with no children) will be shown.
3727
3727
3728 Returns 0 if matching heads are found, 1 if not.
3728 Returns 0 if matching heads are found, 1 if not.
3729 """
3729 """
3730
3730
3731 opts = pycompat.byteskwargs(opts)
3731 opts = pycompat.byteskwargs(opts)
3732 start = None
3732 start = None
3733 rev = opts.get(b'rev')
3733 rev = opts.get(b'rev')
3734 if rev:
3734 if rev:
3735 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
3735 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
3736 start = logcmdutil.revsingle(repo, rev, None).node()
3736 start = logcmdutil.revsingle(repo, rev, None).node()
3737
3737
3738 if opts.get(b'topo'):
3738 if opts.get(b'topo'):
3739 heads = [repo[h] for h in repo.heads(start)]
3739 heads = [repo[h] for h in repo.heads(start)]
3740 else:
3740 else:
3741 heads = []
3741 heads = []
3742 for branch in repo.branchmap():
3742 for branch in repo.branchmap():
3743 heads += repo.branchheads(branch, start, opts.get(b'closed'))
3743 heads += repo.branchheads(branch, start, opts.get(b'closed'))
3744 heads = [repo[h] for h in heads]
3744 heads = [repo[h] for h in heads]
3745
3745
3746 if branchrevs:
3746 if branchrevs:
3747 branches = {
3747 branches = {
3748 repo[r].branch() for r in logcmdutil.revrange(repo, branchrevs)
3748 repo[r].branch() for r in logcmdutil.revrange(repo, branchrevs)
3749 }
3749 }
3750 heads = [h for h in heads if h.branch() in branches]
3750 heads = [h for h in heads if h.branch() in branches]
3751
3751
3752 if opts.get(b'active') and branchrevs:
3752 if opts.get(b'active') and branchrevs:
3753 dagheads = repo.heads(start)
3753 dagheads = repo.heads(start)
3754 heads = [h for h in heads if h.node() in dagheads]
3754 heads = [h for h in heads if h.node() in dagheads]
3755
3755
3756 if branchrevs:
3756 if branchrevs:
3757 haveheads = {h.branch() for h in heads}
3757 haveheads = {h.branch() for h in heads}
3758 if branches - haveheads:
3758 if branches - haveheads:
3759 headless = b', '.join(b for b in branches - haveheads)
3759 headless = b', '.join(b for b in branches - haveheads)
3760 msg = _(b'no open branch heads found on branches %s')
3760 msg = _(b'no open branch heads found on branches %s')
3761 if opts.get(b'rev'):
3761 if opts.get(b'rev'):
3762 msg += _(b' (started at %s)') % opts[b'rev']
3762 msg += _(b' (started at %s)') % opts[b'rev']
3763 ui.warn((msg + b'\n') % headless)
3763 ui.warn((msg + b'\n') % headless)
3764
3764
3765 if not heads:
3765 if not heads:
3766 return 1
3766 return 1
3767
3767
3768 ui.pager(b'heads')
3768 ui.pager(b'heads')
3769 heads = sorted(heads, key=lambda x: -(x.rev()))
3769 heads = sorted(heads, key=lambda x: -(x.rev()))
3770 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
3770 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
3771 for ctx in heads:
3771 for ctx in heads:
3772 displayer.show(ctx)
3772 displayer.show(ctx)
3773 displayer.close()
3773 displayer.close()
3774
3774
3775
3775
3776 @command(
3776 @command(
3777 b'help',
3777 b'help',
3778 [
3778 [
3779 (b'e', b'extension', None, _(b'show only help for extensions')),
3779 (b'e', b'extension', None, _(b'show only help for extensions')),
3780 (b'c', b'command', None, _(b'show only help for commands')),
3780 (b'c', b'command', None, _(b'show only help for commands')),
3781 (b'k', b'keyword', None, _(b'show topics matching keyword')),
3781 (b'k', b'keyword', None, _(b'show topics matching keyword')),
3782 (
3782 (
3783 b's',
3783 b's',
3784 b'system',
3784 b'system',
3785 [],
3785 [],
3786 _(b'show help for specific platform(s)'),
3786 _(b'show help for specific platform(s)'),
3787 _(b'PLATFORM'),
3787 _(b'PLATFORM'),
3788 ),
3788 ),
3789 ],
3789 ],
3790 _(b'[-eck] [-s PLATFORM] [TOPIC]'),
3790 _(b'[-eck] [-s PLATFORM] [TOPIC]'),
3791 helpcategory=command.CATEGORY_HELP,
3791 helpcategory=command.CATEGORY_HELP,
3792 norepo=True,
3792 norepo=True,
3793 intents={INTENT_READONLY},
3793 intents={INTENT_READONLY},
3794 )
3794 )
3795 def help_(ui, name=None, **opts):
3795 def help_(ui, name=None, **opts):
3796 """show help for a given topic or a help overview
3796 """show help for a given topic or a help overview
3797
3797
3798 With no arguments, print a list of commands with short help messages.
3798 With no arguments, print a list of commands with short help messages.
3799
3799
3800 Given a topic, extension, or command name, print help for that
3800 Given a topic, extension, or command name, print help for that
3801 topic.
3801 topic.
3802
3802
3803 Returns 0 if successful.
3803 Returns 0 if successful.
3804 """
3804 """
3805
3805
3806 keep = opts.get('system') or []
3806 keep = opts.get('system') or []
3807 if len(keep) == 0:
3807 if len(keep) == 0:
3808 if pycompat.sysplatform.startswith(b'win'):
3808 if pycompat.sysplatform.startswith(b'win'):
3809 keep.append(b'windows')
3809 keep.append(b'windows')
3810 elif pycompat.sysplatform == b'OpenVMS':
3810 elif pycompat.sysplatform == b'OpenVMS':
3811 keep.append(b'vms')
3811 keep.append(b'vms')
3812 elif pycompat.sysplatform == b'plan9':
3812 elif pycompat.sysplatform == b'plan9':
3813 keep.append(b'plan9')
3813 keep.append(b'plan9')
3814 else:
3814 else:
3815 keep.append(b'unix')
3815 keep.append(b'unix')
3816 keep.append(pycompat.sysplatform.lower())
3816 keep.append(pycompat.sysplatform.lower())
3817 if ui.verbose:
3817 if ui.verbose:
3818 keep.append(b'verbose')
3818 keep.append(b'verbose')
3819
3819
3820 commands = sys.modules[__name__]
3820 commands = sys.modules[__name__]
3821 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
3821 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
3822 ui.pager(b'help')
3822 ui.pager(b'help')
3823 ui.write(formatted)
3823 ui.write(formatted)
3824
3824
3825
3825
3826 @command(
3826 @command(
3827 b'identify|id',
3827 b'identify|id',
3828 [
3828 [
3829 (b'r', b'rev', b'', _(b'identify the specified revision'), _(b'REV')),
3829 (b'r', b'rev', b'', _(b'identify the specified revision'), _(b'REV')),
3830 (b'n', b'num', None, _(b'show local revision number')),
3830 (b'n', b'num', None, _(b'show local revision number')),
3831 (b'i', b'id', None, _(b'show global revision id')),
3831 (b'i', b'id', None, _(b'show global revision id')),
3832 (b'b', b'branch', None, _(b'show branch')),
3832 (b'b', b'branch', None, _(b'show branch')),
3833 (b't', b'tags', None, _(b'show tags')),
3833 (b't', b'tags', None, _(b'show tags')),
3834 (b'B', b'bookmarks', None, _(b'show bookmarks')),
3834 (b'B', b'bookmarks', None, _(b'show bookmarks')),
3835 ]
3835 ]
3836 + remoteopts
3836 + remoteopts
3837 + formatteropts,
3837 + formatteropts,
3838 _(b'[-nibtB] [-r REV] [SOURCE]'),
3838 _(b'[-nibtB] [-r REV] [SOURCE]'),
3839 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3839 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3840 optionalrepo=True,
3840 optionalrepo=True,
3841 intents={INTENT_READONLY},
3841 intents={INTENT_READONLY},
3842 )
3842 )
3843 def identify(
3843 def identify(
3844 ui,
3844 ui,
3845 repo,
3845 repo,
3846 source=None,
3846 source=None,
3847 rev=None,
3847 rev=None,
3848 num=None,
3848 num=None,
3849 id=None,
3849 id=None,
3850 branch=None,
3850 branch=None,
3851 tags=None,
3851 tags=None,
3852 bookmarks=None,
3852 bookmarks=None,
3853 **opts
3853 **opts
3854 ):
3854 ):
3855 """identify the working directory or specified revision
3855 """identify the working directory or specified revision
3856
3856
3857 Print a summary identifying the repository state at REV using one or
3857 Print a summary identifying the repository state at REV using one or
3858 two parent hash identifiers, followed by a "+" if the working
3858 two parent hash identifiers, followed by a "+" if the working
3859 directory has uncommitted changes, the branch name (if not default),
3859 directory has uncommitted changes, the branch name (if not default),
3860 a list of tags, and a list of bookmarks.
3860 a list of tags, and a list of bookmarks.
3861
3861
3862 When REV is not given, print a summary of the current state of the
3862 When REV is not given, print a summary of the current state of the
3863 repository including the working directory. Specify -r. to get information
3863 repository including the working directory. Specify -r. to get information
3864 of the working directory parent without scanning uncommitted changes.
3864 of the working directory parent without scanning uncommitted changes.
3865
3865
3866 Specifying a path to a repository root or Mercurial bundle will
3866 Specifying a path to a repository root or Mercurial bundle will
3867 cause lookup to operate on that repository/bundle.
3867 cause lookup to operate on that repository/bundle.
3868
3868
3869 .. container:: verbose
3869 .. container:: verbose
3870
3870
3871 Template:
3871 Template:
3872
3872
3873 The following keywords are supported in addition to the common template
3873 The following keywords are supported in addition to the common template
3874 keywords and functions. See also :hg:`help templates`.
3874 keywords and functions. See also :hg:`help templates`.
3875
3875
3876 :dirty: String. Character ``+`` denoting if the working directory has
3876 :dirty: String. Character ``+`` denoting if the working directory has
3877 uncommitted changes.
3877 uncommitted changes.
3878 :id: String. One or two nodes, optionally followed by ``+``.
3878 :id: String. One or two nodes, optionally followed by ``+``.
3879 :parents: List of strings. Parent nodes of the changeset.
3879 :parents: List of strings. Parent nodes of the changeset.
3880
3880
3881 Examples:
3881 Examples:
3882
3882
3883 - generate a build identifier for the working directory::
3883 - generate a build identifier for the working directory::
3884
3884
3885 hg id --id > build-id.dat
3885 hg id --id > build-id.dat
3886
3886
3887 - find the revision corresponding to a tag::
3887 - find the revision corresponding to a tag::
3888
3888
3889 hg id -n -r 1.3
3889 hg id -n -r 1.3
3890
3890
3891 - check the most recent revision of a remote repository::
3891 - check the most recent revision of a remote repository::
3892
3892
3893 hg id -r tip https://www.mercurial-scm.org/repo/hg/
3893 hg id -r tip https://www.mercurial-scm.org/repo/hg/
3894
3894
3895 See :hg:`log` for generating more information about specific revisions,
3895 See :hg:`log` for generating more information about specific revisions,
3896 including full hash identifiers.
3896 including full hash identifiers.
3897
3897
3898 Returns 0 if successful.
3898 Returns 0 if successful.
3899 """
3899 """
3900
3900
3901 opts = pycompat.byteskwargs(opts)
3901 opts = pycompat.byteskwargs(opts)
3902 if not repo and not source:
3902 if not repo and not source:
3903 raise error.InputError(
3903 raise error.InputError(
3904 _(b"there is no Mercurial repository here (.hg not found)")
3904 _(b"there is no Mercurial repository here (.hg not found)")
3905 )
3905 )
3906
3906
3907 default = not (num or id or branch or tags or bookmarks)
3907 default = not (num or id or branch or tags or bookmarks)
3908 output = []
3908 output = []
3909 revs = []
3909 revs = []
3910
3910
3911 peer = None
3911 peer = None
3912 try:
3912 try:
3913 if source:
3913 if source:
3914 source, branches = urlutil.get_unique_pull_path(
3914 source, branches = urlutil.get_unique_pull_path(
3915 b'identify', repo, ui, source
3915 b'identify', repo, ui, source
3916 )
3916 )
3917 # only pass ui when no repo
3917 # only pass ui when no repo
3918 peer = hg.peer(repo or ui, opts, source)
3918 peer = hg.peer(repo or ui, opts, source)
3919 repo = peer.local()
3919 repo = peer.local()
3920 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3920 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3921
3921
3922 fm = ui.formatter(b'identify', opts)
3922 fm = ui.formatter(b'identify', opts)
3923 fm.startitem()
3923 fm.startitem()
3924
3924
3925 if not repo:
3925 if not repo:
3926 if num or branch or tags:
3926 if num or branch or tags:
3927 raise error.InputError(
3927 raise error.InputError(
3928 _(b"can't query remote revision number, branch, or tags")
3928 _(b"can't query remote revision number, branch, or tags")
3929 )
3929 )
3930 if not rev and revs:
3930 if not rev and revs:
3931 rev = revs[0]
3931 rev = revs[0]
3932 if not rev:
3932 if not rev:
3933 rev = b"tip"
3933 rev = b"tip"
3934
3934
3935 remoterev = peer.lookup(rev)
3935 remoterev = peer.lookup(rev)
3936 hexrev = fm.hexfunc(remoterev)
3936 hexrev = fm.hexfunc(remoterev)
3937 if default or id:
3937 if default or id:
3938 output = [hexrev]
3938 output = [hexrev]
3939 fm.data(id=hexrev)
3939 fm.data(id=hexrev)
3940
3940
3941 @util.cachefunc
3941 @util.cachefunc
3942 def getbms():
3942 def getbms():
3943 bms = []
3943 bms = []
3944
3944
3945 if b'bookmarks' in peer.listkeys(b'namespaces'):
3945 if b'bookmarks' in peer.listkeys(b'namespaces'):
3946 hexremoterev = hex(remoterev)
3946 hexremoterev = hex(remoterev)
3947 bms = [
3947 bms = [
3948 bm
3948 bm
3949 for bm, bmr in peer.listkeys(b'bookmarks').items()
3949 for bm, bmr in peer.listkeys(b'bookmarks').items()
3950 if bmr == hexremoterev
3950 if bmr == hexremoterev
3951 ]
3951 ]
3952
3952
3953 return sorted(bms)
3953 return sorted(bms)
3954
3954
3955 if fm.isplain():
3955 if fm.isplain():
3956 if bookmarks:
3956 if bookmarks:
3957 output.extend(getbms())
3957 output.extend(getbms())
3958 elif default and not ui.quiet:
3958 elif default and not ui.quiet:
3959 # multiple bookmarks for a single parent separated by '/'
3959 # multiple bookmarks for a single parent separated by '/'
3960 bm = b'/'.join(getbms())
3960 bm = b'/'.join(getbms())
3961 if bm:
3961 if bm:
3962 output.append(bm)
3962 output.append(bm)
3963 else:
3963 else:
3964 fm.data(node=hex(remoterev))
3964 fm.data(node=hex(remoterev))
3965 if bookmarks or b'bookmarks' in fm.datahint():
3965 if bookmarks or b'bookmarks' in fm.datahint():
3966 fm.data(bookmarks=fm.formatlist(getbms(), name=b'bookmark'))
3966 fm.data(bookmarks=fm.formatlist(getbms(), name=b'bookmark'))
3967 else:
3967 else:
3968 if rev:
3968 if rev:
3969 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
3969 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
3970 ctx = logcmdutil.revsingle(repo, rev, None)
3970 ctx = logcmdutil.revsingle(repo, rev, None)
3971
3971
3972 if ctx.rev() is None:
3972 if ctx.rev() is None:
3973 ctx = repo[None]
3973 ctx = repo[None]
3974 parents = ctx.parents()
3974 parents = ctx.parents()
3975 taglist = []
3975 taglist = []
3976 for p in parents:
3976 for p in parents:
3977 taglist.extend(p.tags())
3977 taglist.extend(p.tags())
3978
3978
3979 dirty = b""
3979 dirty = b""
3980 if ctx.dirty(missing=True, merge=False, branch=False):
3980 if ctx.dirty(missing=True, merge=False, branch=False):
3981 dirty = b'+'
3981 dirty = b'+'
3982 fm.data(dirty=dirty)
3982 fm.data(dirty=dirty)
3983
3983
3984 hexoutput = [fm.hexfunc(p.node()) for p in parents]
3984 hexoutput = [fm.hexfunc(p.node()) for p in parents]
3985 if default or id:
3985 if default or id:
3986 output = [b"%s%s" % (b'+'.join(hexoutput), dirty)]
3986 output = [b"%s%s" % (b'+'.join(hexoutput), dirty)]
3987 fm.data(id=b"%s%s" % (b'+'.join(hexoutput), dirty))
3987 fm.data(id=b"%s%s" % (b'+'.join(hexoutput), dirty))
3988
3988
3989 if num:
3989 if num:
3990 numoutput = [b"%d" % p.rev() for p in parents]
3990 numoutput = [b"%d" % p.rev() for p in parents]
3991 output.append(b"%s%s" % (b'+'.join(numoutput), dirty))
3991 output.append(b"%s%s" % (b'+'.join(numoutput), dirty))
3992
3992
3993 fm.data(
3993 fm.data(
3994 parents=fm.formatlist(
3994 parents=fm.formatlist(
3995 [fm.hexfunc(p.node()) for p in parents], name=b'node'
3995 [fm.hexfunc(p.node()) for p in parents], name=b'node'
3996 )
3996 )
3997 )
3997 )
3998 else:
3998 else:
3999 hexoutput = fm.hexfunc(ctx.node())
3999 hexoutput = fm.hexfunc(ctx.node())
4000 if default or id:
4000 if default or id:
4001 output = [hexoutput]
4001 output = [hexoutput]
4002 fm.data(id=hexoutput)
4002 fm.data(id=hexoutput)
4003
4003
4004 if num:
4004 if num:
4005 output.append(pycompat.bytestr(ctx.rev()))
4005 output.append(pycompat.bytestr(ctx.rev()))
4006 taglist = ctx.tags()
4006 taglist = ctx.tags()
4007
4007
4008 if default and not ui.quiet:
4008 if default and not ui.quiet:
4009 b = ctx.branch()
4009 b = ctx.branch()
4010 if b != b'default':
4010 if b != b'default':
4011 output.append(b"(%s)" % b)
4011 output.append(b"(%s)" % b)
4012
4012
4013 # multiple tags for a single parent separated by '/'
4013 # multiple tags for a single parent separated by '/'
4014 t = b'/'.join(taglist)
4014 t = b'/'.join(taglist)
4015 if t:
4015 if t:
4016 output.append(t)
4016 output.append(t)
4017
4017
4018 # multiple bookmarks for a single parent separated by '/'
4018 # multiple bookmarks for a single parent separated by '/'
4019 bm = b'/'.join(ctx.bookmarks())
4019 bm = b'/'.join(ctx.bookmarks())
4020 if bm:
4020 if bm:
4021 output.append(bm)
4021 output.append(bm)
4022 else:
4022 else:
4023 if branch:
4023 if branch:
4024 output.append(ctx.branch())
4024 output.append(ctx.branch())
4025
4025
4026 if tags:
4026 if tags:
4027 output.extend(taglist)
4027 output.extend(taglist)
4028
4028
4029 if bookmarks:
4029 if bookmarks:
4030 output.extend(ctx.bookmarks())
4030 output.extend(ctx.bookmarks())
4031
4031
4032 fm.data(node=ctx.hex())
4032 fm.data(node=ctx.hex())
4033 fm.data(branch=ctx.branch())
4033 fm.data(branch=ctx.branch())
4034 fm.data(tags=fm.formatlist(taglist, name=b'tag', sep=b':'))
4034 fm.data(tags=fm.formatlist(taglist, name=b'tag', sep=b':'))
4035 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name=b'bookmark'))
4035 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name=b'bookmark'))
4036 fm.context(ctx=ctx)
4036 fm.context(ctx=ctx)
4037
4037
4038 fm.plain(b"%s\n" % b' '.join(output))
4038 fm.plain(b"%s\n" % b' '.join(output))
4039 fm.end()
4039 fm.end()
4040 finally:
4040 finally:
4041 if peer:
4041 if peer:
4042 peer.close()
4042 peer.close()
4043
4043
4044
4044
4045 @command(
4045 @command(
4046 b'import|patch',
4046 b'import|patch',
4047 [
4047 [
4048 (
4048 (
4049 b'p',
4049 b'p',
4050 b'strip',
4050 b'strip',
4051 1,
4051 1,
4052 _(
4052 _(
4053 b'directory strip option for patch. This has the same '
4053 b'directory strip option for patch. This has the same '
4054 b'meaning as the corresponding patch option'
4054 b'meaning as the corresponding patch option'
4055 ),
4055 ),
4056 _(b'NUM'),
4056 _(b'NUM'),
4057 ),
4057 ),
4058 (b'b', b'base', b'', _(b'base path (DEPRECATED)'), _(b'PATH')),
4058 (b'b', b'base', b'', _(b'base path (DEPRECATED)'), _(b'PATH')),
4059 (b'', b'secret', None, _(b'use the secret phase for committing')),
4059 (b'', b'secret', None, _(b'use the secret phase for committing')),
4060 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
4060 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
4061 (
4061 (
4062 b'f',
4062 b'f',
4063 b'force',
4063 b'force',
4064 None,
4064 None,
4065 _(b'skip check for outstanding uncommitted changes (DEPRECATED)'),
4065 _(b'skip check for outstanding uncommitted changes (DEPRECATED)'),
4066 ),
4066 ),
4067 (
4067 (
4068 b'',
4068 b'',
4069 b'no-commit',
4069 b'no-commit',
4070 None,
4070 None,
4071 _(b"don't commit, just update the working directory"),
4071 _(b"don't commit, just update the working directory"),
4072 ),
4072 ),
4073 (
4073 (
4074 b'',
4074 b'',
4075 b'bypass',
4075 b'bypass',
4076 None,
4076 None,
4077 _(b"apply patch without touching the working directory"),
4077 _(b"apply patch without touching the working directory"),
4078 ),
4078 ),
4079 (b'', b'partial', None, _(b'commit even if some hunks fail')),
4079 (b'', b'partial', None, _(b'commit even if some hunks fail')),
4080 (b'', b'exact', None, _(b'abort if patch would apply lossily')),
4080 (b'', b'exact', None, _(b'abort if patch would apply lossily')),
4081 (b'', b'prefix', b'', _(b'apply patch to subdirectory'), _(b'DIR')),
4081 (b'', b'prefix', b'', _(b'apply patch to subdirectory'), _(b'DIR')),
4082 (
4082 (
4083 b'',
4083 b'',
4084 b'import-branch',
4084 b'import-branch',
4085 None,
4085 None,
4086 _(b'use any branch information in patch (implied by --exact)'),
4086 _(b'use any branch information in patch (implied by --exact)'),
4087 ),
4087 ),
4088 ]
4088 ]
4089 + commitopts
4089 + commitopts
4090 + commitopts2
4090 + commitopts2
4091 + similarityopts,
4091 + similarityopts,
4092 _(b'[OPTION]... PATCH...'),
4092 _(b'[OPTION]... PATCH...'),
4093 helpcategory=command.CATEGORY_IMPORT_EXPORT,
4093 helpcategory=command.CATEGORY_IMPORT_EXPORT,
4094 )
4094 )
4095 def import_(ui, repo, patch1=None, *patches, **opts):
4095 def import_(ui, repo, patch1=None, *patches, **opts):
4096 """import an ordered set of patches
4096 """import an ordered set of patches
4097
4097
4098 Import a list of patches and commit them individually (unless
4098 Import a list of patches and commit them individually (unless
4099 --no-commit is specified).
4099 --no-commit is specified).
4100
4100
4101 To read a patch from standard input (stdin), use "-" as the patch
4101 To read a patch from standard input (stdin), use "-" as the patch
4102 name. If a URL is specified, the patch will be downloaded from
4102 name. If a URL is specified, the patch will be downloaded from
4103 there.
4103 there.
4104
4104
4105 Import first applies changes to the working directory (unless
4105 Import first applies changes to the working directory (unless
4106 --bypass is specified), import will abort if there are outstanding
4106 --bypass is specified), import will abort if there are outstanding
4107 changes.
4107 changes.
4108
4108
4109 Use --bypass to apply and commit patches directly to the
4109 Use --bypass to apply and commit patches directly to the
4110 repository, without affecting the working directory. Without
4110 repository, without affecting the working directory. Without
4111 --exact, patches will be applied on top of the working directory
4111 --exact, patches will be applied on top of the working directory
4112 parent revision.
4112 parent revision.
4113
4113
4114 You can import a patch straight from a mail message. Even patches
4114 You can import a patch straight from a mail message. Even patches
4115 as attachments work (to use the body part, it must have type
4115 as attachments work (to use the body part, it must have type
4116 text/plain or text/x-patch). From and Subject headers of email
4116 text/plain or text/x-patch). From and Subject headers of email
4117 message are used as default committer and commit message. All
4117 message are used as default committer and commit message. All
4118 text/plain body parts before first diff are added to the commit
4118 text/plain body parts before first diff are added to the commit
4119 message.
4119 message.
4120
4120
4121 If the imported patch was generated by :hg:`export`, user and
4121 If the imported patch was generated by :hg:`export`, user and
4122 description from patch override values from message headers and
4122 description from patch override values from message headers and
4123 body. Values given on command line with -m/--message and -u/--user
4123 body. Values given on command line with -m/--message and -u/--user
4124 override these.
4124 override these.
4125
4125
4126 If --exact is specified, import will set the working directory to
4126 If --exact is specified, import will set the working directory to
4127 the parent of each patch before applying it, and will abort if the
4127 the parent of each patch before applying it, and will abort if the
4128 resulting changeset has a different ID than the one recorded in
4128 resulting changeset has a different ID than the one recorded in
4129 the patch. This will guard against various ways that portable
4129 the patch. This will guard against various ways that portable
4130 patch formats and mail systems might fail to transfer Mercurial
4130 patch formats and mail systems might fail to transfer Mercurial
4131 data or metadata. See :hg:`bundle` for lossless transmission.
4131 data or metadata. See :hg:`bundle` for lossless transmission.
4132
4132
4133 Use --partial to ensure a changeset will be created from the patch
4133 Use --partial to ensure a changeset will be created from the patch
4134 even if some hunks fail to apply. Hunks that fail to apply will be
4134 even if some hunks fail to apply. Hunks that fail to apply will be
4135 written to a <target-file>.rej file. Conflicts can then be resolved
4135 written to a <target-file>.rej file. Conflicts can then be resolved
4136 by hand before :hg:`commit --amend` is run to update the created
4136 by hand before :hg:`commit --amend` is run to update the created
4137 changeset. This flag exists to let people import patches that
4137 changeset. This flag exists to let people import patches that
4138 partially apply without losing the associated metadata (author,
4138 partially apply without losing the associated metadata (author,
4139 date, description, ...).
4139 date, description, ...).
4140
4140
4141 .. note::
4141 .. note::
4142
4142
4143 When no hunks apply cleanly, :hg:`import --partial` will create
4143 When no hunks apply cleanly, :hg:`import --partial` will create
4144 an empty changeset, importing only the patch metadata.
4144 an empty changeset, importing only the patch metadata.
4145
4145
4146 With -s/--similarity, hg will attempt to discover renames and
4146 With -s/--similarity, hg will attempt to discover renames and
4147 copies in the patch in the same way as :hg:`addremove`.
4147 copies in the patch in the same way as :hg:`addremove`.
4148
4148
4149 It is possible to use external patch programs to perform the patch
4149 It is possible to use external patch programs to perform the patch
4150 by setting the ``ui.patch`` configuration option. For the default
4150 by setting the ``ui.patch`` configuration option. For the default
4151 internal tool, the fuzz can also be configured via ``patch.fuzz``.
4151 internal tool, the fuzz can also be configured via ``patch.fuzz``.
4152 See :hg:`help config` for more information about configuration
4152 See :hg:`help config` for more information about configuration
4153 files and how to use these options.
4153 files and how to use these options.
4154
4154
4155 See :hg:`help dates` for a list of formats valid for -d/--date.
4155 See :hg:`help dates` for a list of formats valid for -d/--date.
4156
4156
4157 .. container:: verbose
4157 .. container:: verbose
4158
4158
4159 Examples:
4159 Examples:
4160
4160
4161 - import a traditional patch from a website and detect renames::
4161 - import a traditional patch from a website and detect renames::
4162
4162
4163 hg import -s 80 http://example.com/bugfix.patch
4163 hg import -s 80 http://example.com/bugfix.patch
4164
4164
4165 - import a changeset from an hgweb server::
4165 - import a changeset from an hgweb server::
4166
4166
4167 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
4167 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
4168
4168
4169 - import all the patches in an Unix-style mbox::
4169 - import all the patches in an Unix-style mbox::
4170
4170
4171 hg import incoming-patches.mbox
4171 hg import incoming-patches.mbox
4172
4172
4173 - import patches from stdin::
4173 - import patches from stdin::
4174
4174
4175 hg import -
4175 hg import -
4176
4176
4177 - attempt to exactly restore an exported changeset (not always
4177 - attempt to exactly restore an exported changeset (not always
4178 possible)::
4178 possible)::
4179
4179
4180 hg import --exact proposed-fix.patch
4180 hg import --exact proposed-fix.patch
4181
4181
4182 - use an external tool to apply a patch which is too fuzzy for
4182 - use an external tool to apply a patch which is too fuzzy for
4183 the default internal tool.
4183 the default internal tool.
4184
4184
4185 hg import --config ui.patch="patch --merge" fuzzy.patch
4185 hg import --config ui.patch="patch --merge" fuzzy.patch
4186
4186
4187 - change the default fuzzing from 2 to a less strict 7
4187 - change the default fuzzing from 2 to a less strict 7
4188
4188
4189 hg import --config ui.fuzz=7 fuzz.patch
4189 hg import --config ui.fuzz=7 fuzz.patch
4190
4190
4191 Returns 0 on success, 1 on partial success (see --partial).
4191 Returns 0 on success, 1 on partial success (see --partial).
4192 """
4192 """
4193
4193
4194 cmdutil.check_incompatible_arguments(
4194 cmdutil.check_incompatible_arguments(
4195 opts, 'no_commit', ['bypass', 'secret']
4195 opts, 'no_commit', ['bypass', 'secret']
4196 )
4196 )
4197 cmdutil.check_incompatible_arguments(opts, 'exact', ['edit', 'prefix'])
4197 cmdutil.check_incompatible_arguments(opts, 'exact', ['edit', 'prefix'])
4198 opts = pycompat.byteskwargs(opts)
4198 opts = pycompat.byteskwargs(opts)
4199 if not patch1:
4199 if not patch1:
4200 raise error.InputError(_(b'need at least one patch to import'))
4200 raise error.InputError(_(b'need at least one patch to import'))
4201
4201
4202 patches = (patch1,) + patches
4202 patches = (patch1,) + patches
4203
4203
4204 date = opts.get(b'date')
4204 date = opts.get(b'date')
4205 if date:
4205 if date:
4206 opts[b'date'] = dateutil.parsedate(date)
4206 opts[b'date'] = dateutil.parsedate(date)
4207
4207
4208 exact = opts.get(b'exact')
4208 exact = opts.get(b'exact')
4209 update = not opts.get(b'bypass')
4209 update = not opts.get(b'bypass')
4210 try:
4210 try:
4211 sim = float(opts.get(b'similarity') or 0)
4211 sim = float(opts.get(b'similarity') or 0)
4212 except ValueError:
4212 except ValueError:
4213 raise error.InputError(_(b'similarity must be a number'))
4213 raise error.InputError(_(b'similarity must be a number'))
4214 if sim < 0 or sim > 100:
4214 if sim < 0 or sim > 100:
4215 raise error.InputError(_(b'similarity must be between 0 and 100'))
4215 raise error.InputError(_(b'similarity must be between 0 and 100'))
4216 if sim and not update:
4216 if sim and not update:
4217 raise error.InputError(_(b'cannot use --similarity with --bypass'))
4217 raise error.InputError(_(b'cannot use --similarity with --bypass'))
4218
4218
4219 base = opts[b"base"]
4219 base = opts[b"base"]
4220 msgs = []
4220 msgs = []
4221 ret = 0
4221 ret = 0
4222
4222
4223 with repo.wlock():
4223 with repo.wlock():
4224 if update:
4224 if update:
4225 cmdutil.checkunfinished(repo)
4225 cmdutil.checkunfinished(repo)
4226 if exact or not opts.get(b'force'):
4226 if exact or not opts.get(b'force'):
4227 cmdutil.bailifchanged(repo)
4227 cmdutil.bailifchanged(repo)
4228
4228
4229 if not opts.get(b'no_commit'):
4229 if not opts.get(b'no_commit'):
4230 lock = repo.lock
4230 lock = repo.lock
4231 tr = lambda: repo.transaction(b'import')
4231 tr = lambda: repo.transaction(b'import')
4232 dsguard = util.nullcontextmanager
4232 dsguard = util.nullcontextmanager
4233 else:
4233 else:
4234 lock = util.nullcontextmanager
4234 lock = util.nullcontextmanager
4235 tr = util.nullcontextmanager
4235 tr = util.nullcontextmanager
4236 dsguard = lambda: dirstateguard.dirstateguard(repo, b'import')
4236 dsguard = lambda: dirstateguard.dirstateguard(repo, b'import')
4237 with lock(), tr(), dsguard():
4237 with lock(), tr(), dsguard():
4238 parents = repo[None].parents()
4238 parents = repo[None].parents()
4239 for patchurl in patches:
4239 for patchurl in patches:
4240 if patchurl == b'-':
4240 if patchurl == b'-':
4241 ui.status(_(b'applying patch from stdin\n'))
4241 ui.status(_(b'applying patch from stdin\n'))
4242 patchfile = ui.fin
4242 patchfile = ui.fin
4243 patchurl = b'stdin' # for error message
4243 patchurl = b'stdin' # for error message
4244 else:
4244 else:
4245 patchurl = os.path.join(base, patchurl)
4245 patchurl = os.path.join(base, patchurl)
4246 ui.status(_(b'applying %s\n') % patchurl)
4246 ui.status(_(b'applying %s\n') % patchurl)
4247 patchfile = hg.openpath(ui, patchurl, sendaccept=False)
4247 patchfile = hg.openpath(ui, patchurl, sendaccept=False)
4248
4248
4249 haspatch = False
4249 haspatch = False
4250 for hunk in patch.split(patchfile):
4250 for hunk in patch.split(patchfile):
4251 with patch.extract(ui, hunk) as patchdata:
4251 with patch.extract(ui, hunk) as patchdata:
4252 msg, node, rej = cmdutil.tryimportone(
4252 msg, node, rej = cmdutil.tryimportone(
4253 ui, repo, patchdata, parents, opts, msgs, hg.clean
4253 ui, repo, patchdata, parents, opts, msgs, hg.clean
4254 )
4254 )
4255 if msg:
4255 if msg:
4256 haspatch = True
4256 haspatch = True
4257 ui.note(msg + b'\n')
4257 ui.note(msg + b'\n')
4258 if update or exact:
4258 if update or exact:
4259 parents = repo[None].parents()
4259 parents = repo[None].parents()
4260 else:
4260 else:
4261 parents = [repo[node]]
4261 parents = [repo[node]]
4262 if rej:
4262 if rej:
4263 ui.write_err(_(b"patch applied partially\n"))
4263 ui.write_err(_(b"patch applied partially\n"))
4264 ui.write_err(
4264 ui.write_err(
4265 _(
4265 _(
4266 b"(fix the .rej files and run "
4266 b"(fix the .rej files and run "
4267 b"`hg commit --amend`)\n"
4267 b"`hg commit --amend`)\n"
4268 )
4268 )
4269 )
4269 )
4270 ret = 1
4270 ret = 1
4271 break
4271 break
4272
4272
4273 if not haspatch:
4273 if not haspatch:
4274 raise error.InputError(_(b'%s: no diffs found') % patchurl)
4274 raise error.InputError(_(b'%s: no diffs found') % patchurl)
4275
4275
4276 if msgs:
4276 if msgs:
4277 repo.savecommitmessage(b'\n* * *\n'.join(msgs))
4277 repo.savecommitmessage(b'\n* * *\n'.join(msgs))
4278 return ret
4278 return ret
4279
4279
4280
4280
4281 @command(
4281 @command(
4282 b'incoming|in',
4282 b'incoming|in',
4283 [
4283 [
4284 (
4284 (
4285 b'f',
4285 b'f',
4286 b'force',
4286 b'force',
4287 None,
4287 None,
4288 _(b'run even if remote repository is unrelated'),
4288 _(b'run even if remote repository is unrelated'),
4289 ),
4289 ),
4290 (b'n', b'newest-first', None, _(b'show newest record first')),
4290 (b'n', b'newest-first', None, _(b'show newest record first')),
4291 (b'', b'bundle', b'', _(b'file to store the bundles into'), _(b'FILE')),
4291 (b'', b'bundle', b'', _(b'file to store the bundles into'), _(b'FILE')),
4292 (
4292 (
4293 b'r',
4293 b'r',
4294 b'rev',
4294 b'rev',
4295 [],
4295 [],
4296 _(b'a remote changeset intended to be added'),
4296 _(b'a remote changeset intended to be added'),
4297 _(b'REV'),
4297 _(b'REV'),
4298 ),
4298 ),
4299 (b'B', b'bookmarks', False, _(b"compare bookmarks")),
4299 (b'B', b'bookmarks', False, _(b"compare bookmarks")),
4300 (
4300 (
4301 b'b',
4301 b'b',
4302 b'branch',
4302 b'branch',
4303 [],
4303 [],
4304 _(b'a specific branch you would like to pull'),
4304 _(b'a specific branch you would like to pull'),
4305 _(b'BRANCH'),
4305 _(b'BRANCH'),
4306 ),
4306 ),
4307 ]
4307 ]
4308 + logopts
4308 + logopts
4309 + remoteopts
4309 + remoteopts
4310 + subrepoopts,
4310 + subrepoopts,
4311 _(b'[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'),
4311 _(b'[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'),
4312 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4312 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4313 )
4313 )
4314 def incoming(ui, repo, source=b"default", **opts):
4314 def incoming(ui, repo, source=b"default", **opts):
4315 """show new changesets found in source
4315 """show new changesets found in source
4316
4316
4317 Show new changesets found in the specified path/URL or the default
4317 Show new changesets found in the specified path/URL or the default
4318 pull location. These are the changesets that would have been pulled
4318 pull location. These are the changesets that would have been pulled
4319 by :hg:`pull` at the time you issued this command.
4319 by :hg:`pull` at the time you issued this command.
4320
4320
4321 See pull for valid source format details.
4321 See pull for valid source format details.
4322
4322
4323 .. container:: verbose
4323 .. container:: verbose
4324
4324
4325 With -B/--bookmarks, the result of bookmark comparison between
4325 With -B/--bookmarks, the result of bookmark comparison between
4326 local and remote repositories is displayed. With -v/--verbose,
4326 local and remote repositories is displayed. With -v/--verbose,
4327 status is also displayed for each bookmark like below::
4327 status is also displayed for each bookmark like below::
4328
4328
4329 BM1 01234567890a added
4329 BM1 01234567890a added
4330 BM2 1234567890ab advanced
4330 BM2 1234567890ab advanced
4331 BM3 234567890abc diverged
4331 BM3 234567890abc diverged
4332 BM4 34567890abcd changed
4332 BM4 34567890abcd changed
4333
4333
4334 The action taken locally when pulling depends on the
4334 The action taken locally when pulling depends on the
4335 status of each bookmark:
4335 status of each bookmark:
4336
4336
4337 :``added``: pull will create it
4337 :``added``: pull will create it
4338 :``advanced``: pull will update it
4338 :``advanced``: pull will update it
4339 :``diverged``: pull will create a divergent bookmark
4339 :``diverged``: pull will create a divergent bookmark
4340 :``changed``: result depends on remote changesets
4340 :``changed``: result depends on remote changesets
4341
4341
4342 From the point of view of pulling behavior, bookmark
4342 From the point of view of pulling behavior, bookmark
4343 existing only in the remote repository are treated as ``added``,
4343 existing only in the remote repository are treated as ``added``,
4344 even if it is in fact locally deleted.
4344 even if it is in fact locally deleted.
4345
4345
4346 .. container:: verbose
4346 .. container:: verbose
4347
4347
4348 For remote repository, using --bundle avoids downloading the
4348 For remote repository, using --bundle avoids downloading the
4349 changesets twice if the incoming is followed by a pull.
4349 changesets twice if the incoming is followed by a pull.
4350
4350
4351 Examples:
4351 Examples:
4352
4352
4353 - show incoming changes with patches and full description::
4353 - show incoming changes with patches and full description::
4354
4354
4355 hg incoming -vp
4355 hg incoming -vp
4356
4356
4357 - show incoming changes excluding merges, store a bundle::
4357 - show incoming changes excluding merges, store a bundle::
4358
4358
4359 hg in -vpM --bundle incoming.hg
4359 hg in -vpM --bundle incoming.hg
4360 hg pull incoming.hg
4360 hg pull incoming.hg
4361
4361
4362 - briefly list changes inside a bundle::
4362 - briefly list changes inside a bundle::
4363
4363
4364 hg in changes.hg -T "{desc|firstline}\\n"
4364 hg in changes.hg -T "{desc|firstline}\\n"
4365
4365
4366 Returns 0 if there are incoming changes, 1 otherwise.
4366 Returns 0 if there are incoming changes, 1 otherwise.
4367 """
4367 """
4368 opts = pycompat.byteskwargs(opts)
4368 opts = pycompat.byteskwargs(opts)
4369 if opts.get(b'graph'):
4369 if opts.get(b'graph'):
4370 logcmdutil.checkunsupportedgraphflags([], opts)
4370 logcmdutil.checkunsupportedgraphflags([], opts)
4371
4371
4372 def display(other, chlist, displayer):
4372 def display(other, chlist, displayer):
4373 revdag = logcmdutil.graphrevs(other, chlist, opts)
4373 revdag = logcmdutil.graphrevs(other, chlist, opts)
4374 logcmdutil.displaygraph(
4374 logcmdutil.displaygraph(
4375 ui, repo, revdag, displayer, graphmod.asciiedges
4375 ui, repo, revdag, displayer, graphmod.asciiedges
4376 )
4376 )
4377
4377
4378 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4378 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4379 return 0
4379 return 0
4380
4380
4381 cmdutil.check_incompatible_arguments(opts, b'subrepos', [b'bundle'])
4381 cmdutil.check_incompatible_arguments(opts, b'subrepos', [b'bundle'])
4382
4382
4383 if opts.get(b'bookmarks'):
4383 if opts.get(b'bookmarks'):
4384 srcs = urlutil.get_pull_paths(repo, ui, [source])
4384 srcs = urlutil.get_pull_paths(repo, ui, [source])
4385 for path in srcs:
4385 for path in srcs:
4386 # XXX the "branches" options are not used. Should it be used?
4386 # XXX the "branches" options are not used. Should it be used?
4387 other = hg.peer(repo, opts, path)
4387 other = hg.peer(repo, opts, path)
4388 try:
4388 try:
4389 if b'bookmarks' not in other.listkeys(b'namespaces'):
4389 if b'bookmarks' not in other.listkeys(b'namespaces'):
4390 ui.warn(_(b"remote doesn't support bookmarks\n"))
4390 ui.warn(_(b"remote doesn't support bookmarks\n"))
4391 return 0
4391 return 0
4392 ui.pager(b'incoming')
4392 ui.pager(b'incoming')
4393 ui.status(
4393 ui.status(
4394 _(b'comparing with %s\n') % urlutil.hidepassword(path.loc)
4394 _(b'comparing with %s\n') % urlutil.hidepassword(path.loc)
4395 )
4395 )
4396 return bookmarks.incoming(
4396 return bookmarks.incoming(
4397 ui, repo, other, mode=path.bookmarks_mode
4397 ui, repo, other, mode=path.bookmarks_mode
4398 )
4398 )
4399 finally:
4399 finally:
4400 other.close()
4400 other.close()
4401
4401
4402 return hg.incoming(ui, repo, source, opts)
4402 return hg.incoming(ui, repo, source, opts)
4403
4403
4404
4404
4405 @command(
4405 @command(
4406 b'init',
4406 b'init',
4407 remoteopts,
4407 remoteopts,
4408 _(b'[-e CMD] [--remotecmd CMD] [DEST]'),
4408 _(b'[-e CMD] [--remotecmd CMD] [DEST]'),
4409 helpcategory=command.CATEGORY_REPO_CREATION,
4409 helpcategory=command.CATEGORY_REPO_CREATION,
4410 helpbasic=True,
4410 helpbasic=True,
4411 norepo=True,
4411 norepo=True,
4412 )
4412 )
4413 def init(ui, dest=b".", **opts):
4413 def init(ui, dest=b".", **opts):
4414 """create a new repository in the given directory
4414 """create a new repository in the given directory
4415
4415
4416 Initialize a new repository in the given directory. If the given
4416 Initialize a new repository in the given directory. If the given
4417 directory does not exist, it will be created.
4417 directory does not exist, it will be created.
4418
4418
4419 If no directory is given, the current directory is used.
4419 If no directory is given, the current directory is used.
4420
4420
4421 It is possible to specify an ``ssh://`` URL as the destination.
4421 It is possible to specify an ``ssh://`` URL as the destination.
4422 See :hg:`help urls` for more information.
4422 See :hg:`help urls` for more information.
4423
4423
4424 Returns 0 on success.
4424 Returns 0 on success.
4425 """
4425 """
4426 opts = pycompat.byteskwargs(opts)
4426 opts = pycompat.byteskwargs(opts)
4427 path = urlutil.get_clone_path(ui, dest)[1]
4427 path = urlutil.get_clone_path(ui, dest)[1]
4428 peer = hg.peer(ui, opts, path, create=True)
4428 peer = hg.peer(ui, opts, path, create=True)
4429 peer.close()
4429 peer.close()
4430
4430
4431
4431
4432 @command(
4432 @command(
4433 b'locate',
4433 b'locate',
4434 [
4434 [
4435 (
4435 (
4436 b'r',
4436 b'r',
4437 b'rev',
4437 b'rev',
4438 b'',
4438 b'',
4439 _(b'search the repository as it is in REV'),
4439 _(b'search the repository as it is in REV'),
4440 _(b'REV'),
4440 _(b'REV'),
4441 ),
4441 ),
4442 (
4442 (
4443 b'0',
4443 b'0',
4444 b'print0',
4444 b'print0',
4445 None,
4445 None,
4446 _(b'end filenames with NUL, for use with xargs'),
4446 _(b'end filenames with NUL, for use with xargs'),
4447 ),
4447 ),
4448 (
4448 (
4449 b'f',
4449 b'f',
4450 b'fullpath',
4450 b'fullpath',
4451 None,
4451 None,
4452 _(b'print complete paths from the filesystem root'),
4452 _(b'print complete paths from the filesystem root'),
4453 ),
4453 ),
4454 ]
4454 ]
4455 + walkopts,
4455 + walkopts,
4456 _(b'[OPTION]... [PATTERN]...'),
4456 _(b'[OPTION]... [PATTERN]...'),
4457 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
4457 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
4458 )
4458 )
4459 def locate(ui, repo, *pats, **opts):
4459 def locate(ui, repo, *pats, **opts):
4460 """locate files matching specific patterns (DEPRECATED)
4460 """locate files matching specific patterns (DEPRECATED)
4461
4461
4462 Print files under Mercurial control in the working directory whose
4462 Print files under Mercurial control in the working directory whose
4463 names match the given patterns.
4463 names match the given patterns.
4464
4464
4465 By default, this command searches all directories in the working
4465 By default, this command searches all directories in the working
4466 directory. To search just the current directory and its
4466 directory. To search just the current directory and its
4467 subdirectories, use "--include .".
4467 subdirectories, use "--include .".
4468
4468
4469 If no patterns are given to match, this command prints the names
4469 If no patterns are given to match, this command prints the names
4470 of all files under Mercurial control in the working directory.
4470 of all files under Mercurial control in the working directory.
4471
4471
4472 If you want to feed the output of this command into the "xargs"
4472 If you want to feed the output of this command into the "xargs"
4473 command, use the -0 option to both this command and "xargs". This
4473 command, use the -0 option to both this command and "xargs". This
4474 will avoid the problem of "xargs" treating single filenames that
4474 will avoid the problem of "xargs" treating single filenames that
4475 contain whitespace as multiple filenames.
4475 contain whitespace as multiple filenames.
4476
4476
4477 See :hg:`help files` for a more versatile command.
4477 See :hg:`help files` for a more versatile command.
4478
4478
4479 Returns 0 if a match is found, 1 otherwise.
4479 Returns 0 if a match is found, 1 otherwise.
4480 """
4480 """
4481 opts = pycompat.byteskwargs(opts)
4481 opts = pycompat.byteskwargs(opts)
4482 if opts.get(b'print0'):
4482 if opts.get(b'print0'):
4483 end = b'\0'
4483 end = b'\0'
4484 else:
4484 else:
4485 end = b'\n'
4485 end = b'\n'
4486 ctx = logcmdutil.revsingle(repo, opts.get(b'rev'), None)
4486 ctx = logcmdutil.revsingle(repo, opts.get(b'rev'), None)
4487
4487
4488 ret = 1
4488 ret = 1
4489 m = scmutil.match(
4489 m = scmutil.match(
4490 ctx, pats, opts, default=b'relglob', badfn=lambda x, y: False
4490 ctx, pats, opts, default=b'relglob', badfn=lambda x, y: False
4491 )
4491 )
4492
4492
4493 ui.pager(b'locate')
4493 ui.pager(b'locate')
4494 if ctx.rev() is None:
4494 if ctx.rev() is None:
4495 # When run on the working copy, "locate" includes removed files, so
4495 # When run on the working copy, "locate" includes removed files, so
4496 # we get the list of files from the dirstate.
4496 # we get the list of files from the dirstate.
4497 filesgen = sorted(repo.dirstate.matches(m))
4497 filesgen = sorted(repo.dirstate.matches(m))
4498 else:
4498 else:
4499 filesgen = ctx.matches(m)
4499 filesgen = ctx.matches(m)
4500 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=bool(pats))
4500 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=bool(pats))
4501 for abs in filesgen:
4501 for abs in filesgen:
4502 if opts.get(b'fullpath'):
4502 if opts.get(b'fullpath'):
4503 ui.write(repo.wjoin(abs), end)
4503 ui.write(repo.wjoin(abs), end)
4504 else:
4504 else:
4505 ui.write(uipathfn(abs), end)
4505 ui.write(uipathfn(abs), end)
4506 ret = 0
4506 ret = 0
4507
4507
4508 return ret
4508 return ret
4509
4509
4510
4510
4511 @command(
4511 @command(
4512 b'log|history',
4512 b'log|history',
4513 [
4513 [
4514 (
4514 (
4515 b'f',
4515 b'f',
4516 b'follow',
4516 b'follow',
4517 None,
4517 None,
4518 _(
4518 _(
4519 b'follow changeset history, or file history across copies and renames'
4519 b'follow changeset history, or file history across copies and renames'
4520 ),
4520 ),
4521 ),
4521 ),
4522 (
4522 (
4523 b'',
4523 b'',
4524 b'follow-first',
4524 b'follow-first',
4525 None,
4525 None,
4526 _(b'only follow the first parent of merge changesets (DEPRECATED)'),
4526 _(b'only follow the first parent of merge changesets (DEPRECATED)'),
4527 ),
4527 ),
4528 (
4528 (
4529 b'd',
4529 b'd',
4530 b'date',
4530 b'date',
4531 b'',
4531 b'',
4532 _(b'show revisions matching date spec'),
4532 _(b'show revisions matching date spec'),
4533 _(b'DATE'),
4533 _(b'DATE'),
4534 ),
4534 ),
4535 (b'C', b'copies', None, _(b'show copied files')),
4535 (b'C', b'copies', None, _(b'show copied files')),
4536 (
4536 (
4537 b'k',
4537 b'k',
4538 b'keyword',
4538 b'keyword',
4539 [],
4539 [],
4540 _(b'do case-insensitive search for a given text'),
4540 _(b'do case-insensitive search for a given text'),
4541 _(b'TEXT'),
4541 _(b'TEXT'),
4542 ),
4542 ),
4543 (
4543 (
4544 b'r',
4544 b'r',
4545 b'rev',
4545 b'rev',
4546 [],
4546 [],
4547 _(b'revisions to select or follow from'),
4547 _(b'revisions to select or follow from'),
4548 _(b'REV'),
4548 _(b'REV'),
4549 ),
4549 ),
4550 (
4550 (
4551 b'L',
4551 b'L',
4552 b'line-range',
4552 b'line-range',
4553 [],
4553 [],
4554 _(b'follow line range of specified file (EXPERIMENTAL)'),
4554 _(b'follow line range of specified file (EXPERIMENTAL)'),
4555 _(b'FILE,RANGE'),
4555 _(b'FILE,RANGE'),
4556 ),
4556 ),
4557 (
4557 (
4558 b'',
4558 b'',
4559 b'removed',
4559 b'removed',
4560 None,
4560 None,
4561 _(b'include revisions where files were removed'),
4561 _(b'include revisions where files were removed'),
4562 ),
4562 ),
4563 (
4563 (
4564 b'm',
4564 b'm',
4565 b'only-merges',
4565 b'only-merges',
4566 None,
4566 None,
4567 _(b'show only merges (DEPRECATED) (use -r "merge()" instead)'),
4567 _(b'show only merges (DEPRECATED) (use -r "merge()" instead)'),
4568 ),
4568 ),
4569 (b'u', b'user', [], _(b'revisions committed by user'), _(b'USER')),
4569 (b'u', b'user', [], _(b'revisions committed by user'), _(b'USER')),
4570 (
4570 (
4571 b'',
4571 b'',
4572 b'only-branch',
4572 b'only-branch',
4573 [],
4573 [],
4574 _(
4574 _(
4575 b'show only changesets within the given named branch (DEPRECATED)'
4575 b'show only changesets within the given named branch (DEPRECATED)'
4576 ),
4576 ),
4577 _(b'BRANCH'),
4577 _(b'BRANCH'),
4578 ),
4578 ),
4579 (
4579 (
4580 b'b',
4580 b'b',
4581 b'branch',
4581 b'branch',
4582 [],
4582 [],
4583 _(b'show changesets within the given named branch'),
4583 _(b'show changesets within the given named branch'),
4584 _(b'BRANCH'),
4584 _(b'BRANCH'),
4585 ),
4585 ),
4586 (
4586 (
4587 b'B',
4587 b'B',
4588 b'bookmark',
4588 b'bookmark',
4589 [],
4589 [],
4590 _(b"show changesets within the given bookmark"),
4590 _(b"show changesets within the given bookmark"),
4591 _(b'BOOKMARK'),
4591 _(b'BOOKMARK'),
4592 ),
4592 ),
4593 (
4593 (
4594 b'P',
4594 b'P',
4595 b'prune',
4595 b'prune',
4596 [],
4596 [],
4597 _(b'do not display revision or any of its ancestors'),
4597 _(b'do not display revision or any of its ancestors'),
4598 _(b'REV'),
4598 _(b'REV'),
4599 ),
4599 ),
4600 ]
4600 ]
4601 + logopts
4601 + logopts
4602 + walkopts,
4602 + walkopts,
4603 _(b'[OPTION]... [FILE]'),
4603 _(b'[OPTION]... [FILE]'),
4604 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
4604 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
4605 helpbasic=True,
4605 helpbasic=True,
4606 inferrepo=True,
4606 inferrepo=True,
4607 intents={INTENT_READONLY},
4607 intents={INTENT_READONLY},
4608 )
4608 )
4609 def log(ui, repo, *pats, **opts):
4609 def log(ui, repo, *pats, **opts):
4610 """show revision history of entire repository or files
4610 """show revision history of entire repository or files
4611
4611
4612 Print the revision history of the specified files or the entire
4612 Print the revision history of the specified files or the entire
4613 project.
4613 project.
4614
4614
4615 If no revision range is specified, the default is ``tip:0`` unless
4615 If no revision range is specified, the default is ``tip:0`` unless
4616 --follow is set.
4616 --follow is set.
4617
4617
4618 File history is shown without following rename or copy history of
4618 File history is shown without following rename or copy history of
4619 files. Use -f/--follow with a filename to follow history across
4619 files. Use -f/--follow with a filename to follow history across
4620 renames and copies. --follow without a filename will only show
4620 renames and copies. --follow without a filename will only show
4621 ancestors of the starting revisions. The starting revisions can be
4621 ancestors of the starting revisions. The starting revisions can be
4622 specified by -r/--rev, which default to the working directory parent.
4622 specified by -r/--rev, which default to the working directory parent.
4623
4623
4624 By default this command prints revision number and changeset id,
4624 By default this command prints revision number and changeset id,
4625 tags, non-trivial parents, user, date and time, and a summary for
4625 tags, non-trivial parents, user, date and time, and a summary for
4626 each commit. When the -v/--verbose switch is used, the list of
4626 each commit. When the -v/--verbose switch is used, the list of
4627 changed files and full commit message are shown.
4627 changed files and full commit message are shown.
4628
4628
4629 With --graph the revisions are shown as an ASCII art DAG with the most
4629 With --graph the revisions are shown as an ASCII art DAG with the most
4630 recent changeset at the top.
4630 recent changeset at the top.
4631 'o' is a changeset, '@' is a working directory parent, '%' is a changeset
4631 'o' is a changeset, '@' is a working directory parent, '%' is a changeset
4632 involved in an unresolved merge conflict, '_' closes a branch,
4632 involved in an unresolved merge conflict, '_' closes a branch,
4633 'x' is obsolete, '*' is unstable, and '+' represents a fork where the
4633 'x' is obsolete, '*' is unstable, and '+' represents a fork where the
4634 changeset from the lines below is a parent of the 'o' merge on the same
4634 changeset from the lines below is a parent of the 'o' merge on the same
4635 line.
4635 line.
4636 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
4636 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
4637 of a '|' indicates one or more revisions in a path are omitted.
4637 of a '|' indicates one or more revisions in a path are omitted.
4638
4638
4639 .. container:: verbose
4639 .. container:: verbose
4640
4640
4641 Use -L/--line-range FILE,M:N options to follow the history of lines
4641 Use -L/--line-range FILE,M:N options to follow the history of lines
4642 from M to N in FILE. With -p/--patch only diff hunks affecting
4642 from M to N in FILE. With -p/--patch only diff hunks affecting
4643 specified line range will be shown. This option requires --follow;
4643 specified line range will be shown. This option requires --follow;
4644 it can be specified multiple times. Currently, this option is not
4644 it can be specified multiple times. Currently, this option is not
4645 compatible with --graph. This option is experimental.
4645 compatible with --graph. This option is experimental.
4646
4646
4647 .. note::
4647 .. note::
4648
4648
4649 :hg:`log --patch` may generate unexpected diff output for merge
4649 :hg:`log --patch` may generate unexpected diff output for merge
4650 changesets, as it will only compare the merge changeset against
4650 changesets, as it will only compare the merge changeset against
4651 its first parent. Also, only files different from BOTH parents
4651 its first parent. Also, only files different from BOTH parents
4652 will appear in files:.
4652 will appear in files:.
4653
4653
4654 .. note::
4654 .. note::
4655
4655
4656 For performance reasons, :hg:`log FILE` may omit duplicate changes
4656 For performance reasons, :hg:`log FILE` may omit duplicate changes
4657 made on branches and will not show removals or mode changes. To
4657 made on branches and will not show removals or mode changes. To
4658 see all such changes, use the --removed switch.
4658 see all such changes, use the --removed switch.
4659
4659
4660 .. container:: verbose
4660 .. container:: verbose
4661
4661
4662 .. note::
4662 .. note::
4663
4663
4664 The history resulting from -L/--line-range options depends on diff
4664 The history resulting from -L/--line-range options depends on diff
4665 options; for instance if white-spaces are ignored, respective changes
4665 options; for instance if white-spaces are ignored, respective changes
4666 with only white-spaces in specified line range will not be listed.
4666 with only white-spaces in specified line range will not be listed.
4667
4667
4668 .. container:: verbose
4668 .. container:: verbose
4669
4669
4670 Some examples:
4670 Some examples:
4671
4671
4672 - changesets with full descriptions and file lists::
4672 - changesets with full descriptions and file lists::
4673
4673
4674 hg log -v
4674 hg log -v
4675
4675
4676 - changesets ancestral to the working directory::
4676 - changesets ancestral to the working directory::
4677
4677
4678 hg log -f
4678 hg log -f
4679
4679
4680 - last 10 commits on the current branch::
4680 - last 10 commits on the current branch::
4681
4681
4682 hg log -l 10 -b .
4682 hg log -l 10 -b .
4683
4683
4684 - changesets showing all modifications of a file, including removals::
4684 - changesets showing all modifications of a file, including removals::
4685
4685
4686 hg log --removed file.c
4686 hg log --removed file.c
4687
4687
4688 - all changesets that touch a directory, with diffs, excluding merges::
4688 - all changesets that touch a directory, with diffs, excluding merges::
4689
4689
4690 hg log -Mp lib/
4690 hg log -Mp lib/
4691
4691
4692 - all revision numbers that match a keyword::
4692 - all revision numbers that match a keyword::
4693
4693
4694 hg log -k bug --template "{rev}\\n"
4694 hg log -k bug --template "{rev}\\n"
4695
4695
4696 - the full hash identifier of the working directory parent::
4696 - the full hash identifier of the working directory parent::
4697
4697
4698 hg log -r . --template "{node}\\n"
4698 hg log -r . --template "{node}\\n"
4699
4699
4700 - list available log templates::
4700 - list available log templates::
4701
4701
4702 hg log -T list
4702 hg log -T list
4703
4703
4704 - check if a given changeset is included in a tagged release::
4704 - check if a given changeset is included in a tagged release::
4705
4705
4706 hg log -r "a21ccf and ancestor(1.9)"
4706 hg log -r "a21ccf and ancestor(1.9)"
4707
4707
4708 - find all changesets by some user in a date range::
4708 - find all changesets by some user in a date range::
4709
4709
4710 hg log -k alice -d "may 2008 to jul 2008"
4710 hg log -k alice -d "may 2008 to jul 2008"
4711
4711
4712 - summary of all changesets after the last tag::
4712 - summary of all changesets after the last tag::
4713
4713
4714 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4714 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4715
4715
4716 - changesets touching lines 13 to 23 for file.c::
4716 - changesets touching lines 13 to 23 for file.c::
4717
4717
4718 hg log -L file.c,13:23
4718 hg log -L file.c,13:23
4719
4719
4720 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
4720 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
4721 main.c with patch::
4721 main.c with patch::
4722
4722
4723 hg log -L file.c,13:23 -L main.c,2:6 -p
4723 hg log -L file.c,13:23 -L main.c,2:6 -p
4724
4724
4725 See :hg:`help dates` for a list of formats valid for -d/--date.
4725 See :hg:`help dates` for a list of formats valid for -d/--date.
4726
4726
4727 See :hg:`help revisions` for more about specifying and ordering
4727 See :hg:`help revisions` for more about specifying and ordering
4728 revisions.
4728 revisions.
4729
4729
4730 See :hg:`help templates` for more about pre-packaged styles and
4730 See :hg:`help templates` for more about pre-packaged styles and
4731 specifying custom templates. The default template used by the log
4731 specifying custom templates. The default template used by the log
4732 command can be customized via the ``command-templates.log`` configuration
4732 command can be customized via the ``command-templates.log`` configuration
4733 setting.
4733 setting.
4734
4734
4735 Returns 0 on success.
4735 Returns 0 on success.
4736
4736
4737 """
4737 """
4738 opts = pycompat.byteskwargs(opts)
4738 opts = pycompat.byteskwargs(opts)
4739 linerange = opts.get(b'line_range')
4739 linerange = opts.get(b'line_range')
4740
4740
4741 if linerange and not opts.get(b'follow'):
4741 if linerange and not opts.get(b'follow'):
4742 raise error.InputError(_(b'--line-range requires --follow'))
4742 raise error.InputError(_(b'--line-range requires --follow'))
4743
4743
4744 if linerange and pats:
4744 if linerange and pats:
4745 # TODO: take pats as patterns with no line-range filter
4745 # TODO: take pats as patterns with no line-range filter
4746 raise error.InputError(
4746 raise error.InputError(
4747 _(b'FILE arguments are not compatible with --line-range option')
4747 _(b'FILE arguments are not compatible with --line-range option')
4748 )
4748 )
4749
4749
4750 repo = scmutil.unhidehashlikerevs(repo, opts.get(b'rev'), b'nowarn')
4750 repo = scmutil.unhidehashlikerevs(repo, opts.get(b'rev'), b'nowarn')
4751 walk_opts = logcmdutil.parseopts(ui, pats, opts)
4751 walk_opts = logcmdutil.parseopts(ui, pats, opts)
4752 revs, differ = logcmdutil.getrevs(repo, walk_opts)
4752 revs, differ = logcmdutil.getrevs(repo, walk_opts)
4753 if linerange:
4753 if linerange:
4754 # TODO: should follow file history from logcmdutil._initialrevs(),
4754 # TODO: should follow file history from logcmdutil._initialrevs(),
4755 # then filter the result by logcmdutil._makerevset() and --limit
4755 # then filter the result by logcmdutil._makerevset() and --limit
4756 revs, differ = logcmdutil.getlinerangerevs(repo, revs, opts)
4756 revs, differ = logcmdutil.getlinerangerevs(repo, revs, opts)
4757
4757
4758 getcopies = None
4758 getcopies = None
4759 if opts.get(b'copies'):
4759 if opts.get(b'copies'):
4760 endrev = None
4760 endrev = None
4761 if revs:
4761 if revs:
4762 endrev = revs.max() + 1
4762 endrev = revs.max() + 1
4763 getcopies = scmutil.getcopiesfn(repo, endrev=endrev)
4763 getcopies = scmutil.getcopiesfn(repo, endrev=endrev)
4764
4764
4765 ui.pager(b'log')
4765 ui.pager(b'log')
4766 displayer = logcmdutil.changesetdisplayer(
4766 displayer = logcmdutil.changesetdisplayer(
4767 ui, repo, opts, differ, buffered=True
4767 ui, repo, opts, differ, buffered=True
4768 )
4768 )
4769 if opts.get(b'graph'):
4769 if opts.get(b'graph'):
4770 displayfn = logcmdutil.displaygraphrevs
4770 displayfn = logcmdutil.displaygraphrevs
4771 else:
4771 else:
4772 displayfn = logcmdutil.displayrevs
4772 displayfn = logcmdutil.displayrevs
4773 displayfn(ui, repo, revs, displayer, getcopies)
4773 displayfn(ui, repo, revs, displayer, getcopies)
4774
4774
4775
4775
4776 @command(
4776 @command(
4777 b'manifest',
4777 b'manifest',
4778 [
4778 [
4779 (b'r', b'rev', b'', _(b'revision to display'), _(b'REV')),
4779 (b'r', b'rev', b'', _(b'revision to display'), _(b'REV')),
4780 (b'', b'all', False, _(b"list files from all revisions")),
4780 (b'', b'all', False, _(b"list files from all revisions")),
4781 ]
4781 ]
4782 + formatteropts,
4782 + formatteropts,
4783 _(b'[-r REV]'),
4783 _(b'[-r REV]'),
4784 helpcategory=command.CATEGORY_MAINTENANCE,
4784 helpcategory=command.CATEGORY_MAINTENANCE,
4785 intents={INTENT_READONLY},
4785 intents={INTENT_READONLY},
4786 )
4786 )
4787 def manifest(ui, repo, node=None, rev=None, **opts):
4787 def manifest(ui, repo, node=None, rev=None, **opts):
4788 """output the current or given revision of the project manifest
4788 """output the current or given revision of the project manifest
4789
4789
4790 Print a list of version controlled files for the given revision.
4790 Print a list of version controlled files for the given revision.
4791 If no revision is given, the first parent of the working directory
4791 If no revision is given, the first parent of the working directory
4792 is used, or the null revision if no revision is checked out.
4792 is used, or the null revision if no revision is checked out.
4793
4793
4794 With -v, print file permissions, symlink and executable bits.
4794 With -v, print file permissions, symlink and executable bits.
4795 With --debug, print file revision hashes.
4795 With --debug, print file revision hashes.
4796
4796
4797 If option --all is specified, the list of all files from all revisions
4797 If option --all is specified, the list of all files from all revisions
4798 is printed. This includes deleted and renamed files.
4798 is printed. This includes deleted and renamed files.
4799
4799
4800 Returns 0 on success.
4800 Returns 0 on success.
4801 """
4801 """
4802 opts = pycompat.byteskwargs(opts)
4802 opts = pycompat.byteskwargs(opts)
4803 fm = ui.formatter(b'manifest', opts)
4803 fm = ui.formatter(b'manifest', opts)
4804
4804
4805 if opts.get(b'all'):
4805 if opts.get(b'all'):
4806 if rev or node:
4806 if rev or node:
4807 raise error.InputError(_(b"can't specify a revision with --all"))
4807 raise error.InputError(_(b"can't specify a revision with --all"))
4808
4808
4809 res = set()
4809 res = set()
4810 for rev in repo:
4810 for rev in repo:
4811 ctx = repo[rev]
4811 ctx = repo[rev]
4812 res |= set(ctx.files())
4812 res |= set(ctx.files())
4813
4813
4814 ui.pager(b'manifest')
4814 ui.pager(b'manifest')
4815 for f in sorted(res):
4815 for f in sorted(res):
4816 fm.startitem()
4816 fm.startitem()
4817 fm.write(b"path", b'%s\n', f)
4817 fm.write(b"path", b'%s\n', f)
4818 fm.end()
4818 fm.end()
4819 return
4819 return
4820
4820
4821 if rev and node:
4821 if rev and node:
4822 raise error.InputError(_(b"please specify just one revision"))
4822 raise error.InputError(_(b"please specify just one revision"))
4823
4823
4824 if not node:
4824 if not node:
4825 node = rev
4825 node = rev
4826
4826
4827 char = {b'l': b'@', b'x': b'*', b'': b'', b't': b'd'}
4827 char = {b'l': b'@', b'x': b'*', b'': b'', b't': b'd'}
4828 mode = {b'l': b'644', b'x': b'755', b'': b'644', b't': b'755'}
4828 mode = {b'l': b'644', b'x': b'755', b'': b'644', b't': b'755'}
4829 if node:
4829 if node:
4830 repo = scmutil.unhidehashlikerevs(repo, [node], b'nowarn')
4830 repo = scmutil.unhidehashlikerevs(repo, [node], b'nowarn')
4831 ctx = logcmdutil.revsingle(repo, node)
4831 ctx = logcmdutil.revsingle(repo, node)
4832 mf = ctx.manifest()
4832 mf = ctx.manifest()
4833 ui.pager(b'manifest')
4833 ui.pager(b'manifest')
4834 for f in ctx:
4834 for f in ctx:
4835 fm.startitem()
4835 fm.startitem()
4836 fm.context(ctx=ctx)
4836 fm.context(ctx=ctx)
4837 fl = ctx[f].flags()
4837 fl = ctx[f].flags()
4838 fm.condwrite(ui.debugflag, b'hash', b'%s ', hex(mf[f]))
4838 fm.condwrite(ui.debugflag, b'hash', b'%s ', hex(mf[f]))
4839 fm.condwrite(ui.verbose, b'mode type', b'%s %1s ', mode[fl], char[fl])
4839 fm.condwrite(ui.verbose, b'mode type', b'%s %1s ', mode[fl], char[fl])
4840 fm.write(b'path', b'%s\n', f)
4840 fm.write(b'path', b'%s\n', f)
4841 fm.end()
4841 fm.end()
4842
4842
4843
4843
4844 @command(
4844 @command(
4845 b'merge',
4845 b'merge',
4846 [
4846 [
4847 (
4847 (
4848 b'f',
4848 b'f',
4849 b'force',
4849 b'force',
4850 None,
4850 None,
4851 _(b'force a merge including outstanding changes (DEPRECATED)'),
4851 _(b'force a merge including outstanding changes (DEPRECATED)'),
4852 ),
4852 ),
4853 (b'r', b'rev', b'', _(b'revision to merge'), _(b'REV')),
4853 (b'r', b'rev', b'', _(b'revision to merge'), _(b'REV')),
4854 (
4854 (
4855 b'P',
4855 b'P',
4856 b'preview',
4856 b'preview',
4857 None,
4857 None,
4858 _(b'review revisions to merge (no merge is performed)'),
4858 _(b'review revisions to merge (no merge is performed)'),
4859 ),
4859 ),
4860 (b'', b'abort', None, _(b'abort the ongoing merge')),
4860 (b'', b'abort', None, _(b'abort the ongoing merge')),
4861 ]
4861 ]
4862 + mergetoolopts,
4862 + mergetoolopts,
4863 _(b'[-P] [[-r] REV]'),
4863 _(b'[-P] [[-r] REV]'),
4864 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
4864 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
4865 helpbasic=True,
4865 helpbasic=True,
4866 )
4866 )
4867 def merge(ui, repo, node=None, **opts):
4867 def merge(ui, repo, node=None, **opts):
4868 """merge another revision into working directory
4868 """merge another revision into working directory
4869
4869
4870 The current working directory is updated with all changes made in
4870 The current working directory is updated with all changes made in
4871 the requested revision since the last common predecessor revision.
4871 the requested revision since the last common predecessor revision.
4872
4872
4873 Files that changed between either parent are marked as changed for
4873 Files that changed between either parent are marked as changed for
4874 the next commit and a commit must be performed before any further
4874 the next commit and a commit must be performed before any further
4875 updates to the repository are allowed. The next commit will have
4875 updates to the repository are allowed. The next commit will have
4876 two parents.
4876 two parents.
4877
4877
4878 ``--tool`` can be used to specify the merge tool used for file
4878 ``--tool`` can be used to specify the merge tool used for file
4879 merges. It overrides the HGMERGE environment variable and your
4879 merges. It overrides the HGMERGE environment variable and your
4880 configuration files. See :hg:`help merge-tools` for options.
4880 configuration files. See :hg:`help merge-tools` for options.
4881
4881
4882 If no revision is specified, the working directory's parent is a
4882 If no revision is specified, the working directory's parent is a
4883 head revision, and the current branch contains exactly one other
4883 head revision, and the current branch contains exactly one other
4884 head, the other head is merged with by default. Otherwise, an
4884 head, the other head is merged with by default. Otherwise, an
4885 explicit revision with which to merge must be provided.
4885 explicit revision with which to merge must be provided.
4886
4886
4887 See :hg:`help resolve` for information on handling file conflicts.
4887 See :hg:`help resolve` for information on handling file conflicts.
4888
4888
4889 To undo an uncommitted merge, use :hg:`merge --abort` which
4889 To undo an uncommitted merge, use :hg:`merge --abort` which
4890 will check out a clean copy of the original merge parent, losing
4890 will check out a clean copy of the original merge parent, losing
4891 all changes.
4891 all changes.
4892
4892
4893 Returns 0 on success, 1 if there are unresolved files.
4893 Returns 0 on success, 1 if there are unresolved files.
4894 """
4894 """
4895
4895
4896 opts = pycompat.byteskwargs(opts)
4896 opts = pycompat.byteskwargs(opts)
4897 abort = opts.get(b'abort')
4897 abort = opts.get(b'abort')
4898 if abort and repo.dirstate.p2() == repo.nullid:
4898 if abort and repo.dirstate.p2() == repo.nullid:
4899 cmdutil.wrongtooltocontinue(repo, _(b'merge'))
4899 cmdutil.wrongtooltocontinue(repo, _(b'merge'))
4900 cmdutil.check_incompatible_arguments(opts, b'abort', [b'rev', b'preview'])
4900 cmdutil.check_incompatible_arguments(opts, b'abort', [b'rev', b'preview'])
4901 if abort:
4901 if abort:
4902 state = cmdutil.getunfinishedstate(repo)
4902 state = cmdutil.getunfinishedstate(repo)
4903 if state and state._opname != b'merge':
4903 if state and state._opname != b'merge':
4904 raise error.StateError(
4904 raise error.StateError(
4905 _(b'cannot abort merge with %s in progress') % (state._opname),
4905 _(b'cannot abort merge with %s in progress') % (state._opname),
4906 hint=state.hint(),
4906 hint=state.hint(),
4907 )
4907 )
4908 if node:
4908 if node:
4909 raise error.InputError(_(b"cannot specify a node with --abort"))
4909 raise error.InputError(_(b"cannot specify a node with --abort"))
4910 return hg.abortmerge(repo.ui, repo)
4910 return hg.abortmerge(repo.ui, repo)
4911
4911
4912 if opts.get(b'rev') and node:
4912 if opts.get(b'rev') and node:
4913 raise error.InputError(_(b"please specify just one revision"))
4913 raise error.InputError(_(b"please specify just one revision"))
4914 if not node:
4914 if not node:
4915 node = opts.get(b'rev')
4915 node = opts.get(b'rev')
4916
4916
4917 if node:
4917 if node:
4918 ctx = logcmdutil.revsingle(repo, node)
4918 ctx = logcmdutil.revsingle(repo, node)
4919 else:
4919 else:
4920 if ui.configbool(b'commands', b'merge.require-rev'):
4920 if ui.configbool(b'commands', b'merge.require-rev'):
4921 raise error.InputError(
4921 raise error.InputError(
4922 _(
4922 _(
4923 b'configuration requires specifying revision to merge '
4923 b'configuration requires specifying revision to merge '
4924 b'with'
4924 b'with'
4925 )
4925 )
4926 )
4926 )
4927 ctx = repo[destutil.destmerge(repo)]
4927 ctx = repo[destutil.destmerge(repo)]
4928
4928
4929 if ctx.node() is None:
4929 if ctx.node() is None:
4930 raise error.InputError(
4930 raise error.InputError(
4931 _(b'merging with the working copy has no effect')
4931 _(b'merging with the working copy has no effect')
4932 )
4932 )
4933
4933
4934 if opts.get(b'preview'):
4934 if opts.get(b'preview'):
4935 # find nodes that are ancestors of p2 but not of p1
4935 # find nodes that are ancestors of p2 but not of p1
4936 p1 = repo[b'.'].node()
4936 p1 = repo[b'.'].node()
4937 p2 = ctx.node()
4937 p2 = ctx.node()
4938 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4938 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4939
4939
4940 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4940 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4941 for node in nodes:
4941 for node in nodes:
4942 displayer.show(repo[node])
4942 displayer.show(repo[node])
4943 displayer.close()
4943 displayer.close()
4944 return 0
4944 return 0
4945
4945
4946 # ui.forcemerge is an internal variable, do not document
4946 # ui.forcemerge is an internal variable, do not document
4947 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
4947 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
4948 with ui.configoverride(overrides, b'merge'):
4948 with ui.configoverride(overrides, b'merge'):
4949 force = opts.get(b'force')
4949 force = opts.get(b'force')
4950 labels = [b'working copy', b'merge rev', b'common ancestor']
4950 labels = [b'working copy', b'merge rev', b'common ancestor']
4951 return hg.merge(ctx, force=force, labels=labels)
4951 return hg.merge(ctx, force=force, labels=labels)
4952
4952
4953
4953
4954 statemod.addunfinished(
4954 statemod.addunfinished(
4955 b'merge',
4955 b'merge',
4956 fname=None,
4956 fname=None,
4957 clearable=True,
4957 clearable=True,
4958 allowcommit=True,
4958 allowcommit=True,
4959 cmdmsg=_(b'outstanding uncommitted merge'),
4959 cmdmsg=_(b'outstanding uncommitted merge'),
4960 abortfunc=hg.abortmerge,
4960 abortfunc=hg.abortmerge,
4961 statushint=_(
4961 statushint=_(
4962 b'To continue: hg commit\nTo abort: hg merge --abort'
4962 b'To continue: hg commit\nTo abort: hg merge --abort'
4963 ),
4963 ),
4964 cmdhint=_(b"use 'hg commit' or 'hg merge --abort'"),
4964 cmdhint=_(b"use 'hg commit' or 'hg merge --abort'"),
4965 )
4965 )
4966
4966
4967
4967
4968 @command(
4968 @command(
4969 b'outgoing|out',
4969 b'outgoing|out',
4970 [
4970 [
4971 (
4971 (
4972 b'f',
4972 b'f',
4973 b'force',
4973 b'force',
4974 None,
4974 None,
4975 _(b'run even when the destination is unrelated'),
4975 _(b'run even when the destination is unrelated'),
4976 ),
4976 ),
4977 (
4977 (
4978 b'r',
4978 b'r',
4979 b'rev',
4979 b'rev',
4980 [],
4980 [],
4981 _(b'a changeset intended to be included in the destination'),
4981 _(b'a changeset intended to be included in the destination'),
4982 _(b'REV'),
4982 _(b'REV'),
4983 ),
4983 ),
4984 (b'n', b'newest-first', None, _(b'show newest record first')),
4984 (b'n', b'newest-first', None, _(b'show newest record first')),
4985 (b'B', b'bookmarks', False, _(b'compare bookmarks')),
4985 (b'B', b'bookmarks', False, _(b'compare bookmarks')),
4986 (
4986 (
4987 b'b',
4987 b'b',
4988 b'branch',
4988 b'branch',
4989 [],
4989 [],
4990 _(b'a specific branch you would like to push'),
4990 _(b'a specific branch you would like to push'),
4991 _(b'BRANCH'),
4991 _(b'BRANCH'),
4992 ),
4992 ),
4993 ]
4993 ]
4994 + logopts
4994 + logopts
4995 + remoteopts
4995 + remoteopts
4996 + subrepoopts,
4996 + subrepoopts,
4997 _(b'[-M] [-p] [-n] [-f] [-r REV]... [DEST]...'),
4997 _(b'[-M] [-p] [-n] [-f] [-r REV]... [DEST]...'),
4998 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4998 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4999 )
4999 )
5000 def outgoing(ui, repo, *dests, **opts):
5000 def outgoing(ui, repo, *dests, **opts):
5001 """show changesets not found in the destination
5001 """show changesets not found in the destination
5002
5002
5003 Show changesets not found in the specified destination repository
5003 Show changesets not found in the specified destination repository
5004 or the default push location. These are the changesets that would
5004 or the default push location. These are the changesets that would
5005 be pushed if a push was requested.
5005 be pushed if a push was requested.
5006
5006
5007 See pull for details of valid destination formats.
5007 See pull for details of valid destination formats.
5008
5008
5009 .. container:: verbose
5009 .. container:: verbose
5010
5010
5011 With -B/--bookmarks, the result of bookmark comparison between
5011 With -B/--bookmarks, the result of bookmark comparison between
5012 local and remote repositories is displayed. With -v/--verbose,
5012 local and remote repositories is displayed. With -v/--verbose,
5013 status is also displayed for each bookmark like below::
5013 status is also displayed for each bookmark like below::
5014
5014
5015 BM1 01234567890a added
5015 BM1 01234567890a added
5016 BM2 deleted
5016 BM2 deleted
5017 BM3 234567890abc advanced
5017 BM3 234567890abc advanced
5018 BM4 34567890abcd diverged
5018 BM4 34567890abcd diverged
5019 BM5 4567890abcde changed
5019 BM5 4567890abcde changed
5020
5020
5021 The action taken when pushing depends on the
5021 The action taken when pushing depends on the
5022 status of each bookmark:
5022 status of each bookmark:
5023
5023
5024 :``added``: push with ``-B`` will create it
5024 :``added``: push with ``-B`` will create it
5025 :``deleted``: push with ``-B`` will delete it
5025 :``deleted``: push with ``-B`` will delete it
5026 :``advanced``: push will update it
5026 :``advanced``: push will update it
5027 :``diverged``: push with ``-B`` will update it
5027 :``diverged``: push with ``-B`` will update it
5028 :``changed``: push with ``-B`` will update it
5028 :``changed``: push with ``-B`` will update it
5029
5029
5030 From the point of view of pushing behavior, bookmarks
5030 From the point of view of pushing behavior, bookmarks
5031 existing only in the remote repository are treated as
5031 existing only in the remote repository are treated as
5032 ``deleted``, even if it is in fact added remotely.
5032 ``deleted``, even if it is in fact added remotely.
5033
5033
5034 Returns 0 if there are outgoing changes, 1 otherwise.
5034 Returns 0 if there are outgoing changes, 1 otherwise.
5035 """
5035 """
5036 opts = pycompat.byteskwargs(opts)
5036 opts = pycompat.byteskwargs(opts)
5037 if opts.get(b'bookmarks'):
5037 if opts.get(b'bookmarks'):
5038 for path in urlutil.get_push_paths(repo, ui, dests):
5038 for path in urlutil.get_push_paths(repo, ui, dests):
5039 other = hg.peer(repo, opts, path)
5039 other = hg.peer(repo, opts, path)
5040 try:
5040 try:
5041 if b'bookmarks' not in other.listkeys(b'namespaces'):
5041 if b'bookmarks' not in other.listkeys(b'namespaces'):
5042 ui.warn(_(b"remote doesn't support bookmarks\n"))
5042 ui.warn(_(b"remote doesn't support bookmarks\n"))
5043 return 0
5043 return 0
5044 ui.status(
5044 ui.status(
5045 _(b'comparing with %s\n') % urlutil.hidepassword(path.loc)
5045 _(b'comparing with %s\n') % urlutil.hidepassword(path.loc)
5046 )
5046 )
5047 ui.pager(b'outgoing')
5047 ui.pager(b'outgoing')
5048 return bookmarks.outgoing(ui, repo, other)
5048 return bookmarks.outgoing(ui, repo, other)
5049 finally:
5049 finally:
5050 other.close()
5050 other.close()
5051
5051
5052 return hg.outgoing(ui, repo, dests, opts)
5052 return hg.outgoing(ui, repo, dests, opts)
5053
5053
5054
5054
5055 @command(
5055 @command(
5056 b'parents',
5056 b'parents',
5057 [
5057 [
5058 (
5058 (
5059 b'r',
5059 b'r',
5060 b'rev',
5060 b'rev',
5061 b'',
5061 b'',
5062 _(b'show parents of the specified revision'),
5062 _(b'show parents of the specified revision'),
5063 _(b'REV'),
5063 _(b'REV'),
5064 ),
5064 ),
5065 ]
5065 ]
5066 + templateopts,
5066 + templateopts,
5067 _(b'[-r REV] [FILE]'),
5067 _(b'[-r REV] [FILE]'),
5068 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
5068 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
5069 inferrepo=True,
5069 inferrepo=True,
5070 )
5070 )
5071 def parents(ui, repo, file_=None, **opts):
5071 def parents(ui, repo, file_=None, **opts):
5072 """show the parents of the working directory or revision (DEPRECATED)
5072 """show the parents of the working directory or revision (DEPRECATED)
5073
5073
5074 Print the working directory's parent revisions. If a revision is
5074 Print the working directory's parent revisions. If a revision is
5075 given via -r/--rev, the parent of that revision will be printed.
5075 given via -r/--rev, the parent of that revision will be printed.
5076 If a file argument is given, the revision in which the file was
5076 If a file argument is given, the revision in which the file was
5077 last changed (before the working directory revision or the
5077 last changed (before the working directory revision or the
5078 argument to --rev if given) is printed.
5078 argument to --rev if given) is printed.
5079
5079
5080 This command is equivalent to::
5080 This command is equivalent to::
5081
5081
5082 hg log -r "p1()+p2()" or
5082 hg log -r "p1()+p2()" or
5083 hg log -r "p1(REV)+p2(REV)" or
5083 hg log -r "p1(REV)+p2(REV)" or
5084 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
5084 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
5085 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
5085 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
5086
5086
5087 See :hg:`summary` and :hg:`help revsets` for related information.
5087 See :hg:`summary` and :hg:`help revsets` for related information.
5088
5088
5089 Returns 0 on success.
5089 Returns 0 on success.
5090 """
5090 """
5091
5091
5092 opts = pycompat.byteskwargs(opts)
5092 opts = pycompat.byteskwargs(opts)
5093 rev = opts.get(b'rev')
5093 rev = opts.get(b'rev')
5094 if rev:
5094 if rev:
5095 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
5095 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
5096 ctx = logcmdutil.revsingle(repo, rev, None)
5096 ctx = logcmdutil.revsingle(repo, rev, None)
5097
5097
5098 if file_:
5098 if file_:
5099 m = scmutil.match(ctx, (file_,), opts)
5099 m = scmutil.match(ctx, (file_,), opts)
5100 if m.anypats() or len(m.files()) != 1:
5100 if m.anypats() or len(m.files()) != 1:
5101 raise error.InputError(_(b'can only specify an explicit filename'))
5101 raise error.InputError(_(b'can only specify an explicit filename'))
5102 file_ = m.files()[0]
5102 file_ = m.files()[0]
5103 filenodes = []
5103 filenodes = []
5104 for cp in ctx.parents():
5104 for cp in ctx.parents():
5105 if not cp:
5105 if not cp:
5106 continue
5106 continue
5107 try:
5107 try:
5108 filenodes.append(cp.filenode(file_))
5108 filenodes.append(cp.filenode(file_))
5109 except error.LookupError:
5109 except error.LookupError:
5110 pass
5110 pass
5111 if not filenodes:
5111 if not filenodes:
5112 raise error.InputError(_(b"'%s' not found in manifest") % file_)
5112 raise error.InputError(_(b"'%s' not found in manifest") % file_)
5113 p = []
5113 p = []
5114 for fn in filenodes:
5114 for fn in filenodes:
5115 fctx = repo.filectx(file_, fileid=fn)
5115 fctx = repo.filectx(file_, fileid=fn)
5116 p.append(fctx.node())
5116 p.append(fctx.node())
5117 else:
5117 else:
5118 p = [cp.node() for cp in ctx.parents()]
5118 p = [cp.node() for cp in ctx.parents()]
5119
5119
5120 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
5120 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
5121 for n in p:
5121 for n in p:
5122 if n != repo.nullid:
5122 if n != repo.nullid:
5123 displayer.show(repo[n])
5123 displayer.show(repo[n])
5124 displayer.close()
5124 displayer.close()
5125
5125
5126
5126
5127 @command(
5127 @command(
5128 b'paths',
5128 b'paths',
5129 formatteropts,
5129 formatteropts,
5130 _(b'[NAME]'),
5130 _(b'[NAME]'),
5131 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5131 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5132 optionalrepo=True,
5132 optionalrepo=True,
5133 intents={INTENT_READONLY},
5133 intents={INTENT_READONLY},
5134 )
5134 )
5135 def paths(ui, repo, search=None, **opts):
5135 def paths(ui, repo, search=None, **opts):
5136 """show aliases for remote repositories
5136 """show aliases for remote repositories
5137
5137
5138 Show definition of symbolic path name NAME. If no name is given,
5138 Show definition of symbolic path name NAME. If no name is given,
5139 show definition of all available names.
5139 show definition of all available names.
5140
5140
5141 Option -q/--quiet suppresses all output when searching for NAME
5141 Option -q/--quiet suppresses all output when searching for NAME
5142 and shows only the path names when listing all definitions.
5142 and shows only the path names when listing all definitions.
5143
5143
5144 Path names are defined in the [paths] section of your
5144 Path names are defined in the [paths] section of your
5145 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
5145 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
5146 repository, ``.hg/hgrc`` is used, too.
5146 repository, ``.hg/hgrc`` is used, too.
5147
5147
5148 The path names ``default`` and ``default-push`` have a special
5148 The path names ``default`` and ``default-push`` have a special
5149 meaning. When performing a push or pull operation, they are used
5149 meaning. When performing a push or pull operation, they are used
5150 as fallbacks if no location is specified on the command-line.
5150 as fallbacks if no location is specified on the command-line.
5151 When ``default-push`` is set, it will be used for push and
5151 When ``default-push`` is set, it will be used for push and
5152 ``default`` will be used for pull; otherwise ``default`` is used
5152 ``default`` will be used for pull; otherwise ``default`` is used
5153 as the fallback for both. When cloning a repository, the clone
5153 as the fallback for both. When cloning a repository, the clone
5154 source is written as ``default`` in ``.hg/hgrc``.
5154 source is written as ``default`` in ``.hg/hgrc``.
5155
5155
5156 .. note::
5156 .. note::
5157
5157
5158 ``default`` and ``default-push`` apply to all inbound (e.g.
5158 ``default`` and ``default-push`` apply to all inbound (e.g.
5159 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
5159 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
5160 and :hg:`bundle`) operations.
5160 and :hg:`bundle`) operations.
5161
5161
5162 See :hg:`help urls` for more information.
5162 See :hg:`help urls` for more information.
5163
5163
5164 .. container:: verbose
5164 .. container:: verbose
5165
5165
5166 Template:
5166 Template:
5167
5167
5168 The following keywords are supported. See also :hg:`help templates`.
5168 The following keywords are supported. See also :hg:`help templates`.
5169
5169
5170 :name: String. Symbolic name of the path alias.
5170 :name: String. Symbolic name of the path alias.
5171 :pushurl: String. URL for push operations.
5171 :pushurl: String. URL for push operations.
5172 :url: String. URL or directory path for the other operations.
5172 :url: String. URL or directory path for the other operations.
5173
5173
5174 Returns 0 on success.
5174 Returns 0 on success.
5175 """
5175 """
5176
5176
5177 opts = pycompat.byteskwargs(opts)
5177 opts = pycompat.byteskwargs(opts)
5178
5178
5179 pathitems = urlutil.list_paths(ui, search)
5179 pathitems = urlutil.list_paths(ui, search)
5180 ui.pager(b'paths')
5180 ui.pager(b'paths')
5181
5181
5182 fm = ui.formatter(b'paths', opts)
5182 fm = ui.formatter(b'paths', opts)
5183 if fm.isplain():
5183 if fm.isplain():
5184 hidepassword = urlutil.hidepassword
5184 hidepassword = urlutil.hidepassword
5185 else:
5185 else:
5186 hidepassword = bytes
5186 hidepassword = bytes
5187 if ui.quiet:
5187 if ui.quiet:
5188 namefmt = b'%s\n'
5188 namefmt = b'%s\n'
5189 else:
5189 else:
5190 namefmt = b'%s = '
5190 namefmt = b'%s = '
5191 showsubopts = not search and not ui.quiet
5191 showsubopts = not search and not ui.quiet
5192
5192
5193 for name, path in pathitems:
5193 for name, path in pathitems:
5194 fm.startitem()
5194 fm.startitem()
5195 fm.condwrite(not search, b'name', namefmt, name)
5195 fm.condwrite(not search, b'name', namefmt, name)
5196 fm.condwrite(not ui.quiet, b'url', b'%s\n', hidepassword(path.rawloc))
5196 fm.condwrite(not ui.quiet, b'url', b'%s\n', hidepassword(path.rawloc))
5197 for subopt, value in sorted(path.suboptions.items()):
5197 for subopt, value in sorted(path.suboptions.items()):
5198 assert subopt not in (b'name', b'url')
5198 assert subopt not in (b'name', b'url')
5199 if showsubopts:
5199 if showsubopts:
5200 fm.plain(b'%s:%s = ' % (name, subopt))
5200 fm.plain(b'%s:%s = ' % (name, subopt))
5201 if isinstance(value, bool):
5201 if isinstance(value, bool):
5202 if value:
5202 if value:
5203 value = b'yes'
5203 value = b'yes'
5204 else:
5204 else:
5205 value = b'no'
5205 value = b'no'
5206 fm.condwrite(showsubopts, subopt, b'%s\n', value)
5206 fm.condwrite(showsubopts, subopt, b'%s\n', value)
5207
5207
5208 fm.end()
5208 fm.end()
5209
5209
5210 if search and not pathitems:
5210 if search and not pathitems:
5211 if not ui.quiet:
5211 if not ui.quiet:
5212 ui.warn(_(b"not found!\n"))
5212 ui.warn(_(b"not found!\n"))
5213 return 1
5213 return 1
5214 else:
5214 else:
5215 return 0
5215 return 0
5216
5216
5217
5217
5218 @command(
5218 @command(
5219 b'phase',
5219 b'phase',
5220 [
5220 [
5221 (b'p', b'public', False, _(b'set changeset phase to public')),
5221 (b'p', b'public', False, _(b'set changeset phase to public')),
5222 (b'd', b'draft', False, _(b'set changeset phase to draft')),
5222 (b'd', b'draft', False, _(b'set changeset phase to draft')),
5223 (b's', b'secret', False, _(b'set changeset phase to secret')),
5223 (b's', b'secret', False, _(b'set changeset phase to secret')),
5224 (b'f', b'force', False, _(b'allow to move boundary backward')),
5224 (b'f', b'force', False, _(b'allow to move boundary backward')),
5225 (b'r', b'rev', [], _(b'target revision'), _(b'REV')),
5225 (b'r', b'rev', [], _(b'target revision'), _(b'REV')),
5226 ],
5226 ],
5227 _(b'[-p|-d|-s] [-f] [-r] [REV...]'),
5227 _(b'[-p|-d|-s] [-f] [-r] [REV...]'),
5228 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
5228 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
5229 )
5229 )
5230 def phase(ui, repo, *revs, **opts):
5230 def phase(ui, repo, *revs, **opts):
5231 """set or show the current phase name
5231 """set or show the current phase name
5232
5232
5233 With no argument, show the phase name of the current revision(s).
5233 With no argument, show the phase name of the current revision(s).
5234
5234
5235 With one of -p/--public, -d/--draft or -s/--secret, change the
5235 With one of -p/--public, -d/--draft or -s/--secret, change the
5236 phase value of the specified revisions.
5236 phase value of the specified revisions.
5237
5237
5238 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
5238 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
5239 lower phase to a higher phase. Phases are ordered as follows::
5239 lower phase to a higher phase. Phases are ordered as follows::
5240
5240
5241 public < draft < secret
5241 public < draft < secret
5242
5242
5243 Returns 0 on success, 1 if some phases could not be changed.
5243 Returns 0 on success, 1 if some phases could not be changed.
5244
5244
5245 (For more information about the phases concept, see :hg:`help phases`.)
5245 (For more information about the phases concept, see :hg:`help phases`.)
5246 """
5246 """
5247 opts = pycompat.byteskwargs(opts)
5247 opts = pycompat.byteskwargs(opts)
5248 # search for a unique phase argument
5248 # search for a unique phase argument
5249 targetphase = None
5249 targetphase = None
5250 for idx, name in enumerate(phases.cmdphasenames):
5250 for idx, name in enumerate(phases.cmdphasenames):
5251 if opts[name]:
5251 if opts[name]:
5252 if targetphase is not None:
5252 if targetphase is not None:
5253 raise error.InputError(_(b'only one phase can be specified'))
5253 raise error.InputError(_(b'only one phase can be specified'))
5254 targetphase = idx
5254 targetphase = idx
5255
5255
5256 # look for specified revision
5256 # look for specified revision
5257 revs = list(revs)
5257 revs = list(revs)
5258 revs.extend(opts[b'rev'])
5258 revs.extend(opts[b'rev'])
5259 if revs:
5259 if revs:
5260 revs = logcmdutil.revrange(repo, revs)
5260 revs = logcmdutil.revrange(repo, revs)
5261 else:
5261 else:
5262 # display both parents as the second parent phase can influence
5262 # display both parents as the second parent phase can influence
5263 # the phase of a merge commit
5263 # the phase of a merge commit
5264 revs = [c.rev() for c in repo[None].parents()]
5264 revs = [c.rev() for c in repo[None].parents()]
5265
5265
5266 ret = 0
5266 ret = 0
5267 if targetphase is None:
5267 if targetphase is None:
5268 # display
5268 # display
5269 for r in revs:
5269 for r in revs:
5270 ctx = repo[r]
5270 ctx = repo[r]
5271 ui.write(b'%i: %s\n' % (ctx.rev(), ctx.phasestr()))
5271 ui.write(b'%i: %s\n' % (ctx.rev(), ctx.phasestr()))
5272 else:
5272 else:
5273 with repo.lock(), repo.transaction(b"phase") as tr:
5273 with repo.lock(), repo.transaction(b"phase") as tr:
5274 # set phase
5274 # set phase
5275 if not revs:
5275 if not revs:
5276 raise error.InputError(_(b'empty revision set'))
5276 raise error.InputError(_(b'empty revision set'))
5277 nodes = [repo[r].node() for r in revs]
5277 nodes = [repo[r].node() for r in revs]
5278 # moving revision from public to draft may hide them
5278 # moving revision from public to draft may hide them
5279 # We have to check result on an unfiltered repository
5279 # We have to check result on an unfiltered repository
5280 unfi = repo.unfiltered()
5280 unfi = repo.unfiltered()
5281 getphase = unfi._phasecache.phase
5281 getphase = unfi._phasecache.phase
5282 olddata = [getphase(unfi, r) for r in unfi]
5282 olddata = [getphase(unfi, r) for r in unfi]
5283 phases.advanceboundary(repo, tr, targetphase, nodes)
5283 phases.advanceboundary(repo, tr, targetphase, nodes)
5284 if opts[b'force']:
5284 if opts[b'force']:
5285 phases.retractboundary(repo, tr, targetphase, nodes)
5285 phases.retractboundary(repo, tr, targetphase, nodes)
5286 getphase = unfi._phasecache.phase
5286 getphase = unfi._phasecache.phase
5287 newdata = [getphase(unfi, r) for r in unfi]
5287 newdata = [getphase(unfi, r) for r in unfi]
5288 changes = sum(newdata[r] != olddata[r] for r in unfi)
5288 changes = sum(newdata[r] != olddata[r] for r in unfi)
5289 cl = unfi.changelog
5289 cl = unfi.changelog
5290 rejected = [n for n in nodes if newdata[cl.rev(n)] < targetphase]
5290 rejected = [n for n in nodes if newdata[cl.rev(n)] < targetphase]
5291 if rejected:
5291 if rejected:
5292 ui.warn(
5292 ui.warn(
5293 _(
5293 _(
5294 b'cannot move %i changesets to a higher '
5294 b'cannot move %i changesets to a higher '
5295 b'phase, use --force\n'
5295 b'phase, use --force\n'
5296 )
5296 )
5297 % len(rejected)
5297 % len(rejected)
5298 )
5298 )
5299 ret = 1
5299 ret = 1
5300 if changes:
5300 if changes:
5301 msg = _(b'phase changed for %i changesets\n') % changes
5301 msg = _(b'phase changed for %i changesets\n') % changes
5302 if ret:
5302 if ret:
5303 ui.status(msg)
5303 ui.status(msg)
5304 else:
5304 else:
5305 ui.note(msg)
5305 ui.note(msg)
5306 else:
5306 else:
5307 ui.warn(_(b'no phases changed\n'))
5307 ui.warn(_(b'no phases changed\n'))
5308 return ret
5308 return ret
5309
5309
5310
5310
5311 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
5311 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
5312 """Run after a changegroup has been added via pull/unbundle
5312 """Run after a changegroup has been added via pull/unbundle
5313
5313
5314 This takes arguments below:
5314 This takes arguments below:
5315
5315
5316 :modheads: change of heads by pull/unbundle
5316 :modheads: change of heads by pull/unbundle
5317 :optupdate: updating working directory is needed or not
5317 :optupdate: updating working directory is needed or not
5318 :checkout: update destination revision (or None to default destination)
5318 :checkout: update destination revision (or None to default destination)
5319 :brev: a name, which might be a bookmark to be activated after updating
5319 :brev: a name, which might be a bookmark to be activated after updating
5320
5320
5321 return True if update raise any conflict, False otherwise.
5321 return True if update raise any conflict, False otherwise.
5322 """
5322 """
5323 if modheads == 0:
5323 if modheads == 0:
5324 return False
5324 return False
5325 if optupdate:
5325 if optupdate:
5326 try:
5326 try:
5327 return hg.updatetotally(ui, repo, checkout, brev)
5327 return hg.updatetotally(ui, repo, checkout, brev)
5328 except error.UpdateAbort as inst:
5328 except error.UpdateAbort as inst:
5329 msg = _(b"not updating: %s") % stringutil.forcebytestr(inst)
5329 msg = _(b"not updating: %s") % stringutil.forcebytestr(inst)
5330 hint = inst.hint
5330 hint = inst.hint
5331 raise error.UpdateAbort(msg, hint=hint)
5331 raise error.UpdateAbort(msg, hint=hint)
5332 if modheads is not None and modheads > 1:
5332 if modheads is not None and modheads > 1:
5333 currentbranchheads = len(repo.branchheads())
5333 currentbranchheads = len(repo.branchheads())
5334 if currentbranchheads == modheads:
5334 if currentbranchheads == modheads:
5335 ui.status(
5335 ui.status(
5336 _(b"(run 'hg heads' to see heads, 'hg merge' to merge)\n")
5336 _(b"(run 'hg heads' to see heads, 'hg merge' to merge)\n")
5337 )
5337 )
5338 elif currentbranchheads > 1:
5338 elif currentbranchheads > 1:
5339 ui.status(
5339 ui.status(
5340 _(b"(run 'hg heads .' to see heads, 'hg merge' to merge)\n")
5340 _(b"(run 'hg heads .' to see heads, 'hg merge' to merge)\n")
5341 )
5341 )
5342 else:
5342 else:
5343 ui.status(_(b"(run 'hg heads' to see heads)\n"))
5343 ui.status(_(b"(run 'hg heads' to see heads)\n"))
5344 elif not ui.configbool(b'commands', b'update.requiredest'):
5344 elif not ui.configbool(b'commands', b'update.requiredest'):
5345 ui.status(_(b"(run 'hg update' to get a working copy)\n"))
5345 ui.status(_(b"(run 'hg update' to get a working copy)\n"))
5346 return False
5346 return False
5347
5347
5348
5348
5349 @command(
5349 @command(
5350 b'pull',
5350 b'pull',
5351 [
5351 [
5352 (
5352 (
5353 b'u',
5353 b'u',
5354 b'update',
5354 b'update',
5355 None,
5355 None,
5356 _(b'update to new branch head if new descendants were pulled'),
5356 _(b'update to new branch head if new descendants were pulled'),
5357 ),
5357 ),
5358 (
5358 (
5359 b'f',
5359 b'f',
5360 b'force',
5360 b'force',
5361 None,
5361 None,
5362 _(b'run even when remote repository is unrelated'),
5362 _(b'run even when remote repository is unrelated'),
5363 ),
5363 ),
5364 (
5364 (
5365 b'',
5365 b'',
5366 b'confirm',
5366 b'confirm',
5367 None,
5367 None,
5368 _(b'confirm pull before applying changes'),
5368 _(b'confirm pull before applying changes'),
5369 ),
5369 ),
5370 (
5370 (
5371 b'r',
5371 b'r',
5372 b'rev',
5372 b'rev',
5373 [],
5373 [],
5374 _(b'a remote changeset intended to be added'),
5374 _(b'a remote changeset intended to be added'),
5375 _(b'REV'),
5375 _(b'REV'),
5376 ),
5376 ),
5377 (b'B', b'bookmark', [], _(b"bookmark to pull"), _(b'BOOKMARK')),
5377 (b'B', b'bookmark', [], _(b"bookmark to pull"), _(b'BOOKMARK')),
5378 (
5378 (
5379 b'b',
5379 b'b',
5380 b'branch',
5380 b'branch',
5381 [],
5381 [],
5382 _(b'a specific branch you would like to pull'),
5382 _(b'a specific branch you would like to pull'),
5383 _(b'BRANCH'),
5383 _(b'BRANCH'),
5384 ),
5384 ),
5385 ]
5385 ]
5386 + remoteopts,
5386 + remoteopts,
5387 _(b'[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]...'),
5387 _(b'[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]...'),
5388 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5388 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5389 helpbasic=True,
5389 helpbasic=True,
5390 )
5390 )
5391 def pull(ui, repo, *sources, **opts):
5391 def pull(ui, repo, *sources, **opts):
5392 """pull changes from the specified source
5392 """pull changes from the specified source
5393
5393
5394 Pull changes from a remote repository to a local one.
5394 Pull changes from a remote repository to a local one.
5395
5395
5396 This finds all changes from the repository at the specified path
5396 This finds all changes from the repository at the specified path
5397 or URL and adds them to a local repository (the current one unless
5397 or URL and adds them to a local repository (the current one unless
5398 -R is specified). By default, this does not update the copy of the
5398 -R is specified). By default, this does not update the copy of the
5399 project in the working directory.
5399 project in the working directory.
5400
5400
5401 When cloning from servers that support it, Mercurial may fetch
5401 When cloning from servers that support it, Mercurial may fetch
5402 pre-generated data. When this is done, hooks operating on incoming
5402 pre-generated data. When this is done, hooks operating on incoming
5403 changesets and changegroups may fire more than once, once for each
5403 changesets and changegroups may fire more than once, once for each
5404 pre-generated bundle and as well as for any additional remaining
5404 pre-generated bundle and as well as for any additional remaining
5405 data. See :hg:`help -e clonebundles` for more.
5405 data. See :hg:`help -e clonebundles` for more.
5406
5406
5407 Use :hg:`incoming` if you want to see what would have been added
5407 Use :hg:`incoming` if you want to see what would have been added
5408 by a pull at the time you issued this command. If you then decide
5408 by a pull at the time you issued this command. If you then decide
5409 to add those changes to the repository, you should use :hg:`pull
5409 to add those changes to the repository, you should use :hg:`pull
5410 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
5410 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
5411
5411
5412 If SOURCE is omitted, the 'default' path will be used.
5412 If SOURCE is omitted, the 'default' path will be used.
5413 See :hg:`help urls` for more information.
5413 See :hg:`help urls` for more information.
5414
5414
5415 If multiple sources are specified, they will be pulled sequentially as if
5415 If multiple sources are specified, they will be pulled sequentially as if
5416 the command was run multiple time. If --update is specify and the command
5416 the command was run multiple time. If --update is specify and the command
5417 will stop at the first failed --update.
5417 will stop at the first failed --update.
5418
5418
5419 Specifying bookmark as ``.`` is equivalent to specifying the active
5419 Specifying bookmark as ``.`` is equivalent to specifying the active
5420 bookmark's name.
5420 bookmark's name.
5421
5421
5422 Returns 0 on success, 1 if an update had unresolved files.
5422 Returns 0 on success, 1 if an update had unresolved files.
5423 """
5423 """
5424
5424
5425 opts = pycompat.byteskwargs(opts)
5425 opts = pycompat.byteskwargs(opts)
5426 if ui.configbool(b'commands', b'update.requiredest') and opts.get(
5426 if ui.configbool(b'commands', b'update.requiredest') and opts.get(
5427 b'update'
5427 b'update'
5428 ):
5428 ):
5429 msg = _(b'update destination required by configuration')
5429 msg = _(b'update destination required by configuration')
5430 hint = _(b'use hg pull followed by hg update DEST')
5430 hint = _(b'use hg pull followed by hg update DEST')
5431 raise error.InputError(msg, hint=hint)
5431 raise error.InputError(msg, hint=hint)
5432
5432
5433 for path in urlutil.get_pull_paths(repo, ui, sources):
5433 for path in urlutil.get_pull_paths(repo, ui, sources):
5434 source, branches = urlutil.parseurl(path.rawloc, opts.get(b'branch'))
5434 ui.status(_(b'pulling from %s\n') % urlutil.hidepassword(path.loc))
5435 ui.status(_(b'pulling from %s\n') % urlutil.hidepassword(source))
5436 ui.flush()
5435 ui.flush()
5437 other = hg.peer(repo, opts, source)
5436 other = hg.peer(repo, opts, path)
5438 update_conflict = None
5437 update_conflict = None
5439 try:
5438 try:
5439 branches = (path.branch, opts.get(b'branch', []))
5440 revs, checkout = hg.addbranchrevs(
5440 revs, checkout = hg.addbranchrevs(
5441 repo, other, branches, opts.get(b'rev')
5441 repo, other, branches, opts.get(b'rev')
5442 )
5442 )
5443
5443
5444 pullopargs = {}
5444 pullopargs = {}
5445
5445
5446 nodes = None
5446 nodes = None
5447 if opts.get(b'bookmark') or revs:
5447 if opts.get(b'bookmark') or revs:
5448 # The list of bookmark used here is the same used to actually update
5448 # The list of bookmark used here is the same used to actually update
5449 # the bookmark names, to avoid the race from issue 4689 and we do
5449 # the bookmark names, to avoid the race from issue 4689 and we do
5450 # all lookup and bookmark queries in one go so they see the same
5450 # all lookup and bookmark queries in one go so they see the same
5451 # version of the server state (issue 4700).
5451 # version of the server state (issue 4700).
5452 nodes = []
5452 nodes = []
5453 fnodes = []
5453 fnodes = []
5454 revs = revs or []
5454 revs = revs or []
5455 if revs and not other.capable(b'lookup'):
5455 if revs and not other.capable(b'lookup'):
5456 err = _(
5456 err = _(
5457 b"other repository doesn't support revision lookup, "
5457 b"other repository doesn't support revision lookup, "
5458 b"so a rev cannot be specified."
5458 b"so a rev cannot be specified."
5459 )
5459 )
5460 raise error.Abort(err)
5460 raise error.Abort(err)
5461 with other.commandexecutor() as e:
5461 with other.commandexecutor() as e:
5462 fremotebookmarks = e.callcommand(
5462 fremotebookmarks = e.callcommand(
5463 b'listkeys', {b'namespace': b'bookmarks'}
5463 b'listkeys', {b'namespace': b'bookmarks'}
5464 )
5464 )
5465 for r in revs:
5465 for r in revs:
5466 fnodes.append(e.callcommand(b'lookup', {b'key': r}))
5466 fnodes.append(e.callcommand(b'lookup', {b'key': r}))
5467 remotebookmarks = fremotebookmarks.result()
5467 remotebookmarks = fremotebookmarks.result()
5468 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
5468 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
5469 pullopargs[b'remotebookmarks'] = remotebookmarks
5469 pullopargs[b'remotebookmarks'] = remotebookmarks
5470 for b in opts.get(b'bookmark', []):
5470 for b in opts.get(b'bookmark', []):
5471 b = repo._bookmarks.expandname(b)
5471 b = repo._bookmarks.expandname(b)
5472 if b not in remotebookmarks:
5472 if b not in remotebookmarks:
5473 raise error.InputError(
5473 raise error.InputError(
5474 _(b'remote bookmark %s not found!') % b
5474 _(b'remote bookmark %s not found!') % b
5475 )
5475 )
5476 nodes.append(remotebookmarks[b])
5476 nodes.append(remotebookmarks[b])
5477 for i, rev in enumerate(revs):
5477 for i, rev in enumerate(revs):
5478 node = fnodes[i].result()
5478 node = fnodes[i].result()
5479 nodes.append(node)
5479 nodes.append(node)
5480 if rev == checkout:
5480 if rev == checkout:
5481 checkout = node
5481 checkout = node
5482
5482
5483 wlock = util.nullcontextmanager()
5483 wlock = util.nullcontextmanager()
5484 if opts.get(b'update'):
5484 if opts.get(b'update'):
5485 wlock = repo.wlock()
5485 wlock = repo.wlock()
5486 with wlock:
5486 with wlock:
5487 pullopargs.update(opts.get(b'opargs', {}))
5487 pullopargs.update(opts.get(b'opargs', {}))
5488 modheads = exchange.pull(
5488 modheads = exchange.pull(
5489 repo,
5489 repo,
5490 other,
5490 other,
5491 path=path,
5491 path=path,
5492 heads=nodes,
5492 heads=nodes,
5493 force=opts.get(b'force'),
5493 force=opts.get(b'force'),
5494 bookmarks=opts.get(b'bookmark', ()),
5494 bookmarks=opts.get(b'bookmark', ()),
5495 opargs=pullopargs,
5495 opargs=pullopargs,
5496 confirm=opts.get(b'confirm'),
5496 confirm=opts.get(b'confirm'),
5497 ).cgresult
5497 ).cgresult
5498
5498
5499 # brev is a name, which might be a bookmark to be activated at
5499 # brev is a name, which might be a bookmark to be activated at
5500 # the end of the update. In other words, it is an explicit
5500 # the end of the update. In other words, it is an explicit
5501 # destination of the update
5501 # destination of the update
5502 brev = None
5502 brev = None
5503
5503
5504 if checkout:
5504 if checkout:
5505 checkout = repo.unfiltered().changelog.rev(checkout)
5505 checkout = repo.unfiltered().changelog.rev(checkout)
5506
5506
5507 # order below depends on implementation of
5507 # order below depends on implementation of
5508 # hg.addbranchrevs(). opts['bookmark'] is ignored,
5508 # hg.addbranchrevs(). opts['bookmark'] is ignored,
5509 # because 'checkout' is determined without it.
5509 # because 'checkout' is determined without it.
5510 if opts.get(b'rev'):
5510 if opts.get(b'rev'):
5511 brev = opts[b'rev'][0]
5511 brev = opts[b'rev'][0]
5512 elif opts.get(b'branch'):
5512 elif opts.get(b'branch'):
5513 brev = opts[b'branch'][0]
5513 brev = opts[b'branch'][0]
5514 else:
5514 else:
5515 brev = branches[0]
5515 brev = path.branch
5516 repo._subtoppath = source
5516
5517 # XXX path: we are losing the `path` object here. Keeping it
5518 # would be valuable. For example as a "variant" as we do
5519 # for pushes.
5520 repo._subtoppath = path.loc
5517 try:
5521 try:
5518 update_conflict = postincoming(
5522 update_conflict = postincoming(
5519 ui, repo, modheads, opts.get(b'update'), checkout, brev
5523 ui, repo, modheads, opts.get(b'update'), checkout, brev
5520 )
5524 )
5521 except error.FilteredRepoLookupError as exc:
5525 except error.FilteredRepoLookupError as exc:
5522 msg = _(b'cannot update to target: %s') % exc.args[0]
5526 msg = _(b'cannot update to target: %s') % exc.args[0]
5523 exc.args = (msg,) + exc.args[1:]
5527 exc.args = (msg,) + exc.args[1:]
5524 raise
5528 raise
5525 finally:
5529 finally:
5526 del repo._subtoppath
5530 del repo._subtoppath
5527
5531
5528 finally:
5532 finally:
5529 other.close()
5533 other.close()
5530 # skip the remaining pull source if they are some conflict.
5534 # skip the remaining pull source if they are some conflict.
5531 if update_conflict:
5535 if update_conflict:
5532 break
5536 break
5533 if update_conflict:
5537 if update_conflict:
5534 return 1
5538 return 1
5535 else:
5539 else:
5536 return 0
5540 return 0
5537
5541
5538
5542
5539 @command(
5543 @command(
5540 b'purge|clean',
5544 b'purge|clean',
5541 [
5545 [
5542 (b'a', b'abort-on-err', None, _(b'abort if an error occurs')),
5546 (b'a', b'abort-on-err', None, _(b'abort if an error occurs')),
5543 (b'', b'all', None, _(b'purge ignored files too')),
5547 (b'', b'all', None, _(b'purge ignored files too')),
5544 (b'i', b'ignored', None, _(b'purge only ignored files')),
5548 (b'i', b'ignored', None, _(b'purge only ignored files')),
5545 (b'', b'dirs', None, _(b'purge empty directories')),
5549 (b'', b'dirs', None, _(b'purge empty directories')),
5546 (b'', b'files', None, _(b'purge files')),
5550 (b'', b'files', None, _(b'purge files')),
5547 (b'p', b'print', None, _(b'print filenames instead of deleting them')),
5551 (b'p', b'print', None, _(b'print filenames instead of deleting them')),
5548 (
5552 (
5549 b'0',
5553 b'0',
5550 b'print0',
5554 b'print0',
5551 None,
5555 None,
5552 _(
5556 _(
5553 b'end filenames with NUL, for use with xargs'
5557 b'end filenames with NUL, for use with xargs'
5554 b' (implies -p/--print)'
5558 b' (implies -p/--print)'
5555 ),
5559 ),
5556 ),
5560 ),
5557 (b'', b'confirm', None, _(b'ask before permanently deleting files')),
5561 (b'', b'confirm', None, _(b'ask before permanently deleting files')),
5558 ]
5562 ]
5559 + cmdutil.walkopts,
5563 + cmdutil.walkopts,
5560 _(b'hg purge [OPTION]... [DIR]...'),
5564 _(b'hg purge [OPTION]... [DIR]...'),
5561 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5565 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5562 )
5566 )
5563 def purge(ui, repo, *dirs, **opts):
5567 def purge(ui, repo, *dirs, **opts):
5564 """removes files not tracked by Mercurial
5568 """removes files not tracked by Mercurial
5565
5569
5566 Delete files not known to Mercurial. This is useful to test local
5570 Delete files not known to Mercurial. This is useful to test local
5567 and uncommitted changes in an otherwise-clean source tree.
5571 and uncommitted changes in an otherwise-clean source tree.
5568
5572
5569 This means that purge will delete the following by default:
5573 This means that purge will delete the following by default:
5570
5574
5571 - Unknown files: files marked with "?" by :hg:`status`
5575 - Unknown files: files marked with "?" by :hg:`status`
5572 - Empty directories: in fact Mercurial ignores directories unless
5576 - Empty directories: in fact Mercurial ignores directories unless
5573 they contain files under source control management
5577 they contain files under source control management
5574
5578
5575 But it will leave untouched:
5579 But it will leave untouched:
5576
5580
5577 - Modified and unmodified tracked files
5581 - Modified and unmodified tracked files
5578 - Ignored files (unless -i or --all is specified)
5582 - Ignored files (unless -i or --all is specified)
5579 - New files added to the repository (with :hg:`add`)
5583 - New files added to the repository (with :hg:`add`)
5580
5584
5581 The --files and --dirs options can be used to direct purge to delete
5585 The --files and --dirs options can be used to direct purge to delete
5582 only files, only directories, or both. If neither option is given,
5586 only files, only directories, or both. If neither option is given,
5583 both will be deleted.
5587 both will be deleted.
5584
5588
5585 If directories are given on the command line, only files in these
5589 If directories are given on the command line, only files in these
5586 directories are considered.
5590 directories are considered.
5587
5591
5588 Be careful with purge, as you could irreversibly delete some files
5592 Be careful with purge, as you could irreversibly delete some files
5589 you forgot to add to the repository. If you only want to print the
5593 you forgot to add to the repository. If you only want to print the
5590 list of files that this program would delete, use the --print
5594 list of files that this program would delete, use the --print
5591 option.
5595 option.
5592 """
5596 """
5593 opts = pycompat.byteskwargs(opts)
5597 opts = pycompat.byteskwargs(opts)
5594 cmdutil.check_at_most_one_arg(opts, b'all', b'ignored')
5598 cmdutil.check_at_most_one_arg(opts, b'all', b'ignored')
5595
5599
5596 act = not opts.get(b'print')
5600 act = not opts.get(b'print')
5597 eol = b'\n'
5601 eol = b'\n'
5598 if opts.get(b'print0'):
5602 if opts.get(b'print0'):
5599 eol = b'\0'
5603 eol = b'\0'
5600 act = False # --print0 implies --print
5604 act = False # --print0 implies --print
5601 if opts.get(b'all', False):
5605 if opts.get(b'all', False):
5602 ignored = True
5606 ignored = True
5603 unknown = True
5607 unknown = True
5604 else:
5608 else:
5605 ignored = opts.get(b'ignored', False)
5609 ignored = opts.get(b'ignored', False)
5606 unknown = not ignored
5610 unknown = not ignored
5607
5611
5608 removefiles = opts.get(b'files')
5612 removefiles = opts.get(b'files')
5609 removedirs = opts.get(b'dirs')
5613 removedirs = opts.get(b'dirs')
5610 confirm = opts.get(b'confirm')
5614 confirm = opts.get(b'confirm')
5611 if confirm is None:
5615 if confirm is None:
5612 try:
5616 try:
5613 extensions.find(b'purge')
5617 extensions.find(b'purge')
5614 confirm = False
5618 confirm = False
5615 except KeyError:
5619 except KeyError:
5616 confirm = True
5620 confirm = True
5617
5621
5618 if not removefiles and not removedirs:
5622 if not removefiles and not removedirs:
5619 removefiles = True
5623 removefiles = True
5620 removedirs = True
5624 removedirs = True
5621
5625
5622 match = scmutil.match(repo[None], dirs, opts)
5626 match = scmutil.match(repo[None], dirs, opts)
5623
5627
5624 paths = mergemod.purge(
5628 paths = mergemod.purge(
5625 repo,
5629 repo,
5626 match,
5630 match,
5627 unknown=unknown,
5631 unknown=unknown,
5628 ignored=ignored,
5632 ignored=ignored,
5629 removeemptydirs=removedirs,
5633 removeemptydirs=removedirs,
5630 removefiles=removefiles,
5634 removefiles=removefiles,
5631 abortonerror=opts.get(b'abort_on_err'),
5635 abortonerror=opts.get(b'abort_on_err'),
5632 noop=not act,
5636 noop=not act,
5633 confirm=confirm,
5637 confirm=confirm,
5634 )
5638 )
5635
5639
5636 for path in paths:
5640 for path in paths:
5637 if not act:
5641 if not act:
5638 ui.write(b'%s%s' % (path, eol))
5642 ui.write(b'%s%s' % (path, eol))
5639
5643
5640
5644
5641 @command(
5645 @command(
5642 b'push',
5646 b'push',
5643 [
5647 [
5644 (b'f', b'force', None, _(b'force push')),
5648 (b'f', b'force', None, _(b'force push')),
5645 (
5649 (
5646 b'r',
5650 b'r',
5647 b'rev',
5651 b'rev',
5648 [],
5652 [],
5649 _(b'a changeset intended to be included in the destination'),
5653 _(b'a changeset intended to be included in the destination'),
5650 _(b'REV'),
5654 _(b'REV'),
5651 ),
5655 ),
5652 (b'B', b'bookmark', [], _(b"bookmark to push"), _(b'BOOKMARK')),
5656 (b'B', b'bookmark', [], _(b"bookmark to push"), _(b'BOOKMARK')),
5653 (b'', b'all-bookmarks', None, _(b"push all bookmarks (EXPERIMENTAL)")),
5657 (b'', b'all-bookmarks', None, _(b"push all bookmarks (EXPERIMENTAL)")),
5654 (
5658 (
5655 b'b',
5659 b'b',
5656 b'branch',
5660 b'branch',
5657 [],
5661 [],
5658 _(b'a specific branch you would like to push'),
5662 _(b'a specific branch you would like to push'),
5659 _(b'BRANCH'),
5663 _(b'BRANCH'),
5660 ),
5664 ),
5661 (b'', b'new-branch', False, _(b'allow pushing a new branch')),
5665 (b'', b'new-branch', False, _(b'allow pushing a new branch')),
5662 (
5666 (
5663 b'',
5667 b'',
5664 b'pushvars',
5668 b'pushvars',
5665 [],
5669 [],
5666 _(b'variables that can be sent to server (ADVANCED)'),
5670 _(b'variables that can be sent to server (ADVANCED)'),
5667 ),
5671 ),
5668 (
5672 (
5669 b'',
5673 b'',
5670 b'publish',
5674 b'publish',
5671 False,
5675 False,
5672 _(b'push the changeset as public (EXPERIMENTAL)'),
5676 _(b'push the changeset as public (EXPERIMENTAL)'),
5673 ),
5677 ),
5674 ]
5678 ]
5675 + remoteopts,
5679 + remoteopts,
5676 _(b'[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]...'),
5680 _(b'[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]...'),
5677 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5681 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5678 helpbasic=True,
5682 helpbasic=True,
5679 )
5683 )
5680 def push(ui, repo, *dests, **opts):
5684 def push(ui, repo, *dests, **opts):
5681 """push changes to the specified destination
5685 """push changes to the specified destination
5682
5686
5683 Push changesets from the local repository to the specified
5687 Push changesets from the local repository to the specified
5684 destination.
5688 destination.
5685
5689
5686 This operation is symmetrical to pull: it is identical to a pull
5690 This operation is symmetrical to pull: it is identical to a pull
5687 in the destination repository from the current one.
5691 in the destination repository from the current one.
5688
5692
5689 By default, push will not allow creation of new heads at the
5693 By default, push will not allow creation of new heads at the
5690 destination, since multiple heads would make it unclear which head
5694 destination, since multiple heads would make it unclear which head
5691 to use. In this situation, it is recommended to pull and merge
5695 to use. In this situation, it is recommended to pull and merge
5692 before pushing.
5696 before pushing.
5693
5697
5694 Use --new-branch if you want to allow push to create a new named
5698 Use --new-branch if you want to allow push to create a new named
5695 branch that is not present at the destination. This allows you to
5699 branch that is not present at the destination. This allows you to
5696 only create a new branch without forcing other changes.
5700 only create a new branch without forcing other changes.
5697
5701
5698 .. note::
5702 .. note::
5699
5703
5700 Extra care should be taken with the -f/--force option,
5704 Extra care should be taken with the -f/--force option,
5701 which will push all new heads on all branches, an action which will
5705 which will push all new heads on all branches, an action which will
5702 almost always cause confusion for collaborators.
5706 almost always cause confusion for collaborators.
5703
5707
5704 If -r/--rev is used, the specified revision and all its ancestors
5708 If -r/--rev is used, the specified revision and all its ancestors
5705 will be pushed to the remote repository.
5709 will be pushed to the remote repository.
5706
5710
5707 If -B/--bookmark is used, the specified bookmarked revision, its
5711 If -B/--bookmark is used, the specified bookmarked revision, its
5708 ancestors, and the bookmark will be pushed to the remote
5712 ancestors, and the bookmark will be pushed to the remote
5709 repository. Specifying ``.`` is equivalent to specifying the active
5713 repository. Specifying ``.`` is equivalent to specifying the active
5710 bookmark's name. Use the --all-bookmarks option for pushing all
5714 bookmark's name. Use the --all-bookmarks option for pushing all
5711 current bookmarks.
5715 current bookmarks.
5712
5716
5713 Please see :hg:`help urls` for important details about ``ssh://``
5717 Please see :hg:`help urls` for important details about ``ssh://``
5714 URLs. If DESTINATION is omitted, a default path will be used.
5718 URLs. If DESTINATION is omitted, a default path will be used.
5715
5719
5716 When passed multiple destinations, push will process them one after the
5720 When passed multiple destinations, push will process them one after the
5717 other, but stop should an error occur.
5721 other, but stop should an error occur.
5718
5722
5719 .. container:: verbose
5723 .. container:: verbose
5720
5724
5721 The --pushvars option sends strings to the server that become
5725 The --pushvars option sends strings to the server that become
5722 environment variables prepended with ``HG_USERVAR_``. For example,
5726 environment variables prepended with ``HG_USERVAR_``. For example,
5723 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
5727 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
5724 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
5728 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
5725
5729
5726 pushvars can provide for user-overridable hooks as well as set debug
5730 pushvars can provide for user-overridable hooks as well as set debug
5727 levels. One example is having a hook that blocks commits containing
5731 levels. One example is having a hook that blocks commits containing
5728 conflict markers, but enables the user to override the hook if the file
5732 conflict markers, but enables the user to override the hook if the file
5729 is using conflict markers for testing purposes or the file format has
5733 is using conflict markers for testing purposes or the file format has
5730 strings that look like conflict markers.
5734 strings that look like conflict markers.
5731
5735
5732 By default, servers will ignore `--pushvars`. To enable it add the
5736 By default, servers will ignore `--pushvars`. To enable it add the
5733 following to your configuration file::
5737 following to your configuration file::
5734
5738
5735 [push]
5739 [push]
5736 pushvars.server = true
5740 pushvars.server = true
5737
5741
5738 Returns 0 if push was successful, 1 if nothing to push.
5742 Returns 0 if push was successful, 1 if nothing to push.
5739 """
5743 """
5740
5744
5741 opts = pycompat.byteskwargs(opts)
5745 opts = pycompat.byteskwargs(opts)
5742
5746
5743 if opts.get(b'all_bookmarks'):
5747 if opts.get(b'all_bookmarks'):
5744 cmdutil.check_incompatible_arguments(
5748 cmdutil.check_incompatible_arguments(
5745 opts,
5749 opts,
5746 b'all_bookmarks',
5750 b'all_bookmarks',
5747 [b'bookmark', b'rev'],
5751 [b'bookmark', b'rev'],
5748 )
5752 )
5749 opts[b'bookmark'] = list(repo._bookmarks)
5753 opts[b'bookmark'] = list(repo._bookmarks)
5750
5754
5751 if opts.get(b'bookmark'):
5755 if opts.get(b'bookmark'):
5752 ui.setconfig(b'bookmarks', b'pushing', opts[b'bookmark'], b'push')
5756 ui.setconfig(b'bookmarks', b'pushing', opts[b'bookmark'], b'push')
5753 for b in opts[b'bookmark']:
5757 for b in opts[b'bookmark']:
5754 # translate -B options to -r so changesets get pushed
5758 # translate -B options to -r so changesets get pushed
5755 b = repo._bookmarks.expandname(b)
5759 b = repo._bookmarks.expandname(b)
5756 if b in repo._bookmarks:
5760 if b in repo._bookmarks:
5757 opts.setdefault(b'rev', []).append(b)
5761 opts.setdefault(b'rev', []).append(b)
5758 else:
5762 else:
5759 # if we try to push a deleted bookmark, translate it to null
5763 # if we try to push a deleted bookmark, translate it to null
5760 # this lets simultaneous -r, -b options continue working
5764 # this lets simultaneous -r, -b options continue working
5761 opts.setdefault(b'rev', []).append(b"null")
5765 opts.setdefault(b'rev', []).append(b"null")
5762
5766
5763 some_pushed = False
5767 some_pushed = False
5764 result = 0
5768 result = 0
5765 for path in urlutil.get_push_paths(repo, ui, dests):
5769 for path in urlutil.get_push_paths(repo, ui, dests):
5766 dest = path.loc
5770 dest = path.loc
5767 branches = (path.branch, opts.get(b'branch') or [])
5771 branches = (path.branch, opts.get(b'branch') or [])
5768 ui.status(_(b'pushing to %s\n') % urlutil.hidepassword(dest))
5772 ui.status(_(b'pushing to %s\n') % urlutil.hidepassword(dest))
5769 revs, checkout = hg.addbranchrevs(
5773 revs, checkout = hg.addbranchrevs(
5770 repo, repo, branches, opts.get(b'rev')
5774 repo, repo, branches, opts.get(b'rev')
5771 )
5775 )
5772 other = hg.peer(repo, opts, dest)
5776 other = hg.peer(repo, opts, dest)
5773
5777
5774 try:
5778 try:
5775 if revs:
5779 if revs:
5776 revs = [repo[r].node() for r in logcmdutil.revrange(repo, revs)]
5780 revs = [repo[r].node() for r in logcmdutil.revrange(repo, revs)]
5777 if not revs:
5781 if not revs:
5778 raise error.InputError(
5782 raise error.InputError(
5779 _(b"specified revisions evaluate to an empty set"),
5783 _(b"specified revisions evaluate to an empty set"),
5780 hint=_(b"use different revision arguments"),
5784 hint=_(b"use different revision arguments"),
5781 )
5785 )
5782 elif path.pushrev:
5786 elif path.pushrev:
5783 # It doesn't make any sense to specify ancestor revisions. So limit
5787 # It doesn't make any sense to specify ancestor revisions. So limit
5784 # to DAG heads to make discovery simpler.
5788 # to DAG heads to make discovery simpler.
5785 expr = revsetlang.formatspec(b'heads(%r)', path.pushrev)
5789 expr = revsetlang.formatspec(b'heads(%r)', path.pushrev)
5786 revs = scmutil.revrange(repo, [expr])
5790 revs = scmutil.revrange(repo, [expr])
5787 revs = [repo[rev].node() for rev in revs]
5791 revs = [repo[rev].node() for rev in revs]
5788 if not revs:
5792 if not revs:
5789 raise error.InputError(
5793 raise error.InputError(
5790 _(
5794 _(
5791 b'default push revset for path evaluates to an empty set'
5795 b'default push revset for path evaluates to an empty set'
5792 )
5796 )
5793 )
5797 )
5794 elif ui.configbool(b'commands', b'push.require-revs'):
5798 elif ui.configbool(b'commands', b'push.require-revs'):
5795 raise error.InputError(
5799 raise error.InputError(
5796 _(b'no revisions specified to push'),
5800 _(b'no revisions specified to push'),
5797 hint=_(b'did you mean "hg push -r ."?'),
5801 hint=_(b'did you mean "hg push -r ."?'),
5798 )
5802 )
5799
5803
5800 repo._subtoppath = dest
5804 repo._subtoppath = dest
5801 try:
5805 try:
5802 # push subrepos depth-first for coherent ordering
5806 # push subrepos depth-first for coherent ordering
5803 c = repo[b'.']
5807 c = repo[b'.']
5804 subs = c.substate # only repos that are committed
5808 subs = c.substate # only repos that are committed
5805 for s in sorted(subs):
5809 for s in sorted(subs):
5806 sub_result = c.sub(s).push(opts)
5810 sub_result = c.sub(s).push(opts)
5807 if sub_result == 0:
5811 if sub_result == 0:
5808 return 1
5812 return 1
5809 finally:
5813 finally:
5810 del repo._subtoppath
5814 del repo._subtoppath
5811
5815
5812 opargs = dict(
5816 opargs = dict(
5813 opts.get(b'opargs', {})
5817 opts.get(b'opargs', {})
5814 ) # copy opargs since we may mutate it
5818 ) # copy opargs since we may mutate it
5815 opargs.setdefault(b'pushvars', []).extend(opts.get(b'pushvars', []))
5819 opargs.setdefault(b'pushvars', []).extend(opts.get(b'pushvars', []))
5816
5820
5817 pushop = exchange.push(
5821 pushop = exchange.push(
5818 repo,
5822 repo,
5819 other,
5823 other,
5820 opts.get(b'force'),
5824 opts.get(b'force'),
5821 revs=revs,
5825 revs=revs,
5822 newbranch=opts.get(b'new_branch'),
5826 newbranch=opts.get(b'new_branch'),
5823 bookmarks=opts.get(b'bookmark', ()),
5827 bookmarks=opts.get(b'bookmark', ()),
5824 publish=opts.get(b'publish'),
5828 publish=opts.get(b'publish'),
5825 opargs=opargs,
5829 opargs=opargs,
5826 )
5830 )
5827
5831
5828 if pushop.cgresult == 0:
5832 if pushop.cgresult == 0:
5829 result = 1
5833 result = 1
5830 elif pushop.cgresult is not None:
5834 elif pushop.cgresult is not None:
5831 some_pushed = True
5835 some_pushed = True
5832
5836
5833 if pushop.bkresult is not None:
5837 if pushop.bkresult is not None:
5834 if pushop.bkresult == 2:
5838 if pushop.bkresult == 2:
5835 result = 2
5839 result = 2
5836 elif not result and pushop.bkresult:
5840 elif not result and pushop.bkresult:
5837 result = 2
5841 result = 2
5838
5842
5839 if result:
5843 if result:
5840 break
5844 break
5841
5845
5842 finally:
5846 finally:
5843 other.close()
5847 other.close()
5844 if result == 0 and not some_pushed:
5848 if result == 0 and not some_pushed:
5845 result = 1
5849 result = 1
5846 return result
5850 return result
5847
5851
5848
5852
5849 @command(
5853 @command(
5850 b'recover',
5854 b'recover',
5851 [
5855 [
5852 (b'', b'verify', False, b"run `hg verify` after successful recover"),
5856 (b'', b'verify', False, b"run `hg verify` after successful recover"),
5853 ],
5857 ],
5854 helpcategory=command.CATEGORY_MAINTENANCE,
5858 helpcategory=command.CATEGORY_MAINTENANCE,
5855 )
5859 )
5856 def recover(ui, repo, **opts):
5860 def recover(ui, repo, **opts):
5857 """roll back an interrupted transaction
5861 """roll back an interrupted transaction
5858
5862
5859 Recover from an interrupted commit or pull.
5863 Recover from an interrupted commit or pull.
5860
5864
5861 This command tries to fix the repository status after an
5865 This command tries to fix the repository status after an
5862 interrupted operation. It should only be necessary when Mercurial
5866 interrupted operation. It should only be necessary when Mercurial
5863 suggests it.
5867 suggests it.
5864
5868
5865 Returns 0 if successful, 1 if nothing to recover or verify fails.
5869 Returns 0 if successful, 1 if nothing to recover or verify fails.
5866 """
5870 """
5867 ret = repo.recover()
5871 ret = repo.recover()
5868 if ret:
5872 if ret:
5869 if opts['verify']:
5873 if opts['verify']:
5870 return hg.verify(repo)
5874 return hg.verify(repo)
5871 else:
5875 else:
5872 msg = _(
5876 msg = _(
5873 b"(verify step skipped, run `hg verify` to check your "
5877 b"(verify step skipped, run `hg verify` to check your "
5874 b"repository content)\n"
5878 b"repository content)\n"
5875 )
5879 )
5876 ui.warn(msg)
5880 ui.warn(msg)
5877 return 0
5881 return 0
5878 return 1
5882 return 1
5879
5883
5880
5884
5881 @command(
5885 @command(
5882 b'remove|rm',
5886 b'remove|rm',
5883 [
5887 [
5884 (b'A', b'after', None, _(b'record delete for missing files')),
5888 (b'A', b'after', None, _(b'record delete for missing files')),
5885 (b'f', b'force', None, _(b'forget added files, delete modified files')),
5889 (b'f', b'force', None, _(b'forget added files, delete modified files')),
5886 ]
5890 ]
5887 + subrepoopts
5891 + subrepoopts
5888 + walkopts
5892 + walkopts
5889 + dryrunopts,
5893 + dryrunopts,
5890 _(b'[OPTION]... FILE...'),
5894 _(b'[OPTION]... FILE...'),
5891 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5895 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5892 helpbasic=True,
5896 helpbasic=True,
5893 inferrepo=True,
5897 inferrepo=True,
5894 )
5898 )
5895 def remove(ui, repo, *pats, **opts):
5899 def remove(ui, repo, *pats, **opts):
5896 """remove the specified files on the next commit
5900 """remove the specified files on the next commit
5897
5901
5898 Schedule the indicated files for removal from the current branch.
5902 Schedule the indicated files for removal from the current branch.
5899
5903
5900 This command schedules the files to be removed at the next commit.
5904 This command schedules the files to be removed at the next commit.
5901 To undo a remove before that, see :hg:`revert`. To undo added
5905 To undo a remove before that, see :hg:`revert`. To undo added
5902 files, see :hg:`forget`.
5906 files, see :hg:`forget`.
5903
5907
5904 .. container:: verbose
5908 .. container:: verbose
5905
5909
5906 -A/--after can be used to remove only files that have already
5910 -A/--after can be used to remove only files that have already
5907 been deleted, -f/--force can be used to force deletion, and -Af
5911 been deleted, -f/--force can be used to force deletion, and -Af
5908 can be used to remove files from the next revision without
5912 can be used to remove files from the next revision without
5909 deleting them from the working directory.
5913 deleting them from the working directory.
5910
5914
5911 The following table details the behavior of remove for different
5915 The following table details the behavior of remove for different
5912 file states (columns) and option combinations (rows). The file
5916 file states (columns) and option combinations (rows). The file
5913 states are Added [A], Clean [C], Modified [M] and Missing [!]
5917 states are Added [A], Clean [C], Modified [M] and Missing [!]
5914 (as reported by :hg:`status`). The actions are Warn, Remove
5918 (as reported by :hg:`status`). The actions are Warn, Remove
5915 (from branch) and Delete (from disk):
5919 (from branch) and Delete (from disk):
5916
5920
5917 ========= == == == ==
5921 ========= == == == ==
5918 opt/state A C M !
5922 opt/state A C M !
5919 ========= == == == ==
5923 ========= == == == ==
5920 none W RD W R
5924 none W RD W R
5921 -f R RD RD R
5925 -f R RD RD R
5922 -A W W W R
5926 -A W W W R
5923 -Af R R R R
5927 -Af R R R R
5924 ========= == == == ==
5928 ========= == == == ==
5925
5929
5926 .. note::
5930 .. note::
5927
5931
5928 :hg:`remove` never deletes files in Added [A] state from the
5932 :hg:`remove` never deletes files in Added [A] state from the
5929 working directory, not even if ``--force`` is specified.
5933 working directory, not even if ``--force`` is specified.
5930
5934
5931 Returns 0 on success, 1 if any warnings encountered.
5935 Returns 0 on success, 1 if any warnings encountered.
5932 """
5936 """
5933
5937
5934 opts = pycompat.byteskwargs(opts)
5938 opts = pycompat.byteskwargs(opts)
5935 after, force = opts.get(b'after'), opts.get(b'force')
5939 after, force = opts.get(b'after'), opts.get(b'force')
5936 dryrun = opts.get(b'dry_run')
5940 dryrun = opts.get(b'dry_run')
5937 if not pats and not after:
5941 if not pats and not after:
5938 raise error.InputError(_(b'no files specified'))
5942 raise error.InputError(_(b'no files specified'))
5939
5943
5940 m = scmutil.match(repo[None], pats, opts)
5944 m = scmutil.match(repo[None], pats, opts)
5941 subrepos = opts.get(b'subrepos')
5945 subrepos = opts.get(b'subrepos')
5942 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
5946 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
5943 return cmdutil.remove(
5947 return cmdutil.remove(
5944 ui, repo, m, b"", uipathfn, after, force, subrepos, dryrun=dryrun
5948 ui, repo, m, b"", uipathfn, after, force, subrepos, dryrun=dryrun
5945 )
5949 )
5946
5950
5947
5951
5948 @command(
5952 @command(
5949 b'rename|move|mv',
5953 b'rename|move|mv',
5950 [
5954 [
5951 (b'', b'forget', None, _(b'unmark a destination file as renamed')),
5955 (b'', b'forget', None, _(b'unmark a destination file as renamed')),
5952 (b'A', b'after', None, _(b'record a rename that has already occurred')),
5956 (b'A', b'after', None, _(b'record a rename that has already occurred')),
5953 (
5957 (
5954 b'',
5958 b'',
5955 b'at-rev',
5959 b'at-rev',
5956 b'',
5960 b'',
5957 _(b'(un)mark renames in the given revision (EXPERIMENTAL)'),
5961 _(b'(un)mark renames in the given revision (EXPERIMENTAL)'),
5958 _(b'REV'),
5962 _(b'REV'),
5959 ),
5963 ),
5960 (
5964 (
5961 b'f',
5965 b'f',
5962 b'force',
5966 b'force',
5963 None,
5967 None,
5964 _(b'forcibly move over an existing managed file'),
5968 _(b'forcibly move over an existing managed file'),
5965 ),
5969 ),
5966 ]
5970 ]
5967 + walkopts
5971 + walkopts
5968 + dryrunopts,
5972 + dryrunopts,
5969 _(b'[OPTION]... SOURCE... DEST'),
5973 _(b'[OPTION]... SOURCE... DEST'),
5970 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5974 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5971 )
5975 )
5972 def rename(ui, repo, *pats, **opts):
5976 def rename(ui, repo, *pats, **opts):
5973 """rename files; equivalent of copy + remove
5977 """rename files; equivalent of copy + remove
5974
5978
5975 Mark dest as copies of sources; mark sources for deletion. If dest
5979 Mark dest as copies of sources; mark sources for deletion. If dest
5976 is a directory, copies are put in that directory. If dest is a
5980 is a directory, copies are put in that directory. If dest is a
5977 file, there can only be one source.
5981 file, there can only be one source.
5978
5982
5979 By default, this command copies the contents of files as they
5983 By default, this command copies the contents of files as they
5980 exist in the working directory. If invoked with -A/--after, the
5984 exist in the working directory. If invoked with -A/--after, the
5981 operation is recorded, but no copying is performed.
5985 operation is recorded, but no copying is performed.
5982
5986
5983 To undo marking a destination file as renamed, use --forget. With that
5987 To undo marking a destination file as renamed, use --forget. With that
5984 option, all given (positional) arguments are unmarked as renames. The
5988 option, all given (positional) arguments are unmarked as renames. The
5985 destination file(s) will be left in place (still tracked). The source
5989 destination file(s) will be left in place (still tracked). The source
5986 file(s) will not be restored. Note that :hg:`rename --forget` behaves
5990 file(s) will not be restored. Note that :hg:`rename --forget` behaves
5987 the same way as :hg:`copy --forget`.
5991 the same way as :hg:`copy --forget`.
5988
5992
5989 This command takes effect with the next commit by default.
5993 This command takes effect with the next commit by default.
5990
5994
5991 Returns 0 on success, 1 if errors are encountered.
5995 Returns 0 on success, 1 if errors are encountered.
5992 """
5996 """
5993 opts = pycompat.byteskwargs(opts)
5997 opts = pycompat.byteskwargs(opts)
5994 with repo.wlock():
5998 with repo.wlock():
5995 return cmdutil.copy(ui, repo, pats, opts, rename=True)
5999 return cmdutil.copy(ui, repo, pats, opts, rename=True)
5996
6000
5997
6001
5998 @command(
6002 @command(
5999 b'resolve',
6003 b'resolve',
6000 [
6004 [
6001 (b'a', b'all', None, _(b'select all unresolved files')),
6005 (b'a', b'all', None, _(b'select all unresolved files')),
6002 (b'l', b'list', None, _(b'list state of files needing merge')),
6006 (b'l', b'list', None, _(b'list state of files needing merge')),
6003 (b'm', b'mark', None, _(b'mark files as resolved')),
6007 (b'm', b'mark', None, _(b'mark files as resolved')),
6004 (b'u', b'unmark', None, _(b'mark files as unresolved')),
6008 (b'u', b'unmark', None, _(b'mark files as unresolved')),
6005 (b'n', b'no-status', None, _(b'hide status prefix')),
6009 (b'n', b'no-status', None, _(b'hide status prefix')),
6006 (b'', b're-merge', None, _(b're-merge files')),
6010 (b'', b're-merge', None, _(b're-merge files')),
6007 ]
6011 ]
6008 + mergetoolopts
6012 + mergetoolopts
6009 + walkopts
6013 + walkopts
6010 + formatteropts,
6014 + formatteropts,
6011 _(b'[OPTION]... [FILE]...'),
6015 _(b'[OPTION]... [FILE]...'),
6012 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6016 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6013 inferrepo=True,
6017 inferrepo=True,
6014 )
6018 )
6015 def resolve(ui, repo, *pats, **opts):
6019 def resolve(ui, repo, *pats, **opts):
6016 """redo merges or set/view the merge status of files
6020 """redo merges or set/view the merge status of files
6017
6021
6018 Merges with unresolved conflicts are often the result of
6022 Merges with unresolved conflicts are often the result of
6019 non-interactive merging using the ``internal:merge`` configuration
6023 non-interactive merging using the ``internal:merge`` configuration
6020 setting, or a command-line merge tool like ``diff3``. The resolve
6024 setting, or a command-line merge tool like ``diff3``. The resolve
6021 command is used to manage the files involved in a merge, after
6025 command is used to manage the files involved in a merge, after
6022 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
6026 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
6023 working directory must have two parents). See :hg:`help
6027 working directory must have two parents). See :hg:`help
6024 merge-tools` for information on configuring merge tools.
6028 merge-tools` for information on configuring merge tools.
6025
6029
6026 The resolve command can be used in the following ways:
6030 The resolve command can be used in the following ways:
6027
6031
6028 - :hg:`resolve [--re-merge] [--tool TOOL] FILE...`: attempt to re-merge
6032 - :hg:`resolve [--re-merge] [--tool TOOL] FILE...`: attempt to re-merge
6029 the specified files, discarding any previous merge attempts. Re-merging
6033 the specified files, discarding any previous merge attempts. Re-merging
6030 is not performed for files already marked as resolved. Use ``--all/-a``
6034 is not performed for files already marked as resolved. Use ``--all/-a``
6031 to select all unresolved files. ``--tool`` can be used to specify
6035 to select all unresolved files. ``--tool`` can be used to specify
6032 the merge tool used for the given files. It overrides the HGMERGE
6036 the merge tool used for the given files. It overrides the HGMERGE
6033 environment variable and your configuration files. Previous file
6037 environment variable and your configuration files. Previous file
6034 contents are saved with a ``.orig`` suffix.
6038 contents are saved with a ``.orig`` suffix.
6035
6039
6036 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
6040 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
6037 (e.g. after having manually fixed-up the files). The default is
6041 (e.g. after having manually fixed-up the files). The default is
6038 to mark all unresolved files.
6042 to mark all unresolved files.
6039
6043
6040 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
6044 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
6041 default is to mark all resolved files.
6045 default is to mark all resolved files.
6042
6046
6043 - :hg:`resolve -l`: list files which had or still have conflicts.
6047 - :hg:`resolve -l`: list files which had or still have conflicts.
6044 In the printed list, ``U`` = unresolved and ``R`` = resolved.
6048 In the printed list, ``U`` = unresolved and ``R`` = resolved.
6045 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
6049 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
6046 the list. See :hg:`help filesets` for details.
6050 the list. See :hg:`help filesets` for details.
6047
6051
6048 .. note::
6052 .. note::
6049
6053
6050 Mercurial will not let you commit files with unresolved merge
6054 Mercurial will not let you commit files with unresolved merge
6051 conflicts. You must use :hg:`resolve -m ...` before you can
6055 conflicts. You must use :hg:`resolve -m ...` before you can
6052 commit after a conflicting merge.
6056 commit after a conflicting merge.
6053
6057
6054 .. container:: verbose
6058 .. container:: verbose
6055
6059
6056 Template:
6060 Template:
6057
6061
6058 The following keywords are supported in addition to the common template
6062 The following keywords are supported in addition to the common template
6059 keywords and functions. See also :hg:`help templates`.
6063 keywords and functions. See also :hg:`help templates`.
6060
6064
6061 :mergestatus: String. Character denoting merge conflicts, ``U`` or ``R``.
6065 :mergestatus: String. Character denoting merge conflicts, ``U`` or ``R``.
6062 :path: String. Repository-absolute path of the file.
6066 :path: String. Repository-absolute path of the file.
6063
6067
6064 Returns 0 on success, 1 if any files fail a resolve attempt.
6068 Returns 0 on success, 1 if any files fail a resolve attempt.
6065 """
6069 """
6066
6070
6067 opts = pycompat.byteskwargs(opts)
6071 opts = pycompat.byteskwargs(opts)
6068 confirm = ui.configbool(b'commands', b'resolve.confirm')
6072 confirm = ui.configbool(b'commands', b'resolve.confirm')
6069 flaglist = b'all mark unmark list no_status re_merge'.split()
6073 flaglist = b'all mark unmark list no_status re_merge'.split()
6070 all, mark, unmark, show, nostatus, remerge = [opts.get(o) for o in flaglist]
6074 all, mark, unmark, show, nostatus, remerge = [opts.get(o) for o in flaglist]
6071
6075
6072 actioncount = len(list(filter(None, [show, mark, unmark, remerge])))
6076 actioncount = len(list(filter(None, [show, mark, unmark, remerge])))
6073 if actioncount > 1:
6077 if actioncount > 1:
6074 raise error.InputError(_(b"too many actions specified"))
6078 raise error.InputError(_(b"too many actions specified"))
6075 elif actioncount == 0 and ui.configbool(
6079 elif actioncount == 0 and ui.configbool(
6076 b'commands', b'resolve.explicit-re-merge'
6080 b'commands', b'resolve.explicit-re-merge'
6077 ):
6081 ):
6078 hint = _(b'use --mark, --unmark, --list or --re-merge')
6082 hint = _(b'use --mark, --unmark, --list or --re-merge')
6079 raise error.InputError(_(b'no action specified'), hint=hint)
6083 raise error.InputError(_(b'no action specified'), hint=hint)
6080 if pats and all:
6084 if pats and all:
6081 raise error.InputError(_(b"can't specify --all and patterns"))
6085 raise error.InputError(_(b"can't specify --all and patterns"))
6082 if not (all or pats or show or mark or unmark):
6086 if not (all or pats or show or mark or unmark):
6083 raise error.InputError(
6087 raise error.InputError(
6084 _(b'no files or directories specified'),
6088 _(b'no files or directories specified'),
6085 hint=b'use --all to re-merge all unresolved files',
6089 hint=b'use --all to re-merge all unresolved files',
6086 )
6090 )
6087
6091
6088 if confirm:
6092 if confirm:
6089 if all:
6093 if all:
6090 if ui.promptchoice(
6094 if ui.promptchoice(
6091 _(b're-merge all unresolved files (yn)?$$ &Yes $$ &No')
6095 _(b're-merge all unresolved files (yn)?$$ &Yes $$ &No')
6092 ):
6096 ):
6093 raise error.CanceledError(_(b'user quit'))
6097 raise error.CanceledError(_(b'user quit'))
6094 if mark and not pats:
6098 if mark and not pats:
6095 if ui.promptchoice(
6099 if ui.promptchoice(
6096 _(
6100 _(
6097 b'mark all unresolved files as resolved (yn)?'
6101 b'mark all unresolved files as resolved (yn)?'
6098 b'$$ &Yes $$ &No'
6102 b'$$ &Yes $$ &No'
6099 )
6103 )
6100 ):
6104 ):
6101 raise error.CanceledError(_(b'user quit'))
6105 raise error.CanceledError(_(b'user quit'))
6102 if unmark and not pats:
6106 if unmark and not pats:
6103 if ui.promptchoice(
6107 if ui.promptchoice(
6104 _(
6108 _(
6105 b'mark all resolved files as unresolved (yn)?'
6109 b'mark all resolved files as unresolved (yn)?'
6106 b'$$ &Yes $$ &No'
6110 b'$$ &Yes $$ &No'
6107 )
6111 )
6108 ):
6112 ):
6109 raise error.CanceledError(_(b'user quit'))
6113 raise error.CanceledError(_(b'user quit'))
6110
6114
6111 uipathfn = scmutil.getuipathfn(repo)
6115 uipathfn = scmutil.getuipathfn(repo)
6112
6116
6113 if show:
6117 if show:
6114 ui.pager(b'resolve')
6118 ui.pager(b'resolve')
6115 fm = ui.formatter(b'resolve', opts)
6119 fm = ui.formatter(b'resolve', opts)
6116 ms = mergestatemod.mergestate.read(repo)
6120 ms = mergestatemod.mergestate.read(repo)
6117 wctx = repo[None]
6121 wctx = repo[None]
6118 m = scmutil.match(wctx, pats, opts)
6122 m = scmutil.match(wctx, pats, opts)
6119
6123
6120 # Labels and keys based on merge state. Unresolved path conflicts show
6124 # Labels and keys based on merge state. Unresolved path conflicts show
6121 # as 'P'. Resolved path conflicts show as 'R', the same as normal
6125 # as 'P'. Resolved path conflicts show as 'R', the same as normal
6122 # resolved conflicts.
6126 # resolved conflicts.
6123 mergestateinfo = {
6127 mergestateinfo = {
6124 mergestatemod.MERGE_RECORD_UNRESOLVED: (
6128 mergestatemod.MERGE_RECORD_UNRESOLVED: (
6125 b'resolve.unresolved',
6129 b'resolve.unresolved',
6126 b'U',
6130 b'U',
6127 ),
6131 ),
6128 mergestatemod.MERGE_RECORD_RESOLVED: (b'resolve.resolved', b'R'),
6132 mergestatemod.MERGE_RECORD_RESOLVED: (b'resolve.resolved', b'R'),
6129 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH: (
6133 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH: (
6130 b'resolve.unresolved',
6134 b'resolve.unresolved',
6131 b'P',
6135 b'P',
6132 ),
6136 ),
6133 mergestatemod.MERGE_RECORD_RESOLVED_PATH: (
6137 mergestatemod.MERGE_RECORD_RESOLVED_PATH: (
6134 b'resolve.resolved',
6138 b'resolve.resolved',
6135 b'R',
6139 b'R',
6136 ),
6140 ),
6137 }
6141 }
6138
6142
6139 for f in ms:
6143 for f in ms:
6140 if not m(f):
6144 if not m(f):
6141 continue
6145 continue
6142
6146
6143 label, key = mergestateinfo[ms[f]]
6147 label, key = mergestateinfo[ms[f]]
6144 fm.startitem()
6148 fm.startitem()
6145 fm.context(ctx=wctx)
6149 fm.context(ctx=wctx)
6146 fm.condwrite(not nostatus, b'mergestatus', b'%s ', key, label=label)
6150 fm.condwrite(not nostatus, b'mergestatus', b'%s ', key, label=label)
6147 fm.data(path=f)
6151 fm.data(path=f)
6148 fm.plain(b'%s\n' % uipathfn(f), label=label)
6152 fm.plain(b'%s\n' % uipathfn(f), label=label)
6149 fm.end()
6153 fm.end()
6150 return 0
6154 return 0
6151
6155
6152 with repo.wlock():
6156 with repo.wlock():
6153 ms = mergestatemod.mergestate.read(repo)
6157 ms = mergestatemod.mergestate.read(repo)
6154
6158
6155 if not (ms.active() or repo.dirstate.p2() != repo.nullid):
6159 if not (ms.active() or repo.dirstate.p2() != repo.nullid):
6156 raise error.StateError(
6160 raise error.StateError(
6157 _(b'resolve command not applicable when not merging')
6161 _(b'resolve command not applicable when not merging')
6158 )
6162 )
6159
6163
6160 wctx = repo[None]
6164 wctx = repo[None]
6161 m = scmutil.match(wctx, pats, opts)
6165 m = scmutil.match(wctx, pats, opts)
6162 ret = 0
6166 ret = 0
6163 didwork = False
6167 didwork = False
6164
6168
6165 hasconflictmarkers = []
6169 hasconflictmarkers = []
6166 if mark:
6170 if mark:
6167 markcheck = ui.config(b'commands', b'resolve.mark-check')
6171 markcheck = ui.config(b'commands', b'resolve.mark-check')
6168 if markcheck not in [b'warn', b'abort']:
6172 if markcheck not in [b'warn', b'abort']:
6169 # Treat all invalid / unrecognized values as 'none'.
6173 # Treat all invalid / unrecognized values as 'none'.
6170 markcheck = False
6174 markcheck = False
6171 for f in ms:
6175 for f in ms:
6172 if not m(f):
6176 if not m(f):
6173 continue
6177 continue
6174
6178
6175 didwork = True
6179 didwork = True
6176
6180
6177 # path conflicts must be resolved manually
6181 # path conflicts must be resolved manually
6178 if ms[f] in (
6182 if ms[f] in (
6179 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH,
6183 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH,
6180 mergestatemod.MERGE_RECORD_RESOLVED_PATH,
6184 mergestatemod.MERGE_RECORD_RESOLVED_PATH,
6181 ):
6185 ):
6182 if mark:
6186 if mark:
6183 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED_PATH)
6187 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED_PATH)
6184 elif unmark:
6188 elif unmark:
6185 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED_PATH)
6189 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED_PATH)
6186 elif ms[f] == mergestatemod.MERGE_RECORD_UNRESOLVED_PATH:
6190 elif ms[f] == mergestatemod.MERGE_RECORD_UNRESOLVED_PATH:
6187 ui.warn(
6191 ui.warn(
6188 _(b'%s: path conflict must be resolved manually\n')
6192 _(b'%s: path conflict must be resolved manually\n')
6189 % uipathfn(f)
6193 % uipathfn(f)
6190 )
6194 )
6191 continue
6195 continue
6192
6196
6193 if mark:
6197 if mark:
6194 if markcheck:
6198 if markcheck:
6195 fdata = repo.wvfs.tryread(f)
6199 fdata = repo.wvfs.tryread(f)
6196 if (
6200 if (
6197 filemerge.hasconflictmarkers(fdata)
6201 filemerge.hasconflictmarkers(fdata)
6198 and ms[f] != mergestatemod.MERGE_RECORD_RESOLVED
6202 and ms[f] != mergestatemod.MERGE_RECORD_RESOLVED
6199 ):
6203 ):
6200 hasconflictmarkers.append(f)
6204 hasconflictmarkers.append(f)
6201 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED)
6205 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED)
6202 elif unmark:
6206 elif unmark:
6203 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED)
6207 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED)
6204 else:
6208 else:
6205 # backup pre-resolve (merge uses .orig for its own purposes)
6209 # backup pre-resolve (merge uses .orig for its own purposes)
6206 a = repo.wjoin(f)
6210 a = repo.wjoin(f)
6207 try:
6211 try:
6208 util.copyfile(a, a + b".resolve")
6212 util.copyfile(a, a + b".resolve")
6209 except FileNotFoundError:
6213 except FileNotFoundError:
6210 pass
6214 pass
6211
6215
6212 try:
6216 try:
6213 # preresolve file
6217 # preresolve file
6214 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
6218 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
6215 with ui.configoverride(overrides, b'resolve'):
6219 with ui.configoverride(overrides, b'resolve'):
6216 r = ms.resolve(f, wctx)
6220 r = ms.resolve(f, wctx)
6217 if r:
6221 if r:
6218 ret = 1
6222 ret = 1
6219 finally:
6223 finally:
6220 ms.commit()
6224 ms.commit()
6221
6225
6222 # replace filemerge's .orig file with our resolve file
6226 # replace filemerge's .orig file with our resolve file
6223 try:
6227 try:
6224 util.rename(
6228 util.rename(
6225 a + b".resolve", scmutil.backuppath(ui, repo, f)
6229 a + b".resolve", scmutil.backuppath(ui, repo, f)
6226 )
6230 )
6227 except FileNotFoundError:
6231 except FileNotFoundError:
6228 pass
6232 pass
6229
6233
6230 if hasconflictmarkers:
6234 if hasconflictmarkers:
6231 ui.warn(
6235 ui.warn(
6232 _(
6236 _(
6233 b'warning: the following files still have conflict '
6237 b'warning: the following files still have conflict '
6234 b'markers:\n'
6238 b'markers:\n'
6235 )
6239 )
6236 + b''.join(
6240 + b''.join(
6237 b' ' + uipathfn(f) + b'\n' for f in hasconflictmarkers
6241 b' ' + uipathfn(f) + b'\n' for f in hasconflictmarkers
6238 )
6242 )
6239 )
6243 )
6240 if markcheck == b'abort' and not all and not pats:
6244 if markcheck == b'abort' and not all and not pats:
6241 raise error.StateError(
6245 raise error.StateError(
6242 _(b'conflict markers detected'),
6246 _(b'conflict markers detected'),
6243 hint=_(b'use --all to mark anyway'),
6247 hint=_(b'use --all to mark anyway'),
6244 )
6248 )
6245
6249
6246 ms.commit()
6250 ms.commit()
6247 branchmerge = repo.dirstate.p2() != repo.nullid
6251 branchmerge = repo.dirstate.p2() != repo.nullid
6248 # resolve is not doing a parent change here, however, `record updates`
6252 # resolve is not doing a parent change here, however, `record updates`
6249 # will call some dirstate API that at intended for parent changes call.
6253 # will call some dirstate API that at intended for parent changes call.
6250 # Ideally we would not need this and could implement a lighter version
6254 # Ideally we would not need this and could implement a lighter version
6251 # of the recordupdateslogic that will not have to deal with the part
6255 # of the recordupdateslogic that will not have to deal with the part
6252 # related to parent changes. However this would requires that:
6256 # related to parent changes. However this would requires that:
6253 # - we are sure we passed around enough information at update/merge
6257 # - we are sure we passed around enough information at update/merge
6254 # time to no longer needs it at `hg resolve time`
6258 # time to no longer needs it at `hg resolve time`
6255 # - we are sure we store that information well enough to be able to reuse it
6259 # - we are sure we store that information well enough to be able to reuse it
6256 # - we are the necessary logic to reuse it right.
6260 # - we are the necessary logic to reuse it right.
6257 #
6261 #
6258 # All this should eventually happens, but in the mean time, we use this
6262 # All this should eventually happens, but in the mean time, we use this
6259 # context manager slightly out of the context it should be.
6263 # context manager slightly out of the context it should be.
6260 with repo.dirstate.parentchange():
6264 with repo.dirstate.parentchange():
6261 mergestatemod.recordupdates(repo, ms.actions(), branchmerge, None)
6265 mergestatemod.recordupdates(repo, ms.actions(), branchmerge, None)
6262
6266
6263 if not didwork and pats:
6267 if not didwork and pats:
6264 hint = None
6268 hint = None
6265 if not any([p for p in pats if p.find(b':') >= 0]):
6269 if not any([p for p in pats if p.find(b':') >= 0]):
6266 pats = [b'path:%s' % p for p in pats]
6270 pats = [b'path:%s' % p for p in pats]
6267 m = scmutil.match(wctx, pats, opts)
6271 m = scmutil.match(wctx, pats, opts)
6268 for f in ms:
6272 for f in ms:
6269 if not m(f):
6273 if not m(f):
6270 continue
6274 continue
6271
6275
6272 def flag(o):
6276 def flag(o):
6273 if o == b're_merge':
6277 if o == b're_merge':
6274 return b'--re-merge '
6278 return b'--re-merge '
6275 return b'-%s ' % o[0:1]
6279 return b'-%s ' % o[0:1]
6276
6280
6277 flags = b''.join([flag(o) for o in flaglist if opts.get(o)])
6281 flags = b''.join([flag(o) for o in flaglist if opts.get(o)])
6278 hint = _(b"(try: hg resolve %s%s)\n") % (
6282 hint = _(b"(try: hg resolve %s%s)\n") % (
6279 flags,
6283 flags,
6280 b' '.join(pats),
6284 b' '.join(pats),
6281 )
6285 )
6282 break
6286 break
6283 ui.warn(_(b"arguments do not match paths that need resolving\n"))
6287 ui.warn(_(b"arguments do not match paths that need resolving\n"))
6284 if hint:
6288 if hint:
6285 ui.warn(hint)
6289 ui.warn(hint)
6286
6290
6287 unresolvedf = ms.unresolvedcount()
6291 unresolvedf = ms.unresolvedcount()
6288 if not unresolvedf:
6292 if not unresolvedf:
6289 ui.status(_(b'(no more unresolved files)\n'))
6293 ui.status(_(b'(no more unresolved files)\n'))
6290 cmdutil.checkafterresolved(repo)
6294 cmdutil.checkafterresolved(repo)
6291
6295
6292 return ret
6296 return ret
6293
6297
6294
6298
6295 @command(
6299 @command(
6296 b'revert',
6300 b'revert',
6297 [
6301 [
6298 (b'a', b'all', None, _(b'revert all changes when no arguments given')),
6302 (b'a', b'all', None, _(b'revert all changes when no arguments given')),
6299 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
6303 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
6300 (b'r', b'rev', b'', _(b'revert to the specified revision'), _(b'REV')),
6304 (b'r', b'rev', b'', _(b'revert to the specified revision'), _(b'REV')),
6301 (b'C', b'no-backup', None, _(b'do not save backup copies of files')),
6305 (b'C', b'no-backup', None, _(b'do not save backup copies of files')),
6302 (b'i', b'interactive', None, _(b'interactively select the changes')),
6306 (b'i', b'interactive', None, _(b'interactively select the changes')),
6303 ]
6307 ]
6304 + walkopts
6308 + walkopts
6305 + dryrunopts,
6309 + dryrunopts,
6306 _(b'[OPTION]... [-r REV] [NAME]...'),
6310 _(b'[OPTION]... [-r REV] [NAME]...'),
6307 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6311 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6308 )
6312 )
6309 def revert(ui, repo, *pats, **opts):
6313 def revert(ui, repo, *pats, **opts):
6310 """restore files to their checkout state
6314 """restore files to their checkout state
6311
6315
6312 .. note::
6316 .. note::
6313
6317
6314 To check out earlier revisions, you should use :hg:`update REV`.
6318 To check out earlier revisions, you should use :hg:`update REV`.
6315 To cancel an uncommitted merge (and lose your changes),
6319 To cancel an uncommitted merge (and lose your changes),
6316 use :hg:`merge --abort`.
6320 use :hg:`merge --abort`.
6317
6321
6318 With no revision specified, revert the specified files or directories
6322 With no revision specified, revert the specified files or directories
6319 to the contents they had in the parent of the working directory.
6323 to the contents they had in the parent of the working directory.
6320 This restores the contents of files to an unmodified
6324 This restores the contents of files to an unmodified
6321 state and unschedules adds, removes, copies, and renames. If the
6325 state and unschedules adds, removes, copies, and renames. If the
6322 working directory has two parents, you must explicitly specify a
6326 working directory has two parents, you must explicitly specify a
6323 revision.
6327 revision.
6324
6328
6325 Using the -r/--rev or -d/--date options, revert the given files or
6329 Using the -r/--rev or -d/--date options, revert the given files or
6326 directories to their states as of a specific revision. Because
6330 directories to their states as of a specific revision. Because
6327 revert does not change the working directory parents, this will
6331 revert does not change the working directory parents, this will
6328 cause these files to appear modified. This can be helpful to "back
6332 cause these files to appear modified. This can be helpful to "back
6329 out" some or all of an earlier change. See :hg:`backout` for a
6333 out" some or all of an earlier change. See :hg:`backout` for a
6330 related method.
6334 related method.
6331
6335
6332 Modified files are saved with a .orig suffix before reverting.
6336 Modified files are saved with a .orig suffix before reverting.
6333 To disable these backups, use --no-backup. It is possible to store
6337 To disable these backups, use --no-backup. It is possible to store
6334 the backup files in a custom directory relative to the root of the
6338 the backup files in a custom directory relative to the root of the
6335 repository by setting the ``ui.origbackuppath`` configuration
6339 repository by setting the ``ui.origbackuppath`` configuration
6336 option.
6340 option.
6337
6341
6338 See :hg:`help dates` for a list of formats valid for -d/--date.
6342 See :hg:`help dates` for a list of formats valid for -d/--date.
6339
6343
6340 See :hg:`help backout` for a way to reverse the effect of an
6344 See :hg:`help backout` for a way to reverse the effect of an
6341 earlier changeset.
6345 earlier changeset.
6342
6346
6343 Returns 0 on success.
6347 Returns 0 on success.
6344 """
6348 """
6345
6349
6346 opts = pycompat.byteskwargs(opts)
6350 opts = pycompat.byteskwargs(opts)
6347 if opts.get(b"date"):
6351 if opts.get(b"date"):
6348 cmdutil.check_incompatible_arguments(opts, b'date', [b'rev'])
6352 cmdutil.check_incompatible_arguments(opts, b'date', [b'rev'])
6349 opts[b"rev"] = cmdutil.finddate(ui, repo, opts[b"date"])
6353 opts[b"rev"] = cmdutil.finddate(ui, repo, opts[b"date"])
6350
6354
6351 parent, p2 = repo.dirstate.parents()
6355 parent, p2 = repo.dirstate.parents()
6352 if not opts.get(b'rev') and p2 != repo.nullid:
6356 if not opts.get(b'rev') and p2 != repo.nullid:
6353 # revert after merge is a trap for new users (issue2915)
6357 # revert after merge is a trap for new users (issue2915)
6354 raise error.InputError(
6358 raise error.InputError(
6355 _(b'uncommitted merge with no revision specified'),
6359 _(b'uncommitted merge with no revision specified'),
6356 hint=_(b"use 'hg update' or see 'hg help revert'"),
6360 hint=_(b"use 'hg update' or see 'hg help revert'"),
6357 )
6361 )
6358
6362
6359 rev = opts.get(b'rev')
6363 rev = opts.get(b'rev')
6360 if rev:
6364 if rev:
6361 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
6365 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
6362 ctx = logcmdutil.revsingle(repo, rev)
6366 ctx = logcmdutil.revsingle(repo, rev)
6363
6367
6364 if not (
6368 if not (
6365 pats
6369 pats
6366 or opts.get(b'include')
6370 or opts.get(b'include')
6367 or opts.get(b'exclude')
6371 or opts.get(b'exclude')
6368 or opts.get(b'all')
6372 or opts.get(b'all')
6369 or opts.get(b'interactive')
6373 or opts.get(b'interactive')
6370 ):
6374 ):
6371 msg = _(b"no files or directories specified")
6375 msg = _(b"no files or directories specified")
6372 if p2 != repo.nullid:
6376 if p2 != repo.nullid:
6373 hint = _(
6377 hint = _(
6374 b"uncommitted merge, use --all to discard all changes,"
6378 b"uncommitted merge, use --all to discard all changes,"
6375 b" or 'hg update -C .' to abort the merge"
6379 b" or 'hg update -C .' to abort the merge"
6376 )
6380 )
6377 raise error.InputError(msg, hint=hint)
6381 raise error.InputError(msg, hint=hint)
6378 dirty = any(repo.status())
6382 dirty = any(repo.status())
6379 node = ctx.node()
6383 node = ctx.node()
6380 if node != parent:
6384 if node != parent:
6381 if dirty:
6385 if dirty:
6382 hint = (
6386 hint = (
6383 _(
6387 _(
6384 b"uncommitted changes, use --all to discard all"
6388 b"uncommitted changes, use --all to discard all"
6385 b" changes, or 'hg update %d' to update"
6389 b" changes, or 'hg update %d' to update"
6386 )
6390 )
6387 % ctx.rev()
6391 % ctx.rev()
6388 )
6392 )
6389 else:
6393 else:
6390 hint = (
6394 hint = (
6391 _(
6395 _(
6392 b"use --all to revert all files,"
6396 b"use --all to revert all files,"
6393 b" or 'hg update %d' to update"
6397 b" or 'hg update %d' to update"
6394 )
6398 )
6395 % ctx.rev()
6399 % ctx.rev()
6396 )
6400 )
6397 elif dirty:
6401 elif dirty:
6398 hint = _(b"uncommitted changes, use --all to discard all changes")
6402 hint = _(b"uncommitted changes, use --all to discard all changes")
6399 else:
6403 else:
6400 hint = _(b"use --all to revert all files")
6404 hint = _(b"use --all to revert all files")
6401 raise error.InputError(msg, hint=hint)
6405 raise error.InputError(msg, hint=hint)
6402
6406
6403 return cmdutil.revert(ui, repo, ctx, *pats, **pycompat.strkwargs(opts))
6407 return cmdutil.revert(ui, repo, ctx, *pats, **pycompat.strkwargs(opts))
6404
6408
6405
6409
6406 @command(
6410 @command(
6407 b'rollback',
6411 b'rollback',
6408 dryrunopts + [(b'f', b'force', False, _(b'ignore safety measures'))],
6412 dryrunopts + [(b'f', b'force', False, _(b'ignore safety measures'))],
6409 helpcategory=command.CATEGORY_MAINTENANCE,
6413 helpcategory=command.CATEGORY_MAINTENANCE,
6410 )
6414 )
6411 def rollback(ui, repo, **opts):
6415 def rollback(ui, repo, **opts):
6412 """roll back the last transaction (DANGEROUS) (DEPRECATED)
6416 """roll back the last transaction (DANGEROUS) (DEPRECATED)
6413
6417
6414 Please use :hg:`commit --amend` instead of rollback to correct
6418 Please use :hg:`commit --amend` instead of rollback to correct
6415 mistakes in the last commit.
6419 mistakes in the last commit.
6416
6420
6417 This command should be used with care. There is only one level of
6421 This command should be used with care. There is only one level of
6418 rollback, and there is no way to undo a rollback. It will also
6422 rollback, and there is no way to undo a rollback. It will also
6419 restore the dirstate at the time of the last transaction, losing
6423 restore the dirstate at the time of the last transaction, losing
6420 any dirstate changes since that time. This command does not alter
6424 any dirstate changes since that time. This command does not alter
6421 the working directory.
6425 the working directory.
6422
6426
6423 Transactions are used to encapsulate the effects of all commands
6427 Transactions are used to encapsulate the effects of all commands
6424 that create new changesets or propagate existing changesets into a
6428 that create new changesets or propagate existing changesets into a
6425 repository.
6429 repository.
6426
6430
6427 .. container:: verbose
6431 .. container:: verbose
6428
6432
6429 For example, the following commands are transactional, and their
6433 For example, the following commands are transactional, and their
6430 effects can be rolled back:
6434 effects can be rolled back:
6431
6435
6432 - commit
6436 - commit
6433 - import
6437 - import
6434 - pull
6438 - pull
6435 - push (with this repository as the destination)
6439 - push (with this repository as the destination)
6436 - unbundle
6440 - unbundle
6437
6441
6438 To avoid permanent data loss, rollback will refuse to rollback a
6442 To avoid permanent data loss, rollback will refuse to rollback a
6439 commit transaction if it isn't checked out. Use --force to
6443 commit transaction if it isn't checked out. Use --force to
6440 override this protection.
6444 override this protection.
6441
6445
6442 The rollback command can be entirely disabled by setting the
6446 The rollback command can be entirely disabled by setting the
6443 ``ui.rollback`` configuration setting to false. If you're here
6447 ``ui.rollback`` configuration setting to false. If you're here
6444 because you want to use rollback and it's disabled, you can
6448 because you want to use rollback and it's disabled, you can
6445 re-enable the command by setting ``ui.rollback`` to true.
6449 re-enable the command by setting ``ui.rollback`` to true.
6446
6450
6447 This command is not intended for use on public repositories. Once
6451 This command is not intended for use on public repositories. Once
6448 changes are visible for pull by other users, rolling a transaction
6452 changes are visible for pull by other users, rolling a transaction
6449 back locally is ineffective (someone else may already have pulled
6453 back locally is ineffective (someone else may already have pulled
6450 the changes). Furthermore, a race is possible with readers of the
6454 the changes). Furthermore, a race is possible with readers of the
6451 repository; for example an in-progress pull from the repository
6455 repository; for example an in-progress pull from the repository
6452 may fail if a rollback is performed.
6456 may fail if a rollback is performed.
6453
6457
6454 Returns 0 on success, 1 if no rollback data is available.
6458 Returns 0 on success, 1 if no rollback data is available.
6455 """
6459 """
6456 if not ui.configbool(b'ui', b'rollback'):
6460 if not ui.configbool(b'ui', b'rollback'):
6457 raise error.Abort(
6461 raise error.Abort(
6458 _(b'rollback is disabled because it is unsafe'),
6462 _(b'rollback is disabled because it is unsafe'),
6459 hint=b'see `hg help -v rollback` for information',
6463 hint=b'see `hg help -v rollback` for information',
6460 )
6464 )
6461 return repo.rollback(dryrun=opts.get('dry_run'), force=opts.get('force'))
6465 return repo.rollback(dryrun=opts.get('dry_run'), force=opts.get('force'))
6462
6466
6463
6467
6464 @command(
6468 @command(
6465 b'root',
6469 b'root',
6466 [] + formatteropts,
6470 [] + formatteropts,
6467 intents={INTENT_READONLY},
6471 intents={INTENT_READONLY},
6468 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6472 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6469 )
6473 )
6470 def root(ui, repo, **opts):
6474 def root(ui, repo, **opts):
6471 """print the root (top) of the current working directory
6475 """print the root (top) of the current working directory
6472
6476
6473 Print the root directory of the current repository.
6477 Print the root directory of the current repository.
6474
6478
6475 .. container:: verbose
6479 .. container:: verbose
6476
6480
6477 Template:
6481 Template:
6478
6482
6479 The following keywords are supported in addition to the common template
6483 The following keywords are supported in addition to the common template
6480 keywords and functions. See also :hg:`help templates`.
6484 keywords and functions. See also :hg:`help templates`.
6481
6485
6482 :hgpath: String. Path to the .hg directory.
6486 :hgpath: String. Path to the .hg directory.
6483 :storepath: String. Path to the directory holding versioned data.
6487 :storepath: String. Path to the directory holding versioned data.
6484
6488
6485 Returns 0 on success.
6489 Returns 0 on success.
6486 """
6490 """
6487 opts = pycompat.byteskwargs(opts)
6491 opts = pycompat.byteskwargs(opts)
6488 with ui.formatter(b'root', opts) as fm:
6492 with ui.formatter(b'root', opts) as fm:
6489 fm.startitem()
6493 fm.startitem()
6490 fm.write(b'reporoot', b'%s\n', repo.root)
6494 fm.write(b'reporoot', b'%s\n', repo.root)
6491 fm.data(hgpath=repo.path, storepath=repo.spath)
6495 fm.data(hgpath=repo.path, storepath=repo.spath)
6492
6496
6493
6497
6494 @command(
6498 @command(
6495 b'serve',
6499 b'serve',
6496 [
6500 [
6497 (
6501 (
6498 b'A',
6502 b'A',
6499 b'accesslog',
6503 b'accesslog',
6500 b'',
6504 b'',
6501 _(b'name of access log file to write to'),
6505 _(b'name of access log file to write to'),
6502 _(b'FILE'),
6506 _(b'FILE'),
6503 ),
6507 ),
6504 (b'd', b'daemon', None, _(b'run server in background')),
6508 (b'd', b'daemon', None, _(b'run server in background')),
6505 (b'', b'daemon-postexec', [], _(b'used internally by daemon mode')),
6509 (b'', b'daemon-postexec', [], _(b'used internally by daemon mode')),
6506 (
6510 (
6507 b'E',
6511 b'E',
6508 b'errorlog',
6512 b'errorlog',
6509 b'',
6513 b'',
6510 _(b'name of error log file to write to'),
6514 _(b'name of error log file to write to'),
6511 _(b'FILE'),
6515 _(b'FILE'),
6512 ),
6516 ),
6513 # use string type, then we can check if something was passed
6517 # use string type, then we can check if something was passed
6514 (
6518 (
6515 b'p',
6519 b'p',
6516 b'port',
6520 b'port',
6517 b'',
6521 b'',
6518 _(b'port to listen on (default: 8000)'),
6522 _(b'port to listen on (default: 8000)'),
6519 _(b'PORT'),
6523 _(b'PORT'),
6520 ),
6524 ),
6521 (
6525 (
6522 b'a',
6526 b'a',
6523 b'address',
6527 b'address',
6524 b'',
6528 b'',
6525 _(b'address to listen on (default: all interfaces)'),
6529 _(b'address to listen on (default: all interfaces)'),
6526 _(b'ADDR'),
6530 _(b'ADDR'),
6527 ),
6531 ),
6528 (
6532 (
6529 b'',
6533 b'',
6530 b'prefix',
6534 b'prefix',
6531 b'',
6535 b'',
6532 _(b'prefix path to serve from (default: server root)'),
6536 _(b'prefix path to serve from (default: server root)'),
6533 _(b'PREFIX'),
6537 _(b'PREFIX'),
6534 ),
6538 ),
6535 (
6539 (
6536 b'n',
6540 b'n',
6537 b'name',
6541 b'name',
6538 b'',
6542 b'',
6539 _(b'name to show in web pages (default: working directory)'),
6543 _(b'name to show in web pages (default: working directory)'),
6540 _(b'NAME'),
6544 _(b'NAME'),
6541 ),
6545 ),
6542 (
6546 (
6543 b'',
6547 b'',
6544 b'web-conf',
6548 b'web-conf',
6545 b'',
6549 b'',
6546 _(b"name of the hgweb config file (see 'hg help hgweb')"),
6550 _(b"name of the hgweb config file (see 'hg help hgweb')"),
6547 _(b'FILE'),
6551 _(b'FILE'),
6548 ),
6552 ),
6549 (
6553 (
6550 b'',
6554 b'',
6551 b'webdir-conf',
6555 b'webdir-conf',
6552 b'',
6556 b'',
6553 _(b'name of the hgweb config file (DEPRECATED)'),
6557 _(b'name of the hgweb config file (DEPRECATED)'),
6554 _(b'FILE'),
6558 _(b'FILE'),
6555 ),
6559 ),
6556 (
6560 (
6557 b'',
6561 b'',
6558 b'pid-file',
6562 b'pid-file',
6559 b'',
6563 b'',
6560 _(b'name of file to write process ID to'),
6564 _(b'name of file to write process ID to'),
6561 _(b'FILE'),
6565 _(b'FILE'),
6562 ),
6566 ),
6563 (b'', b'stdio', None, _(b'for remote clients (ADVANCED)')),
6567 (b'', b'stdio', None, _(b'for remote clients (ADVANCED)')),
6564 (
6568 (
6565 b'',
6569 b'',
6566 b'cmdserver',
6570 b'cmdserver',
6567 b'',
6571 b'',
6568 _(b'for remote clients (ADVANCED)'),
6572 _(b'for remote clients (ADVANCED)'),
6569 _(b'MODE'),
6573 _(b'MODE'),
6570 ),
6574 ),
6571 (b't', b'templates', b'', _(b'web templates to use'), _(b'TEMPLATE')),
6575 (b't', b'templates', b'', _(b'web templates to use'), _(b'TEMPLATE')),
6572 (b'', b'style', b'', _(b'template style to use'), _(b'STYLE')),
6576 (b'', b'style', b'', _(b'template style to use'), _(b'STYLE')),
6573 (b'6', b'ipv6', None, _(b'use IPv6 in addition to IPv4')),
6577 (b'6', b'ipv6', None, _(b'use IPv6 in addition to IPv4')),
6574 (b'', b'certificate', b'', _(b'SSL certificate file'), _(b'FILE')),
6578 (b'', b'certificate', b'', _(b'SSL certificate file'), _(b'FILE')),
6575 (b'', b'print-url', None, _(b'start and print only the URL')),
6579 (b'', b'print-url', None, _(b'start and print only the URL')),
6576 ]
6580 ]
6577 + subrepoopts,
6581 + subrepoopts,
6578 _(b'[OPTION]...'),
6582 _(b'[OPTION]...'),
6579 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
6583 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
6580 helpbasic=True,
6584 helpbasic=True,
6581 optionalrepo=True,
6585 optionalrepo=True,
6582 )
6586 )
6583 def serve(ui, repo, **opts):
6587 def serve(ui, repo, **opts):
6584 """start stand-alone webserver
6588 """start stand-alone webserver
6585
6589
6586 Start a local HTTP repository browser and pull server. You can use
6590 Start a local HTTP repository browser and pull server. You can use
6587 this for ad-hoc sharing and browsing of repositories. It is
6591 this for ad-hoc sharing and browsing of repositories. It is
6588 recommended to use a real web server to serve a repository for
6592 recommended to use a real web server to serve a repository for
6589 longer periods of time.
6593 longer periods of time.
6590
6594
6591 Please note that the server does not implement access control.
6595 Please note that the server does not implement access control.
6592 This means that, by default, anybody can read from the server and
6596 This means that, by default, anybody can read from the server and
6593 nobody can write to it by default. Set the ``web.allow-push``
6597 nobody can write to it by default. Set the ``web.allow-push``
6594 option to ``*`` to allow everybody to push to the server. You
6598 option to ``*`` to allow everybody to push to the server. You
6595 should use a real web server if you need to authenticate users.
6599 should use a real web server if you need to authenticate users.
6596
6600
6597 By default, the server logs accesses to stdout and errors to
6601 By default, the server logs accesses to stdout and errors to
6598 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
6602 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
6599 files.
6603 files.
6600
6604
6601 To have the server choose a free port number to listen on, specify
6605 To have the server choose a free port number to listen on, specify
6602 a port number of 0; in this case, the server will print the port
6606 a port number of 0; in this case, the server will print the port
6603 number it uses.
6607 number it uses.
6604
6608
6605 Returns 0 on success.
6609 Returns 0 on success.
6606 """
6610 """
6607
6611
6608 cmdutil.check_incompatible_arguments(opts, 'stdio', ['cmdserver'])
6612 cmdutil.check_incompatible_arguments(opts, 'stdio', ['cmdserver'])
6609 opts = pycompat.byteskwargs(opts)
6613 opts = pycompat.byteskwargs(opts)
6610 if opts[b"print_url"] and ui.verbose:
6614 if opts[b"print_url"] and ui.verbose:
6611 raise error.InputError(_(b"cannot use --print-url with --verbose"))
6615 raise error.InputError(_(b"cannot use --print-url with --verbose"))
6612
6616
6613 if opts[b"stdio"]:
6617 if opts[b"stdio"]:
6614 if repo is None:
6618 if repo is None:
6615 raise error.RepoError(
6619 raise error.RepoError(
6616 _(b"there is no Mercurial repository here (.hg not found)")
6620 _(b"there is no Mercurial repository here (.hg not found)")
6617 )
6621 )
6618 s = wireprotoserver.sshserver(ui, repo)
6622 s = wireprotoserver.sshserver(ui, repo)
6619 s.serve_forever()
6623 s.serve_forever()
6620 return
6624 return
6621
6625
6622 service = server.createservice(ui, repo, opts)
6626 service = server.createservice(ui, repo, opts)
6623 return server.runservice(opts, initfn=service.init, runfn=service.run)
6627 return server.runservice(opts, initfn=service.init, runfn=service.run)
6624
6628
6625
6629
6626 @command(
6630 @command(
6627 b'shelve',
6631 b'shelve',
6628 [
6632 [
6629 (
6633 (
6630 b'A',
6634 b'A',
6631 b'addremove',
6635 b'addremove',
6632 None,
6636 None,
6633 _(b'mark new/missing files as added/removed before shelving'),
6637 _(b'mark new/missing files as added/removed before shelving'),
6634 ),
6638 ),
6635 (b'u', b'unknown', None, _(b'store unknown files in the shelve')),
6639 (b'u', b'unknown', None, _(b'store unknown files in the shelve')),
6636 (b'', b'cleanup', None, _(b'delete all shelved changes')),
6640 (b'', b'cleanup', None, _(b'delete all shelved changes')),
6637 (
6641 (
6638 b'',
6642 b'',
6639 b'date',
6643 b'date',
6640 b'',
6644 b'',
6641 _(b'shelve with the specified commit date'),
6645 _(b'shelve with the specified commit date'),
6642 _(b'DATE'),
6646 _(b'DATE'),
6643 ),
6647 ),
6644 (b'd', b'delete', None, _(b'delete the named shelved change(s)')),
6648 (b'd', b'delete', None, _(b'delete the named shelved change(s)')),
6645 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
6649 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
6646 (
6650 (
6647 b'k',
6651 b'k',
6648 b'keep',
6652 b'keep',
6649 False,
6653 False,
6650 _(b'shelve, but keep changes in the working directory'),
6654 _(b'shelve, but keep changes in the working directory'),
6651 ),
6655 ),
6652 (b'l', b'list', None, _(b'list current shelves')),
6656 (b'l', b'list', None, _(b'list current shelves')),
6653 (b'm', b'message', b'', _(b'use text as shelve message'), _(b'TEXT')),
6657 (b'm', b'message', b'', _(b'use text as shelve message'), _(b'TEXT')),
6654 (
6658 (
6655 b'n',
6659 b'n',
6656 b'name',
6660 b'name',
6657 b'',
6661 b'',
6658 _(b'use the given name for the shelved commit'),
6662 _(b'use the given name for the shelved commit'),
6659 _(b'NAME'),
6663 _(b'NAME'),
6660 ),
6664 ),
6661 (
6665 (
6662 b'p',
6666 b'p',
6663 b'patch',
6667 b'patch',
6664 None,
6668 None,
6665 _(
6669 _(
6666 b'output patches for changes (provide the names of the shelved '
6670 b'output patches for changes (provide the names of the shelved '
6667 b'changes as positional arguments)'
6671 b'changes as positional arguments)'
6668 ),
6672 ),
6669 ),
6673 ),
6670 (b'i', b'interactive', None, _(b'interactive mode')),
6674 (b'i', b'interactive', None, _(b'interactive mode')),
6671 (
6675 (
6672 b'',
6676 b'',
6673 b'stat',
6677 b'stat',
6674 None,
6678 None,
6675 _(
6679 _(
6676 b'output diffstat-style summary of changes (provide the names of '
6680 b'output diffstat-style summary of changes (provide the names of '
6677 b'the shelved changes as positional arguments)'
6681 b'the shelved changes as positional arguments)'
6678 ),
6682 ),
6679 ),
6683 ),
6680 ]
6684 ]
6681 + cmdutil.walkopts,
6685 + cmdutil.walkopts,
6682 _(b'hg shelve [OPTION]... [FILE]...'),
6686 _(b'hg shelve [OPTION]... [FILE]...'),
6683 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6687 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6684 )
6688 )
6685 def shelve(ui, repo, *pats, **opts):
6689 def shelve(ui, repo, *pats, **opts):
6686 """save and set aside changes from the working directory
6690 """save and set aside changes from the working directory
6687
6691
6688 Shelving takes files that "hg status" reports as not clean, saves
6692 Shelving takes files that "hg status" reports as not clean, saves
6689 the modifications to a bundle (a shelved change), and reverts the
6693 the modifications to a bundle (a shelved change), and reverts the
6690 files so that their state in the working directory becomes clean.
6694 files so that their state in the working directory becomes clean.
6691
6695
6692 To restore these changes to the working directory, using "hg
6696 To restore these changes to the working directory, using "hg
6693 unshelve"; this will work even if you switch to a different
6697 unshelve"; this will work even if you switch to a different
6694 commit.
6698 commit.
6695
6699
6696 When no files are specified, "hg shelve" saves all not-clean
6700 When no files are specified, "hg shelve" saves all not-clean
6697 files. If specific files or directories are named, only changes to
6701 files. If specific files or directories are named, only changes to
6698 those files are shelved.
6702 those files are shelved.
6699
6703
6700 In bare shelve (when no files are specified, without interactive,
6704 In bare shelve (when no files are specified, without interactive,
6701 include and exclude option), shelving remembers information if the
6705 include and exclude option), shelving remembers information if the
6702 working directory was on newly created branch, in other words working
6706 working directory was on newly created branch, in other words working
6703 directory was on different branch than its first parent. In this
6707 directory was on different branch than its first parent. In this
6704 situation unshelving restores branch information to the working directory.
6708 situation unshelving restores branch information to the working directory.
6705
6709
6706 Each shelved change has a name that makes it easier to find later.
6710 Each shelved change has a name that makes it easier to find later.
6707 The name of a shelved change defaults to being based on the active
6711 The name of a shelved change defaults to being based on the active
6708 bookmark, or if there is no active bookmark, the current named
6712 bookmark, or if there is no active bookmark, the current named
6709 branch. To specify a different name, use ``--name``.
6713 branch. To specify a different name, use ``--name``.
6710
6714
6711 To see a list of existing shelved changes, use the ``--list``
6715 To see a list of existing shelved changes, use the ``--list``
6712 option. For each shelved change, this will print its name, age,
6716 option. For each shelved change, this will print its name, age,
6713 and description; use ``--patch`` or ``--stat`` for more details.
6717 and description; use ``--patch`` or ``--stat`` for more details.
6714
6718
6715 To delete specific shelved changes, use ``--delete``. To delete
6719 To delete specific shelved changes, use ``--delete``. To delete
6716 all shelved changes, use ``--cleanup``.
6720 all shelved changes, use ``--cleanup``.
6717 """
6721 """
6718 opts = pycompat.byteskwargs(opts)
6722 opts = pycompat.byteskwargs(opts)
6719 allowables = [
6723 allowables = [
6720 (b'addremove', {b'create'}), # 'create' is pseudo action
6724 (b'addremove', {b'create'}), # 'create' is pseudo action
6721 (b'unknown', {b'create'}),
6725 (b'unknown', {b'create'}),
6722 (b'cleanup', {b'cleanup'}),
6726 (b'cleanup', {b'cleanup'}),
6723 # ('date', {'create'}), # ignored for passing '--date "0 0"' in tests
6727 # ('date', {'create'}), # ignored for passing '--date "0 0"' in tests
6724 (b'delete', {b'delete'}),
6728 (b'delete', {b'delete'}),
6725 (b'edit', {b'create'}),
6729 (b'edit', {b'create'}),
6726 (b'keep', {b'create'}),
6730 (b'keep', {b'create'}),
6727 (b'list', {b'list'}),
6731 (b'list', {b'list'}),
6728 (b'message', {b'create'}),
6732 (b'message', {b'create'}),
6729 (b'name', {b'create'}),
6733 (b'name', {b'create'}),
6730 (b'patch', {b'patch', b'list'}),
6734 (b'patch', {b'patch', b'list'}),
6731 (b'stat', {b'stat', b'list'}),
6735 (b'stat', {b'stat', b'list'}),
6732 ]
6736 ]
6733
6737
6734 def checkopt(opt):
6738 def checkopt(opt):
6735 if opts.get(opt):
6739 if opts.get(opt):
6736 for i, allowable in allowables:
6740 for i, allowable in allowables:
6737 if opts[i] and opt not in allowable:
6741 if opts[i] and opt not in allowable:
6738 raise error.InputError(
6742 raise error.InputError(
6739 _(
6743 _(
6740 b"options '--%s' and '--%s' may not be "
6744 b"options '--%s' and '--%s' may not be "
6741 b"used together"
6745 b"used together"
6742 )
6746 )
6743 % (opt, i)
6747 % (opt, i)
6744 )
6748 )
6745 return True
6749 return True
6746
6750
6747 if checkopt(b'cleanup'):
6751 if checkopt(b'cleanup'):
6748 if pats:
6752 if pats:
6749 raise error.InputError(
6753 raise error.InputError(
6750 _(b"cannot specify names when using '--cleanup'")
6754 _(b"cannot specify names when using '--cleanup'")
6751 )
6755 )
6752 return shelvemod.cleanupcmd(ui, repo)
6756 return shelvemod.cleanupcmd(ui, repo)
6753 elif checkopt(b'delete'):
6757 elif checkopt(b'delete'):
6754 return shelvemod.deletecmd(ui, repo, pats)
6758 return shelvemod.deletecmd(ui, repo, pats)
6755 elif checkopt(b'list'):
6759 elif checkopt(b'list'):
6756 return shelvemod.listcmd(ui, repo, pats, opts)
6760 return shelvemod.listcmd(ui, repo, pats, opts)
6757 elif checkopt(b'patch') or checkopt(b'stat'):
6761 elif checkopt(b'patch') or checkopt(b'stat'):
6758 return shelvemod.patchcmds(ui, repo, pats, opts)
6762 return shelvemod.patchcmds(ui, repo, pats, opts)
6759 else:
6763 else:
6760 return shelvemod.createcmd(ui, repo, pats, opts)
6764 return shelvemod.createcmd(ui, repo, pats, opts)
6761
6765
6762
6766
6763 _NOTTERSE = b'nothing'
6767 _NOTTERSE = b'nothing'
6764
6768
6765
6769
6766 @command(
6770 @command(
6767 b'status|st',
6771 b'status|st',
6768 [
6772 [
6769 (b'A', b'all', None, _(b'show status of all files')),
6773 (b'A', b'all', None, _(b'show status of all files')),
6770 (b'm', b'modified', None, _(b'show only modified files')),
6774 (b'm', b'modified', None, _(b'show only modified files')),
6771 (b'a', b'added', None, _(b'show only added files')),
6775 (b'a', b'added', None, _(b'show only added files')),
6772 (b'r', b'removed', None, _(b'show only removed files')),
6776 (b'r', b'removed', None, _(b'show only removed files')),
6773 (b'd', b'deleted', None, _(b'show only missing files')),
6777 (b'd', b'deleted', None, _(b'show only missing files')),
6774 (b'c', b'clean', None, _(b'show only files without changes')),
6778 (b'c', b'clean', None, _(b'show only files without changes')),
6775 (b'u', b'unknown', None, _(b'show only unknown (not tracked) files')),
6779 (b'u', b'unknown', None, _(b'show only unknown (not tracked) files')),
6776 (b'i', b'ignored', None, _(b'show only ignored files')),
6780 (b'i', b'ignored', None, _(b'show only ignored files')),
6777 (b'n', b'no-status', None, _(b'hide status prefix')),
6781 (b'n', b'no-status', None, _(b'hide status prefix')),
6778 (b't', b'terse', _NOTTERSE, _(b'show the terse output (EXPERIMENTAL)')),
6782 (b't', b'terse', _NOTTERSE, _(b'show the terse output (EXPERIMENTAL)')),
6779 (
6783 (
6780 b'C',
6784 b'C',
6781 b'copies',
6785 b'copies',
6782 None,
6786 None,
6783 _(b'show source of copied files (DEFAULT: ui.statuscopies)'),
6787 _(b'show source of copied files (DEFAULT: ui.statuscopies)'),
6784 ),
6788 ),
6785 (
6789 (
6786 b'0',
6790 b'0',
6787 b'print0',
6791 b'print0',
6788 None,
6792 None,
6789 _(b'end filenames with NUL, for use with xargs'),
6793 _(b'end filenames with NUL, for use with xargs'),
6790 ),
6794 ),
6791 (b'', b'rev', [], _(b'show difference from revision'), _(b'REV')),
6795 (b'', b'rev', [], _(b'show difference from revision'), _(b'REV')),
6792 (
6796 (
6793 b'',
6797 b'',
6794 b'change',
6798 b'change',
6795 b'',
6799 b'',
6796 _(b'list the changed files of a revision'),
6800 _(b'list the changed files of a revision'),
6797 _(b'REV'),
6801 _(b'REV'),
6798 ),
6802 ),
6799 ]
6803 ]
6800 + walkopts
6804 + walkopts
6801 + subrepoopts
6805 + subrepoopts
6802 + formatteropts,
6806 + formatteropts,
6803 _(b'[OPTION]... [FILE]...'),
6807 _(b'[OPTION]... [FILE]...'),
6804 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6808 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6805 helpbasic=True,
6809 helpbasic=True,
6806 inferrepo=True,
6810 inferrepo=True,
6807 intents={INTENT_READONLY},
6811 intents={INTENT_READONLY},
6808 )
6812 )
6809 def status(ui, repo, *pats, **opts):
6813 def status(ui, repo, *pats, **opts):
6810 """show changed files in the working directory
6814 """show changed files in the working directory
6811
6815
6812 Show status of files in the repository. If names are given, only
6816 Show status of files in the repository. If names are given, only
6813 files that match are shown. Files that are clean or ignored or
6817 files that match are shown. Files that are clean or ignored or
6814 the source of a copy/move operation, are not listed unless
6818 the source of a copy/move operation, are not listed unless
6815 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
6819 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
6816 Unless options described with "show only ..." are given, the
6820 Unless options described with "show only ..." are given, the
6817 options -mardu are used.
6821 options -mardu are used.
6818
6822
6819 Option -q/--quiet hides untracked (unknown and ignored) files
6823 Option -q/--quiet hides untracked (unknown and ignored) files
6820 unless explicitly requested with -u/--unknown or -i/--ignored.
6824 unless explicitly requested with -u/--unknown or -i/--ignored.
6821
6825
6822 .. note::
6826 .. note::
6823
6827
6824 :hg:`status` may appear to disagree with diff if permissions have
6828 :hg:`status` may appear to disagree with diff if permissions have
6825 changed or a merge has occurred. The standard diff format does
6829 changed or a merge has occurred. The standard diff format does
6826 not report permission changes and diff only reports changes
6830 not report permission changes and diff only reports changes
6827 relative to one merge parent.
6831 relative to one merge parent.
6828
6832
6829 If one revision is given, it is used as the base revision.
6833 If one revision is given, it is used as the base revision.
6830 If two revisions are given, the differences between them are
6834 If two revisions are given, the differences between them are
6831 shown. The --change option can also be used as a shortcut to list
6835 shown. The --change option can also be used as a shortcut to list
6832 the changed files of a revision from its first parent.
6836 the changed files of a revision from its first parent.
6833
6837
6834 The codes used to show the status of files are::
6838 The codes used to show the status of files are::
6835
6839
6836 M = modified
6840 M = modified
6837 A = added
6841 A = added
6838 R = removed
6842 R = removed
6839 C = clean
6843 C = clean
6840 ! = missing (deleted by non-hg command, but still tracked)
6844 ! = missing (deleted by non-hg command, but still tracked)
6841 ? = not tracked
6845 ? = not tracked
6842 I = ignored
6846 I = ignored
6843 = origin of the previous file (with --copies)
6847 = origin of the previous file (with --copies)
6844
6848
6845 .. container:: verbose
6849 .. container:: verbose
6846
6850
6847 The -t/--terse option abbreviates the output by showing only the directory
6851 The -t/--terse option abbreviates the output by showing only the directory
6848 name if all the files in it share the same status. The option takes an
6852 name if all the files in it share the same status. The option takes an
6849 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
6853 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
6850 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
6854 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
6851 for 'ignored' and 'c' for clean.
6855 for 'ignored' and 'c' for clean.
6852
6856
6853 It abbreviates only those statuses which are passed. Note that clean and
6857 It abbreviates only those statuses which are passed. Note that clean and
6854 ignored files are not displayed with '--terse ic' unless the -c/--clean
6858 ignored files are not displayed with '--terse ic' unless the -c/--clean
6855 and -i/--ignored options are also used.
6859 and -i/--ignored options are also used.
6856
6860
6857 The -v/--verbose option shows information when the repository is in an
6861 The -v/--verbose option shows information when the repository is in an
6858 unfinished merge, shelve, rebase state etc. You can have this behavior
6862 unfinished merge, shelve, rebase state etc. You can have this behavior
6859 turned on by default by enabling the ``commands.status.verbose`` option.
6863 turned on by default by enabling the ``commands.status.verbose`` option.
6860
6864
6861 You can skip displaying some of these states by setting
6865 You can skip displaying some of these states by setting
6862 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
6866 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
6863 'histedit', 'merge', 'rebase', or 'unshelve'.
6867 'histedit', 'merge', 'rebase', or 'unshelve'.
6864
6868
6865 Template:
6869 Template:
6866
6870
6867 The following keywords are supported in addition to the common template
6871 The following keywords are supported in addition to the common template
6868 keywords and functions. See also :hg:`help templates`.
6872 keywords and functions. See also :hg:`help templates`.
6869
6873
6870 :path: String. Repository-absolute path of the file.
6874 :path: String. Repository-absolute path of the file.
6871 :source: String. Repository-absolute path of the file originated from.
6875 :source: String. Repository-absolute path of the file originated from.
6872 Available if ``--copies`` is specified.
6876 Available if ``--copies`` is specified.
6873 :status: String. Character denoting file's status.
6877 :status: String. Character denoting file's status.
6874
6878
6875 Examples:
6879 Examples:
6876
6880
6877 - show changes in the working directory relative to a
6881 - show changes in the working directory relative to a
6878 changeset::
6882 changeset::
6879
6883
6880 hg status --rev 9353
6884 hg status --rev 9353
6881
6885
6882 - show changes in the working directory relative to the
6886 - show changes in the working directory relative to the
6883 current directory (see :hg:`help patterns` for more information)::
6887 current directory (see :hg:`help patterns` for more information)::
6884
6888
6885 hg status re:
6889 hg status re:
6886
6890
6887 - show all changes including copies in an existing changeset::
6891 - show all changes including copies in an existing changeset::
6888
6892
6889 hg status --copies --change 9353
6893 hg status --copies --change 9353
6890
6894
6891 - get a NUL separated list of added files, suitable for xargs::
6895 - get a NUL separated list of added files, suitable for xargs::
6892
6896
6893 hg status -an0
6897 hg status -an0
6894
6898
6895 - show more information about the repository status, abbreviating
6899 - show more information about the repository status, abbreviating
6896 added, removed, modified, deleted, and untracked paths::
6900 added, removed, modified, deleted, and untracked paths::
6897
6901
6898 hg status -v -t mardu
6902 hg status -v -t mardu
6899
6903
6900 Returns 0 on success.
6904 Returns 0 on success.
6901
6905
6902 """
6906 """
6903
6907
6904 cmdutil.check_at_most_one_arg(opts, 'rev', 'change')
6908 cmdutil.check_at_most_one_arg(opts, 'rev', 'change')
6905 opts = pycompat.byteskwargs(opts)
6909 opts = pycompat.byteskwargs(opts)
6906 revs = opts.get(b'rev', [])
6910 revs = opts.get(b'rev', [])
6907 change = opts.get(b'change', b'')
6911 change = opts.get(b'change', b'')
6908 terse = opts.get(b'terse', _NOTTERSE)
6912 terse = opts.get(b'terse', _NOTTERSE)
6909 if terse is _NOTTERSE:
6913 if terse is _NOTTERSE:
6910 if revs:
6914 if revs:
6911 terse = b''
6915 terse = b''
6912 else:
6916 else:
6913 terse = ui.config(b'commands', b'status.terse')
6917 terse = ui.config(b'commands', b'status.terse')
6914
6918
6915 if revs and terse:
6919 if revs and terse:
6916 msg = _(b'cannot use --terse with --rev')
6920 msg = _(b'cannot use --terse with --rev')
6917 raise error.InputError(msg)
6921 raise error.InputError(msg)
6918 elif change:
6922 elif change:
6919 repo = scmutil.unhidehashlikerevs(repo, [change], b'nowarn')
6923 repo = scmutil.unhidehashlikerevs(repo, [change], b'nowarn')
6920 ctx2 = logcmdutil.revsingle(repo, change, None)
6924 ctx2 = logcmdutil.revsingle(repo, change, None)
6921 ctx1 = ctx2.p1()
6925 ctx1 = ctx2.p1()
6922 else:
6926 else:
6923 repo = scmutil.unhidehashlikerevs(repo, revs, b'nowarn')
6927 repo = scmutil.unhidehashlikerevs(repo, revs, b'nowarn')
6924 ctx1, ctx2 = logcmdutil.revpair(repo, revs)
6928 ctx1, ctx2 = logcmdutil.revpair(repo, revs)
6925
6929
6926 forcerelativevalue = None
6930 forcerelativevalue = None
6927 if ui.hasconfig(b'commands', b'status.relative'):
6931 if ui.hasconfig(b'commands', b'status.relative'):
6928 forcerelativevalue = ui.configbool(b'commands', b'status.relative')
6932 forcerelativevalue = ui.configbool(b'commands', b'status.relative')
6929 uipathfn = scmutil.getuipathfn(
6933 uipathfn = scmutil.getuipathfn(
6930 repo,
6934 repo,
6931 legacyrelativevalue=bool(pats),
6935 legacyrelativevalue=bool(pats),
6932 forcerelativevalue=forcerelativevalue,
6936 forcerelativevalue=forcerelativevalue,
6933 )
6937 )
6934
6938
6935 if opts.get(b'print0'):
6939 if opts.get(b'print0'):
6936 end = b'\0'
6940 end = b'\0'
6937 else:
6941 else:
6938 end = b'\n'
6942 end = b'\n'
6939 states = b'modified added removed deleted unknown ignored clean'.split()
6943 states = b'modified added removed deleted unknown ignored clean'.split()
6940 show = [k for k in states if opts.get(k)]
6944 show = [k for k in states if opts.get(k)]
6941 if opts.get(b'all'):
6945 if opts.get(b'all'):
6942 show += ui.quiet and (states[:4] + [b'clean']) or states
6946 show += ui.quiet and (states[:4] + [b'clean']) or states
6943
6947
6944 if not show:
6948 if not show:
6945 if ui.quiet:
6949 if ui.quiet:
6946 show = states[:4]
6950 show = states[:4]
6947 else:
6951 else:
6948 show = states[:5]
6952 show = states[:5]
6949
6953
6950 m = scmutil.match(ctx2, pats, opts)
6954 m = scmutil.match(ctx2, pats, opts)
6951 if terse:
6955 if terse:
6952 # we need to compute clean and unknown to terse
6956 # we need to compute clean and unknown to terse
6953 stat = repo.status(
6957 stat = repo.status(
6954 ctx1.node(),
6958 ctx1.node(),
6955 ctx2.node(),
6959 ctx2.node(),
6956 m,
6960 m,
6957 b'ignored' in show or b'i' in terse,
6961 b'ignored' in show or b'i' in terse,
6958 clean=True,
6962 clean=True,
6959 unknown=True,
6963 unknown=True,
6960 listsubrepos=opts.get(b'subrepos'),
6964 listsubrepos=opts.get(b'subrepos'),
6961 )
6965 )
6962
6966
6963 stat = cmdutil.tersedir(stat, terse)
6967 stat = cmdutil.tersedir(stat, terse)
6964 else:
6968 else:
6965 stat = repo.status(
6969 stat = repo.status(
6966 ctx1.node(),
6970 ctx1.node(),
6967 ctx2.node(),
6971 ctx2.node(),
6968 m,
6972 m,
6969 b'ignored' in show,
6973 b'ignored' in show,
6970 b'clean' in show,
6974 b'clean' in show,
6971 b'unknown' in show,
6975 b'unknown' in show,
6972 opts.get(b'subrepos'),
6976 opts.get(b'subrepos'),
6973 )
6977 )
6974
6978
6975 changestates = zip(
6979 changestates = zip(
6976 states,
6980 states,
6977 pycompat.iterbytestr(b'MAR!?IC'),
6981 pycompat.iterbytestr(b'MAR!?IC'),
6978 [getattr(stat, s.decode('utf8')) for s in states],
6982 [getattr(stat, s.decode('utf8')) for s in states],
6979 )
6983 )
6980
6984
6981 copy = {}
6985 copy = {}
6982 show_copies = ui.configbool(b'ui', b'statuscopies')
6986 show_copies = ui.configbool(b'ui', b'statuscopies')
6983 if opts.get(b'copies') is not None:
6987 if opts.get(b'copies') is not None:
6984 show_copies = opts.get(b'copies')
6988 show_copies = opts.get(b'copies')
6985 show_copies = (show_copies or opts.get(b'all')) and not opts.get(
6989 show_copies = (show_copies or opts.get(b'all')) and not opts.get(
6986 b'no_status'
6990 b'no_status'
6987 )
6991 )
6988 if show_copies:
6992 if show_copies:
6989 copy = copies.pathcopies(ctx1, ctx2, m)
6993 copy = copies.pathcopies(ctx1, ctx2, m)
6990
6994
6991 morestatus = None
6995 morestatus = None
6992 if (
6996 if (
6993 (ui.verbose or ui.configbool(b'commands', b'status.verbose'))
6997 (ui.verbose or ui.configbool(b'commands', b'status.verbose'))
6994 and not ui.plain()
6998 and not ui.plain()
6995 and not opts.get(b'print0')
6999 and not opts.get(b'print0')
6996 ):
7000 ):
6997 morestatus = cmdutil.readmorestatus(repo)
7001 morestatus = cmdutil.readmorestatus(repo)
6998
7002
6999 ui.pager(b'status')
7003 ui.pager(b'status')
7000 fm = ui.formatter(b'status', opts)
7004 fm = ui.formatter(b'status', opts)
7001 fmt = b'%s' + end
7005 fmt = b'%s' + end
7002 showchar = not opts.get(b'no_status')
7006 showchar = not opts.get(b'no_status')
7003
7007
7004 for state, char, files in changestates:
7008 for state, char, files in changestates:
7005 if state in show:
7009 if state in show:
7006 label = b'status.' + state
7010 label = b'status.' + state
7007 for f in files:
7011 for f in files:
7008 fm.startitem()
7012 fm.startitem()
7009 fm.context(ctx=ctx2)
7013 fm.context(ctx=ctx2)
7010 fm.data(itemtype=b'file', path=f)
7014 fm.data(itemtype=b'file', path=f)
7011 fm.condwrite(showchar, b'status', b'%s ', char, label=label)
7015 fm.condwrite(showchar, b'status', b'%s ', char, label=label)
7012 fm.plain(fmt % uipathfn(f), label=label)
7016 fm.plain(fmt % uipathfn(f), label=label)
7013 if f in copy:
7017 if f in copy:
7014 fm.data(source=copy[f])
7018 fm.data(source=copy[f])
7015 fm.plain(
7019 fm.plain(
7016 (b' %s' + end) % uipathfn(copy[f]),
7020 (b' %s' + end) % uipathfn(copy[f]),
7017 label=b'status.copied',
7021 label=b'status.copied',
7018 )
7022 )
7019 if morestatus:
7023 if morestatus:
7020 morestatus.formatfile(f, fm)
7024 morestatus.formatfile(f, fm)
7021
7025
7022 if morestatus:
7026 if morestatus:
7023 morestatus.formatfooter(fm)
7027 morestatus.formatfooter(fm)
7024 fm.end()
7028 fm.end()
7025
7029
7026
7030
7027 @command(
7031 @command(
7028 b'summary|sum',
7032 b'summary|sum',
7029 [(b'', b'remote', None, _(b'check for push and pull'))],
7033 [(b'', b'remote', None, _(b'check for push and pull'))],
7030 b'[--remote]',
7034 b'[--remote]',
7031 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7035 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7032 helpbasic=True,
7036 helpbasic=True,
7033 intents={INTENT_READONLY},
7037 intents={INTENT_READONLY},
7034 )
7038 )
7035 def summary(ui, repo, **opts):
7039 def summary(ui, repo, **opts):
7036 """summarize working directory state
7040 """summarize working directory state
7037
7041
7038 This generates a brief summary of the working directory state,
7042 This generates a brief summary of the working directory state,
7039 including parents, branch, commit status, phase and available updates.
7043 including parents, branch, commit status, phase and available updates.
7040
7044
7041 With the --remote option, this will check the default paths for
7045 With the --remote option, this will check the default paths for
7042 incoming and outgoing changes. This can be time-consuming.
7046 incoming and outgoing changes. This can be time-consuming.
7043
7047
7044 Returns 0 on success.
7048 Returns 0 on success.
7045 """
7049 """
7046
7050
7047 opts = pycompat.byteskwargs(opts)
7051 opts = pycompat.byteskwargs(opts)
7048 ui.pager(b'summary')
7052 ui.pager(b'summary')
7049 ctx = repo[None]
7053 ctx = repo[None]
7050 parents = ctx.parents()
7054 parents = ctx.parents()
7051 pnode = parents[0].node()
7055 pnode = parents[0].node()
7052 marks = []
7056 marks = []
7053
7057
7054 try:
7058 try:
7055 ms = mergestatemod.mergestate.read(repo)
7059 ms = mergestatemod.mergestate.read(repo)
7056 except error.UnsupportedMergeRecords as e:
7060 except error.UnsupportedMergeRecords as e:
7057 s = b' '.join(e.recordtypes)
7061 s = b' '.join(e.recordtypes)
7058 ui.warn(
7062 ui.warn(
7059 _(b'warning: merge state has unsupported record types: %s\n') % s
7063 _(b'warning: merge state has unsupported record types: %s\n') % s
7060 )
7064 )
7061 unresolved = []
7065 unresolved = []
7062 else:
7066 else:
7063 unresolved = list(ms.unresolved())
7067 unresolved = list(ms.unresolved())
7064
7068
7065 for p in parents:
7069 for p in parents:
7066 # label with log.changeset (instead of log.parent) since this
7070 # label with log.changeset (instead of log.parent) since this
7067 # shows a working directory parent *changeset*:
7071 # shows a working directory parent *changeset*:
7068 # i18n: column positioning for "hg summary"
7072 # i18n: column positioning for "hg summary"
7069 ui.write(
7073 ui.write(
7070 _(b'parent: %d:%s ') % (p.rev(), p),
7074 _(b'parent: %d:%s ') % (p.rev(), p),
7071 label=logcmdutil.changesetlabels(p),
7075 label=logcmdutil.changesetlabels(p),
7072 )
7076 )
7073 ui.write(b' '.join(p.tags()), label=b'log.tag')
7077 ui.write(b' '.join(p.tags()), label=b'log.tag')
7074 if p.bookmarks():
7078 if p.bookmarks():
7075 marks.extend(p.bookmarks())
7079 marks.extend(p.bookmarks())
7076 if p.rev() == -1:
7080 if p.rev() == -1:
7077 if not len(repo):
7081 if not len(repo):
7078 ui.write(_(b' (empty repository)'))
7082 ui.write(_(b' (empty repository)'))
7079 else:
7083 else:
7080 ui.write(_(b' (no revision checked out)'))
7084 ui.write(_(b' (no revision checked out)'))
7081 if p.obsolete():
7085 if p.obsolete():
7082 ui.write(_(b' (obsolete)'))
7086 ui.write(_(b' (obsolete)'))
7083 if p.isunstable():
7087 if p.isunstable():
7084 instabilities = (
7088 instabilities = (
7085 ui.label(instability, b'trouble.%s' % instability)
7089 ui.label(instability, b'trouble.%s' % instability)
7086 for instability in p.instabilities()
7090 for instability in p.instabilities()
7087 )
7091 )
7088 ui.write(b' (' + b', '.join(instabilities) + b')')
7092 ui.write(b' (' + b', '.join(instabilities) + b')')
7089 ui.write(b'\n')
7093 ui.write(b'\n')
7090 if p.description():
7094 if p.description():
7091 ui.status(
7095 ui.status(
7092 b' ' + p.description().splitlines()[0].strip() + b'\n',
7096 b' ' + p.description().splitlines()[0].strip() + b'\n',
7093 label=b'log.summary',
7097 label=b'log.summary',
7094 )
7098 )
7095
7099
7096 branch = ctx.branch()
7100 branch = ctx.branch()
7097 bheads = repo.branchheads(branch)
7101 bheads = repo.branchheads(branch)
7098 # i18n: column positioning for "hg summary"
7102 # i18n: column positioning for "hg summary"
7099 m = _(b'branch: %s\n') % branch
7103 m = _(b'branch: %s\n') % branch
7100 if branch != b'default':
7104 if branch != b'default':
7101 ui.write(m, label=b'log.branch')
7105 ui.write(m, label=b'log.branch')
7102 else:
7106 else:
7103 ui.status(m, label=b'log.branch')
7107 ui.status(m, label=b'log.branch')
7104
7108
7105 if marks:
7109 if marks:
7106 active = repo._activebookmark
7110 active = repo._activebookmark
7107 # i18n: column positioning for "hg summary"
7111 # i18n: column positioning for "hg summary"
7108 ui.write(_(b'bookmarks:'), label=b'log.bookmark')
7112 ui.write(_(b'bookmarks:'), label=b'log.bookmark')
7109 if active is not None:
7113 if active is not None:
7110 if active in marks:
7114 if active in marks:
7111 ui.write(b' *' + active, label=bookmarks.activebookmarklabel)
7115 ui.write(b' *' + active, label=bookmarks.activebookmarklabel)
7112 marks.remove(active)
7116 marks.remove(active)
7113 else:
7117 else:
7114 ui.write(b' [%s]' % active, label=bookmarks.activebookmarklabel)
7118 ui.write(b' [%s]' % active, label=bookmarks.activebookmarklabel)
7115 for m in marks:
7119 for m in marks:
7116 ui.write(b' ' + m, label=b'log.bookmark')
7120 ui.write(b' ' + m, label=b'log.bookmark')
7117 ui.write(b'\n', label=b'log.bookmark')
7121 ui.write(b'\n', label=b'log.bookmark')
7118
7122
7119 status = repo.status(unknown=True)
7123 status = repo.status(unknown=True)
7120
7124
7121 c = repo.dirstate.copies()
7125 c = repo.dirstate.copies()
7122 copied, renamed = [], []
7126 copied, renamed = [], []
7123 for d, s in c.items():
7127 for d, s in c.items():
7124 if s in status.removed:
7128 if s in status.removed:
7125 status.removed.remove(s)
7129 status.removed.remove(s)
7126 renamed.append(d)
7130 renamed.append(d)
7127 else:
7131 else:
7128 copied.append(d)
7132 copied.append(d)
7129 if d in status.added:
7133 if d in status.added:
7130 status.added.remove(d)
7134 status.added.remove(d)
7131
7135
7132 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
7136 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
7133
7137
7134 labels = [
7138 labels = [
7135 (ui.label(_(b'%d modified'), b'status.modified'), status.modified),
7139 (ui.label(_(b'%d modified'), b'status.modified'), status.modified),
7136 (ui.label(_(b'%d added'), b'status.added'), status.added),
7140 (ui.label(_(b'%d added'), b'status.added'), status.added),
7137 (ui.label(_(b'%d removed'), b'status.removed'), status.removed),
7141 (ui.label(_(b'%d removed'), b'status.removed'), status.removed),
7138 (ui.label(_(b'%d renamed'), b'status.copied'), renamed),
7142 (ui.label(_(b'%d renamed'), b'status.copied'), renamed),
7139 (ui.label(_(b'%d copied'), b'status.copied'), copied),
7143 (ui.label(_(b'%d copied'), b'status.copied'), copied),
7140 (ui.label(_(b'%d deleted'), b'status.deleted'), status.deleted),
7144 (ui.label(_(b'%d deleted'), b'status.deleted'), status.deleted),
7141 (ui.label(_(b'%d unknown'), b'status.unknown'), status.unknown),
7145 (ui.label(_(b'%d unknown'), b'status.unknown'), status.unknown),
7142 (ui.label(_(b'%d unresolved'), b'resolve.unresolved'), unresolved),
7146 (ui.label(_(b'%d unresolved'), b'resolve.unresolved'), unresolved),
7143 (ui.label(_(b'%d subrepos'), b'status.modified'), subs),
7147 (ui.label(_(b'%d subrepos'), b'status.modified'), subs),
7144 ]
7148 ]
7145 t = []
7149 t = []
7146 for l, s in labels:
7150 for l, s in labels:
7147 if s:
7151 if s:
7148 t.append(l % len(s))
7152 t.append(l % len(s))
7149
7153
7150 t = b', '.join(t)
7154 t = b', '.join(t)
7151 cleanworkdir = False
7155 cleanworkdir = False
7152
7156
7153 if repo.vfs.exists(b'graftstate'):
7157 if repo.vfs.exists(b'graftstate'):
7154 t += _(b' (graft in progress)')
7158 t += _(b' (graft in progress)')
7155 if repo.vfs.exists(b'updatestate'):
7159 if repo.vfs.exists(b'updatestate'):
7156 t += _(b' (interrupted update)')
7160 t += _(b' (interrupted update)')
7157 elif len(parents) > 1:
7161 elif len(parents) > 1:
7158 t += _(b' (merge)')
7162 t += _(b' (merge)')
7159 elif branch != parents[0].branch():
7163 elif branch != parents[0].branch():
7160 t += _(b' (new branch)')
7164 t += _(b' (new branch)')
7161 elif parents[0].closesbranch() and pnode in repo.branchheads(
7165 elif parents[0].closesbranch() and pnode in repo.branchheads(
7162 branch, closed=True
7166 branch, closed=True
7163 ):
7167 ):
7164 t += _(b' (head closed)')
7168 t += _(b' (head closed)')
7165 elif not (
7169 elif not (
7166 status.modified
7170 status.modified
7167 or status.added
7171 or status.added
7168 or status.removed
7172 or status.removed
7169 or renamed
7173 or renamed
7170 or copied
7174 or copied
7171 or subs
7175 or subs
7172 ):
7176 ):
7173 t += _(b' (clean)')
7177 t += _(b' (clean)')
7174 cleanworkdir = True
7178 cleanworkdir = True
7175 elif pnode not in bheads:
7179 elif pnode not in bheads:
7176 t += _(b' (new branch head)')
7180 t += _(b' (new branch head)')
7177
7181
7178 if parents:
7182 if parents:
7179 pendingphase = max(p.phase() for p in parents)
7183 pendingphase = max(p.phase() for p in parents)
7180 else:
7184 else:
7181 pendingphase = phases.public
7185 pendingphase = phases.public
7182
7186
7183 if pendingphase > phases.newcommitphase(ui):
7187 if pendingphase > phases.newcommitphase(ui):
7184 t += b' (%s)' % phases.phasenames[pendingphase]
7188 t += b' (%s)' % phases.phasenames[pendingphase]
7185
7189
7186 if cleanworkdir:
7190 if cleanworkdir:
7187 # i18n: column positioning for "hg summary"
7191 # i18n: column positioning for "hg summary"
7188 ui.status(_(b'commit: %s\n') % t.strip())
7192 ui.status(_(b'commit: %s\n') % t.strip())
7189 else:
7193 else:
7190 # i18n: column positioning for "hg summary"
7194 # i18n: column positioning for "hg summary"
7191 ui.write(_(b'commit: %s\n') % t.strip())
7195 ui.write(_(b'commit: %s\n') % t.strip())
7192
7196
7193 # all ancestors of branch heads - all ancestors of parent = new csets
7197 # all ancestors of branch heads - all ancestors of parent = new csets
7194 new = len(
7198 new = len(
7195 repo.changelog.findmissing([pctx.node() for pctx in parents], bheads)
7199 repo.changelog.findmissing([pctx.node() for pctx in parents], bheads)
7196 )
7200 )
7197
7201
7198 if new == 0:
7202 if new == 0:
7199 # i18n: column positioning for "hg summary"
7203 # i18n: column positioning for "hg summary"
7200 ui.status(_(b'update: (current)\n'))
7204 ui.status(_(b'update: (current)\n'))
7201 elif pnode not in bheads:
7205 elif pnode not in bheads:
7202 # i18n: column positioning for "hg summary"
7206 # i18n: column positioning for "hg summary"
7203 ui.write(_(b'update: %d new changesets (update)\n') % new)
7207 ui.write(_(b'update: %d new changesets (update)\n') % new)
7204 else:
7208 else:
7205 # i18n: column positioning for "hg summary"
7209 # i18n: column positioning for "hg summary"
7206 ui.write(
7210 ui.write(
7207 _(b'update: %d new changesets, %d branch heads (merge)\n')
7211 _(b'update: %d new changesets, %d branch heads (merge)\n')
7208 % (new, len(bheads))
7212 % (new, len(bheads))
7209 )
7213 )
7210
7214
7211 t = []
7215 t = []
7212 draft = len(repo.revs(b'draft()'))
7216 draft = len(repo.revs(b'draft()'))
7213 if draft:
7217 if draft:
7214 t.append(_(b'%d draft') % draft)
7218 t.append(_(b'%d draft') % draft)
7215 secret = len(repo.revs(b'secret()'))
7219 secret = len(repo.revs(b'secret()'))
7216 if secret:
7220 if secret:
7217 t.append(_(b'%d secret') % secret)
7221 t.append(_(b'%d secret') % secret)
7218
7222
7219 if draft or secret:
7223 if draft or secret:
7220 ui.status(_(b'phases: %s\n') % b', '.join(t))
7224 ui.status(_(b'phases: %s\n') % b', '.join(t))
7221
7225
7222 if obsolete.isenabled(repo, obsolete.createmarkersopt):
7226 if obsolete.isenabled(repo, obsolete.createmarkersopt):
7223 for trouble in (b"orphan", b"contentdivergent", b"phasedivergent"):
7227 for trouble in (b"orphan", b"contentdivergent", b"phasedivergent"):
7224 numtrouble = len(repo.revs(trouble + b"()"))
7228 numtrouble = len(repo.revs(trouble + b"()"))
7225 # We write all the possibilities to ease translation
7229 # We write all the possibilities to ease translation
7226 troublemsg = {
7230 troublemsg = {
7227 b"orphan": _(b"orphan: %d changesets"),
7231 b"orphan": _(b"orphan: %d changesets"),
7228 b"contentdivergent": _(b"content-divergent: %d changesets"),
7232 b"contentdivergent": _(b"content-divergent: %d changesets"),
7229 b"phasedivergent": _(b"phase-divergent: %d changesets"),
7233 b"phasedivergent": _(b"phase-divergent: %d changesets"),
7230 }
7234 }
7231 if numtrouble > 0:
7235 if numtrouble > 0:
7232 ui.status(troublemsg[trouble] % numtrouble + b"\n")
7236 ui.status(troublemsg[trouble] % numtrouble + b"\n")
7233
7237
7234 cmdutil.summaryhooks(ui, repo)
7238 cmdutil.summaryhooks(ui, repo)
7235
7239
7236 if opts.get(b'remote'):
7240 if opts.get(b'remote'):
7237 needsincoming, needsoutgoing = True, True
7241 needsincoming, needsoutgoing = True, True
7238 else:
7242 else:
7239 needsincoming, needsoutgoing = False, False
7243 needsincoming, needsoutgoing = False, False
7240 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
7244 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
7241 if i:
7245 if i:
7242 needsincoming = True
7246 needsincoming = True
7243 if o:
7247 if o:
7244 needsoutgoing = True
7248 needsoutgoing = True
7245 if not needsincoming and not needsoutgoing:
7249 if not needsincoming and not needsoutgoing:
7246 return
7250 return
7247
7251
7248 def getincoming():
7252 def getincoming():
7249 # XXX We should actually skip this if no default is specified, instead
7253 # XXX We should actually skip this if no default is specified, instead
7250 # of passing "default" which will resolve as "./default/" if no default
7254 # of passing "default" which will resolve as "./default/" if no default
7251 # path is defined.
7255 # path is defined.
7252 source, branches = urlutil.get_unique_pull_path(
7256 source, branches = urlutil.get_unique_pull_path(
7253 b'summary', repo, ui, b'default'
7257 b'summary', repo, ui, b'default'
7254 )
7258 )
7255 sbranch = branches[0]
7259 sbranch = branches[0]
7256 try:
7260 try:
7257 other = hg.peer(repo, {}, source)
7261 other = hg.peer(repo, {}, source)
7258 except error.RepoError:
7262 except error.RepoError:
7259 if opts.get(b'remote'):
7263 if opts.get(b'remote'):
7260 raise
7264 raise
7261 return source, sbranch, None, None, None
7265 return source, sbranch, None, None, None
7262 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
7266 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
7263 if revs:
7267 if revs:
7264 revs = [other.lookup(rev) for rev in revs]
7268 revs = [other.lookup(rev) for rev in revs]
7265 ui.debug(b'comparing with %s\n' % urlutil.hidepassword(source))
7269 ui.debug(b'comparing with %s\n' % urlutil.hidepassword(source))
7266 with repo.ui.silent():
7270 with repo.ui.silent():
7267 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
7271 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
7268 return source, sbranch, other, commoninc, commoninc[1]
7272 return source, sbranch, other, commoninc, commoninc[1]
7269
7273
7270 if needsincoming:
7274 if needsincoming:
7271 source, sbranch, sother, commoninc, incoming = getincoming()
7275 source, sbranch, sother, commoninc, incoming = getincoming()
7272 else:
7276 else:
7273 source = sbranch = sother = commoninc = incoming = None
7277 source = sbranch = sother = commoninc = incoming = None
7274
7278
7275 def getoutgoing():
7279 def getoutgoing():
7276 # XXX We should actually skip this if no default is specified, instead
7280 # XXX We should actually skip this if no default is specified, instead
7277 # of passing "default" which will resolve as "./default/" if no default
7281 # of passing "default" which will resolve as "./default/" if no default
7278 # path is defined.
7282 # path is defined.
7279 d = None
7283 d = None
7280 if b'default-push' in ui.paths:
7284 if b'default-push' in ui.paths:
7281 d = b'default-push'
7285 d = b'default-push'
7282 elif b'default' in ui.paths:
7286 elif b'default' in ui.paths:
7283 d = b'default'
7287 d = b'default'
7284 path = None
7288 path = None
7285 if d is not None:
7289 if d is not None:
7286 path = urlutil.get_unique_push_path(b'summary', repo, ui, d)
7290 path = urlutil.get_unique_push_path(b'summary', repo, ui, d)
7287 dest = path.loc
7291 dest = path.loc
7288 dbranch = path.branch
7292 dbranch = path.branch
7289 else:
7293 else:
7290 dest = b'default'
7294 dest = b'default'
7291 dbranch = None
7295 dbranch = None
7292 revs, checkout = hg.addbranchrevs(repo, repo, (dbranch, []), None)
7296 revs, checkout = hg.addbranchrevs(repo, repo, (dbranch, []), None)
7293 if source != dest:
7297 if source != dest:
7294 try:
7298 try:
7295 dother = hg.peer(repo, {}, path if path is not None else dest)
7299 dother = hg.peer(repo, {}, path if path is not None else dest)
7296 except error.RepoError:
7300 except error.RepoError:
7297 if opts.get(b'remote'):
7301 if opts.get(b'remote'):
7298 raise
7302 raise
7299 return dest, dbranch, None, None
7303 return dest, dbranch, None, None
7300 ui.debug(b'comparing with %s\n' % urlutil.hidepassword(dest))
7304 ui.debug(b'comparing with %s\n' % urlutil.hidepassword(dest))
7301 elif sother is None:
7305 elif sother is None:
7302 # there is no explicit destination peer, but source one is invalid
7306 # there is no explicit destination peer, but source one is invalid
7303 return dest, dbranch, None, None
7307 return dest, dbranch, None, None
7304 else:
7308 else:
7305 dother = sother
7309 dother = sother
7306 if source != dest or (sbranch is not None and sbranch != dbranch):
7310 if source != dest or (sbranch is not None and sbranch != dbranch):
7307 common = None
7311 common = None
7308 else:
7312 else:
7309 common = commoninc
7313 common = commoninc
7310 if revs:
7314 if revs:
7311 revs = [repo.lookup(rev) for rev in revs]
7315 revs = [repo.lookup(rev) for rev in revs]
7312 with repo.ui.silent():
7316 with repo.ui.silent():
7313 outgoing = discovery.findcommonoutgoing(
7317 outgoing = discovery.findcommonoutgoing(
7314 repo, dother, onlyheads=revs, commoninc=common
7318 repo, dother, onlyheads=revs, commoninc=common
7315 )
7319 )
7316 return dest, dbranch, dother, outgoing
7320 return dest, dbranch, dother, outgoing
7317
7321
7318 if needsoutgoing:
7322 if needsoutgoing:
7319 dest, dbranch, dother, outgoing = getoutgoing()
7323 dest, dbranch, dother, outgoing = getoutgoing()
7320 else:
7324 else:
7321 dest = dbranch = dother = outgoing = None
7325 dest = dbranch = dother = outgoing = None
7322
7326
7323 if opts.get(b'remote'):
7327 if opts.get(b'remote'):
7324 # Help pytype. --remote sets both `needsincoming` and `needsoutgoing`.
7328 # Help pytype. --remote sets both `needsincoming` and `needsoutgoing`.
7325 # The former always sets `sother` (or raises an exception if it can't);
7329 # The former always sets `sother` (or raises an exception if it can't);
7326 # the latter always sets `outgoing`.
7330 # the latter always sets `outgoing`.
7327 assert sother is not None
7331 assert sother is not None
7328 assert outgoing is not None
7332 assert outgoing is not None
7329
7333
7330 t = []
7334 t = []
7331 if incoming:
7335 if incoming:
7332 t.append(_(b'1 or more incoming'))
7336 t.append(_(b'1 or more incoming'))
7333 o = outgoing.missing
7337 o = outgoing.missing
7334 if o:
7338 if o:
7335 t.append(_(b'%d outgoing') % len(o))
7339 t.append(_(b'%d outgoing') % len(o))
7336 other = dother or sother
7340 other = dother or sother
7337 if b'bookmarks' in other.listkeys(b'namespaces'):
7341 if b'bookmarks' in other.listkeys(b'namespaces'):
7338 counts = bookmarks.summary(repo, other)
7342 counts = bookmarks.summary(repo, other)
7339 if counts[0] > 0:
7343 if counts[0] > 0:
7340 t.append(_(b'%d incoming bookmarks') % counts[0])
7344 t.append(_(b'%d incoming bookmarks') % counts[0])
7341 if counts[1] > 0:
7345 if counts[1] > 0:
7342 t.append(_(b'%d outgoing bookmarks') % counts[1])
7346 t.append(_(b'%d outgoing bookmarks') % counts[1])
7343
7347
7344 if t:
7348 if t:
7345 # i18n: column positioning for "hg summary"
7349 # i18n: column positioning for "hg summary"
7346 ui.write(_(b'remote: %s\n') % (b', '.join(t)))
7350 ui.write(_(b'remote: %s\n') % (b', '.join(t)))
7347 else:
7351 else:
7348 # i18n: column positioning for "hg summary"
7352 # i18n: column positioning for "hg summary"
7349 ui.status(_(b'remote: (synced)\n'))
7353 ui.status(_(b'remote: (synced)\n'))
7350
7354
7351 cmdutil.summaryremotehooks(
7355 cmdutil.summaryremotehooks(
7352 ui,
7356 ui,
7353 repo,
7357 repo,
7354 opts,
7358 opts,
7355 (
7359 (
7356 (source, sbranch, sother, commoninc),
7360 (source, sbranch, sother, commoninc),
7357 (dest, dbranch, dother, outgoing),
7361 (dest, dbranch, dother, outgoing),
7358 ),
7362 ),
7359 )
7363 )
7360
7364
7361
7365
7362 @command(
7366 @command(
7363 b'tag',
7367 b'tag',
7364 [
7368 [
7365 (b'f', b'force', None, _(b'force tag')),
7369 (b'f', b'force', None, _(b'force tag')),
7366 (b'l', b'local', None, _(b'make the tag local')),
7370 (b'l', b'local', None, _(b'make the tag local')),
7367 (b'r', b'rev', b'', _(b'revision to tag'), _(b'REV')),
7371 (b'r', b'rev', b'', _(b'revision to tag'), _(b'REV')),
7368 (b'', b'remove', None, _(b'remove a tag')),
7372 (b'', b'remove', None, _(b'remove a tag')),
7369 # -l/--local is already there, commitopts cannot be used
7373 # -l/--local is already there, commitopts cannot be used
7370 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
7374 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
7371 (b'm', b'message', b'', _(b'use text as commit message'), _(b'TEXT')),
7375 (b'm', b'message', b'', _(b'use text as commit message'), _(b'TEXT')),
7372 ]
7376 ]
7373 + commitopts2,
7377 + commitopts2,
7374 _(b'[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'),
7378 _(b'[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'),
7375 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7379 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7376 )
7380 )
7377 def tag(ui, repo, name1, *names, **opts):
7381 def tag(ui, repo, name1, *names, **opts):
7378 """add one or more tags for the current or given revision
7382 """add one or more tags for the current or given revision
7379
7383
7380 Name a particular revision using <name>.
7384 Name a particular revision using <name>.
7381
7385
7382 Tags are used to name particular revisions of the repository and are
7386 Tags are used to name particular revisions of the repository and are
7383 very useful to compare different revisions, to go back to significant
7387 very useful to compare different revisions, to go back to significant
7384 earlier versions or to mark branch points as releases, etc. Changing
7388 earlier versions or to mark branch points as releases, etc. Changing
7385 an existing tag is normally disallowed; use -f/--force to override.
7389 an existing tag is normally disallowed; use -f/--force to override.
7386
7390
7387 If no revision is given, the parent of the working directory is
7391 If no revision is given, the parent of the working directory is
7388 used.
7392 used.
7389
7393
7390 To facilitate version control, distribution, and merging of tags,
7394 To facilitate version control, distribution, and merging of tags,
7391 they are stored as a file named ".hgtags" which is managed similarly
7395 they are stored as a file named ".hgtags" which is managed similarly
7392 to other project files and can be hand-edited if necessary. This
7396 to other project files and can be hand-edited if necessary. This
7393 also means that tagging creates a new commit. The file
7397 also means that tagging creates a new commit. The file
7394 ".hg/localtags" is used for local tags (not shared among
7398 ".hg/localtags" is used for local tags (not shared among
7395 repositories).
7399 repositories).
7396
7400
7397 Tag commits are usually made at the head of a branch. If the parent
7401 Tag commits are usually made at the head of a branch. If the parent
7398 of the working directory is not a branch head, :hg:`tag` aborts; use
7402 of the working directory is not a branch head, :hg:`tag` aborts; use
7399 -f/--force to force the tag commit to be based on a non-head
7403 -f/--force to force the tag commit to be based on a non-head
7400 changeset.
7404 changeset.
7401
7405
7402 See :hg:`help dates` for a list of formats valid for -d/--date.
7406 See :hg:`help dates` for a list of formats valid for -d/--date.
7403
7407
7404 Since tag names have priority over branch names during revision
7408 Since tag names have priority over branch names during revision
7405 lookup, using an existing branch name as a tag name is discouraged.
7409 lookup, using an existing branch name as a tag name is discouraged.
7406
7410
7407 Returns 0 on success.
7411 Returns 0 on success.
7408 """
7412 """
7409 cmdutil.check_incompatible_arguments(opts, 'remove', ['rev'])
7413 cmdutil.check_incompatible_arguments(opts, 'remove', ['rev'])
7410 opts = pycompat.byteskwargs(opts)
7414 opts = pycompat.byteskwargs(opts)
7411 with repo.wlock(), repo.lock():
7415 with repo.wlock(), repo.lock():
7412 rev_ = b"."
7416 rev_ = b"."
7413 names = [t.strip() for t in (name1,) + names]
7417 names = [t.strip() for t in (name1,) + names]
7414 if len(names) != len(set(names)):
7418 if len(names) != len(set(names)):
7415 raise error.InputError(_(b'tag names must be unique'))
7419 raise error.InputError(_(b'tag names must be unique'))
7416 for n in names:
7420 for n in names:
7417 scmutil.checknewlabel(repo, n, b'tag')
7421 scmutil.checknewlabel(repo, n, b'tag')
7418 if not n:
7422 if not n:
7419 raise error.InputError(
7423 raise error.InputError(
7420 _(b'tag names cannot consist entirely of whitespace')
7424 _(b'tag names cannot consist entirely of whitespace')
7421 )
7425 )
7422 if opts.get(b'rev'):
7426 if opts.get(b'rev'):
7423 rev_ = opts[b'rev']
7427 rev_ = opts[b'rev']
7424 message = opts.get(b'message')
7428 message = opts.get(b'message')
7425 if opts.get(b'remove'):
7429 if opts.get(b'remove'):
7426 if opts.get(b'local'):
7430 if opts.get(b'local'):
7427 expectedtype = b'local'
7431 expectedtype = b'local'
7428 else:
7432 else:
7429 expectedtype = b'global'
7433 expectedtype = b'global'
7430
7434
7431 for n in names:
7435 for n in names:
7432 if repo.tagtype(n) == b'global':
7436 if repo.tagtype(n) == b'global':
7433 alltags = tagsmod.findglobaltags(ui, repo)
7437 alltags = tagsmod.findglobaltags(ui, repo)
7434 if alltags[n][0] == repo.nullid:
7438 if alltags[n][0] == repo.nullid:
7435 raise error.InputError(
7439 raise error.InputError(
7436 _(b"tag '%s' is already removed") % n
7440 _(b"tag '%s' is already removed") % n
7437 )
7441 )
7438 if not repo.tagtype(n):
7442 if not repo.tagtype(n):
7439 raise error.InputError(_(b"tag '%s' does not exist") % n)
7443 raise error.InputError(_(b"tag '%s' does not exist") % n)
7440 if repo.tagtype(n) != expectedtype:
7444 if repo.tagtype(n) != expectedtype:
7441 if expectedtype == b'global':
7445 if expectedtype == b'global':
7442 raise error.InputError(
7446 raise error.InputError(
7443 _(b"tag '%s' is not a global tag") % n
7447 _(b"tag '%s' is not a global tag") % n
7444 )
7448 )
7445 else:
7449 else:
7446 raise error.InputError(
7450 raise error.InputError(
7447 _(b"tag '%s' is not a local tag") % n
7451 _(b"tag '%s' is not a local tag") % n
7448 )
7452 )
7449 rev_ = b'null'
7453 rev_ = b'null'
7450 if not message:
7454 if not message:
7451 # we don't translate commit messages
7455 # we don't translate commit messages
7452 message = b'Removed tag %s' % b', '.join(names)
7456 message = b'Removed tag %s' % b', '.join(names)
7453 elif not opts.get(b'force'):
7457 elif not opts.get(b'force'):
7454 for n in names:
7458 for n in names:
7455 if n in repo.tags():
7459 if n in repo.tags():
7456 raise error.InputError(
7460 raise error.InputError(
7457 _(b"tag '%s' already exists (use -f to force)") % n
7461 _(b"tag '%s' already exists (use -f to force)") % n
7458 )
7462 )
7459 if not opts.get(b'local'):
7463 if not opts.get(b'local'):
7460 p1, p2 = repo.dirstate.parents()
7464 p1, p2 = repo.dirstate.parents()
7461 if p2 != repo.nullid:
7465 if p2 != repo.nullid:
7462 raise error.StateError(_(b'uncommitted merge'))
7466 raise error.StateError(_(b'uncommitted merge'))
7463 bheads = repo.branchheads()
7467 bheads = repo.branchheads()
7464 if not opts.get(b'force') and bheads and p1 not in bheads:
7468 if not opts.get(b'force') and bheads and p1 not in bheads:
7465 raise error.InputError(
7469 raise error.InputError(
7466 _(
7470 _(
7467 b'working directory is not at a branch head '
7471 b'working directory is not at a branch head '
7468 b'(use -f to force)'
7472 b'(use -f to force)'
7469 )
7473 )
7470 )
7474 )
7471 node = logcmdutil.revsingle(repo, rev_).node()
7475 node = logcmdutil.revsingle(repo, rev_).node()
7472
7476
7473 if not message:
7477 if not message:
7474 # we don't translate commit messages
7478 # we don't translate commit messages
7475 message = b'Added tag %s for changeset %s' % (
7479 message = b'Added tag %s for changeset %s' % (
7476 b', '.join(names),
7480 b', '.join(names),
7477 short(node),
7481 short(node),
7478 )
7482 )
7479
7483
7480 date = opts.get(b'date')
7484 date = opts.get(b'date')
7481 if date:
7485 if date:
7482 date = dateutil.parsedate(date)
7486 date = dateutil.parsedate(date)
7483
7487
7484 if opts.get(b'remove'):
7488 if opts.get(b'remove'):
7485 editform = b'tag.remove'
7489 editform = b'tag.remove'
7486 else:
7490 else:
7487 editform = b'tag.add'
7491 editform = b'tag.add'
7488 editor = cmdutil.getcommiteditor(
7492 editor = cmdutil.getcommiteditor(
7489 editform=editform, **pycompat.strkwargs(opts)
7493 editform=editform, **pycompat.strkwargs(opts)
7490 )
7494 )
7491
7495
7492 # don't allow tagging the null rev
7496 # don't allow tagging the null rev
7493 if (
7497 if (
7494 not opts.get(b'remove')
7498 not opts.get(b'remove')
7495 and logcmdutil.revsingle(repo, rev_).rev() == nullrev
7499 and logcmdutil.revsingle(repo, rev_).rev() == nullrev
7496 ):
7500 ):
7497 raise error.InputError(_(b"cannot tag null revision"))
7501 raise error.InputError(_(b"cannot tag null revision"))
7498
7502
7499 tagsmod.tag(
7503 tagsmod.tag(
7500 repo,
7504 repo,
7501 names,
7505 names,
7502 node,
7506 node,
7503 message,
7507 message,
7504 opts.get(b'local'),
7508 opts.get(b'local'),
7505 opts.get(b'user'),
7509 opts.get(b'user'),
7506 date,
7510 date,
7507 editor=editor,
7511 editor=editor,
7508 )
7512 )
7509
7513
7510
7514
7511 @command(
7515 @command(
7512 b'tags',
7516 b'tags',
7513 formatteropts,
7517 formatteropts,
7514 b'',
7518 b'',
7515 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7519 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7516 intents={INTENT_READONLY},
7520 intents={INTENT_READONLY},
7517 )
7521 )
7518 def tags(ui, repo, **opts):
7522 def tags(ui, repo, **opts):
7519 """list repository tags
7523 """list repository tags
7520
7524
7521 This lists both regular and local tags. When the -v/--verbose
7525 This lists both regular and local tags. When the -v/--verbose
7522 switch is used, a third column "local" is printed for local tags.
7526 switch is used, a third column "local" is printed for local tags.
7523 When the -q/--quiet switch is used, only the tag name is printed.
7527 When the -q/--quiet switch is used, only the tag name is printed.
7524
7528
7525 .. container:: verbose
7529 .. container:: verbose
7526
7530
7527 Template:
7531 Template:
7528
7532
7529 The following keywords are supported in addition to the common template
7533 The following keywords are supported in addition to the common template
7530 keywords and functions such as ``{tag}``. See also
7534 keywords and functions such as ``{tag}``. See also
7531 :hg:`help templates`.
7535 :hg:`help templates`.
7532
7536
7533 :type: String. ``local`` for local tags.
7537 :type: String. ``local`` for local tags.
7534
7538
7535 Returns 0 on success.
7539 Returns 0 on success.
7536 """
7540 """
7537
7541
7538 opts = pycompat.byteskwargs(opts)
7542 opts = pycompat.byteskwargs(opts)
7539 ui.pager(b'tags')
7543 ui.pager(b'tags')
7540 fm = ui.formatter(b'tags', opts)
7544 fm = ui.formatter(b'tags', opts)
7541 hexfunc = fm.hexfunc
7545 hexfunc = fm.hexfunc
7542
7546
7543 for t, n in reversed(repo.tagslist()):
7547 for t, n in reversed(repo.tagslist()):
7544 hn = hexfunc(n)
7548 hn = hexfunc(n)
7545 label = b'tags.normal'
7549 label = b'tags.normal'
7546 tagtype = repo.tagtype(t)
7550 tagtype = repo.tagtype(t)
7547 if not tagtype or tagtype == b'global':
7551 if not tagtype or tagtype == b'global':
7548 tagtype = b''
7552 tagtype = b''
7549 else:
7553 else:
7550 label = b'tags.' + tagtype
7554 label = b'tags.' + tagtype
7551
7555
7552 fm.startitem()
7556 fm.startitem()
7553 fm.context(repo=repo)
7557 fm.context(repo=repo)
7554 fm.write(b'tag', b'%s', t, label=label)
7558 fm.write(b'tag', b'%s', t, label=label)
7555 fmt = b" " * (30 - encoding.colwidth(t)) + b' %5d:%s'
7559 fmt = b" " * (30 - encoding.colwidth(t)) + b' %5d:%s'
7556 fm.condwrite(
7560 fm.condwrite(
7557 not ui.quiet,
7561 not ui.quiet,
7558 b'rev node',
7562 b'rev node',
7559 fmt,
7563 fmt,
7560 repo.changelog.rev(n),
7564 repo.changelog.rev(n),
7561 hn,
7565 hn,
7562 label=label,
7566 label=label,
7563 )
7567 )
7564 fm.condwrite(
7568 fm.condwrite(
7565 ui.verbose and tagtype, b'type', b' %s', tagtype, label=label
7569 ui.verbose and tagtype, b'type', b' %s', tagtype, label=label
7566 )
7570 )
7567 fm.plain(b'\n')
7571 fm.plain(b'\n')
7568 fm.end()
7572 fm.end()
7569
7573
7570
7574
7571 @command(
7575 @command(
7572 b'tip',
7576 b'tip',
7573 [
7577 [
7574 (b'p', b'patch', None, _(b'show patch')),
7578 (b'p', b'patch', None, _(b'show patch')),
7575 (b'g', b'git', None, _(b'use git extended diff format')),
7579 (b'g', b'git', None, _(b'use git extended diff format')),
7576 ]
7580 ]
7577 + templateopts,
7581 + templateopts,
7578 _(b'[-p] [-g]'),
7582 _(b'[-p] [-g]'),
7579 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
7583 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
7580 )
7584 )
7581 def tip(ui, repo, **opts):
7585 def tip(ui, repo, **opts):
7582 """show the tip revision (DEPRECATED)
7586 """show the tip revision (DEPRECATED)
7583
7587
7584 The tip revision (usually just called the tip) is the changeset
7588 The tip revision (usually just called the tip) is the changeset
7585 most recently added to the repository (and therefore the most
7589 most recently added to the repository (and therefore the most
7586 recently changed head).
7590 recently changed head).
7587
7591
7588 If you have just made a commit, that commit will be the tip. If
7592 If you have just made a commit, that commit will be the tip. If
7589 you have just pulled changes from another repository, the tip of
7593 you have just pulled changes from another repository, the tip of
7590 that repository becomes the current tip. The "tip" tag is special
7594 that repository becomes the current tip. The "tip" tag is special
7591 and cannot be renamed or assigned to a different changeset.
7595 and cannot be renamed or assigned to a different changeset.
7592
7596
7593 This command is deprecated, please use :hg:`heads` instead.
7597 This command is deprecated, please use :hg:`heads` instead.
7594
7598
7595 Returns 0 on success.
7599 Returns 0 on success.
7596 """
7600 """
7597 opts = pycompat.byteskwargs(opts)
7601 opts = pycompat.byteskwargs(opts)
7598 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
7602 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
7599 displayer.show(repo[b'tip'])
7603 displayer.show(repo[b'tip'])
7600 displayer.close()
7604 displayer.close()
7601
7605
7602
7606
7603 @command(
7607 @command(
7604 b'unbundle',
7608 b'unbundle',
7605 [
7609 [
7606 (
7610 (
7607 b'u',
7611 b'u',
7608 b'update',
7612 b'update',
7609 None,
7613 None,
7610 _(b'update to new branch head if changesets were unbundled'),
7614 _(b'update to new branch head if changesets were unbundled'),
7611 )
7615 )
7612 ],
7616 ],
7613 _(b'[-u] FILE...'),
7617 _(b'[-u] FILE...'),
7614 helpcategory=command.CATEGORY_IMPORT_EXPORT,
7618 helpcategory=command.CATEGORY_IMPORT_EXPORT,
7615 )
7619 )
7616 def unbundle(ui, repo, fname1, *fnames, **opts):
7620 def unbundle(ui, repo, fname1, *fnames, **opts):
7617 """apply one or more bundle files
7621 """apply one or more bundle files
7618
7622
7619 Apply one or more bundle files generated by :hg:`bundle`.
7623 Apply one or more bundle files generated by :hg:`bundle`.
7620
7624
7621 Returns 0 on success, 1 if an update has unresolved files.
7625 Returns 0 on success, 1 if an update has unresolved files.
7622 """
7626 """
7623 fnames = (fname1,) + fnames
7627 fnames = (fname1,) + fnames
7624
7628
7625 with repo.lock():
7629 with repo.lock():
7626 for fname in fnames:
7630 for fname in fnames:
7627 f = hg.openpath(ui, fname)
7631 f = hg.openpath(ui, fname)
7628 gen = exchange.readbundle(ui, f, fname)
7632 gen = exchange.readbundle(ui, f, fname)
7629 if isinstance(gen, streamclone.streamcloneapplier):
7633 if isinstance(gen, streamclone.streamcloneapplier):
7630 raise error.InputError(
7634 raise error.InputError(
7631 _(
7635 _(
7632 b'packed bundles cannot be applied with '
7636 b'packed bundles cannot be applied with '
7633 b'"hg unbundle"'
7637 b'"hg unbundle"'
7634 ),
7638 ),
7635 hint=_(b'use "hg debugapplystreamclonebundle"'),
7639 hint=_(b'use "hg debugapplystreamclonebundle"'),
7636 )
7640 )
7637 url = b'bundle:' + fname
7641 url = b'bundle:' + fname
7638 try:
7642 try:
7639 txnname = b'unbundle'
7643 txnname = b'unbundle'
7640 if not isinstance(gen, bundle2.unbundle20):
7644 if not isinstance(gen, bundle2.unbundle20):
7641 txnname = b'unbundle\n%s' % urlutil.hidepassword(url)
7645 txnname = b'unbundle\n%s' % urlutil.hidepassword(url)
7642 with repo.transaction(txnname) as tr:
7646 with repo.transaction(txnname) as tr:
7643 op = bundle2.applybundle(
7647 op = bundle2.applybundle(
7644 repo, gen, tr, source=b'unbundle', url=url
7648 repo, gen, tr, source=b'unbundle', url=url
7645 )
7649 )
7646 except error.BundleUnknownFeatureError as exc:
7650 except error.BundleUnknownFeatureError as exc:
7647 raise error.Abort(
7651 raise error.Abort(
7648 _(b'%s: unknown bundle feature, %s') % (fname, exc),
7652 _(b'%s: unknown bundle feature, %s') % (fname, exc),
7649 hint=_(
7653 hint=_(
7650 b"see https://mercurial-scm.org/"
7654 b"see https://mercurial-scm.org/"
7651 b"wiki/BundleFeature for more "
7655 b"wiki/BundleFeature for more "
7652 b"information"
7656 b"information"
7653 ),
7657 ),
7654 )
7658 )
7655 modheads = bundle2.combinechangegroupresults(op)
7659 modheads = bundle2.combinechangegroupresults(op)
7656
7660
7657 if postincoming(ui, repo, modheads, opts.get('update'), None, None):
7661 if postincoming(ui, repo, modheads, opts.get('update'), None, None):
7658 return 1
7662 return 1
7659 else:
7663 else:
7660 return 0
7664 return 0
7661
7665
7662
7666
7663 @command(
7667 @command(
7664 b'unshelve',
7668 b'unshelve',
7665 [
7669 [
7666 (b'a', b'abort', None, _(b'abort an incomplete unshelve operation')),
7670 (b'a', b'abort', None, _(b'abort an incomplete unshelve operation')),
7667 (
7671 (
7668 b'c',
7672 b'c',
7669 b'continue',
7673 b'continue',
7670 None,
7674 None,
7671 _(b'continue an incomplete unshelve operation'),
7675 _(b'continue an incomplete unshelve operation'),
7672 ),
7676 ),
7673 (b'i', b'interactive', None, _(b'use interactive mode (EXPERIMENTAL)')),
7677 (b'i', b'interactive', None, _(b'use interactive mode (EXPERIMENTAL)')),
7674 (b'k', b'keep', None, _(b'keep shelve after unshelving')),
7678 (b'k', b'keep', None, _(b'keep shelve after unshelving')),
7675 (
7679 (
7676 b'n',
7680 b'n',
7677 b'name',
7681 b'name',
7678 b'',
7682 b'',
7679 _(b'restore shelved change with given name'),
7683 _(b'restore shelved change with given name'),
7680 _(b'NAME'),
7684 _(b'NAME'),
7681 ),
7685 ),
7682 (b't', b'tool', b'', _(b'specify merge tool')),
7686 (b't', b'tool', b'', _(b'specify merge tool')),
7683 (
7687 (
7684 b'',
7688 b'',
7685 b'date',
7689 b'date',
7686 b'',
7690 b'',
7687 _(b'set date for temporary commits (DEPRECATED)'),
7691 _(b'set date for temporary commits (DEPRECATED)'),
7688 _(b'DATE'),
7692 _(b'DATE'),
7689 ),
7693 ),
7690 ],
7694 ],
7691 _(b'hg unshelve [OPTION]... [[-n] SHELVED]'),
7695 _(b'hg unshelve [OPTION]... [[-n] SHELVED]'),
7692 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7696 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7693 )
7697 )
7694 def unshelve(ui, repo, *shelved, **opts):
7698 def unshelve(ui, repo, *shelved, **opts):
7695 """restore a shelved change to the working directory
7699 """restore a shelved change to the working directory
7696
7700
7697 This command accepts an optional name of a shelved change to
7701 This command accepts an optional name of a shelved change to
7698 restore. If none is given, the most recent shelved change is used.
7702 restore. If none is given, the most recent shelved change is used.
7699
7703
7700 If a shelved change is applied successfully, the bundle that
7704 If a shelved change is applied successfully, the bundle that
7701 contains the shelved changes is moved to a backup location
7705 contains the shelved changes is moved to a backup location
7702 (.hg/shelve-backup).
7706 (.hg/shelve-backup).
7703
7707
7704 Since you can restore a shelved change on top of an arbitrary
7708 Since you can restore a shelved change on top of an arbitrary
7705 commit, it is possible that unshelving will result in a conflict
7709 commit, it is possible that unshelving will result in a conflict
7706 between your changes and the commits you are unshelving onto. If
7710 between your changes and the commits you are unshelving onto. If
7707 this occurs, you must resolve the conflict, then use
7711 this occurs, you must resolve the conflict, then use
7708 ``--continue`` to complete the unshelve operation. (The bundle
7712 ``--continue`` to complete the unshelve operation. (The bundle
7709 will not be moved until you successfully complete the unshelve.)
7713 will not be moved until you successfully complete the unshelve.)
7710
7714
7711 (Alternatively, you can use ``--abort`` to abandon an unshelve
7715 (Alternatively, you can use ``--abort`` to abandon an unshelve
7712 that causes a conflict. This reverts the unshelved changes, and
7716 that causes a conflict. This reverts the unshelved changes, and
7713 leaves the bundle in place.)
7717 leaves the bundle in place.)
7714
7718
7715 If bare shelved change (without interactive, include and exclude
7719 If bare shelved change (without interactive, include and exclude
7716 option) was done on newly created branch it would restore branch
7720 option) was done on newly created branch it would restore branch
7717 information to the working directory.
7721 information to the working directory.
7718
7722
7719 After a successful unshelve, the shelved changes are stored in a
7723 After a successful unshelve, the shelved changes are stored in a
7720 backup directory. Only the N most recent backups are kept. N
7724 backup directory. Only the N most recent backups are kept. N
7721 defaults to 10 but can be overridden using the ``shelve.maxbackups``
7725 defaults to 10 but can be overridden using the ``shelve.maxbackups``
7722 configuration option.
7726 configuration option.
7723
7727
7724 .. container:: verbose
7728 .. container:: verbose
7725
7729
7726 Timestamp in seconds is used to decide order of backups. More
7730 Timestamp in seconds is used to decide order of backups. More
7727 than ``maxbackups`` backups are kept, if same timestamp
7731 than ``maxbackups`` backups are kept, if same timestamp
7728 prevents from deciding exact order of them, for safety.
7732 prevents from deciding exact order of them, for safety.
7729
7733
7730 Selected changes can be unshelved with ``--interactive`` flag.
7734 Selected changes can be unshelved with ``--interactive`` flag.
7731 The working directory is updated with the selected changes, and
7735 The working directory is updated with the selected changes, and
7732 only the unselected changes remain shelved.
7736 only the unselected changes remain shelved.
7733 Note: The whole shelve is applied to working directory first before
7737 Note: The whole shelve is applied to working directory first before
7734 running interactively. So, this will bring up all the conflicts between
7738 running interactively. So, this will bring up all the conflicts between
7735 working directory and the shelve, irrespective of which changes will be
7739 working directory and the shelve, irrespective of which changes will be
7736 unshelved.
7740 unshelved.
7737 """
7741 """
7738 with repo.wlock():
7742 with repo.wlock():
7739 return shelvemod.unshelvecmd(ui, repo, *shelved, **opts)
7743 return shelvemod.unshelvecmd(ui, repo, *shelved, **opts)
7740
7744
7741
7745
7742 statemod.addunfinished(
7746 statemod.addunfinished(
7743 b'unshelve',
7747 b'unshelve',
7744 fname=b'shelvedstate',
7748 fname=b'shelvedstate',
7745 continueflag=True,
7749 continueflag=True,
7746 abortfunc=shelvemod.hgabortunshelve,
7750 abortfunc=shelvemod.hgabortunshelve,
7747 continuefunc=shelvemod.hgcontinueunshelve,
7751 continuefunc=shelvemod.hgcontinueunshelve,
7748 cmdmsg=_(b'unshelve already in progress'),
7752 cmdmsg=_(b'unshelve already in progress'),
7749 )
7753 )
7750
7754
7751
7755
7752 @command(
7756 @command(
7753 b'update|up|checkout|co',
7757 b'update|up|checkout|co',
7754 [
7758 [
7755 (b'C', b'clean', None, _(b'discard uncommitted changes (no backup)')),
7759 (b'C', b'clean', None, _(b'discard uncommitted changes (no backup)')),
7756 (b'c', b'check', None, _(b'require clean working directory')),
7760 (b'c', b'check', None, _(b'require clean working directory')),
7757 (b'm', b'merge', None, _(b'merge uncommitted changes')),
7761 (b'm', b'merge', None, _(b'merge uncommitted changes')),
7758 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
7762 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
7759 (b'r', b'rev', b'', _(b'revision'), _(b'REV')),
7763 (b'r', b'rev', b'', _(b'revision'), _(b'REV')),
7760 ]
7764 ]
7761 + mergetoolopts,
7765 + mergetoolopts,
7762 _(b'[-C|-c|-m] [-d DATE] [[-r] REV]'),
7766 _(b'[-C|-c|-m] [-d DATE] [[-r] REV]'),
7763 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7767 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7764 helpbasic=True,
7768 helpbasic=True,
7765 )
7769 )
7766 def update(ui, repo, node=None, **opts):
7770 def update(ui, repo, node=None, **opts):
7767 """update working directory (or switch revisions)
7771 """update working directory (or switch revisions)
7768
7772
7769 Update the repository's working directory to the specified
7773 Update the repository's working directory to the specified
7770 changeset. If no changeset is specified, update to the tip of the
7774 changeset. If no changeset is specified, update to the tip of the
7771 current named branch and move the active bookmark (see :hg:`help
7775 current named branch and move the active bookmark (see :hg:`help
7772 bookmarks`).
7776 bookmarks`).
7773
7777
7774 Update sets the working directory's parent revision to the specified
7778 Update sets the working directory's parent revision to the specified
7775 changeset (see :hg:`help parents`).
7779 changeset (see :hg:`help parents`).
7776
7780
7777 If the changeset is not a descendant or ancestor of the working
7781 If the changeset is not a descendant or ancestor of the working
7778 directory's parent and there are uncommitted changes, the update is
7782 directory's parent and there are uncommitted changes, the update is
7779 aborted. With the -c/--check option, the working directory is checked
7783 aborted. With the -c/--check option, the working directory is checked
7780 for uncommitted changes; if none are found, the working directory is
7784 for uncommitted changes; if none are found, the working directory is
7781 updated to the specified changeset.
7785 updated to the specified changeset.
7782
7786
7783 .. container:: verbose
7787 .. container:: verbose
7784
7788
7785 The -C/--clean, -c/--check, and -m/--merge options control what
7789 The -C/--clean, -c/--check, and -m/--merge options control what
7786 happens if the working directory contains uncommitted changes.
7790 happens if the working directory contains uncommitted changes.
7787 At most of one of them can be specified.
7791 At most of one of them can be specified.
7788
7792
7789 1. If no option is specified, and if
7793 1. If no option is specified, and if
7790 the requested changeset is an ancestor or descendant of
7794 the requested changeset is an ancestor or descendant of
7791 the working directory's parent, the uncommitted changes
7795 the working directory's parent, the uncommitted changes
7792 are merged into the requested changeset and the merged
7796 are merged into the requested changeset and the merged
7793 result is left uncommitted. If the requested changeset is
7797 result is left uncommitted. If the requested changeset is
7794 not an ancestor or descendant (that is, it is on another
7798 not an ancestor or descendant (that is, it is on another
7795 branch), the update is aborted and the uncommitted changes
7799 branch), the update is aborted and the uncommitted changes
7796 are preserved.
7800 are preserved.
7797
7801
7798 2. With the -m/--merge option, the update is allowed even if the
7802 2. With the -m/--merge option, the update is allowed even if the
7799 requested changeset is not an ancestor or descendant of
7803 requested changeset is not an ancestor or descendant of
7800 the working directory's parent.
7804 the working directory's parent.
7801
7805
7802 3. With the -c/--check option, the update is aborted and the
7806 3. With the -c/--check option, the update is aborted and the
7803 uncommitted changes are preserved.
7807 uncommitted changes are preserved.
7804
7808
7805 4. With the -C/--clean option, uncommitted changes are discarded and
7809 4. With the -C/--clean option, uncommitted changes are discarded and
7806 the working directory is updated to the requested changeset.
7810 the working directory is updated to the requested changeset.
7807
7811
7808 To cancel an uncommitted merge (and lose your changes), use
7812 To cancel an uncommitted merge (and lose your changes), use
7809 :hg:`merge --abort`.
7813 :hg:`merge --abort`.
7810
7814
7811 Use null as the changeset to remove the working directory (like
7815 Use null as the changeset to remove the working directory (like
7812 :hg:`clone -U`).
7816 :hg:`clone -U`).
7813
7817
7814 If you want to revert just one file to an older revision, use
7818 If you want to revert just one file to an older revision, use
7815 :hg:`revert [-r REV] NAME`.
7819 :hg:`revert [-r REV] NAME`.
7816
7820
7817 See :hg:`help dates` for a list of formats valid for -d/--date.
7821 See :hg:`help dates` for a list of formats valid for -d/--date.
7818
7822
7819 Returns 0 on success, 1 if there are unresolved files.
7823 Returns 0 on success, 1 if there are unresolved files.
7820 """
7824 """
7821 cmdutil.check_at_most_one_arg(opts, 'clean', 'check', 'merge')
7825 cmdutil.check_at_most_one_arg(opts, 'clean', 'check', 'merge')
7822 rev = opts.get('rev')
7826 rev = opts.get('rev')
7823 date = opts.get('date')
7827 date = opts.get('date')
7824 clean = opts.get('clean')
7828 clean = opts.get('clean')
7825 check = opts.get('check')
7829 check = opts.get('check')
7826 merge = opts.get('merge')
7830 merge = opts.get('merge')
7827 if rev and node:
7831 if rev and node:
7828 raise error.InputError(_(b"please specify just one revision"))
7832 raise error.InputError(_(b"please specify just one revision"))
7829
7833
7830 if ui.configbool(b'commands', b'update.requiredest'):
7834 if ui.configbool(b'commands', b'update.requiredest'):
7831 if not node and not rev and not date:
7835 if not node and not rev and not date:
7832 raise error.InputError(
7836 raise error.InputError(
7833 _(b'you must specify a destination'),
7837 _(b'you must specify a destination'),
7834 hint=_(b'for example: hg update ".::"'),
7838 hint=_(b'for example: hg update ".::"'),
7835 )
7839 )
7836
7840
7837 if rev is None or rev == b'':
7841 if rev is None or rev == b'':
7838 rev = node
7842 rev = node
7839
7843
7840 if date and rev is not None:
7844 if date and rev is not None:
7841 raise error.InputError(_(b"you can't specify a revision and a date"))
7845 raise error.InputError(_(b"you can't specify a revision and a date"))
7842
7846
7843 updatecheck = None
7847 updatecheck = None
7844 if check or merge is not None and not merge:
7848 if check or merge is not None and not merge:
7845 updatecheck = b'abort'
7849 updatecheck = b'abort'
7846 elif merge or check is not None and not check:
7850 elif merge or check is not None and not check:
7847 updatecheck = b'none'
7851 updatecheck = b'none'
7848
7852
7849 with repo.wlock():
7853 with repo.wlock():
7850 cmdutil.clearunfinished(repo)
7854 cmdutil.clearunfinished(repo)
7851 if date:
7855 if date:
7852 rev = cmdutil.finddate(ui, repo, date)
7856 rev = cmdutil.finddate(ui, repo, date)
7853
7857
7854 # if we defined a bookmark, we have to remember the original name
7858 # if we defined a bookmark, we have to remember the original name
7855 brev = rev
7859 brev = rev
7856 if rev:
7860 if rev:
7857 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
7861 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
7858 ctx = logcmdutil.revsingle(repo, rev, default=None)
7862 ctx = logcmdutil.revsingle(repo, rev, default=None)
7859 rev = ctx.rev()
7863 rev = ctx.rev()
7860 hidden = ctx.hidden()
7864 hidden = ctx.hidden()
7861 overrides = {(b'ui', b'forcemerge'): opts.get('tool', b'')}
7865 overrides = {(b'ui', b'forcemerge'): opts.get('tool', b'')}
7862 with ui.configoverride(overrides, b'update'):
7866 with ui.configoverride(overrides, b'update'):
7863 ret = hg.updatetotally(
7867 ret = hg.updatetotally(
7864 ui, repo, rev, brev, clean=clean, updatecheck=updatecheck
7868 ui, repo, rev, brev, clean=clean, updatecheck=updatecheck
7865 )
7869 )
7866 if hidden:
7870 if hidden:
7867 ctxstr = ctx.hex()[:12]
7871 ctxstr = ctx.hex()[:12]
7868 ui.warn(_(b"updated to hidden changeset %s\n") % ctxstr)
7872 ui.warn(_(b"updated to hidden changeset %s\n") % ctxstr)
7869
7873
7870 if ctx.obsolete():
7874 if ctx.obsolete():
7871 obsfatemsg = obsutil._getfilteredreason(repo, ctxstr, ctx)
7875 obsfatemsg = obsutil._getfilteredreason(repo, ctxstr, ctx)
7872 ui.warn(b"(%s)\n" % obsfatemsg)
7876 ui.warn(b"(%s)\n" % obsfatemsg)
7873 return ret
7877 return ret
7874
7878
7875
7879
7876 @command(
7880 @command(
7877 b'verify',
7881 b'verify',
7878 [(b'', b'full', False, b'perform more checks (EXPERIMENTAL)')],
7882 [(b'', b'full', False, b'perform more checks (EXPERIMENTAL)')],
7879 helpcategory=command.CATEGORY_MAINTENANCE,
7883 helpcategory=command.CATEGORY_MAINTENANCE,
7880 )
7884 )
7881 def verify(ui, repo, **opts):
7885 def verify(ui, repo, **opts):
7882 """verify the integrity of the repository
7886 """verify the integrity of the repository
7883
7887
7884 Verify the integrity of the current repository.
7888 Verify the integrity of the current repository.
7885
7889
7886 This will perform an extensive check of the repository's
7890 This will perform an extensive check of the repository's
7887 integrity, validating the hashes and checksums of each entry in
7891 integrity, validating the hashes and checksums of each entry in
7888 the changelog, manifest, and tracked files, as well as the
7892 the changelog, manifest, and tracked files, as well as the
7889 integrity of their crosslinks and indices.
7893 integrity of their crosslinks and indices.
7890
7894
7891 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
7895 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
7892 for more information about recovery from corruption of the
7896 for more information about recovery from corruption of the
7893 repository.
7897 repository.
7894
7898
7895 Returns 0 on success, 1 if errors are encountered.
7899 Returns 0 on success, 1 if errors are encountered.
7896 """
7900 """
7897 opts = pycompat.byteskwargs(opts)
7901 opts = pycompat.byteskwargs(opts)
7898
7902
7899 level = None
7903 level = None
7900 if opts[b'full']:
7904 if opts[b'full']:
7901 level = verifymod.VERIFY_FULL
7905 level = verifymod.VERIFY_FULL
7902 return hg.verify(repo, level)
7906 return hg.verify(repo, level)
7903
7907
7904
7908
7905 @command(
7909 @command(
7906 b'version',
7910 b'version',
7907 [] + formatteropts,
7911 [] + formatteropts,
7908 helpcategory=command.CATEGORY_HELP,
7912 helpcategory=command.CATEGORY_HELP,
7909 norepo=True,
7913 norepo=True,
7910 intents={INTENT_READONLY},
7914 intents={INTENT_READONLY},
7911 )
7915 )
7912 def version_(ui, **opts):
7916 def version_(ui, **opts):
7913 """output version and copyright information
7917 """output version and copyright information
7914
7918
7915 .. container:: verbose
7919 .. container:: verbose
7916
7920
7917 Template:
7921 Template:
7918
7922
7919 The following keywords are supported. See also :hg:`help templates`.
7923 The following keywords are supported. See also :hg:`help templates`.
7920
7924
7921 :extensions: List of extensions.
7925 :extensions: List of extensions.
7922 :ver: String. Version number.
7926 :ver: String. Version number.
7923
7927
7924 And each entry of ``{extensions}`` provides the following sub-keywords
7928 And each entry of ``{extensions}`` provides the following sub-keywords
7925 in addition to ``{ver}``.
7929 in addition to ``{ver}``.
7926
7930
7927 :bundled: Boolean. True if included in the release.
7931 :bundled: Boolean. True if included in the release.
7928 :name: String. Extension name.
7932 :name: String. Extension name.
7929 """
7933 """
7930 opts = pycompat.byteskwargs(opts)
7934 opts = pycompat.byteskwargs(opts)
7931 if ui.verbose:
7935 if ui.verbose:
7932 ui.pager(b'version')
7936 ui.pager(b'version')
7933 fm = ui.formatter(b"version", opts)
7937 fm = ui.formatter(b"version", opts)
7934 fm.startitem()
7938 fm.startitem()
7935 fm.write(
7939 fm.write(
7936 b"ver", _(b"Mercurial Distributed SCM (version %s)\n"), util.version()
7940 b"ver", _(b"Mercurial Distributed SCM (version %s)\n"), util.version()
7937 )
7941 )
7938 license = _(
7942 license = _(
7939 b"(see https://mercurial-scm.org for more information)\n"
7943 b"(see https://mercurial-scm.org for more information)\n"
7940 b"\nCopyright (C) 2005-2022 Olivia Mackall and others\n"
7944 b"\nCopyright (C) 2005-2022 Olivia Mackall and others\n"
7941 b"This is free software; see the source for copying conditions. "
7945 b"This is free software; see the source for copying conditions. "
7942 b"There is NO\nwarranty; "
7946 b"There is NO\nwarranty; "
7943 b"not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
7947 b"not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
7944 )
7948 )
7945 if not ui.quiet:
7949 if not ui.quiet:
7946 fm.plain(license)
7950 fm.plain(license)
7947
7951
7948 if ui.verbose:
7952 if ui.verbose:
7949 fm.plain(_(b"\nEnabled extensions:\n\n"))
7953 fm.plain(_(b"\nEnabled extensions:\n\n"))
7950 # format names and versions into columns
7954 # format names and versions into columns
7951 names = []
7955 names = []
7952 vers = []
7956 vers = []
7953 isinternals = []
7957 isinternals = []
7954 for name, module in sorted(extensions.extensions()):
7958 for name, module in sorted(extensions.extensions()):
7955 names.append(name)
7959 names.append(name)
7956 vers.append(extensions.moduleversion(module) or None)
7960 vers.append(extensions.moduleversion(module) or None)
7957 isinternals.append(extensions.ismoduleinternal(module))
7961 isinternals.append(extensions.ismoduleinternal(module))
7958 fn = fm.nested(b"extensions", tmpl=b'{name}\n')
7962 fn = fm.nested(b"extensions", tmpl=b'{name}\n')
7959 if names:
7963 if names:
7960 namefmt = b" %%-%ds " % max(len(n) for n in names)
7964 namefmt = b" %%-%ds " % max(len(n) for n in names)
7961 places = [_(b"external"), _(b"internal")]
7965 places = [_(b"external"), _(b"internal")]
7962 for n, v, p in zip(names, vers, isinternals):
7966 for n, v, p in zip(names, vers, isinternals):
7963 fn.startitem()
7967 fn.startitem()
7964 fn.condwrite(ui.verbose, b"name", namefmt, n)
7968 fn.condwrite(ui.verbose, b"name", namefmt, n)
7965 if ui.verbose:
7969 if ui.verbose:
7966 fn.plain(b"%s " % places[p])
7970 fn.plain(b"%s " % places[p])
7967 fn.data(bundled=p)
7971 fn.data(bundled=p)
7968 fn.condwrite(ui.verbose and v, b"ver", b"%s", v)
7972 fn.condwrite(ui.verbose and v, b"ver", b"%s", v)
7969 if ui.verbose:
7973 if ui.verbose:
7970 fn.plain(b"\n")
7974 fn.plain(b"\n")
7971 fn.end()
7975 fn.end()
7972 fm.end()
7976 fm.end()
7973
7977
7974
7978
7975 def loadcmdtable(ui, name, cmdtable):
7979 def loadcmdtable(ui, name, cmdtable):
7976 """Load command functions from specified cmdtable"""
7980 """Load command functions from specified cmdtable"""
7977 overrides = [cmd for cmd in cmdtable if cmd in table]
7981 overrides = [cmd for cmd in cmdtable if cmd in table]
7978 if overrides:
7982 if overrides:
7979 ui.warn(
7983 ui.warn(
7980 _(b"extension '%s' overrides commands: %s\n")
7984 _(b"extension '%s' overrides commands: %s\n")
7981 % (name, b" ".join(overrides))
7985 % (name, b" ".join(overrides))
7982 )
7986 )
7983 table.update(cmdtable)
7987 table.update(cmdtable)
General Comments 0
You need to be logged in to leave comments. Login now