##// END OF EJS Templates
path: pass `path` to `peer` in `hg identify`...
marmoute -
r50618:970491e6 default
parent child Browse files
Show More
@@ -1,7987 +1,7986 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 path = urlutil.get_unique_pull_path_obj(b'identify', ui, source)
3915 b'identify', repo, ui, source
3916 )
3917 # only pass ui when no repo
3915 # only pass ui when no repo
3918 peer = hg.peer(repo or ui, opts, source)
3916 peer = hg.peer(repo or ui, opts, path)
3919 repo = peer.local()
3917 repo = peer.local()
3918 branches = (path.branch, [])
3920 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3919 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3921
3920
3922 fm = ui.formatter(b'identify', opts)
3921 fm = ui.formatter(b'identify', opts)
3923 fm.startitem()
3922 fm.startitem()
3924
3923
3925 if not repo:
3924 if not repo:
3926 if num or branch or tags:
3925 if num or branch or tags:
3927 raise error.InputError(
3926 raise error.InputError(
3928 _(b"can't query remote revision number, branch, or tags")
3927 _(b"can't query remote revision number, branch, or tags")
3929 )
3928 )
3930 if not rev and revs:
3929 if not rev and revs:
3931 rev = revs[0]
3930 rev = revs[0]
3932 if not rev:
3931 if not rev:
3933 rev = b"tip"
3932 rev = b"tip"
3934
3933
3935 remoterev = peer.lookup(rev)
3934 remoterev = peer.lookup(rev)
3936 hexrev = fm.hexfunc(remoterev)
3935 hexrev = fm.hexfunc(remoterev)
3937 if default or id:
3936 if default or id:
3938 output = [hexrev]
3937 output = [hexrev]
3939 fm.data(id=hexrev)
3938 fm.data(id=hexrev)
3940
3939
3941 @util.cachefunc
3940 @util.cachefunc
3942 def getbms():
3941 def getbms():
3943 bms = []
3942 bms = []
3944
3943
3945 if b'bookmarks' in peer.listkeys(b'namespaces'):
3944 if b'bookmarks' in peer.listkeys(b'namespaces'):
3946 hexremoterev = hex(remoterev)
3945 hexremoterev = hex(remoterev)
3947 bms = [
3946 bms = [
3948 bm
3947 bm
3949 for bm, bmr in peer.listkeys(b'bookmarks').items()
3948 for bm, bmr in peer.listkeys(b'bookmarks').items()
3950 if bmr == hexremoterev
3949 if bmr == hexremoterev
3951 ]
3950 ]
3952
3951
3953 return sorted(bms)
3952 return sorted(bms)
3954
3953
3955 if fm.isplain():
3954 if fm.isplain():
3956 if bookmarks:
3955 if bookmarks:
3957 output.extend(getbms())
3956 output.extend(getbms())
3958 elif default and not ui.quiet:
3957 elif default and not ui.quiet:
3959 # multiple bookmarks for a single parent separated by '/'
3958 # multiple bookmarks for a single parent separated by '/'
3960 bm = b'/'.join(getbms())
3959 bm = b'/'.join(getbms())
3961 if bm:
3960 if bm:
3962 output.append(bm)
3961 output.append(bm)
3963 else:
3962 else:
3964 fm.data(node=hex(remoterev))
3963 fm.data(node=hex(remoterev))
3965 if bookmarks or b'bookmarks' in fm.datahint():
3964 if bookmarks or b'bookmarks' in fm.datahint():
3966 fm.data(bookmarks=fm.formatlist(getbms(), name=b'bookmark'))
3965 fm.data(bookmarks=fm.formatlist(getbms(), name=b'bookmark'))
3967 else:
3966 else:
3968 if rev:
3967 if rev:
3969 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
3968 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
3970 ctx = logcmdutil.revsingle(repo, rev, None)
3969 ctx = logcmdutil.revsingle(repo, rev, None)
3971
3970
3972 if ctx.rev() is None:
3971 if ctx.rev() is None:
3973 ctx = repo[None]
3972 ctx = repo[None]
3974 parents = ctx.parents()
3973 parents = ctx.parents()
3975 taglist = []
3974 taglist = []
3976 for p in parents:
3975 for p in parents:
3977 taglist.extend(p.tags())
3976 taglist.extend(p.tags())
3978
3977
3979 dirty = b""
3978 dirty = b""
3980 if ctx.dirty(missing=True, merge=False, branch=False):
3979 if ctx.dirty(missing=True, merge=False, branch=False):
3981 dirty = b'+'
3980 dirty = b'+'
3982 fm.data(dirty=dirty)
3981 fm.data(dirty=dirty)
3983
3982
3984 hexoutput = [fm.hexfunc(p.node()) for p in parents]
3983 hexoutput = [fm.hexfunc(p.node()) for p in parents]
3985 if default or id:
3984 if default or id:
3986 output = [b"%s%s" % (b'+'.join(hexoutput), dirty)]
3985 output = [b"%s%s" % (b'+'.join(hexoutput), dirty)]
3987 fm.data(id=b"%s%s" % (b'+'.join(hexoutput), dirty))
3986 fm.data(id=b"%s%s" % (b'+'.join(hexoutput), dirty))
3988
3987
3989 if num:
3988 if num:
3990 numoutput = [b"%d" % p.rev() for p in parents]
3989 numoutput = [b"%d" % p.rev() for p in parents]
3991 output.append(b"%s%s" % (b'+'.join(numoutput), dirty))
3990 output.append(b"%s%s" % (b'+'.join(numoutput), dirty))
3992
3991
3993 fm.data(
3992 fm.data(
3994 parents=fm.formatlist(
3993 parents=fm.formatlist(
3995 [fm.hexfunc(p.node()) for p in parents], name=b'node'
3994 [fm.hexfunc(p.node()) for p in parents], name=b'node'
3996 )
3995 )
3997 )
3996 )
3998 else:
3997 else:
3999 hexoutput = fm.hexfunc(ctx.node())
3998 hexoutput = fm.hexfunc(ctx.node())
4000 if default or id:
3999 if default or id:
4001 output = [hexoutput]
4000 output = [hexoutput]
4002 fm.data(id=hexoutput)
4001 fm.data(id=hexoutput)
4003
4002
4004 if num:
4003 if num:
4005 output.append(pycompat.bytestr(ctx.rev()))
4004 output.append(pycompat.bytestr(ctx.rev()))
4006 taglist = ctx.tags()
4005 taglist = ctx.tags()
4007
4006
4008 if default and not ui.quiet:
4007 if default and not ui.quiet:
4009 b = ctx.branch()
4008 b = ctx.branch()
4010 if b != b'default':
4009 if b != b'default':
4011 output.append(b"(%s)" % b)
4010 output.append(b"(%s)" % b)
4012
4011
4013 # multiple tags for a single parent separated by '/'
4012 # multiple tags for a single parent separated by '/'
4014 t = b'/'.join(taglist)
4013 t = b'/'.join(taglist)
4015 if t:
4014 if t:
4016 output.append(t)
4015 output.append(t)
4017
4016
4018 # multiple bookmarks for a single parent separated by '/'
4017 # multiple bookmarks for a single parent separated by '/'
4019 bm = b'/'.join(ctx.bookmarks())
4018 bm = b'/'.join(ctx.bookmarks())
4020 if bm:
4019 if bm:
4021 output.append(bm)
4020 output.append(bm)
4022 else:
4021 else:
4023 if branch:
4022 if branch:
4024 output.append(ctx.branch())
4023 output.append(ctx.branch())
4025
4024
4026 if tags:
4025 if tags:
4027 output.extend(taglist)
4026 output.extend(taglist)
4028
4027
4029 if bookmarks:
4028 if bookmarks:
4030 output.extend(ctx.bookmarks())
4029 output.extend(ctx.bookmarks())
4031
4030
4032 fm.data(node=ctx.hex())
4031 fm.data(node=ctx.hex())
4033 fm.data(branch=ctx.branch())
4032 fm.data(branch=ctx.branch())
4034 fm.data(tags=fm.formatlist(taglist, name=b'tag', sep=b':'))
4033 fm.data(tags=fm.formatlist(taglist, name=b'tag', sep=b':'))
4035 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name=b'bookmark'))
4034 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name=b'bookmark'))
4036 fm.context(ctx=ctx)
4035 fm.context(ctx=ctx)
4037
4036
4038 fm.plain(b"%s\n" % b' '.join(output))
4037 fm.plain(b"%s\n" % b' '.join(output))
4039 fm.end()
4038 fm.end()
4040 finally:
4039 finally:
4041 if peer:
4040 if peer:
4042 peer.close()
4041 peer.close()
4043
4042
4044
4043
4045 @command(
4044 @command(
4046 b'import|patch',
4045 b'import|patch',
4047 [
4046 [
4048 (
4047 (
4049 b'p',
4048 b'p',
4050 b'strip',
4049 b'strip',
4051 1,
4050 1,
4052 _(
4051 _(
4053 b'directory strip option for patch. This has the same '
4052 b'directory strip option for patch. This has the same '
4054 b'meaning as the corresponding patch option'
4053 b'meaning as the corresponding patch option'
4055 ),
4054 ),
4056 _(b'NUM'),
4055 _(b'NUM'),
4057 ),
4056 ),
4058 (b'b', b'base', b'', _(b'base path (DEPRECATED)'), _(b'PATH')),
4057 (b'b', b'base', b'', _(b'base path (DEPRECATED)'), _(b'PATH')),
4059 (b'', b'secret', None, _(b'use the secret phase for committing')),
4058 (b'', b'secret', None, _(b'use the secret phase for committing')),
4060 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
4059 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
4061 (
4060 (
4062 b'f',
4061 b'f',
4063 b'force',
4062 b'force',
4064 None,
4063 None,
4065 _(b'skip check for outstanding uncommitted changes (DEPRECATED)'),
4064 _(b'skip check for outstanding uncommitted changes (DEPRECATED)'),
4066 ),
4065 ),
4067 (
4066 (
4068 b'',
4067 b'',
4069 b'no-commit',
4068 b'no-commit',
4070 None,
4069 None,
4071 _(b"don't commit, just update the working directory"),
4070 _(b"don't commit, just update the working directory"),
4072 ),
4071 ),
4073 (
4072 (
4074 b'',
4073 b'',
4075 b'bypass',
4074 b'bypass',
4076 None,
4075 None,
4077 _(b"apply patch without touching the working directory"),
4076 _(b"apply patch without touching the working directory"),
4078 ),
4077 ),
4079 (b'', b'partial', None, _(b'commit even if some hunks fail')),
4078 (b'', b'partial', None, _(b'commit even if some hunks fail')),
4080 (b'', b'exact', None, _(b'abort if patch would apply lossily')),
4079 (b'', b'exact', None, _(b'abort if patch would apply lossily')),
4081 (b'', b'prefix', b'', _(b'apply patch to subdirectory'), _(b'DIR')),
4080 (b'', b'prefix', b'', _(b'apply patch to subdirectory'), _(b'DIR')),
4082 (
4081 (
4083 b'',
4082 b'',
4084 b'import-branch',
4083 b'import-branch',
4085 None,
4084 None,
4086 _(b'use any branch information in patch (implied by --exact)'),
4085 _(b'use any branch information in patch (implied by --exact)'),
4087 ),
4086 ),
4088 ]
4087 ]
4089 + commitopts
4088 + commitopts
4090 + commitopts2
4089 + commitopts2
4091 + similarityopts,
4090 + similarityopts,
4092 _(b'[OPTION]... PATCH...'),
4091 _(b'[OPTION]... PATCH...'),
4093 helpcategory=command.CATEGORY_IMPORT_EXPORT,
4092 helpcategory=command.CATEGORY_IMPORT_EXPORT,
4094 )
4093 )
4095 def import_(ui, repo, patch1=None, *patches, **opts):
4094 def import_(ui, repo, patch1=None, *patches, **opts):
4096 """import an ordered set of patches
4095 """import an ordered set of patches
4097
4096
4098 Import a list of patches and commit them individually (unless
4097 Import a list of patches and commit them individually (unless
4099 --no-commit is specified).
4098 --no-commit is specified).
4100
4099
4101 To read a patch from standard input (stdin), use "-" as the patch
4100 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
4101 name. If a URL is specified, the patch will be downloaded from
4103 there.
4102 there.
4104
4103
4105 Import first applies changes to the working directory (unless
4104 Import first applies changes to the working directory (unless
4106 --bypass is specified), import will abort if there are outstanding
4105 --bypass is specified), import will abort if there are outstanding
4107 changes.
4106 changes.
4108
4107
4109 Use --bypass to apply and commit patches directly to the
4108 Use --bypass to apply and commit patches directly to the
4110 repository, without affecting the working directory. Without
4109 repository, without affecting the working directory. Without
4111 --exact, patches will be applied on top of the working directory
4110 --exact, patches will be applied on top of the working directory
4112 parent revision.
4111 parent revision.
4113
4112
4114 You can import a patch straight from a mail message. Even patches
4113 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
4114 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
4115 text/plain or text/x-patch). From and Subject headers of email
4117 message are used as default committer and commit message. All
4116 message are used as default committer and commit message. All
4118 text/plain body parts before first diff are added to the commit
4117 text/plain body parts before first diff are added to the commit
4119 message.
4118 message.
4120
4119
4121 If the imported patch was generated by :hg:`export`, user and
4120 If the imported patch was generated by :hg:`export`, user and
4122 description from patch override values from message headers and
4121 description from patch override values from message headers and
4123 body. Values given on command line with -m/--message and -u/--user
4122 body. Values given on command line with -m/--message and -u/--user
4124 override these.
4123 override these.
4125
4124
4126 If --exact is specified, import will set the working directory to
4125 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
4126 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
4127 resulting changeset has a different ID than the one recorded in
4129 the patch. This will guard against various ways that portable
4128 the patch. This will guard against various ways that portable
4130 patch formats and mail systems might fail to transfer Mercurial
4129 patch formats and mail systems might fail to transfer Mercurial
4131 data or metadata. See :hg:`bundle` for lossless transmission.
4130 data or metadata. See :hg:`bundle` for lossless transmission.
4132
4131
4133 Use --partial to ensure a changeset will be created from the patch
4132 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
4133 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
4134 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
4135 by hand before :hg:`commit --amend` is run to update the created
4137 changeset. This flag exists to let people import patches that
4136 changeset. This flag exists to let people import patches that
4138 partially apply without losing the associated metadata (author,
4137 partially apply without losing the associated metadata (author,
4139 date, description, ...).
4138 date, description, ...).
4140
4139
4141 .. note::
4140 .. note::
4142
4141
4143 When no hunks apply cleanly, :hg:`import --partial` will create
4142 When no hunks apply cleanly, :hg:`import --partial` will create
4144 an empty changeset, importing only the patch metadata.
4143 an empty changeset, importing only the patch metadata.
4145
4144
4146 With -s/--similarity, hg will attempt to discover renames and
4145 With -s/--similarity, hg will attempt to discover renames and
4147 copies in the patch in the same way as :hg:`addremove`.
4146 copies in the patch in the same way as :hg:`addremove`.
4148
4147
4149 It is possible to use external patch programs to perform the patch
4148 It is possible to use external patch programs to perform the patch
4150 by setting the ``ui.patch`` configuration option. For the default
4149 by setting the ``ui.patch`` configuration option. For the default
4151 internal tool, the fuzz can also be configured via ``patch.fuzz``.
4150 internal tool, the fuzz can also be configured via ``patch.fuzz``.
4152 See :hg:`help config` for more information about configuration
4151 See :hg:`help config` for more information about configuration
4153 files and how to use these options.
4152 files and how to use these options.
4154
4153
4155 See :hg:`help dates` for a list of formats valid for -d/--date.
4154 See :hg:`help dates` for a list of formats valid for -d/--date.
4156
4155
4157 .. container:: verbose
4156 .. container:: verbose
4158
4157
4159 Examples:
4158 Examples:
4160
4159
4161 - import a traditional patch from a website and detect renames::
4160 - import a traditional patch from a website and detect renames::
4162
4161
4163 hg import -s 80 http://example.com/bugfix.patch
4162 hg import -s 80 http://example.com/bugfix.patch
4164
4163
4165 - import a changeset from an hgweb server::
4164 - import a changeset from an hgweb server::
4166
4165
4167 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
4166 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
4168
4167
4169 - import all the patches in an Unix-style mbox::
4168 - import all the patches in an Unix-style mbox::
4170
4169
4171 hg import incoming-patches.mbox
4170 hg import incoming-patches.mbox
4172
4171
4173 - import patches from stdin::
4172 - import patches from stdin::
4174
4173
4175 hg import -
4174 hg import -
4176
4175
4177 - attempt to exactly restore an exported changeset (not always
4176 - attempt to exactly restore an exported changeset (not always
4178 possible)::
4177 possible)::
4179
4178
4180 hg import --exact proposed-fix.patch
4179 hg import --exact proposed-fix.patch
4181
4180
4182 - use an external tool to apply a patch which is too fuzzy for
4181 - use an external tool to apply a patch which is too fuzzy for
4183 the default internal tool.
4182 the default internal tool.
4184
4183
4185 hg import --config ui.patch="patch --merge" fuzzy.patch
4184 hg import --config ui.patch="patch --merge" fuzzy.patch
4186
4185
4187 - change the default fuzzing from 2 to a less strict 7
4186 - change the default fuzzing from 2 to a less strict 7
4188
4187
4189 hg import --config ui.fuzz=7 fuzz.patch
4188 hg import --config ui.fuzz=7 fuzz.patch
4190
4189
4191 Returns 0 on success, 1 on partial success (see --partial).
4190 Returns 0 on success, 1 on partial success (see --partial).
4192 """
4191 """
4193
4192
4194 cmdutil.check_incompatible_arguments(
4193 cmdutil.check_incompatible_arguments(
4195 opts, 'no_commit', ['bypass', 'secret']
4194 opts, 'no_commit', ['bypass', 'secret']
4196 )
4195 )
4197 cmdutil.check_incompatible_arguments(opts, 'exact', ['edit', 'prefix'])
4196 cmdutil.check_incompatible_arguments(opts, 'exact', ['edit', 'prefix'])
4198 opts = pycompat.byteskwargs(opts)
4197 opts = pycompat.byteskwargs(opts)
4199 if not patch1:
4198 if not patch1:
4200 raise error.InputError(_(b'need at least one patch to import'))
4199 raise error.InputError(_(b'need at least one patch to import'))
4201
4200
4202 patches = (patch1,) + patches
4201 patches = (patch1,) + patches
4203
4202
4204 date = opts.get(b'date')
4203 date = opts.get(b'date')
4205 if date:
4204 if date:
4206 opts[b'date'] = dateutil.parsedate(date)
4205 opts[b'date'] = dateutil.parsedate(date)
4207
4206
4208 exact = opts.get(b'exact')
4207 exact = opts.get(b'exact')
4209 update = not opts.get(b'bypass')
4208 update = not opts.get(b'bypass')
4210 try:
4209 try:
4211 sim = float(opts.get(b'similarity') or 0)
4210 sim = float(opts.get(b'similarity') or 0)
4212 except ValueError:
4211 except ValueError:
4213 raise error.InputError(_(b'similarity must be a number'))
4212 raise error.InputError(_(b'similarity must be a number'))
4214 if sim < 0 or sim > 100:
4213 if sim < 0 or sim > 100:
4215 raise error.InputError(_(b'similarity must be between 0 and 100'))
4214 raise error.InputError(_(b'similarity must be between 0 and 100'))
4216 if sim and not update:
4215 if sim and not update:
4217 raise error.InputError(_(b'cannot use --similarity with --bypass'))
4216 raise error.InputError(_(b'cannot use --similarity with --bypass'))
4218
4217
4219 base = opts[b"base"]
4218 base = opts[b"base"]
4220 msgs = []
4219 msgs = []
4221 ret = 0
4220 ret = 0
4222
4221
4223 with repo.wlock():
4222 with repo.wlock():
4224 if update:
4223 if update:
4225 cmdutil.checkunfinished(repo)
4224 cmdutil.checkunfinished(repo)
4226 if exact or not opts.get(b'force'):
4225 if exact or not opts.get(b'force'):
4227 cmdutil.bailifchanged(repo)
4226 cmdutil.bailifchanged(repo)
4228
4227
4229 if not opts.get(b'no_commit'):
4228 if not opts.get(b'no_commit'):
4230 lock = repo.lock
4229 lock = repo.lock
4231 tr = lambda: repo.transaction(b'import')
4230 tr = lambda: repo.transaction(b'import')
4232 dsguard = util.nullcontextmanager
4231 dsguard = util.nullcontextmanager
4233 else:
4232 else:
4234 lock = util.nullcontextmanager
4233 lock = util.nullcontextmanager
4235 tr = util.nullcontextmanager
4234 tr = util.nullcontextmanager
4236 dsguard = lambda: dirstateguard.dirstateguard(repo, b'import')
4235 dsguard = lambda: dirstateguard.dirstateguard(repo, b'import')
4237 with lock(), tr(), dsguard():
4236 with lock(), tr(), dsguard():
4238 parents = repo[None].parents()
4237 parents = repo[None].parents()
4239 for patchurl in patches:
4238 for patchurl in patches:
4240 if patchurl == b'-':
4239 if patchurl == b'-':
4241 ui.status(_(b'applying patch from stdin\n'))
4240 ui.status(_(b'applying patch from stdin\n'))
4242 patchfile = ui.fin
4241 patchfile = ui.fin
4243 patchurl = b'stdin' # for error message
4242 patchurl = b'stdin' # for error message
4244 else:
4243 else:
4245 patchurl = os.path.join(base, patchurl)
4244 patchurl = os.path.join(base, patchurl)
4246 ui.status(_(b'applying %s\n') % patchurl)
4245 ui.status(_(b'applying %s\n') % patchurl)
4247 patchfile = hg.openpath(ui, patchurl, sendaccept=False)
4246 patchfile = hg.openpath(ui, patchurl, sendaccept=False)
4248
4247
4249 haspatch = False
4248 haspatch = False
4250 for hunk in patch.split(patchfile):
4249 for hunk in patch.split(patchfile):
4251 with patch.extract(ui, hunk) as patchdata:
4250 with patch.extract(ui, hunk) as patchdata:
4252 msg, node, rej = cmdutil.tryimportone(
4251 msg, node, rej = cmdutil.tryimportone(
4253 ui, repo, patchdata, parents, opts, msgs, hg.clean
4252 ui, repo, patchdata, parents, opts, msgs, hg.clean
4254 )
4253 )
4255 if msg:
4254 if msg:
4256 haspatch = True
4255 haspatch = True
4257 ui.note(msg + b'\n')
4256 ui.note(msg + b'\n')
4258 if update or exact:
4257 if update or exact:
4259 parents = repo[None].parents()
4258 parents = repo[None].parents()
4260 else:
4259 else:
4261 parents = [repo[node]]
4260 parents = [repo[node]]
4262 if rej:
4261 if rej:
4263 ui.write_err(_(b"patch applied partially\n"))
4262 ui.write_err(_(b"patch applied partially\n"))
4264 ui.write_err(
4263 ui.write_err(
4265 _(
4264 _(
4266 b"(fix the .rej files and run "
4265 b"(fix the .rej files and run "
4267 b"`hg commit --amend`)\n"
4266 b"`hg commit --amend`)\n"
4268 )
4267 )
4269 )
4268 )
4270 ret = 1
4269 ret = 1
4271 break
4270 break
4272
4271
4273 if not haspatch:
4272 if not haspatch:
4274 raise error.InputError(_(b'%s: no diffs found') % patchurl)
4273 raise error.InputError(_(b'%s: no diffs found') % patchurl)
4275
4274
4276 if msgs:
4275 if msgs:
4277 repo.savecommitmessage(b'\n* * *\n'.join(msgs))
4276 repo.savecommitmessage(b'\n* * *\n'.join(msgs))
4278 return ret
4277 return ret
4279
4278
4280
4279
4281 @command(
4280 @command(
4282 b'incoming|in',
4281 b'incoming|in',
4283 [
4282 [
4284 (
4283 (
4285 b'f',
4284 b'f',
4286 b'force',
4285 b'force',
4287 None,
4286 None,
4288 _(b'run even if remote repository is unrelated'),
4287 _(b'run even if remote repository is unrelated'),
4289 ),
4288 ),
4290 (b'n', b'newest-first', None, _(b'show newest record first')),
4289 (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')),
4290 (b'', b'bundle', b'', _(b'file to store the bundles into'), _(b'FILE')),
4292 (
4291 (
4293 b'r',
4292 b'r',
4294 b'rev',
4293 b'rev',
4295 [],
4294 [],
4296 _(b'a remote changeset intended to be added'),
4295 _(b'a remote changeset intended to be added'),
4297 _(b'REV'),
4296 _(b'REV'),
4298 ),
4297 ),
4299 (b'B', b'bookmarks', False, _(b"compare bookmarks")),
4298 (b'B', b'bookmarks', False, _(b"compare bookmarks")),
4300 (
4299 (
4301 b'b',
4300 b'b',
4302 b'branch',
4301 b'branch',
4303 [],
4302 [],
4304 _(b'a specific branch you would like to pull'),
4303 _(b'a specific branch you would like to pull'),
4305 _(b'BRANCH'),
4304 _(b'BRANCH'),
4306 ),
4305 ),
4307 ]
4306 ]
4308 + logopts
4307 + logopts
4309 + remoteopts
4308 + remoteopts
4310 + subrepoopts,
4309 + subrepoopts,
4311 _(b'[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'),
4310 _(b'[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'),
4312 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4311 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4313 )
4312 )
4314 def incoming(ui, repo, source=b"default", **opts):
4313 def incoming(ui, repo, source=b"default", **opts):
4315 """show new changesets found in source
4314 """show new changesets found in source
4316
4315
4317 Show new changesets found in the specified path/URL or the default
4316 Show new changesets found in the specified path/URL or the default
4318 pull location. These are the changesets that would have been pulled
4317 pull location. These are the changesets that would have been pulled
4319 by :hg:`pull` at the time you issued this command.
4318 by :hg:`pull` at the time you issued this command.
4320
4319
4321 See pull for valid source format details.
4320 See pull for valid source format details.
4322
4321
4323 .. container:: verbose
4322 .. container:: verbose
4324
4323
4325 With -B/--bookmarks, the result of bookmark comparison between
4324 With -B/--bookmarks, the result of bookmark comparison between
4326 local and remote repositories is displayed. With -v/--verbose,
4325 local and remote repositories is displayed. With -v/--verbose,
4327 status is also displayed for each bookmark like below::
4326 status is also displayed for each bookmark like below::
4328
4327
4329 BM1 01234567890a added
4328 BM1 01234567890a added
4330 BM2 1234567890ab advanced
4329 BM2 1234567890ab advanced
4331 BM3 234567890abc diverged
4330 BM3 234567890abc diverged
4332 BM4 34567890abcd changed
4331 BM4 34567890abcd changed
4333
4332
4334 The action taken locally when pulling depends on the
4333 The action taken locally when pulling depends on the
4335 status of each bookmark:
4334 status of each bookmark:
4336
4335
4337 :``added``: pull will create it
4336 :``added``: pull will create it
4338 :``advanced``: pull will update it
4337 :``advanced``: pull will update it
4339 :``diverged``: pull will create a divergent bookmark
4338 :``diverged``: pull will create a divergent bookmark
4340 :``changed``: result depends on remote changesets
4339 :``changed``: result depends on remote changesets
4341
4340
4342 From the point of view of pulling behavior, bookmark
4341 From the point of view of pulling behavior, bookmark
4343 existing only in the remote repository are treated as ``added``,
4342 existing only in the remote repository are treated as ``added``,
4344 even if it is in fact locally deleted.
4343 even if it is in fact locally deleted.
4345
4344
4346 .. container:: verbose
4345 .. container:: verbose
4347
4346
4348 For remote repository, using --bundle avoids downloading the
4347 For remote repository, using --bundle avoids downloading the
4349 changesets twice if the incoming is followed by a pull.
4348 changesets twice if the incoming is followed by a pull.
4350
4349
4351 Examples:
4350 Examples:
4352
4351
4353 - show incoming changes with patches and full description::
4352 - show incoming changes with patches and full description::
4354
4353
4355 hg incoming -vp
4354 hg incoming -vp
4356
4355
4357 - show incoming changes excluding merges, store a bundle::
4356 - show incoming changes excluding merges, store a bundle::
4358
4357
4359 hg in -vpM --bundle incoming.hg
4358 hg in -vpM --bundle incoming.hg
4360 hg pull incoming.hg
4359 hg pull incoming.hg
4361
4360
4362 - briefly list changes inside a bundle::
4361 - briefly list changes inside a bundle::
4363
4362
4364 hg in changes.hg -T "{desc|firstline}\\n"
4363 hg in changes.hg -T "{desc|firstline}\\n"
4365
4364
4366 Returns 0 if there are incoming changes, 1 otherwise.
4365 Returns 0 if there are incoming changes, 1 otherwise.
4367 """
4366 """
4368 opts = pycompat.byteskwargs(opts)
4367 opts = pycompat.byteskwargs(opts)
4369 if opts.get(b'graph'):
4368 if opts.get(b'graph'):
4370 logcmdutil.checkunsupportedgraphflags([], opts)
4369 logcmdutil.checkunsupportedgraphflags([], opts)
4371
4370
4372 def display(other, chlist, displayer):
4371 def display(other, chlist, displayer):
4373 revdag = logcmdutil.graphrevs(other, chlist, opts)
4372 revdag = logcmdutil.graphrevs(other, chlist, opts)
4374 logcmdutil.displaygraph(
4373 logcmdutil.displaygraph(
4375 ui, repo, revdag, displayer, graphmod.asciiedges
4374 ui, repo, revdag, displayer, graphmod.asciiedges
4376 )
4375 )
4377
4376
4378 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4377 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4379 return 0
4378 return 0
4380
4379
4381 cmdutil.check_incompatible_arguments(opts, b'subrepos', [b'bundle'])
4380 cmdutil.check_incompatible_arguments(opts, b'subrepos', [b'bundle'])
4382
4381
4383 if opts.get(b'bookmarks'):
4382 if opts.get(b'bookmarks'):
4384 srcs = urlutil.get_pull_paths(repo, ui, [source])
4383 srcs = urlutil.get_pull_paths(repo, ui, [source])
4385 for path in srcs:
4384 for path in srcs:
4386 # XXX the "branches" options are not used. Should it be used?
4385 # XXX the "branches" options are not used. Should it be used?
4387 other = hg.peer(repo, opts, path)
4386 other = hg.peer(repo, opts, path)
4388 try:
4387 try:
4389 if b'bookmarks' not in other.listkeys(b'namespaces'):
4388 if b'bookmarks' not in other.listkeys(b'namespaces'):
4390 ui.warn(_(b"remote doesn't support bookmarks\n"))
4389 ui.warn(_(b"remote doesn't support bookmarks\n"))
4391 return 0
4390 return 0
4392 ui.pager(b'incoming')
4391 ui.pager(b'incoming')
4393 ui.status(
4392 ui.status(
4394 _(b'comparing with %s\n') % urlutil.hidepassword(path.loc)
4393 _(b'comparing with %s\n') % urlutil.hidepassword(path.loc)
4395 )
4394 )
4396 return bookmarks.incoming(
4395 return bookmarks.incoming(
4397 ui, repo, other, mode=path.bookmarks_mode
4396 ui, repo, other, mode=path.bookmarks_mode
4398 )
4397 )
4399 finally:
4398 finally:
4400 other.close()
4399 other.close()
4401
4400
4402 return hg.incoming(ui, repo, source, opts)
4401 return hg.incoming(ui, repo, source, opts)
4403
4402
4404
4403
4405 @command(
4404 @command(
4406 b'init',
4405 b'init',
4407 remoteopts,
4406 remoteopts,
4408 _(b'[-e CMD] [--remotecmd CMD] [DEST]'),
4407 _(b'[-e CMD] [--remotecmd CMD] [DEST]'),
4409 helpcategory=command.CATEGORY_REPO_CREATION,
4408 helpcategory=command.CATEGORY_REPO_CREATION,
4410 helpbasic=True,
4409 helpbasic=True,
4411 norepo=True,
4410 norepo=True,
4412 )
4411 )
4413 def init(ui, dest=b".", **opts):
4412 def init(ui, dest=b".", **opts):
4414 """create a new repository in the given directory
4413 """create a new repository in the given directory
4415
4414
4416 Initialize a new repository in the given directory. If the given
4415 Initialize a new repository in the given directory. If the given
4417 directory does not exist, it will be created.
4416 directory does not exist, it will be created.
4418
4417
4419 If no directory is given, the current directory is used.
4418 If no directory is given, the current directory is used.
4420
4419
4421 It is possible to specify an ``ssh://`` URL as the destination.
4420 It is possible to specify an ``ssh://`` URL as the destination.
4422 See :hg:`help urls` for more information.
4421 See :hg:`help urls` for more information.
4423
4422
4424 Returns 0 on success.
4423 Returns 0 on success.
4425 """
4424 """
4426 opts = pycompat.byteskwargs(opts)
4425 opts = pycompat.byteskwargs(opts)
4427 path = urlutil.get_clone_path(ui, dest)[1]
4426 path = urlutil.get_clone_path(ui, dest)[1]
4428 peer = hg.peer(ui, opts, path, create=True)
4427 peer = hg.peer(ui, opts, path, create=True)
4429 peer.close()
4428 peer.close()
4430
4429
4431
4430
4432 @command(
4431 @command(
4433 b'locate',
4432 b'locate',
4434 [
4433 [
4435 (
4434 (
4436 b'r',
4435 b'r',
4437 b'rev',
4436 b'rev',
4438 b'',
4437 b'',
4439 _(b'search the repository as it is in REV'),
4438 _(b'search the repository as it is in REV'),
4440 _(b'REV'),
4439 _(b'REV'),
4441 ),
4440 ),
4442 (
4441 (
4443 b'0',
4442 b'0',
4444 b'print0',
4443 b'print0',
4445 None,
4444 None,
4446 _(b'end filenames with NUL, for use with xargs'),
4445 _(b'end filenames with NUL, for use with xargs'),
4447 ),
4446 ),
4448 (
4447 (
4449 b'f',
4448 b'f',
4450 b'fullpath',
4449 b'fullpath',
4451 None,
4450 None,
4452 _(b'print complete paths from the filesystem root'),
4451 _(b'print complete paths from the filesystem root'),
4453 ),
4452 ),
4454 ]
4453 ]
4455 + walkopts,
4454 + walkopts,
4456 _(b'[OPTION]... [PATTERN]...'),
4455 _(b'[OPTION]... [PATTERN]...'),
4457 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
4456 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
4458 )
4457 )
4459 def locate(ui, repo, *pats, **opts):
4458 def locate(ui, repo, *pats, **opts):
4460 """locate files matching specific patterns (DEPRECATED)
4459 """locate files matching specific patterns (DEPRECATED)
4461
4460
4462 Print files under Mercurial control in the working directory whose
4461 Print files under Mercurial control in the working directory whose
4463 names match the given patterns.
4462 names match the given patterns.
4464
4463
4465 By default, this command searches all directories in the working
4464 By default, this command searches all directories in the working
4466 directory. To search just the current directory and its
4465 directory. To search just the current directory and its
4467 subdirectories, use "--include .".
4466 subdirectories, use "--include .".
4468
4467
4469 If no patterns are given to match, this command prints the names
4468 If no patterns are given to match, this command prints the names
4470 of all files under Mercurial control in the working directory.
4469 of all files under Mercurial control in the working directory.
4471
4470
4472 If you want to feed the output of this command into the "xargs"
4471 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
4472 command, use the -0 option to both this command and "xargs". This
4474 will avoid the problem of "xargs" treating single filenames that
4473 will avoid the problem of "xargs" treating single filenames that
4475 contain whitespace as multiple filenames.
4474 contain whitespace as multiple filenames.
4476
4475
4477 See :hg:`help files` for a more versatile command.
4476 See :hg:`help files` for a more versatile command.
4478
4477
4479 Returns 0 if a match is found, 1 otherwise.
4478 Returns 0 if a match is found, 1 otherwise.
4480 """
4479 """
4481 opts = pycompat.byteskwargs(opts)
4480 opts = pycompat.byteskwargs(opts)
4482 if opts.get(b'print0'):
4481 if opts.get(b'print0'):
4483 end = b'\0'
4482 end = b'\0'
4484 else:
4483 else:
4485 end = b'\n'
4484 end = b'\n'
4486 ctx = logcmdutil.revsingle(repo, opts.get(b'rev'), None)
4485 ctx = logcmdutil.revsingle(repo, opts.get(b'rev'), None)
4487
4486
4488 ret = 1
4487 ret = 1
4489 m = scmutil.match(
4488 m = scmutil.match(
4490 ctx, pats, opts, default=b'relglob', badfn=lambda x, y: False
4489 ctx, pats, opts, default=b'relglob', badfn=lambda x, y: False
4491 )
4490 )
4492
4491
4493 ui.pager(b'locate')
4492 ui.pager(b'locate')
4494 if ctx.rev() is None:
4493 if ctx.rev() is None:
4495 # When run on the working copy, "locate" includes removed files, so
4494 # When run on the working copy, "locate" includes removed files, so
4496 # we get the list of files from the dirstate.
4495 # we get the list of files from the dirstate.
4497 filesgen = sorted(repo.dirstate.matches(m))
4496 filesgen = sorted(repo.dirstate.matches(m))
4498 else:
4497 else:
4499 filesgen = ctx.matches(m)
4498 filesgen = ctx.matches(m)
4500 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=bool(pats))
4499 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=bool(pats))
4501 for abs in filesgen:
4500 for abs in filesgen:
4502 if opts.get(b'fullpath'):
4501 if opts.get(b'fullpath'):
4503 ui.write(repo.wjoin(abs), end)
4502 ui.write(repo.wjoin(abs), end)
4504 else:
4503 else:
4505 ui.write(uipathfn(abs), end)
4504 ui.write(uipathfn(abs), end)
4506 ret = 0
4505 ret = 0
4507
4506
4508 return ret
4507 return ret
4509
4508
4510
4509
4511 @command(
4510 @command(
4512 b'log|history',
4511 b'log|history',
4513 [
4512 [
4514 (
4513 (
4515 b'f',
4514 b'f',
4516 b'follow',
4515 b'follow',
4517 None,
4516 None,
4518 _(
4517 _(
4519 b'follow changeset history, or file history across copies and renames'
4518 b'follow changeset history, or file history across copies and renames'
4520 ),
4519 ),
4521 ),
4520 ),
4522 (
4521 (
4523 b'',
4522 b'',
4524 b'follow-first',
4523 b'follow-first',
4525 None,
4524 None,
4526 _(b'only follow the first parent of merge changesets (DEPRECATED)'),
4525 _(b'only follow the first parent of merge changesets (DEPRECATED)'),
4527 ),
4526 ),
4528 (
4527 (
4529 b'd',
4528 b'd',
4530 b'date',
4529 b'date',
4531 b'',
4530 b'',
4532 _(b'show revisions matching date spec'),
4531 _(b'show revisions matching date spec'),
4533 _(b'DATE'),
4532 _(b'DATE'),
4534 ),
4533 ),
4535 (b'C', b'copies', None, _(b'show copied files')),
4534 (b'C', b'copies', None, _(b'show copied files')),
4536 (
4535 (
4537 b'k',
4536 b'k',
4538 b'keyword',
4537 b'keyword',
4539 [],
4538 [],
4540 _(b'do case-insensitive search for a given text'),
4539 _(b'do case-insensitive search for a given text'),
4541 _(b'TEXT'),
4540 _(b'TEXT'),
4542 ),
4541 ),
4543 (
4542 (
4544 b'r',
4543 b'r',
4545 b'rev',
4544 b'rev',
4546 [],
4545 [],
4547 _(b'revisions to select or follow from'),
4546 _(b'revisions to select or follow from'),
4548 _(b'REV'),
4547 _(b'REV'),
4549 ),
4548 ),
4550 (
4549 (
4551 b'L',
4550 b'L',
4552 b'line-range',
4551 b'line-range',
4553 [],
4552 [],
4554 _(b'follow line range of specified file (EXPERIMENTAL)'),
4553 _(b'follow line range of specified file (EXPERIMENTAL)'),
4555 _(b'FILE,RANGE'),
4554 _(b'FILE,RANGE'),
4556 ),
4555 ),
4557 (
4556 (
4558 b'',
4557 b'',
4559 b'removed',
4558 b'removed',
4560 None,
4559 None,
4561 _(b'include revisions where files were removed'),
4560 _(b'include revisions where files were removed'),
4562 ),
4561 ),
4563 (
4562 (
4564 b'm',
4563 b'm',
4565 b'only-merges',
4564 b'only-merges',
4566 None,
4565 None,
4567 _(b'show only merges (DEPRECATED) (use -r "merge()" instead)'),
4566 _(b'show only merges (DEPRECATED) (use -r "merge()" instead)'),
4568 ),
4567 ),
4569 (b'u', b'user', [], _(b'revisions committed by user'), _(b'USER')),
4568 (b'u', b'user', [], _(b'revisions committed by user'), _(b'USER')),
4570 (
4569 (
4571 b'',
4570 b'',
4572 b'only-branch',
4571 b'only-branch',
4573 [],
4572 [],
4574 _(
4573 _(
4575 b'show only changesets within the given named branch (DEPRECATED)'
4574 b'show only changesets within the given named branch (DEPRECATED)'
4576 ),
4575 ),
4577 _(b'BRANCH'),
4576 _(b'BRANCH'),
4578 ),
4577 ),
4579 (
4578 (
4580 b'b',
4579 b'b',
4581 b'branch',
4580 b'branch',
4582 [],
4581 [],
4583 _(b'show changesets within the given named branch'),
4582 _(b'show changesets within the given named branch'),
4584 _(b'BRANCH'),
4583 _(b'BRANCH'),
4585 ),
4584 ),
4586 (
4585 (
4587 b'B',
4586 b'B',
4588 b'bookmark',
4587 b'bookmark',
4589 [],
4588 [],
4590 _(b"show changesets within the given bookmark"),
4589 _(b"show changesets within the given bookmark"),
4591 _(b'BOOKMARK'),
4590 _(b'BOOKMARK'),
4592 ),
4591 ),
4593 (
4592 (
4594 b'P',
4593 b'P',
4595 b'prune',
4594 b'prune',
4596 [],
4595 [],
4597 _(b'do not display revision or any of its ancestors'),
4596 _(b'do not display revision or any of its ancestors'),
4598 _(b'REV'),
4597 _(b'REV'),
4599 ),
4598 ),
4600 ]
4599 ]
4601 + logopts
4600 + logopts
4602 + walkopts,
4601 + walkopts,
4603 _(b'[OPTION]... [FILE]'),
4602 _(b'[OPTION]... [FILE]'),
4604 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
4603 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
4605 helpbasic=True,
4604 helpbasic=True,
4606 inferrepo=True,
4605 inferrepo=True,
4607 intents={INTENT_READONLY},
4606 intents={INTENT_READONLY},
4608 )
4607 )
4609 def log(ui, repo, *pats, **opts):
4608 def log(ui, repo, *pats, **opts):
4610 """show revision history of entire repository or files
4609 """show revision history of entire repository or files
4611
4610
4612 Print the revision history of the specified files or the entire
4611 Print the revision history of the specified files or the entire
4613 project.
4612 project.
4614
4613
4615 If no revision range is specified, the default is ``tip:0`` unless
4614 If no revision range is specified, the default is ``tip:0`` unless
4616 --follow is set.
4615 --follow is set.
4617
4616
4618 File history is shown without following rename or copy history of
4617 File history is shown without following rename or copy history of
4619 files. Use -f/--follow with a filename to follow history across
4618 files. Use -f/--follow with a filename to follow history across
4620 renames and copies. --follow without a filename will only show
4619 renames and copies. --follow without a filename will only show
4621 ancestors of the starting revisions. The starting revisions can be
4620 ancestors of the starting revisions. The starting revisions can be
4622 specified by -r/--rev, which default to the working directory parent.
4621 specified by -r/--rev, which default to the working directory parent.
4623
4622
4624 By default this command prints revision number and changeset id,
4623 By default this command prints revision number and changeset id,
4625 tags, non-trivial parents, user, date and time, and a summary for
4624 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
4625 each commit. When the -v/--verbose switch is used, the list of
4627 changed files and full commit message are shown.
4626 changed files and full commit message are shown.
4628
4627
4629 With --graph the revisions are shown as an ASCII art DAG with the most
4628 With --graph the revisions are shown as an ASCII art DAG with the most
4630 recent changeset at the top.
4629 recent changeset at the top.
4631 'o' is a changeset, '@' is a working directory parent, '%' is a changeset
4630 'o' is a changeset, '@' is a working directory parent, '%' is a changeset
4632 involved in an unresolved merge conflict, '_' closes a branch,
4631 involved in an unresolved merge conflict, '_' closes a branch,
4633 'x' is obsolete, '*' is unstable, and '+' represents a fork where the
4632 '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
4633 changeset from the lines below is a parent of the 'o' merge on the same
4635 line.
4634 line.
4636 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
4635 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.
4636 of a '|' indicates one or more revisions in a path are omitted.
4638
4637
4639 .. container:: verbose
4638 .. container:: verbose
4640
4639
4641 Use -L/--line-range FILE,M:N options to follow the history of lines
4640 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
4641 from M to N in FILE. With -p/--patch only diff hunks affecting
4643 specified line range will be shown. This option requires --follow;
4642 specified line range will be shown. This option requires --follow;
4644 it can be specified multiple times. Currently, this option is not
4643 it can be specified multiple times. Currently, this option is not
4645 compatible with --graph. This option is experimental.
4644 compatible with --graph. This option is experimental.
4646
4645
4647 .. note::
4646 .. note::
4648
4647
4649 :hg:`log --patch` may generate unexpected diff output for merge
4648 :hg:`log --patch` may generate unexpected diff output for merge
4650 changesets, as it will only compare the merge changeset against
4649 changesets, as it will only compare the merge changeset against
4651 its first parent. Also, only files different from BOTH parents
4650 its first parent. Also, only files different from BOTH parents
4652 will appear in files:.
4651 will appear in files:.
4653
4652
4654 .. note::
4653 .. note::
4655
4654
4656 For performance reasons, :hg:`log FILE` may omit duplicate changes
4655 For performance reasons, :hg:`log FILE` may omit duplicate changes
4657 made on branches and will not show removals or mode changes. To
4656 made on branches and will not show removals or mode changes. To
4658 see all such changes, use the --removed switch.
4657 see all such changes, use the --removed switch.
4659
4658
4660 .. container:: verbose
4659 .. container:: verbose
4661
4660
4662 .. note::
4661 .. note::
4663
4662
4664 The history resulting from -L/--line-range options depends on diff
4663 The history resulting from -L/--line-range options depends on diff
4665 options; for instance if white-spaces are ignored, respective changes
4664 options; for instance if white-spaces are ignored, respective changes
4666 with only white-spaces in specified line range will not be listed.
4665 with only white-spaces in specified line range will not be listed.
4667
4666
4668 .. container:: verbose
4667 .. container:: verbose
4669
4668
4670 Some examples:
4669 Some examples:
4671
4670
4672 - changesets with full descriptions and file lists::
4671 - changesets with full descriptions and file lists::
4673
4672
4674 hg log -v
4673 hg log -v
4675
4674
4676 - changesets ancestral to the working directory::
4675 - changesets ancestral to the working directory::
4677
4676
4678 hg log -f
4677 hg log -f
4679
4678
4680 - last 10 commits on the current branch::
4679 - last 10 commits on the current branch::
4681
4680
4682 hg log -l 10 -b .
4681 hg log -l 10 -b .
4683
4682
4684 - changesets showing all modifications of a file, including removals::
4683 - changesets showing all modifications of a file, including removals::
4685
4684
4686 hg log --removed file.c
4685 hg log --removed file.c
4687
4686
4688 - all changesets that touch a directory, with diffs, excluding merges::
4687 - all changesets that touch a directory, with diffs, excluding merges::
4689
4688
4690 hg log -Mp lib/
4689 hg log -Mp lib/
4691
4690
4692 - all revision numbers that match a keyword::
4691 - all revision numbers that match a keyword::
4693
4692
4694 hg log -k bug --template "{rev}\\n"
4693 hg log -k bug --template "{rev}\\n"
4695
4694
4696 - the full hash identifier of the working directory parent::
4695 - the full hash identifier of the working directory parent::
4697
4696
4698 hg log -r . --template "{node}\\n"
4697 hg log -r . --template "{node}\\n"
4699
4698
4700 - list available log templates::
4699 - list available log templates::
4701
4700
4702 hg log -T list
4701 hg log -T list
4703
4702
4704 - check if a given changeset is included in a tagged release::
4703 - check if a given changeset is included in a tagged release::
4705
4704
4706 hg log -r "a21ccf and ancestor(1.9)"
4705 hg log -r "a21ccf and ancestor(1.9)"
4707
4706
4708 - find all changesets by some user in a date range::
4707 - find all changesets by some user in a date range::
4709
4708
4710 hg log -k alice -d "may 2008 to jul 2008"
4709 hg log -k alice -d "may 2008 to jul 2008"
4711
4710
4712 - summary of all changesets after the last tag::
4711 - summary of all changesets after the last tag::
4713
4712
4714 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4713 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4715
4714
4716 - changesets touching lines 13 to 23 for file.c::
4715 - changesets touching lines 13 to 23 for file.c::
4717
4716
4718 hg log -L file.c,13:23
4717 hg log -L file.c,13:23
4719
4718
4720 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
4719 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
4721 main.c with patch::
4720 main.c with patch::
4722
4721
4723 hg log -L file.c,13:23 -L main.c,2:6 -p
4722 hg log -L file.c,13:23 -L main.c,2:6 -p
4724
4723
4725 See :hg:`help dates` for a list of formats valid for -d/--date.
4724 See :hg:`help dates` for a list of formats valid for -d/--date.
4726
4725
4727 See :hg:`help revisions` for more about specifying and ordering
4726 See :hg:`help revisions` for more about specifying and ordering
4728 revisions.
4727 revisions.
4729
4728
4730 See :hg:`help templates` for more about pre-packaged styles and
4729 See :hg:`help templates` for more about pre-packaged styles and
4731 specifying custom templates. The default template used by the log
4730 specifying custom templates. The default template used by the log
4732 command can be customized via the ``command-templates.log`` configuration
4731 command can be customized via the ``command-templates.log`` configuration
4733 setting.
4732 setting.
4734
4733
4735 Returns 0 on success.
4734 Returns 0 on success.
4736
4735
4737 """
4736 """
4738 opts = pycompat.byteskwargs(opts)
4737 opts = pycompat.byteskwargs(opts)
4739 linerange = opts.get(b'line_range')
4738 linerange = opts.get(b'line_range')
4740
4739
4741 if linerange and not opts.get(b'follow'):
4740 if linerange and not opts.get(b'follow'):
4742 raise error.InputError(_(b'--line-range requires --follow'))
4741 raise error.InputError(_(b'--line-range requires --follow'))
4743
4742
4744 if linerange and pats:
4743 if linerange and pats:
4745 # TODO: take pats as patterns with no line-range filter
4744 # TODO: take pats as patterns with no line-range filter
4746 raise error.InputError(
4745 raise error.InputError(
4747 _(b'FILE arguments are not compatible with --line-range option')
4746 _(b'FILE arguments are not compatible with --line-range option')
4748 )
4747 )
4749
4748
4750 repo = scmutil.unhidehashlikerevs(repo, opts.get(b'rev'), b'nowarn')
4749 repo = scmutil.unhidehashlikerevs(repo, opts.get(b'rev'), b'nowarn')
4751 walk_opts = logcmdutil.parseopts(ui, pats, opts)
4750 walk_opts = logcmdutil.parseopts(ui, pats, opts)
4752 revs, differ = logcmdutil.getrevs(repo, walk_opts)
4751 revs, differ = logcmdutil.getrevs(repo, walk_opts)
4753 if linerange:
4752 if linerange:
4754 # TODO: should follow file history from logcmdutil._initialrevs(),
4753 # TODO: should follow file history from logcmdutil._initialrevs(),
4755 # then filter the result by logcmdutil._makerevset() and --limit
4754 # then filter the result by logcmdutil._makerevset() and --limit
4756 revs, differ = logcmdutil.getlinerangerevs(repo, revs, opts)
4755 revs, differ = logcmdutil.getlinerangerevs(repo, revs, opts)
4757
4756
4758 getcopies = None
4757 getcopies = None
4759 if opts.get(b'copies'):
4758 if opts.get(b'copies'):
4760 endrev = None
4759 endrev = None
4761 if revs:
4760 if revs:
4762 endrev = revs.max() + 1
4761 endrev = revs.max() + 1
4763 getcopies = scmutil.getcopiesfn(repo, endrev=endrev)
4762 getcopies = scmutil.getcopiesfn(repo, endrev=endrev)
4764
4763
4765 ui.pager(b'log')
4764 ui.pager(b'log')
4766 displayer = logcmdutil.changesetdisplayer(
4765 displayer = logcmdutil.changesetdisplayer(
4767 ui, repo, opts, differ, buffered=True
4766 ui, repo, opts, differ, buffered=True
4768 )
4767 )
4769 if opts.get(b'graph'):
4768 if opts.get(b'graph'):
4770 displayfn = logcmdutil.displaygraphrevs
4769 displayfn = logcmdutil.displaygraphrevs
4771 else:
4770 else:
4772 displayfn = logcmdutil.displayrevs
4771 displayfn = logcmdutil.displayrevs
4773 displayfn(ui, repo, revs, displayer, getcopies)
4772 displayfn(ui, repo, revs, displayer, getcopies)
4774
4773
4775
4774
4776 @command(
4775 @command(
4777 b'manifest',
4776 b'manifest',
4778 [
4777 [
4779 (b'r', b'rev', b'', _(b'revision to display'), _(b'REV')),
4778 (b'r', b'rev', b'', _(b'revision to display'), _(b'REV')),
4780 (b'', b'all', False, _(b"list files from all revisions")),
4779 (b'', b'all', False, _(b"list files from all revisions")),
4781 ]
4780 ]
4782 + formatteropts,
4781 + formatteropts,
4783 _(b'[-r REV]'),
4782 _(b'[-r REV]'),
4784 helpcategory=command.CATEGORY_MAINTENANCE,
4783 helpcategory=command.CATEGORY_MAINTENANCE,
4785 intents={INTENT_READONLY},
4784 intents={INTENT_READONLY},
4786 )
4785 )
4787 def manifest(ui, repo, node=None, rev=None, **opts):
4786 def manifest(ui, repo, node=None, rev=None, **opts):
4788 """output the current or given revision of the project manifest
4787 """output the current or given revision of the project manifest
4789
4788
4790 Print a list of version controlled files for the given revision.
4789 Print a list of version controlled files for the given revision.
4791 If no revision is given, the first parent of the working directory
4790 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.
4791 is used, or the null revision if no revision is checked out.
4793
4792
4794 With -v, print file permissions, symlink and executable bits.
4793 With -v, print file permissions, symlink and executable bits.
4795 With --debug, print file revision hashes.
4794 With --debug, print file revision hashes.
4796
4795
4797 If option --all is specified, the list of all files from all revisions
4796 If option --all is specified, the list of all files from all revisions
4798 is printed. This includes deleted and renamed files.
4797 is printed. This includes deleted and renamed files.
4799
4798
4800 Returns 0 on success.
4799 Returns 0 on success.
4801 """
4800 """
4802 opts = pycompat.byteskwargs(opts)
4801 opts = pycompat.byteskwargs(opts)
4803 fm = ui.formatter(b'manifest', opts)
4802 fm = ui.formatter(b'manifest', opts)
4804
4803
4805 if opts.get(b'all'):
4804 if opts.get(b'all'):
4806 if rev or node:
4805 if rev or node:
4807 raise error.InputError(_(b"can't specify a revision with --all"))
4806 raise error.InputError(_(b"can't specify a revision with --all"))
4808
4807
4809 res = set()
4808 res = set()
4810 for rev in repo:
4809 for rev in repo:
4811 ctx = repo[rev]
4810 ctx = repo[rev]
4812 res |= set(ctx.files())
4811 res |= set(ctx.files())
4813
4812
4814 ui.pager(b'manifest')
4813 ui.pager(b'manifest')
4815 for f in sorted(res):
4814 for f in sorted(res):
4816 fm.startitem()
4815 fm.startitem()
4817 fm.write(b"path", b'%s\n', f)
4816 fm.write(b"path", b'%s\n', f)
4818 fm.end()
4817 fm.end()
4819 return
4818 return
4820
4819
4821 if rev and node:
4820 if rev and node:
4822 raise error.InputError(_(b"please specify just one revision"))
4821 raise error.InputError(_(b"please specify just one revision"))
4823
4822
4824 if not node:
4823 if not node:
4825 node = rev
4824 node = rev
4826
4825
4827 char = {b'l': b'@', b'x': b'*', b'': b'', b't': b'd'}
4826 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'}
4827 mode = {b'l': b'644', b'x': b'755', b'': b'644', b't': b'755'}
4829 if node:
4828 if node:
4830 repo = scmutil.unhidehashlikerevs(repo, [node], b'nowarn')
4829 repo = scmutil.unhidehashlikerevs(repo, [node], b'nowarn')
4831 ctx = logcmdutil.revsingle(repo, node)
4830 ctx = logcmdutil.revsingle(repo, node)
4832 mf = ctx.manifest()
4831 mf = ctx.manifest()
4833 ui.pager(b'manifest')
4832 ui.pager(b'manifest')
4834 for f in ctx:
4833 for f in ctx:
4835 fm.startitem()
4834 fm.startitem()
4836 fm.context(ctx=ctx)
4835 fm.context(ctx=ctx)
4837 fl = ctx[f].flags()
4836 fl = ctx[f].flags()
4838 fm.condwrite(ui.debugflag, b'hash', b'%s ', hex(mf[f]))
4837 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])
4838 fm.condwrite(ui.verbose, b'mode type', b'%s %1s ', mode[fl], char[fl])
4840 fm.write(b'path', b'%s\n', f)
4839 fm.write(b'path', b'%s\n', f)
4841 fm.end()
4840 fm.end()
4842
4841
4843
4842
4844 @command(
4843 @command(
4845 b'merge',
4844 b'merge',
4846 [
4845 [
4847 (
4846 (
4848 b'f',
4847 b'f',
4849 b'force',
4848 b'force',
4850 None,
4849 None,
4851 _(b'force a merge including outstanding changes (DEPRECATED)'),
4850 _(b'force a merge including outstanding changes (DEPRECATED)'),
4852 ),
4851 ),
4853 (b'r', b'rev', b'', _(b'revision to merge'), _(b'REV')),
4852 (b'r', b'rev', b'', _(b'revision to merge'), _(b'REV')),
4854 (
4853 (
4855 b'P',
4854 b'P',
4856 b'preview',
4855 b'preview',
4857 None,
4856 None,
4858 _(b'review revisions to merge (no merge is performed)'),
4857 _(b'review revisions to merge (no merge is performed)'),
4859 ),
4858 ),
4860 (b'', b'abort', None, _(b'abort the ongoing merge')),
4859 (b'', b'abort', None, _(b'abort the ongoing merge')),
4861 ]
4860 ]
4862 + mergetoolopts,
4861 + mergetoolopts,
4863 _(b'[-P] [[-r] REV]'),
4862 _(b'[-P] [[-r] REV]'),
4864 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
4863 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
4865 helpbasic=True,
4864 helpbasic=True,
4866 )
4865 )
4867 def merge(ui, repo, node=None, **opts):
4866 def merge(ui, repo, node=None, **opts):
4868 """merge another revision into working directory
4867 """merge another revision into working directory
4869
4868
4870 The current working directory is updated with all changes made in
4869 The current working directory is updated with all changes made in
4871 the requested revision since the last common predecessor revision.
4870 the requested revision since the last common predecessor revision.
4872
4871
4873 Files that changed between either parent are marked as changed for
4872 Files that changed between either parent are marked as changed for
4874 the next commit and a commit must be performed before any further
4873 the next commit and a commit must be performed before any further
4875 updates to the repository are allowed. The next commit will have
4874 updates to the repository are allowed. The next commit will have
4876 two parents.
4875 two parents.
4877
4876
4878 ``--tool`` can be used to specify the merge tool used for file
4877 ``--tool`` can be used to specify the merge tool used for file
4879 merges. It overrides the HGMERGE environment variable and your
4878 merges. It overrides the HGMERGE environment variable and your
4880 configuration files. See :hg:`help merge-tools` for options.
4879 configuration files. See :hg:`help merge-tools` for options.
4881
4880
4882 If no revision is specified, the working directory's parent is a
4881 If no revision is specified, the working directory's parent is a
4883 head revision, and the current branch contains exactly one other
4882 head revision, and the current branch contains exactly one other
4884 head, the other head is merged with by default. Otherwise, an
4883 head, the other head is merged with by default. Otherwise, an
4885 explicit revision with which to merge must be provided.
4884 explicit revision with which to merge must be provided.
4886
4885
4887 See :hg:`help resolve` for information on handling file conflicts.
4886 See :hg:`help resolve` for information on handling file conflicts.
4888
4887
4889 To undo an uncommitted merge, use :hg:`merge --abort` which
4888 To undo an uncommitted merge, use :hg:`merge --abort` which
4890 will check out a clean copy of the original merge parent, losing
4889 will check out a clean copy of the original merge parent, losing
4891 all changes.
4890 all changes.
4892
4891
4893 Returns 0 on success, 1 if there are unresolved files.
4892 Returns 0 on success, 1 if there are unresolved files.
4894 """
4893 """
4895
4894
4896 opts = pycompat.byteskwargs(opts)
4895 opts = pycompat.byteskwargs(opts)
4897 abort = opts.get(b'abort')
4896 abort = opts.get(b'abort')
4898 if abort and repo.dirstate.p2() == repo.nullid:
4897 if abort and repo.dirstate.p2() == repo.nullid:
4899 cmdutil.wrongtooltocontinue(repo, _(b'merge'))
4898 cmdutil.wrongtooltocontinue(repo, _(b'merge'))
4900 cmdutil.check_incompatible_arguments(opts, b'abort', [b'rev', b'preview'])
4899 cmdutil.check_incompatible_arguments(opts, b'abort', [b'rev', b'preview'])
4901 if abort:
4900 if abort:
4902 state = cmdutil.getunfinishedstate(repo)
4901 state = cmdutil.getunfinishedstate(repo)
4903 if state and state._opname != b'merge':
4902 if state and state._opname != b'merge':
4904 raise error.StateError(
4903 raise error.StateError(
4905 _(b'cannot abort merge with %s in progress') % (state._opname),
4904 _(b'cannot abort merge with %s in progress') % (state._opname),
4906 hint=state.hint(),
4905 hint=state.hint(),
4907 )
4906 )
4908 if node:
4907 if node:
4909 raise error.InputError(_(b"cannot specify a node with --abort"))
4908 raise error.InputError(_(b"cannot specify a node with --abort"))
4910 return hg.abortmerge(repo.ui, repo)
4909 return hg.abortmerge(repo.ui, repo)
4911
4910
4912 if opts.get(b'rev') and node:
4911 if opts.get(b'rev') and node:
4913 raise error.InputError(_(b"please specify just one revision"))
4912 raise error.InputError(_(b"please specify just one revision"))
4914 if not node:
4913 if not node:
4915 node = opts.get(b'rev')
4914 node = opts.get(b'rev')
4916
4915
4917 if node:
4916 if node:
4918 ctx = logcmdutil.revsingle(repo, node)
4917 ctx = logcmdutil.revsingle(repo, node)
4919 else:
4918 else:
4920 if ui.configbool(b'commands', b'merge.require-rev'):
4919 if ui.configbool(b'commands', b'merge.require-rev'):
4921 raise error.InputError(
4920 raise error.InputError(
4922 _(
4921 _(
4923 b'configuration requires specifying revision to merge '
4922 b'configuration requires specifying revision to merge '
4924 b'with'
4923 b'with'
4925 )
4924 )
4926 )
4925 )
4927 ctx = repo[destutil.destmerge(repo)]
4926 ctx = repo[destutil.destmerge(repo)]
4928
4927
4929 if ctx.node() is None:
4928 if ctx.node() is None:
4930 raise error.InputError(
4929 raise error.InputError(
4931 _(b'merging with the working copy has no effect')
4930 _(b'merging with the working copy has no effect')
4932 )
4931 )
4933
4932
4934 if opts.get(b'preview'):
4933 if opts.get(b'preview'):
4935 # find nodes that are ancestors of p2 but not of p1
4934 # find nodes that are ancestors of p2 but not of p1
4936 p1 = repo[b'.'].node()
4935 p1 = repo[b'.'].node()
4937 p2 = ctx.node()
4936 p2 = ctx.node()
4938 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4937 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4939
4938
4940 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4939 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4941 for node in nodes:
4940 for node in nodes:
4942 displayer.show(repo[node])
4941 displayer.show(repo[node])
4943 displayer.close()
4942 displayer.close()
4944 return 0
4943 return 0
4945
4944
4946 # ui.forcemerge is an internal variable, do not document
4945 # ui.forcemerge is an internal variable, do not document
4947 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
4946 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
4948 with ui.configoverride(overrides, b'merge'):
4947 with ui.configoverride(overrides, b'merge'):
4949 force = opts.get(b'force')
4948 force = opts.get(b'force')
4950 labels = [b'working copy', b'merge rev', b'common ancestor']
4949 labels = [b'working copy', b'merge rev', b'common ancestor']
4951 return hg.merge(ctx, force=force, labels=labels)
4950 return hg.merge(ctx, force=force, labels=labels)
4952
4951
4953
4952
4954 statemod.addunfinished(
4953 statemod.addunfinished(
4955 b'merge',
4954 b'merge',
4956 fname=None,
4955 fname=None,
4957 clearable=True,
4956 clearable=True,
4958 allowcommit=True,
4957 allowcommit=True,
4959 cmdmsg=_(b'outstanding uncommitted merge'),
4958 cmdmsg=_(b'outstanding uncommitted merge'),
4960 abortfunc=hg.abortmerge,
4959 abortfunc=hg.abortmerge,
4961 statushint=_(
4960 statushint=_(
4962 b'To continue: hg commit\nTo abort: hg merge --abort'
4961 b'To continue: hg commit\nTo abort: hg merge --abort'
4963 ),
4962 ),
4964 cmdhint=_(b"use 'hg commit' or 'hg merge --abort'"),
4963 cmdhint=_(b"use 'hg commit' or 'hg merge --abort'"),
4965 )
4964 )
4966
4965
4967
4966
4968 @command(
4967 @command(
4969 b'outgoing|out',
4968 b'outgoing|out',
4970 [
4969 [
4971 (
4970 (
4972 b'f',
4971 b'f',
4973 b'force',
4972 b'force',
4974 None,
4973 None,
4975 _(b'run even when the destination is unrelated'),
4974 _(b'run even when the destination is unrelated'),
4976 ),
4975 ),
4977 (
4976 (
4978 b'r',
4977 b'r',
4979 b'rev',
4978 b'rev',
4980 [],
4979 [],
4981 _(b'a changeset intended to be included in the destination'),
4980 _(b'a changeset intended to be included in the destination'),
4982 _(b'REV'),
4981 _(b'REV'),
4983 ),
4982 ),
4984 (b'n', b'newest-first', None, _(b'show newest record first')),
4983 (b'n', b'newest-first', None, _(b'show newest record first')),
4985 (b'B', b'bookmarks', False, _(b'compare bookmarks')),
4984 (b'B', b'bookmarks', False, _(b'compare bookmarks')),
4986 (
4985 (
4987 b'b',
4986 b'b',
4988 b'branch',
4987 b'branch',
4989 [],
4988 [],
4990 _(b'a specific branch you would like to push'),
4989 _(b'a specific branch you would like to push'),
4991 _(b'BRANCH'),
4990 _(b'BRANCH'),
4992 ),
4991 ),
4993 ]
4992 ]
4994 + logopts
4993 + logopts
4995 + remoteopts
4994 + remoteopts
4996 + subrepoopts,
4995 + subrepoopts,
4997 _(b'[-M] [-p] [-n] [-f] [-r REV]... [DEST]...'),
4996 _(b'[-M] [-p] [-n] [-f] [-r REV]... [DEST]...'),
4998 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4997 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4999 )
4998 )
5000 def outgoing(ui, repo, *dests, **opts):
4999 def outgoing(ui, repo, *dests, **opts):
5001 """show changesets not found in the destination
5000 """show changesets not found in the destination
5002
5001
5003 Show changesets not found in the specified destination repository
5002 Show changesets not found in the specified destination repository
5004 or the default push location. These are the changesets that would
5003 or the default push location. These are the changesets that would
5005 be pushed if a push was requested.
5004 be pushed if a push was requested.
5006
5005
5007 See pull for details of valid destination formats.
5006 See pull for details of valid destination formats.
5008
5007
5009 .. container:: verbose
5008 .. container:: verbose
5010
5009
5011 With -B/--bookmarks, the result of bookmark comparison between
5010 With -B/--bookmarks, the result of bookmark comparison between
5012 local and remote repositories is displayed. With -v/--verbose,
5011 local and remote repositories is displayed. With -v/--verbose,
5013 status is also displayed for each bookmark like below::
5012 status is also displayed for each bookmark like below::
5014
5013
5015 BM1 01234567890a added
5014 BM1 01234567890a added
5016 BM2 deleted
5015 BM2 deleted
5017 BM3 234567890abc advanced
5016 BM3 234567890abc advanced
5018 BM4 34567890abcd diverged
5017 BM4 34567890abcd diverged
5019 BM5 4567890abcde changed
5018 BM5 4567890abcde changed
5020
5019
5021 The action taken when pushing depends on the
5020 The action taken when pushing depends on the
5022 status of each bookmark:
5021 status of each bookmark:
5023
5022
5024 :``added``: push with ``-B`` will create it
5023 :``added``: push with ``-B`` will create it
5025 :``deleted``: push with ``-B`` will delete it
5024 :``deleted``: push with ``-B`` will delete it
5026 :``advanced``: push will update it
5025 :``advanced``: push will update it
5027 :``diverged``: push with ``-B`` will update it
5026 :``diverged``: push with ``-B`` will update it
5028 :``changed``: push with ``-B`` will update it
5027 :``changed``: push with ``-B`` will update it
5029
5028
5030 From the point of view of pushing behavior, bookmarks
5029 From the point of view of pushing behavior, bookmarks
5031 existing only in the remote repository are treated as
5030 existing only in the remote repository are treated as
5032 ``deleted``, even if it is in fact added remotely.
5031 ``deleted``, even if it is in fact added remotely.
5033
5032
5034 Returns 0 if there are outgoing changes, 1 otherwise.
5033 Returns 0 if there are outgoing changes, 1 otherwise.
5035 """
5034 """
5036 opts = pycompat.byteskwargs(opts)
5035 opts = pycompat.byteskwargs(opts)
5037 if opts.get(b'bookmarks'):
5036 if opts.get(b'bookmarks'):
5038 for path in urlutil.get_push_paths(repo, ui, dests):
5037 for path in urlutil.get_push_paths(repo, ui, dests):
5039 other = hg.peer(repo, opts, path)
5038 other = hg.peer(repo, opts, path)
5040 try:
5039 try:
5041 if b'bookmarks' not in other.listkeys(b'namespaces'):
5040 if b'bookmarks' not in other.listkeys(b'namespaces'):
5042 ui.warn(_(b"remote doesn't support bookmarks\n"))
5041 ui.warn(_(b"remote doesn't support bookmarks\n"))
5043 return 0
5042 return 0
5044 ui.status(
5043 ui.status(
5045 _(b'comparing with %s\n') % urlutil.hidepassword(path.loc)
5044 _(b'comparing with %s\n') % urlutil.hidepassword(path.loc)
5046 )
5045 )
5047 ui.pager(b'outgoing')
5046 ui.pager(b'outgoing')
5048 return bookmarks.outgoing(ui, repo, other)
5047 return bookmarks.outgoing(ui, repo, other)
5049 finally:
5048 finally:
5050 other.close()
5049 other.close()
5051
5050
5052 return hg.outgoing(ui, repo, dests, opts)
5051 return hg.outgoing(ui, repo, dests, opts)
5053
5052
5054
5053
5055 @command(
5054 @command(
5056 b'parents',
5055 b'parents',
5057 [
5056 [
5058 (
5057 (
5059 b'r',
5058 b'r',
5060 b'rev',
5059 b'rev',
5061 b'',
5060 b'',
5062 _(b'show parents of the specified revision'),
5061 _(b'show parents of the specified revision'),
5063 _(b'REV'),
5062 _(b'REV'),
5064 ),
5063 ),
5065 ]
5064 ]
5066 + templateopts,
5065 + templateopts,
5067 _(b'[-r REV] [FILE]'),
5066 _(b'[-r REV] [FILE]'),
5068 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
5067 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
5069 inferrepo=True,
5068 inferrepo=True,
5070 )
5069 )
5071 def parents(ui, repo, file_=None, **opts):
5070 def parents(ui, repo, file_=None, **opts):
5072 """show the parents of the working directory or revision (DEPRECATED)
5071 """show the parents of the working directory or revision (DEPRECATED)
5073
5072
5074 Print the working directory's parent revisions. If a revision is
5073 Print the working directory's parent revisions. If a revision is
5075 given via -r/--rev, the parent of that revision will be printed.
5074 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
5075 If a file argument is given, the revision in which the file was
5077 last changed (before the working directory revision or the
5076 last changed (before the working directory revision or the
5078 argument to --rev if given) is printed.
5077 argument to --rev if given) is printed.
5079
5078
5080 This command is equivalent to::
5079 This command is equivalent to::
5081
5080
5082 hg log -r "p1()+p2()" or
5081 hg log -r "p1()+p2()" or
5083 hg log -r "p1(REV)+p2(REV)" or
5082 hg log -r "p1(REV)+p2(REV)" or
5084 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
5083 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))"
5084 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
5086
5085
5087 See :hg:`summary` and :hg:`help revsets` for related information.
5086 See :hg:`summary` and :hg:`help revsets` for related information.
5088
5087
5089 Returns 0 on success.
5088 Returns 0 on success.
5090 """
5089 """
5091
5090
5092 opts = pycompat.byteskwargs(opts)
5091 opts = pycompat.byteskwargs(opts)
5093 rev = opts.get(b'rev')
5092 rev = opts.get(b'rev')
5094 if rev:
5093 if rev:
5095 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
5094 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
5096 ctx = logcmdutil.revsingle(repo, rev, None)
5095 ctx = logcmdutil.revsingle(repo, rev, None)
5097
5096
5098 if file_:
5097 if file_:
5099 m = scmutil.match(ctx, (file_,), opts)
5098 m = scmutil.match(ctx, (file_,), opts)
5100 if m.anypats() or len(m.files()) != 1:
5099 if m.anypats() or len(m.files()) != 1:
5101 raise error.InputError(_(b'can only specify an explicit filename'))
5100 raise error.InputError(_(b'can only specify an explicit filename'))
5102 file_ = m.files()[0]
5101 file_ = m.files()[0]
5103 filenodes = []
5102 filenodes = []
5104 for cp in ctx.parents():
5103 for cp in ctx.parents():
5105 if not cp:
5104 if not cp:
5106 continue
5105 continue
5107 try:
5106 try:
5108 filenodes.append(cp.filenode(file_))
5107 filenodes.append(cp.filenode(file_))
5109 except error.LookupError:
5108 except error.LookupError:
5110 pass
5109 pass
5111 if not filenodes:
5110 if not filenodes:
5112 raise error.InputError(_(b"'%s' not found in manifest") % file_)
5111 raise error.InputError(_(b"'%s' not found in manifest") % file_)
5113 p = []
5112 p = []
5114 for fn in filenodes:
5113 for fn in filenodes:
5115 fctx = repo.filectx(file_, fileid=fn)
5114 fctx = repo.filectx(file_, fileid=fn)
5116 p.append(fctx.node())
5115 p.append(fctx.node())
5117 else:
5116 else:
5118 p = [cp.node() for cp in ctx.parents()]
5117 p = [cp.node() for cp in ctx.parents()]
5119
5118
5120 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
5119 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
5121 for n in p:
5120 for n in p:
5122 if n != repo.nullid:
5121 if n != repo.nullid:
5123 displayer.show(repo[n])
5122 displayer.show(repo[n])
5124 displayer.close()
5123 displayer.close()
5125
5124
5126
5125
5127 @command(
5126 @command(
5128 b'paths',
5127 b'paths',
5129 formatteropts,
5128 formatteropts,
5130 _(b'[NAME]'),
5129 _(b'[NAME]'),
5131 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5130 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5132 optionalrepo=True,
5131 optionalrepo=True,
5133 intents={INTENT_READONLY},
5132 intents={INTENT_READONLY},
5134 )
5133 )
5135 def paths(ui, repo, search=None, **opts):
5134 def paths(ui, repo, search=None, **opts):
5136 """show aliases for remote repositories
5135 """show aliases for remote repositories
5137
5136
5138 Show definition of symbolic path name NAME. If no name is given,
5137 Show definition of symbolic path name NAME. If no name is given,
5139 show definition of all available names.
5138 show definition of all available names.
5140
5139
5141 Option -q/--quiet suppresses all output when searching for NAME
5140 Option -q/--quiet suppresses all output when searching for NAME
5142 and shows only the path names when listing all definitions.
5141 and shows only the path names when listing all definitions.
5143
5142
5144 Path names are defined in the [paths] section of your
5143 Path names are defined in the [paths] section of your
5145 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
5144 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
5146 repository, ``.hg/hgrc`` is used, too.
5145 repository, ``.hg/hgrc`` is used, too.
5147
5146
5148 The path names ``default`` and ``default-push`` have a special
5147 The path names ``default`` and ``default-push`` have a special
5149 meaning. When performing a push or pull operation, they are used
5148 meaning. When performing a push or pull operation, they are used
5150 as fallbacks if no location is specified on the command-line.
5149 as fallbacks if no location is specified on the command-line.
5151 When ``default-push`` is set, it will be used for push and
5150 When ``default-push`` is set, it will be used for push and
5152 ``default`` will be used for pull; otherwise ``default`` is used
5151 ``default`` will be used for pull; otherwise ``default`` is used
5153 as the fallback for both. When cloning a repository, the clone
5152 as the fallback for both. When cloning a repository, the clone
5154 source is written as ``default`` in ``.hg/hgrc``.
5153 source is written as ``default`` in ``.hg/hgrc``.
5155
5154
5156 .. note::
5155 .. note::
5157
5156
5158 ``default`` and ``default-push`` apply to all inbound (e.g.
5157 ``default`` and ``default-push`` apply to all inbound (e.g.
5159 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
5158 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
5160 and :hg:`bundle`) operations.
5159 and :hg:`bundle`) operations.
5161
5160
5162 See :hg:`help urls` for more information.
5161 See :hg:`help urls` for more information.
5163
5162
5164 .. container:: verbose
5163 .. container:: verbose
5165
5164
5166 Template:
5165 Template:
5167
5166
5168 The following keywords are supported. See also :hg:`help templates`.
5167 The following keywords are supported. See also :hg:`help templates`.
5169
5168
5170 :name: String. Symbolic name of the path alias.
5169 :name: String. Symbolic name of the path alias.
5171 :pushurl: String. URL for push operations.
5170 :pushurl: String. URL for push operations.
5172 :url: String. URL or directory path for the other operations.
5171 :url: String. URL or directory path for the other operations.
5173
5172
5174 Returns 0 on success.
5173 Returns 0 on success.
5175 """
5174 """
5176
5175
5177 opts = pycompat.byteskwargs(opts)
5176 opts = pycompat.byteskwargs(opts)
5178
5177
5179 pathitems = urlutil.list_paths(ui, search)
5178 pathitems = urlutil.list_paths(ui, search)
5180 ui.pager(b'paths')
5179 ui.pager(b'paths')
5181
5180
5182 fm = ui.formatter(b'paths', opts)
5181 fm = ui.formatter(b'paths', opts)
5183 if fm.isplain():
5182 if fm.isplain():
5184 hidepassword = urlutil.hidepassword
5183 hidepassword = urlutil.hidepassword
5185 else:
5184 else:
5186 hidepassword = bytes
5185 hidepassword = bytes
5187 if ui.quiet:
5186 if ui.quiet:
5188 namefmt = b'%s\n'
5187 namefmt = b'%s\n'
5189 else:
5188 else:
5190 namefmt = b'%s = '
5189 namefmt = b'%s = '
5191 showsubopts = not search and not ui.quiet
5190 showsubopts = not search and not ui.quiet
5192
5191
5193 for name, path in pathitems:
5192 for name, path in pathitems:
5194 fm.startitem()
5193 fm.startitem()
5195 fm.condwrite(not search, b'name', namefmt, name)
5194 fm.condwrite(not search, b'name', namefmt, name)
5196 fm.condwrite(not ui.quiet, b'url', b'%s\n', hidepassword(path.rawloc))
5195 fm.condwrite(not ui.quiet, b'url', b'%s\n', hidepassword(path.rawloc))
5197 for subopt, value in sorted(path.suboptions.items()):
5196 for subopt, value in sorted(path.suboptions.items()):
5198 assert subopt not in (b'name', b'url')
5197 assert subopt not in (b'name', b'url')
5199 if showsubopts:
5198 if showsubopts:
5200 fm.plain(b'%s:%s = ' % (name, subopt))
5199 fm.plain(b'%s:%s = ' % (name, subopt))
5201 if isinstance(value, bool):
5200 if isinstance(value, bool):
5202 if value:
5201 if value:
5203 value = b'yes'
5202 value = b'yes'
5204 else:
5203 else:
5205 value = b'no'
5204 value = b'no'
5206 fm.condwrite(showsubopts, subopt, b'%s\n', value)
5205 fm.condwrite(showsubopts, subopt, b'%s\n', value)
5207
5206
5208 fm.end()
5207 fm.end()
5209
5208
5210 if search and not pathitems:
5209 if search and not pathitems:
5211 if not ui.quiet:
5210 if not ui.quiet:
5212 ui.warn(_(b"not found!\n"))
5211 ui.warn(_(b"not found!\n"))
5213 return 1
5212 return 1
5214 else:
5213 else:
5215 return 0
5214 return 0
5216
5215
5217
5216
5218 @command(
5217 @command(
5219 b'phase',
5218 b'phase',
5220 [
5219 [
5221 (b'p', b'public', False, _(b'set changeset phase to public')),
5220 (b'p', b'public', False, _(b'set changeset phase to public')),
5222 (b'd', b'draft', False, _(b'set changeset phase to draft')),
5221 (b'd', b'draft', False, _(b'set changeset phase to draft')),
5223 (b's', b'secret', False, _(b'set changeset phase to secret')),
5222 (b's', b'secret', False, _(b'set changeset phase to secret')),
5224 (b'f', b'force', False, _(b'allow to move boundary backward')),
5223 (b'f', b'force', False, _(b'allow to move boundary backward')),
5225 (b'r', b'rev', [], _(b'target revision'), _(b'REV')),
5224 (b'r', b'rev', [], _(b'target revision'), _(b'REV')),
5226 ],
5225 ],
5227 _(b'[-p|-d|-s] [-f] [-r] [REV...]'),
5226 _(b'[-p|-d|-s] [-f] [-r] [REV...]'),
5228 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
5227 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
5229 )
5228 )
5230 def phase(ui, repo, *revs, **opts):
5229 def phase(ui, repo, *revs, **opts):
5231 """set or show the current phase name
5230 """set or show the current phase name
5232
5231
5233 With no argument, show the phase name of the current revision(s).
5232 With no argument, show the phase name of the current revision(s).
5234
5233
5235 With one of -p/--public, -d/--draft or -s/--secret, change the
5234 With one of -p/--public, -d/--draft or -s/--secret, change the
5236 phase value of the specified revisions.
5235 phase value of the specified revisions.
5237
5236
5238 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
5237 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::
5238 lower phase to a higher phase. Phases are ordered as follows::
5240
5239
5241 public < draft < secret
5240 public < draft < secret
5242
5241
5243 Returns 0 on success, 1 if some phases could not be changed.
5242 Returns 0 on success, 1 if some phases could not be changed.
5244
5243
5245 (For more information about the phases concept, see :hg:`help phases`.)
5244 (For more information about the phases concept, see :hg:`help phases`.)
5246 """
5245 """
5247 opts = pycompat.byteskwargs(opts)
5246 opts = pycompat.byteskwargs(opts)
5248 # search for a unique phase argument
5247 # search for a unique phase argument
5249 targetphase = None
5248 targetphase = None
5250 for idx, name in enumerate(phases.cmdphasenames):
5249 for idx, name in enumerate(phases.cmdphasenames):
5251 if opts[name]:
5250 if opts[name]:
5252 if targetphase is not None:
5251 if targetphase is not None:
5253 raise error.InputError(_(b'only one phase can be specified'))
5252 raise error.InputError(_(b'only one phase can be specified'))
5254 targetphase = idx
5253 targetphase = idx
5255
5254
5256 # look for specified revision
5255 # look for specified revision
5257 revs = list(revs)
5256 revs = list(revs)
5258 revs.extend(opts[b'rev'])
5257 revs.extend(opts[b'rev'])
5259 if revs:
5258 if revs:
5260 revs = logcmdutil.revrange(repo, revs)
5259 revs = logcmdutil.revrange(repo, revs)
5261 else:
5260 else:
5262 # display both parents as the second parent phase can influence
5261 # display both parents as the second parent phase can influence
5263 # the phase of a merge commit
5262 # the phase of a merge commit
5264 revs = [c.rev() for c in repo[None].parents()]
5263 revs = [c.rev() for c in repo[None].parents()]
5265
5264
5266 ret = 0
5265 ret = 0
5267 if targetphase is None:
5266 if targetphase is None:
5268 # display
5267 # display
5269 for r in revs:
5268 for r in revs:
5270 ctx = repo[r]
5269 ctx = repo[r]
5271 ui.write(b'%i: %s\n' % (ctx.rev(), ctx.phasestr()))
5270 ui.write(b'%i: %s\n' % (ctx.rev(), ctx.phasestr()))
5272 else:
5271 else:
5273 with repo.lock(), repo.transaction(b"phase") as tr:
5272 with repo.lock(), repo.transaction(b"phase") as tr:
5274 # set phase
5273 # set phase
5275 if not revs:
5274 if not revs:
5276 raise error.InputError(_(b'empty revision set'))
5275 raise error.InputError(_(b'empty revision set'))
5277 nodes = [repo[r].node() for r in revs]
5276 nodes = [repo[r].node() for r in revs]
5278 # moving revision from public to draft may hide them
5277 # moving revision from public to draft may hide them
5279 # We have to check result on an unfiltered repository
5278 # We have to check result on an unfiltered repository
5280 unfi = repo.unfiltered()
5279 unfi = repo.unfiltered()
5281 getphase = unfi._phasecache.phase
5280 getphase = unfi._phasecache.phase
5282 olddata = [getphase(unfi, r) for r in unfi]
5281 olddata = [getphase(unfi, r) for r in unfi]
5283 phases.advanceboundary(repo, tr, targetphase, nodes)
5282 phases.advanceboundary(repo, tr, targetphase, nodes)
5284 if opts[b'force']:
5283 if opts[b'force']:
5285 phases.retractboundary(repo, tr, targetphase, nodes)
5284 phases.retractboundary(repo, tr, targetphase, nodes)
5286 getphase = unfi._phasecache.phase
5285 getphase = unfi._phasecache.phase
5287 newdata = [getphase(unfi, r) for r in unfi]
5286 newdata = [getphase(unfi, r) for r in unfi]
5288 changes = sum(newdata[r] != olddata[r] for r in unfi)
5287 changes = sum(newdata[r] != olddata[r] for r in unfi)
5289 cl = unfi.changelog
5288 cl = unfi.changelog
5290 rejected = [n for n in nodes if newdata[cl.rev(n)] < targetphase]
5289 rejected = [n for n in nodes if newdata[cl.rev(n)] < targetphase]
5291 if rejected:
5290 if rejected:
5292 ui.warn(
5291 ui.warn(
5293 _(
5292 _(
5294 b'cannot move %i changesets to a higher '
5293 b'cannot move %i changesets to a higher '
5295 b'phase, use --force\n'
5294 b'phase, use --force\n'
5296 )
5295 )
5297 % len(rejected)
5296 % len(rejected)
5298 )
5297 )
5299 ret = 1
5298 ret = 1
5300 if changes:
5299 if changes:
5301 msg = _(b'phase changed for %i changesets\n') % changes
5300 msg = _(b'phase changed for %i changesets\n') % changes
5302 if ret:
5301 if ret:
5303 ui.status(msg)
5302 ui.status(msg)
5304 else:
5303 else:
5305 ui.note(msg)
5304 ui.note(msg)
5306 else:
5305 else:
5307 ui.warn(_(b'no phases changed\n'))
5306 ui.warn(_(b'no phases changed\n'))
5308 return ret
5307 return ret
5309
5308
5310
5309
5311 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
5310 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
5312 """Run after a changegroup has been added via pull/unbundle
5311 """Run after a changegroup has been added via pull/unbundle
5313
5312
5314 This takes arguments below:
5313 This takes arguments below:
5315
5314
5316 :modheads: change of heads by pull/unbundle
5315 :modheads: change of heads by pull/unbundle
5317 :optupdate: updating working directory is needed or not
5316 :optupdate: updating working directory is needed or not
5318 :checkout: update destination revision (or None to default destination)
5317 :checkout: update destination revision (or None to default destination)
5319 :brev: a name, which might be a bookmark to be activated after updating
5318 :brev: a name, which might be a bookmark to be activated after updating
5320
5319
5321 return True if update raise any conflict, False otherwise.
5320 return True if update raise any conflict, False otherwise.
5322 """
5321 """
5323 if modheads == 0:
5322 if modheads == 0:
5324 return False
5323 return False
5325 if optupdate:
5324 if optupdate:
5326 try:
5325 try:
5327 return hg.updatetotally(ui, repo, checkout, brev)
5326 return hg.updatetotally(ui, repo, checkout, brev)
5328 except error.UpdateAbort as inst:
5327 except error.UpdateAbort as inst:
5329 msg = _(b"not updating: %s") % stringutil.forcebytestr(inst)
5328 msg = _(b"not updating: %s") % stringutil.forcebytestr(inst)
5330 hint = inst.hint
5329 hint = inst.hint
5331 raise error.UpdateAbort(msg, hint=hint)
5330 raise error.UpdateAbort(msg, hint=hint)
5332 if modheads is not None and modheads > 1:
5331 if modheads is not None and modheads > 1:
5333 currentbranchheads = len(repo.branchheads())
5332 currentbranchheads = len(repo.branchheads())
5334 if currentbranchheads == modheads:
5333 if currentbranchheads == modheads:
5335 ui.status(
5334 ui.status(
5336 _(b"(run 'hg heads' to see heads, 'hg merge' to merge)\n")
5335 _(b"(run 'hg heads' to see heads, 'hg merge' to merge)\n")
5337 )
5336 )
5338 elif currentbranchheads > 1:
5337 elif currentbranchheads > 1:
5339 ui.status(
5338 ui.status(
5340 _(b"(run 'hg heads .' to see heads, 'hg merge' to merge)\n")
5339 _(b"(run 'hg heads .' to see heads, 'hg merge' to merge)\n")
5341 )
5340 )
5342 else:
5341 else:
5343 ui.status(_(b"(run 'hg heads' to see heads)\n"))
5342 ui.status(_(b"(run 'hg heads' to see heads)\n"))
5344 elif not ui.configbool(b'commands', b'update.requiredest'):
5343 elif not ui.configbool(b'commands', b'update.requiredest'):
5345 ui.status(_(b"(run 'hg update' to get a working copy)\n"))
5344 ui.status(_(b"(run 'hg update' to get a working copy)\n"))
5346 return False
5345 return False
5347
5346
5348
5347
5349 @command(
5348 @command(
5350 b'pull',
5349 b'pull',
5351 [
5350 [
5352 (
5351 (
5353 b'u',
5352 b'u',
5354 b'update',
5353 b'update',
5355 None,
5354 None,
5356 _(b'update to new branch head if new descendants were pulled'),
5355 _(b'update to new branch head if new descendants were pulled'),
5357 ),
5356 ),
5358 (
5357 (
5359 b'f',
5358 b'f',
5360 b'force',
5359 b'force',
5361 None,
5360 None,
5362 _(b'run even when remote repository is unrelated'),
5361 _(b'run even when remote repository is unrelated'),
5363 ),
5362 ),
5364 (
5363 (
5365 b'',
5364 b'',
5366 b'confirm',
5365 b'confirm',
5367 None,
5366 None,
5368 _(b'confirm pull before applying changes'),
5367 _(b'confirm pull before applying changes'),
5369 ),
5368 ),
5370 (
5369 (
5371 b'r',
5370 b'r',
5372 b'rev',
5371 b'rev',
5373 [],
5372 [],
5374 _(b'a remote changeset intended to be added'),
5373 _(b'a remote changeset intended to be added'),
5375 _(b'REV'),
5374 _(b'REV'),
5376 ),
5375 ),
5377 (b'B', b'bookmark', [], _(b"bookmark to pull"), _(b'BOOKMARK')),
5376 (b'B', b'bookmark', [], _(b"bookmark to pull"), _(b'BOOKMARK')),
5378 (
5377 (
5379 b'b',
5378 b'b',
5380 b'branch',
5379 b'branch',
5381 [],
5380 [],
5382 _(b'a specific branch you would like to pull'),
5381 _(b'a specific branch you would like to pull'),
5383 _(b'BRANCH'),
5382 _(b'BRANCH'),
5384 ),
5383 ),
5385 ]
5384 ]
5386 + remoteopts,
5385 + remoteopts,
5387 _(b'[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]...'),
5386 _(b'[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]...'),
5388 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5387 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5389 helpbasic=True,
5388 helpbasic=True,
5390 )
5389 )
5391 def pull(ui, repo, *sources, **opts):
5390 def pull(ui, repo, *sources, **opts):
5392 """pull changes from the specified source
5391 """pull changes from the specified source
5393
5392
5394 Pull changes from a remote repository to a local one.
5393 Pull changes from a remote repository to a local one.
5395
5394
5396 This finds all changes from the repository at the specified path
5395 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
5396 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
5397 -R is specified). By default, this does not update the copy of the
5399 project in the working directory.
5398 project in the working directory.
5400
5399
5401 When cloning from servers that support it, Mercurial may fetch
5400 When cloning from servers that support it, Mercurial may fetch
5402 pre-generated data. When this is done, hooks operating on incoming
5401 pre-generated data. When this is done, hooks operating on incoming
5403 changesets and changegroups may fire more than once, once for each
5402 changesets and changegroups may fire more than once, once for each
5404 pre-generated bundle and as well as for any additional remaining
5403 pre-generated bundle and as well as for any additional remaining
5405 data. See :hg:`help -e clonebundles` for more.
5404 data. See :hg:`help -e clonebundles` for more.
5406
5405
5407 Use :hg:`incoming` if you want to see what would have been added
5406 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
5407 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
5408 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`.
5409 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
5411
5410
5412 If SOURCE is omitted, the 'default' path will be used.
5411 If SOURCE is omitted, the 'default' path will be used.
5413 See :hg:`help urls` for more information.
5412 See :hg:`help urls` for more information.
5414
5413
5415 If multiple sources are specified, they will be pulled sequentially as if
5414 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
5415 the command was run multiple time. If --update is specify and the command
5417 will stop at the first failed --update.
5416 will stop at the first failed --update.
5418
5417
5419 Specifying bookmark as ``.`` is equivalent to specifying the active
5418 Specifying bookmark as ``.`` is equivalent to specifying the active
5420 bookmark's name.
5419 bookmark's name.
5421
5420
5422 Returns 0 on success, 1 if an update had unresolved files.
5421 Returns 0 on success, 1 if an update had unresolved files.
5423 """
5422 """
5424
5423
5425 opts = pycompat.byteskwargs(opts)
5424 opts = pycompat.byteskwargs(opts)
5426 if ui.configbool(b'commands', b'update.requiredest') and opts.get(
5425 if ui.configbool(b'commands', b'update.requiredest') and opts.get(
5427 b'update'
5426 b'update'
5428 ):
5427 ):
5429 msg = _(b'update destination required by configuration')
5428 msg = _(b'update destination required by configuration')
5430 hint = _(b'use hg pull followed by hg update DEST')
5429 hint = _(b'use hg pull followed by hg update DEST')
5431 raise error.InputError(msg, hint=hint)
5430 raise error.InputError(msg, hint=hint)
5432
5431
5433 for path in urlutil.get_pull_paths(repo, ui, sources):
5432 for path in urlutil.get_pull_paths(repo, ui, sources):
5434 ui.status(_(b'pulling from %s\n') % urlutil.hidepassword(path.loc))
5433 ui.status(_(b'pulling from %s\n') % urlutil.hidepassword(path.loc))
5435 ui.flush()
5434 ui.flush()
5436 other = hg.peer(repo, opts, path)
5435 other = hg.peer(repo, opts, path)
5437 update_conflict = None
5436 update_conflict = None
5438 try:
5437 try:
5439 branches = (path.branch, opts.get(b'branch', []))
5438 branches = (path.branch, opts.get(b'branch', []))
5440 revs, checkout = hg.addbranchrevs(
5439 revs, checkout = hg.addbranchrevs(
5441 repo, other, branches, opts.get(b'rev')
5440 repo, other, branches, opts.get(b'rev')
5442 )
5441 )
5443
5442
5444 pullopargs = {}
5443 pullopargs = {}
5445
5444
5446 nodes = None
5445 nodes = None
5447 if opts.get(b'bookmark') or revs:
5446 if opts.get(b'bookmark') or revs:
5448 # The list of bookmark used here is the same used to actually update
5447 # 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
5448 # 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
5449 # all lookup and bookmark queries in one go so they see the same
5451 # version of the server state (issue 4700).
5450 # version of the server state (issue 4700).
5452 nodes = []
5451 nodes = []
5453 fnodes = []
5452 fnodes = []
5454 revs = revs or []
5453 revs = revs or []
5455 if revs and not other.capable(b'lookup'):
5454 if revs and not other.capable(b'lookup'):
5456 err = _(
5455 err = _(
5457 b"other repository doesn't support revision lookup, "
5456 b"other repository doesn't support revision lookup, "
5458 b"so a rev cannot be specified."
5457 b"so a rev cannot be specified."
5459 )
5458 )
5460 raise error.Abort(err)
5459 raise error.Abort(err)
5461 with other.commandexecutor() as e:
5460 with other.commandexecutor() as e:
5462 fremotebookmarks = e.callcommand(
5461 fremotebookmarks = e.callcommand(
5463 b'listkeys', {b'namespace': b'bookmarks'}
5462 b'listkeys', {b'namespace': b'bookmarks'}
5464 )
5463 )
5465 for r in revs:
5464 for r in revs:
5466 fnodes.append(e.callcommand(b'lookup', {b'key': r}))
5465 fnodes.append(e.callcommand(b'lookup', {b'key': r}))
5467 remotebookmarks = fremotebookmarks.result()
5466 remotebookmarks = fremotebookmarks.result()
5468 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
5467 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
5469 pullopargs[b'remotebookmarks'] = remotebookmarks
5468 pullopargs[b'remotebookmarks'] = remotebookmarks
5470 for b in opts.get(b'bookmark', []):
5469 for b in opts.get(b'bookmark', []):
5471 b = repo._bookmarks.expandname(b)
5470 b = repo._bookmarks.expandname(b)
5472 if b not in remotebookmarks:
5471 if b not in remotebookmarks:
5473 raise error.InputError(
5472 raise error.InputError(
5474 _(b'remote bookmark %s not found!') % b
5473 _(b'remote bookmark %s not found!') % b
5475 )
5474 )
5476 nodes.append(remotebookmarks[b])
5475 nodes.append(remotebookmarks[b])
5477 for i, rev in enumerate(revs):
5476 for i, rev in enumerate(revs):
5478 node = fnodes[i].result()
5477 node = fnodes[i].result()
5479 nodes.append(node)
5478 nodes.append(node)
5480 if rev == checkout:
5479 if rev == checkout:
5481 checkout = node
5480 checkout = node
5482
5481
5483 wlock = util.nullcontextmanager()
5482 wlock = util.nullcontextmanager()
5484 if opts.get(b'update'):
5483 if opts.get(b'update'):
5485 wlock = repo.wlock()
5484 wlock = repo.wlock()
5486 with wlock:
5485 with wlock:
5487 pullopargs.update(opts.get(b'opargs', {}))
5486 pullopargs.update(opts.get(b'opargs', {}))
5488 modheads = exchange.pull(
5487 modheads = exchange.pull(
5489 repo,
5488 repo,
5490 other,
5489 other,
5491 path=path,
5490 path=path,
5492 heads=nodes,
5491 heads=nodes,
5493 force=opts.get(b'force'),
5492 force=opts.get(b'force'),
5494 bookmarks=opts.get(b'bookmark', ()),
5493 bookmarks=opts.get(b'bookmark', ()),
5495 opargs=pullopargs,
5494 opargs=pullopargs,
5496 confirm=opts.get(b'confirm'),
5495 confirm=opts.get(b'confirm'),
5497 ).cgresult
5496 ).cgresult
5498
5497
5499 # brev is a name, which might be a bookmark to be activated at
5498 # 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
5499 # the end of the update. In other words, it is an explicit
5501 # destination of the update
5500 # destination of the update
5502 brev = None
5501 brev = None
5503
5502
5504 if checkout:
5503 if checkout:
5505 checkout = repo.unfiltered().changelog.rev(checkout)
5504 checkout = repo.unfiltered().changelog.rev(checkout)
5506
5505
5507 # order below depends on implementation of
5506 # order below depends on implementation of
5508 # hg.addbranchrevs(). opts['bookmark'] is ignored,
5507 # hg.addbranchrevs(). opts['bookmark'] is ignored,
5509 # because 'checkout' is determined without it.
5508 # because 'checkout' is determined without it.
5510 if opts.get(b'rev'):
5509 if opts.get(b'rev'):
5511 brev = opts[b'rev'][0]
5510 brev = opts[b'rev'][0]
5512 elif opts.get(b'branch'):
5511 elif opts.get(b'branch'):
5513 brev = opts[b'branch'][0]
5512 brev = opts[b'branch'][0]
5514 else:
5513 else:
5515 brev = path.branch
5514 brev = path.branch
5516
5515
5517 # XXX path: we are losing the `path` object here. Keeping it
5516 # XXX path: we are losing the `path` object here. Keeping it
5518 # would be valuable. For example as a "variant" as we do
5517 # would be valuable. For example as a "variant" as we do
5519 # for pushes.
5518 # for pushes.
5520 repo._subtoppath = path.loc
5519 repo._subtoppath = path.loc
5521 try:
5520 try:
5522 update_conflict = postincoming(
5521 update_conflict = postincoming(
5523 ui, repo, modheads, opts.get(b'update'), checkout, brev
5522 ui, repo, modheads, opts.get(b'update'), checkout, brev
5524 )
5523 )
5525 except error.FilteredRepoLookupError as exc:
5524 except error.FilteredRepoLookupError as exc:
5526 msg = _(b'cannot update to target: %s') % exc.args[0]
5525 msg = _(b'cannot update to target: %s') % exc.args[0]
5527 exc.args = (msg,) + exc.args[1:]
5526 exc.args = (msg,) + exc.args[1:]
5528 raise
5527 raise
5529 finally:
5528 finally:
5530 del repo._subtoppath
5529 del repo._subtoppath
5531
5530
5532 finally:
5531 finally:
5533 other.close()
5532 other.close()
5534 # skip the remaining pull source if they are some conflict.
5533 # skip the remaining pull source if they are some conflict.
5535 if update_conflict:
5534 if update_conflict:
5536 break
5535 break
5537 if update_conflict:
5536 if update_conflict:
5538 return 1
5537 return 1
5539 else:
5538 else:
5540 return 0
5539 return 0
5541
5540
5542
5541
5543 @command(
5542 @command(
5544 b'purge|clean',
5543 b'purge|clean',
5545 [
5544 [
5546 (b'a', b'abort-on-err', None, _(b'abort if an error occurs')),
5545 (b'a', b'abort-on-err', None, _(b'abort if an error occurs')),
5547 (b'', b'all', None, _(b'purge ignored files too')),
5546 (b'', b'all', None, _(b'purge ignored files too')),
5548 (b'i', b'ignored', None, _(b'purge only ignored files')),
5547 (b'i', b'ignored', None, _(b'purge only ignored files')),
5549 (b'', b'dirs', None, _(b'purge empty directories')),
5548 (b'', b'dirs', None, _(b'purge empty directories')),
5550 (b'', b'files', None, _(b'purge files')),
5549 (b'', b'files', None, _(b'purge files')),
5551 (b'p', b'print', None, _(b'print filenames instead of deleting them')),
5550 (b'p', b'print', None, _(b'print filenames instead of deleting them')),
5552 (
5551 (
5553 b'0',
5552 b'0',
5554 b'print0',
5553 b'print0',
5555 None,
5554 None,
5556 _(
5555 _(
5557 b'end filenames with NUL, for use with xargs'
5556 b'end filenames with NUL, for use with xargs'
5558 b' (implies -p/--print)'
5557 b' (implies -p/--print)'
5559 ),
5558 ),
5560 ),
5559 ),
5561 (b'', b'confirm', None, _(b'ask before permanently deleting files')),
5560 (b'', b'confirm', None, _(b'ask before permanently deleting files')),
5562 ]
5561 ]
5563 + cmdutil.walkopts,
5562 + cmdutil.walkopts,
5564 _(b'hg purge [OPTION]... [DIR]...'),
5563 _(b'hg purge [OPTION]... [DIR]...'),
5565 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5564 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5566 )
5565 )
5567 def purge(ui, repo, *dirs, **opts):
5566 def purge(ui, repo, *dirs, **opts):
5568 """removes files not tracked by Mercurial
5567 """removes files not tracked by Mercurial
5569
5568
5570 Delete files not known to Mercurial. This is useful to test local
5569 Delete files not known to Mercurial. This is useful to test local
5571 and uncommitted changes in an otherwise-clean source tree.
5570 and uncommitted changes in an otherwise-clean source tree.
5572
5571
5573 This means that purge will delete the following by default:
5572 This means that purge will delete the following by default:
5574
5573
5575 - Unknown files: files marked with "?" by :hg:`status`
5574 - Unknown files: files marked with "?" by :hg:`status`
5576 - Empty directories: in fact Mercurial ignores directories unless
5575 - Empty directories: in fact Mercurial ignores directories unless
5577 they contain files under source control management
5576 they contain files under source control management
5578
5577
5579 But it will leave untouched:
5578 But it will leave untouched:
5580
5579
5581 - Modified and unmodified tracked files
5580 - Modified and unmodified tracked files
5582 - Ignored files (unless -i or --all is specified)
5581 - Ignored files (unless -i or --all is specified)
5583 - New files added to the repository (with :hg:`add`)
5582 - New files added to the repository (with :hg:`add`)
5584
5583
5585 The --files and --dirs options can be used to direct purge to delete
5584 The --files and --dirs options can be used to direct purge to delete
5586 only files, only directories, or both. If neither option is given,
5585 only files, only directories, or both. If neither option is given,
5587 both will be deleted.
5586 both will be deleted.
5588
5587
5589 If directories are given on the command line, only files in these
5588 If directories are given on the command line, only files in these
5590 directories are considered.
5589 directories are considered.
5591
5590
5592 Be careful with purge, as you could irreversibly delete some files
5591 Be careful with purge, as you could irreversibly delete some files
5593 you forgot to add to the repository. If you only want to print the
5592 you forgot to add to the repository. If you only want to print the
5594 list of files that this program would delete, use the --print
5593 list of files that this program would delete, use the --print
5595 option.
5594 option.
5596 """
5595 """
5597 opts = pycompat.byteskwargs(opts)
5596 opts = pycompat.byteskwargs(opts)
5598 cmdutil.check_at_most_one_arg(opts, b'all', b'ignored')
5597 cmdutil.check_at_most_one_arg(opts, b'all', b'ignored')
5599
5598
5600 act = not opts.get(b'print')
5599 act = not opts.get(b'print')
5601 eol = b'\n'
5600 eol = b'\n'
5602 if opts.get(b'print0'):
5601 if opts.get(b'print0'):
5603 eol = b'\0'
5602 eol = b'\0'
5604 act = False # --print0 implies --print
5603 act = False # --print0 implies --print
5605 if opts.get(b'all', False):
5604 if opts.get(b'all', False):
5606 ignored = True
5605 ignored = True
5607 unknown = True
5606 unknown = True
5608 else:
5607 else:
5609 ignored = opts.get(b'ignored', False)
5608 ignored = opts.get(b'ignored', False)
5610 unknown = not ignored
5609 unknown = not ignored
5611
5610
5612 removefiles = opts.get(b'files')
5611 removefiles = opts.get(b'files')
5613 removedirs = opts.get(b'dirs')
5612 removedirs = opts.get(b'dirs')
5614 confirm = opts.get(b'confirm')
5613 confirm = opts.get(b'confirm')
5615 if confirm is None:
5614 if confirm is None:
5616 try:
5615 try:
5617 extensions.find(b'purge')
5616 extensions.find(b'purge')
5618 confirm = False
5617 confirm = False
5619 except KeyError:
5618 except KeyError:
5620 confirm = True
5619 confirm = True
5621
5620
5622 if not removefiles and not removedirs:
5621 if not removefiles and not removedirs:
5623 removefiles = True
5622 removefiles = True
5624 removedirs = True
5623 removedirs = True
5625
5624
5626 match = scmutil.match(repo[None], dirs, opts)
5625 match = scmutil.match(repo[None], dirs, opts)
5627
5626
5628 paths = mergemod.purge(
5627 paths = mergemod.purge(
5629 repo,
5628 repo,
5630 match,
5629 match,
5631 unknown=unknown,
5630 unknown=unknown,
5632 ignored=ignored,
5631 ignored=ignored,
5633 removeemptydirs=removedirs,
5632 removeemptydirs=removedirs,
5634 removefiles=removefiles,
5633 removefiles=removefiles,
5635 abortonerror=opts.get(b'abort_on_err'),
5634 abortonerror=opts.get(b'abort_on_err'),
5636 noop=not act,
5635 noop=not act,
5637 confirm=confirm,
5636 confirm=confirm,
5638 )
5637 )
5639
5638
5640 for path in paths:
5639 for path in paths:
5641 if not act:
5640 if not act:
5642 ui.write(b'%s%s' % (path, eol))
5641 ui.write(b'%s%s' % (path, eol))
5643
5642
5644
5643
5645 @command(
5644 @command(
5646 b'push',
5645 b'push',
5647 [
5646 [
5648 (b'f', b'force', None, _(b'force push')),
5647 (b'f', b'force', None, _(b'force push')),
5649 (
5648 (
5650 b'r',
5649 b'r',
5651 b'rev',
5650 b'rev',
5652 [],
5651 [],
5653 _(b'a changeset intended to be included in the destination'),
5652 _(b'a changeset intended to be included in the destination'),
5654 _(b'REV'),
5653 _(b'REV'),
5655 ),
5654 ),
5656 (b'B', b'bookmark', [], _(b"bookmark to push"), _(b'BOOKMARK')),
5655 (b'B', b'bookmark', [], _(b"bookmark to push"), _(b'BOOKMARK')),
5657 (b'', b'all-bookmarks', None, _(b"push all bookmarks (EXPERIMENTAL)")),
5656 (b'', b'all-bookmarks', None, _(b"push all bookmarks (EXPERIMENTAL)")),
5658 (
5657 (
5659 b'b',
5658 b'b',
5660 b'branch',
5659 b'branch',
5661 [],
5660 [],
5662 _(b'a specific branch you would like to push'),
5661 _(b'a specific branch you would like to push'),
5663 _(b'BRANCH'),
5662 _(b'BRANCH'),
5664 ),
5663 ),
5665 (b'', b'new-branch', False, _(b'allow pushing a new branch')),
5664 (b'', b'new-branch', False, _(b'allow pushing a new branch')),
5666 (
5665 (
5667 b'',
5666 b'',
5668 b'pushvars',
5667 b'pushvars',
5669 [],
5668 [],
5670 _(b'variables that can be sent to server (ADVANCED)'),
5669 _(b'variables that can be sent to server (ADVANCED)'),
5671 ),
5670 ),
5672 (
5671 (
5673 b'',
5672 b'',
5674 b'publish',
5673 b'publish',
5675 False,
5674 False,
5676 _(b'push the changeset as public (EXPERIMENTAL)'),
5675 _(b'push the changeset as public (EXPERIMENTAL)'),
5677 ),
5676 ),
5678 ]
5677 ]
5679 + remoteopts,
5678 + remoteopts,
5680 _(b'[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]...'),
5679 _(b'[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]...'),
5681 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5680 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5682 helpbasic=True,
5681 helpbasic=True,
5683 )
5682 )
5684 def push(ui, repo, *dests, **opts):
5683 def push(ui, repo, *dests, **opts):
5685 """push changes to the specified destination
5684 """push changes to the specified destination
5686
5685
5687 Push changesets from the local repository to the specified
5686 Push changesets from the local repository to the specified
5688 destination.
5687 destination.
5689
5688
5690 This operation is symmetrical to pull: it is identical to a pull
5689 This operation is symmetrical to pull: it is identical to a pull
5691 in the destination repository from the current one.
5690 in the destination repository from the current one.
5692
5691
5693 By default, push will not allow creation of new heads at the
5692 By default, push will not allow creation of new heads at the
5694 destination, since multiple heads would make it unclear which head
5693 destination, since multiple heads would make it unclear which head
5695 to use. In this situation, it is recommended to pull and merge
5694 to use. In this situation, it is recommended to pull and merge
5696 before pushing.
5695 before pushing.
5697
5696
5698 Use --new-branch if you want to allow push to create a new named
5697 Use --new-branch if you want to allow push to create a new named
5699 branch that is not present at the destination. This allows you to
5698 branch that is not present at the destination. This allows you to
5700 only create a new branch without forcing other changes.
5699 only create a new branch without forcing other changes.
5701
5700
5702 .. note::
5701 .. note::
5703
5702
5704 Extra care should be taken with the -f/--force option,
5703 Extra care should be taken with the -f/--force option,
5705 which will push all new heads on all branches, an action which will
5704 which will push all new heads on all branches, an action which will
5706 almost always cause confusion for collaborators.
5705 almost always cause confusion for collaborators.
5707
5706
5708 If -r/--rev is used, the specified revision and all its ancestors
5707 If -r/--rev is used, the specified revision and all its ancestors
5709 will be pushed to the remote repository.
5708 will be pushed to the remote repository.
5710
5709
5711 If -B/--bookmark is used, the specified bookmarked revision, its
5710 If -B/--bookmark is used, the specified bookmarked revision, its
5712 ancestors, and the bookmark will be pushed to the remote
5711 ancestors, and the bookmark will be pushed to the remote
5713 repository. Specifying ``.`` is equivalent to specifying the active
5712 repository. Specifying ``.`` is equivalent to specifying the active
5714 bookmark's name. Use the --all-bookmarks option for pushing all
5713 bookmark's name. Use the --all-bookmarks option for pushing all
5715 current bookmarks.
5714 current bookmarks.
5716
5715
5717 Please see :hg:`help urls` for important details about ``ssh://``
5716 Please see :hg:`help urls` for important details about ``ssh://``
5718 URLs. If DESTINATION is omitted, a default path will be used.
5717 URLs. If DESTINATION is omitted, a default path will be used.
5719
5718
5720 When passed multiple destinations, push will process them one after the
5719 When passed multiple destinations, push will process them one after the
5721 other, but stop should an error occur.
5720 other, but stop should an error occur.
5722
5721
5723 .. container:: verbose
5722 .. container:: verbose
5724
5723
5725 The --pushvars option sends strings to the server that become
5724 The --pushvars option sends strings to the server that become
5726 environment variables prepended with ``HG_USERVAR_``. For example,
5725 environment variables prepended with ``HG_USERVAR_``. For example,
5727 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
5726 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
5728 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
5727 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
5729
5728
5730 pushvars can provide for user-overridable hooks as well as set debug
5729 pushvars can provide for user-overridable hooks as well as set debug
5731 levels. One example is having a hook that blocks commits containing
5730 levels. One example is having a hook that blocks commits containing
5732 conflict markers, but enables the user to override the hook if the file
5731 conflict markers, but enables the user to override the hook if the file
5733 is using conflict markers for testing purposes or the file format has
5732 is using conflict markers for testing purposes or the file format has
5734 strings that look like conflict markers.
5733 strings that look like conflict markers.
5735
5734
5736 By default, servers will ignore `--pushvars`. To enable it add the
5735 By default, servers will ignore `--pushvars`. To enable it add the
5737 following to your configuration file::
5736 following to your configuration file::
5738
5737
5739 [push]
5738 [push]
5740 pushvars.server = true
5739 pushvars.server = true
5741
5740
5742 Returns 0 if push was successful, 1 if nothing to push.
5741 Returns 0 if push was successful, 1 if nothing to push.
5743 """
5742 """
5744
5743
5745 opts = pycompat.byteskwargs(opts)
5744 opts = pycompat.byteskwargs(opts)
5746
5745
5747 if opts.get(b'all_bookmarks'):
5746 if opts.get(b'all_bookmarks'):
5748 cmdutil.check_incompatible_arguments(
5747 cmdutil.check_incompatible_arguments(
5749 opts,
5748 opts,
5750 b'all_bookmarks',
5749 b'all_bookmarks',
5751 [b'bookmark', b'rev'],
5750 [b'bookmark', b'rev'],
5752 )
5751 )
5753 opts[b'bookmark'] = list(repo._bookmarks)
5752 opts[b'bookmark'] = list(repo._bookmarks)
5754
5753
5755 if opts.get(b'bookmark'):
5754 if opts.get(b'bookmark'):
5756 ui.setconfig(b'bookmarks', b'pushing', opts[b'bookmark'], b'push')
5755 ui.setconfig(b'bookmarks', b'pushing', opts[b'bookmark'], b'push')
5757 for b in opts[b'bookmark']:
5756 for b in opts[b'bookmark']:
5758 # translate -B options to -r so changesets get pushed
5757 # translate -B options to -r so changesets get pushed
5759 b = repo._bookmarks.expandname(b)
5758 b = repo._bookmarks.expandname(b)
5760 if b in repo._bookmarks:
5759 if b in repo._bookmarks:
5761 opts.setdefault(b'rev', []).append(b)
5760 opts.setdefault(b'rev', []).append(b)
5762 else:
5761 else:
5763 # if we try to push a deleted bookmark, translate it to null
5762 # if we try to push a deleted bookmark, translate it to null
5764 # this lets simultaneous -r, -b options continue working
5763 # this lets simultaneous -r, -b options continue working
5765 opts.setdefault(b'rev', []).append(b"null")
5764 opts.setdefault(b'rev', []).append(b"null")
5766
5765
5767 some_pushed = False
5766 some_pushed = False
5768 result = 0
5767 result = 0
5769 for path in urlutil.get_push_paths(repo, ui, dests):
5768 for path in urlutil.get_push_paths(repo, ui, dests):
5770 dest = path.loc
5769 dest = path.loc
5771 branches = (path.branch, opts.get(b'branch') or [])
5770 branches = (path.branch, opts.get(b'branch') or [])
5772 ui.status(_(b'pushing to %s\n') % urlutil.hidepassword(dest))
5771 ui.status(_(b'pushing to %s\n') % urlutil.hidepassword(dest))
5773 revs, checkout = hg.addbranchrevs(
5772 revs, checkout = hg.addbranchrevs(
5774 repo, repo, branches, opts.get(b'rev')
5773 repo, repo, branches, opts.get(b'rev')
5775 )
5774 )
5776 other = hg.peer(repo, opts, dest)
5775 other = hg.peer(repo, opts, dest)
5777
5776
5778 try:
5777 try:
5779 if revs:
5778 if revs:
5780 revs = [repo[r].node() for r in logcmdutil.revrange(repo, revs)]
5779 revs = [repo[r].node() for r in logcmdutil.revrange(repo, revs)]
5781 if not revs:
5780 if not revs:
5782 raise error.InputError(
5781 raise error.InputError(
5783 _(b"specified revisions evaluate to an empty set"),
5782 _(b"specified revisions evaluate to an empty set"),
5784 hint=_(b"use different revision arguments"),
5783 hint=_(b"use different revision arguments"),
5785 )
5784 )
5786 elif path.pushrev:
5785 elif path.pushrev:
5787 # It doesn't make any sense to specify ancestor revisions. So limit
5786 # It doesn't make any sense to specify ancestor revisions. So limit
5788 # to DAG heads to make discovery simpler.
5787 # to DAG heads to make discovery simpler.
5789 expr = revsetlang.formatspec(b'heads(%r)', path.pushrev)
5788 expr = revsetlang.formatspec(b'heads(%r)', path.pushrev)
5790 revs = scmutil.revrange(repo, [expr])
5789 revs = scmutil.revrange(repo, [expr])
5791 revs = [repo[rev].node() for rev in revs]
5790 revs = [repo[rev].node() for rev in revs]
5792 if not revs:
5791 if not revs:
5793 raise error.InputError(
5792 raise error.InputError(
5794 _(
5793 _(
5795 b'default push revset for path evaluates to an empty set'
5794 b'default push revset for path evaluates to an empty set'
5796 )
5795 )
5797 )
5796 )
5798 elif ui.configbool(b'commands', b'push.require-revs'):
5797 elif ui.configbool(b'commands', b'push.require-revs'):
5799 raise error.InputError(
5798 raise error.InputError(
5800 _(b'no revisions specified to push'),
5799 _(b'no revisions specified to push'),
5801 hint=_(b'did you mean "hg push -r ."?'),
5800 hint=_(b'did you mean "hg push -r ."?'),
5802 )
5801 )
5803
5802
5804 repo._subtoppath = dest
5803 repo._subtoppath = dest
5805 try:
5804 try:
5806 # push subrepos depth-first for coherent ordering
5805 # push subrepos depth-first for coherent ordering
5807 c = repo[b'.']
5806 c = repo[b'.']
5808 subs = c.substate # only repos that are committed
5807 subs = c.substate # only repos that are committed
5809 for s in sorted(subs):
5808 for s in sorted(subs):
5810 sub_result = c.sub(s).push(opts)
5809 sub_result = c.sub(s).push(opts)
5811 if sub_result == 0:
5810 if sub_result == 0:
5812 return 1
5811 return 1
5813 finally:
5812 finally:
5814 del repo._subtoppath
5813 del repo._subtoppath
5815
5814
5816 opargs = dict(
5815 opargs = dict(
5817 opts.get(b'opargs', {})
5816 opts.get(b'opargs', {})
5818 ) # copy opargs since we may mutate it
5817 ) # copy opargs since we may mutate it
5819 opargs.setdefault(b'pushvars', []).extend(opts.get(b'pushvars', []))
5818 opargs.setdefault(b'pushvars', []).extend(opts.get(b'pushvars', []))
5820
5819
5821 pushop = exchange.push(
5820 pushop = exchange.push(
5822 repo,
5821 repo,
5823 other,
5822 other,
5824 opts.get(b'force'),
5823 opts.get(b'force'),
5825 revs=revs,
5824 revs=revs,
5826 newbranch=opts.get(b'new_branch'),
5825 newbranch=opts.get(b'new_branch'),
5827 bookmarks=opts.get(b'bookmark', ()),
5826 bookmarks=opts.get(b'bookmark', ()),
5828 publish=opts.get(b'publish'),
5827 publish=opts.get(b'publish'),
5829 opargs=opargs,
5828 opargs=opargs,
5830 )
5829 )
5831
5830
5832 if pushop.cgresult == 0:
5831 if pushop.cgresult == 0:
5833 result = 1
5832 result = 1
5834 elif pushop.cgresult is not None:
5833 elif pushop.cgresult is not None:
5835 some_pushed = True
5834 some_pushed = True
5836
5835
5837 if pushop.bkresult is not None:
5836 if pushop.bkresult is not None:
5838 if pushop.bkresult == 2:
5837 if pushop.bkresult == 2:
5839 result = 2
5838 result = 2
5840 elif not result and pushop.bkresult:
5839 elif not result and pushop.bkresult:
5841 result = 2
5840 result = 2
5842
5841
5843 if result:
5842 if result:
5844 break
5843 break
5845
5844
5846 finally:
5845 finally:
5847 other.close()
5846 other.close()
5848 if result == 0 and not some_pushed:
5847 if result == 0 and not some_pushed:
5849 result = 1
5848 result = 1
5850 return result
5849 return result
5851
5850
5852
5851
5853 @command(
5852 @command(
5854 b'recover',
5853 b'recover',
5855 [
5854 [
5856 (b'', b'verify', False, b"run `hg verify` after successful recover"),
5855 (b'', b'verify', False, b"run `hg verify` after successful recover"),
5857 ],
5856 ],
5858 helpcategory=command.CATEGORY_MAINTENANCE,
5857 helpcategory=command.CATEGORY_MAINTENANCE,
5859 )
5858 )
5860 def recover(ui, repo, **opts):
5859 def recover(ui, repo, **opts):
5861 """roll back an interrupted transaction
5860 """roll back an interrupted transaction
5862
5861
5863 Recover from an interrupted commit or pull.
5862 Recover from an interrupted commit or pull.
5864
5863
5865 This command tries to fix the repository status after an
5864 This command tries to fix the repository status after an
5866 interrupted operation. It should only be necessary when Mercurial
5865 interrupted operation. It should only be necessary when Mercurial
5867 suggests it.
5866 suggests it.
5868
5867
5869 Returns 0 if successful, 1 if nothing to recover or verify fails.
5868 Returns 0 if successful, 1 if nothing to recover or verify fails.
5870 """
5869 """
5871 ret = repo.recover()
5870 ret = repo.recover()
5872 if ret:
5871 if ret:
5873 if opts['verify']:
5872 if opts['verify']:
5874 return hg.verify(repo)
5873 return hg.verify(repo)
5875 else:
5874 else:
5876 msg = _(
5875 msg = _(
5877 b"(verify step skipped, run `hg verify` to check your "
5876 b"(verify step skipped, run `hg verify` to check your "
5878 b"repository content)\n"
5877 b"repository content)\n"
5879 )
5878 )
5880 ui.warn(msg)
5879 ui.warn(msg)
5881 return 0
5880 return 0
5882 return 1
5881 return 1
5883
5882
5884
5883
5885 @command(
5884 @command(
5886 b'remove|rm',
5885 b'remove|rm',
5887 [
5886 [
5888 (b'A', b'after', None, _(b'record delete for missing files')),
5887 (b'A', b'after', None, _(b'record delete for missing files')),
5889 (b'f', b'force', None, _(b'forget added files, delete modified files')),
5888 (b'f', b'force', None, _(b'forget added files, delete modified files')),
5890 ]
5889 ]
5891 + subrepoopts
5890 + subrepoopts
5892 + walkopts
5891 + walkopts
5893 + dryrunopts,
5892 + dryrunopts,
5894 _(b'[OPTION]... FILE...'),
5893 _(b'[OPTION]... FILE...'),
5895 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5894 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5896 helpbasic=True,
5895 helpbasic=True,
5897 inferrepo=True,
5896 inferrepo=True,
5898 )
5897 )
5899 def remove(ui, repo, *pats, **opts):
5898 def remove(ui, repo, *pats, **opts):
5900 """remove the specified files on the next commit
5899 """remove the specified files on the next commit
5901
5900
5902 Schedule the indicated files for removal from the current branch.
5901 Schedule the indicated files for removal from the current branch.
5903
5902
5904 This command schedules the files to be removed at the next commit.
5903 This command schedules the files to be removed at the next commit.
5905 To undo a remove before that, see :hg:`revert`. To undo added
5904 To undo a remove before that, see :hg:`revert`. To undo added
5906 files, see :hg:`forget`.
5905 files, see :hg:`forget`.
5907
5906
5908 .. container:: verbose
5907 .. container:: verbose
5909
5908
5910 -A/--after can be used to remove only files that have already
5909 -A/--after can be used to remove only files that have already
5911 been deleted, -f/--force can be used to force deletion, and -Af
5910 been deleted, -f/--force can be used to force deletion, and -Af
5912 can be used to remove files from the next revision without
5911 can be used to remove files from the next revision without
5913 deleting them from the working directory.
5912 deleting them from the working directory.
5914
5913
5915 The following table details the behavior of remove for different
5914 The following table details the behavior of remove for different
5916 file states (columns) and option combinations (rows). The file
5915 file states (columns) and option combinations (rows). The file
5917 states are Added [A], Clean [C], Modified [M] and Missing [!]
5916 states are Added [A], Clean [C], Modified [M] and Missing [!]
5918 (as reported by :hg:`status`). The actions are Warn, Remove
5917 (as reported by :hg:`status`). The actions are Warn, Remove
5919 (from branch) and Delete (from disk):
5918 (from branch) and Delete (from disk):
5920
5919
5921 ========= == == == ==
5920 ========= == == == ==
5922 opt/state A C M !
5921 opt/state A C M !
5923 ========= == == == ==
5922 ========= == == == ==
5924 none W RD W R
5923 none W RD W R
5925 -f R RD RD R
5924 -f R RD RD R
5926 -A W W W R
5925 -A W W W R
5927 -Af R R R R
5926 -Af R R R R
5928 ========= == == == ==
5927 ========= == == == ==
5929
5928
5930 .. note::
5929 .. note::
5931
5930
5932 :hg:`remove` never deletes files in Added [A] state from the
5931 :hg:`remove` never deletes files in Added [A] state from the
5933 working directory, not even if ``--force`` is specified.
5932 working directory, not even if ``--force`` is specified.
5934
5933
5935 Returns 0 on success, 1 if any warnings encountered.
5934 Returns 0 on success, 1 if any warnings encountered.
5936 """
5935 """
5937
5936
5938 opts = pycompat.byteskwargs(opts)
5937 opts = pycompat.byteskwargs(opts)
5939 after, force = opts.get(b'after'), opts.get(b'force')
5938 after, force = opts.get(b'after'), opts.get(b'force')
5940 dryrun = opts.get(b'dry_run')
5939 dryrun = opts.get(b'dry_run')
5941 if not pats and not after:
5940 if not pats and not after:
5942 raise error.InputError(_(b'no files specified'))
5941 raise error.InputError(_(b'no files specified'))
5943
5942
5944 m = scmutil.match(repo[None], pats, opts)
5943 m = scmutil.match(repo[None], pats, opts)
5945 subrepos = opts.get(b'subrepos')
5944 subrepos = opts.get(b'subrepos')
5946 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
5945 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
5947 return cmdutil.remove(
5946 return cmdutil.remove(
5948 ui, repo, m, b"", uipathfn, after, force, subrepos, dryrun=dryrun
5947 ui, repo, m, b"", uipathfn, after, force, subrepos, dryrun=dryrun
5949 )
5948 )
5950
5949
5951
5950
5952 @command(
5951 @command(
5953 b'rename|move|mv',
5952 b'rename|move|mv',
5954 [
5953 [
5955 (b'', b'forget', None, _(b'unmark a destination file as renamed')),
5954 (b'', b'forget', None, _(b'unmark a destination file as renamed')),
5956 (b'A', b'after', None, _(b'record a rename that has already occurred')),
5955 (b'A', b'after', None, _(b'record a rename that has already occurred')),
5957 (
5956 (
5958 b'',
5957 b'',
5959 b'at-rev',
5958 b'at-rev',
5960 b'',
5959 b'',
5961 _(b'(un)mark renames in the given revision (EXPERIMENTAL)'),
5960 _(b'(un)mark renames in the given revision (EXPERIMENTAL)'),
5962 _(b'REV'),
5961 _(b'REV'),
5963 ),
5962 ),
5964 (
5963 (
5965 b'f',
5964 b'f',
5966 b'force',
5965 b'force',
5967 None,
5966 None,
5968 _(b'forcibly move over an existing managed file'),
5967 _(b'forcibly move over an existing managed file'),
5969 ),
5968 ),
5970 ]
5969 ]
5971 + walkopts
5970 + walkopts
5972 + dryrunopts,
5971 + dryrunopts,
5973 _(b'[OPTION]... SOURCE... DEST'),
5972 _(b'[OPTION]... SOURCE... DEST'),
5974 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5973 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5975 )
5974 )
5976 def rename(ui, repo, *pats, **opts):
5975 def rename(ui, repo, *pats, **opts):
5977 """rename files; equivalent of copy + remove
5976 """rename files; equivalent of copy + remove
5978
5977
5979 Mark dest as copies of sources; mark sources for deletion. If dest
5978 Mark dest as copies of sources; mark sources for deletion. If dest
5980 is a directory, copies are put in that directory. If dest is a
5979 is a directory, copies are put in that directory. If dest is a
5981 file, there can only be one source.
5980 file, there can only be one source.
5982
5981
5983 By default, this command copies the contents of files as they
5982 By default, this command copies the contents of files as they
5984 exist in the working directory. If invoked with -A/--after, the
5983 exist in the working directory. If invoked with -A/--after, the
5985 operation is recorded, but no copying is performed.
5984 operation is recorded, but no copying is performed.
5986
5985
5987 To undo marking a destination file as renamed, use --forget. With that
5986 To undo marking a destination file as renamed, use --forget. With that
5988 option, all given (positional) arguments are unmarked as renames. The
5987 option, all given (positional) arguments are unmarked as renames. The
5989 destination file(s) will be left in place (still tracked). The source
5988 destination file(s) will be left in place (still tracked). The source
5990 file(s) will not be restored. Note that :hg:`rename --forget` behaves
5989 file(s) will not be restored. Note that :hg:`rename --forget` behaves
5991 the same way as :hg:`copy --forget`.
5990 the same way as :hg:`copy --forget`.
5992
5991
5993 This command takes effect with the next commit by default.
5992 This command takes effect with the next commit by default.
5994
5993
5995 Returns 0 on success, 1 if errors are encountered.
5994 Returns 0 on success, 1 if errors are encountered.
5996 """
5995 """
5997 opts = pycompat.byteskwargs(opts)
5996 opts = pycompat.byteskwargs(opts)
5998 with repo.wlock():
5997 with repo.wlock():
5999 return cmdutil.copy(ui, repo, pats, opts, rename=True)
5998 return cmdutil.copy(ui, repo, pats, opts, rename=True)
6000
5999
6001
6000
6002 @command(
6001 @command(
6003 b'resolve',
6002 b'resolve',
6004 [
6003 [
6005 (b'a', b'all', None, _(b'select all unresolved files')),
6004 (b'a', b'all', None, _(b'select all unresolved files')),
6006 (b'l', b'list', None, _(b'list state of files needing merge')),
6005 (b'l', b'list', None, _(b'list state of files needing merge')),
6007 (b'm', b'mark', None, _(b'mark files as resolved')),
6006 (b'm', b'mark', None, _(b'mark files as resolved')),
6008 (b'u', b'unmark', None, _(b'mark files as unresolved')),
6007 (b'u', b'unmark', None, _(b'mark files as unresolved')),
6009 (b'n', b'no-status', None, _(b'hide status prefix')),
6008 (b'n', b'no-status', None, _(b'hide status prefix')),
6010 (b'', b're-merge', None, _(b're-merge files')),
6009 (b'', b're-merge', None, _(b're-merge files')),
6011 ]
6010 ]
6012 + mergetoolopts
6011 + mergetoolopts
6013 + walkopts
6012 + walkopts
6014 + formatteropts,
6013 + formatteropts,
6015 _(b'[OPTION]... [FILE]...'),
6014 _(b'[OPTION]... [FILE]...'),
6016 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6015 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6017 inferrepo=True,
6016 inferrepo=True,
6018 )
6017 )
6019 def resolve(ui, repo, *pats, **opts):
6018 def resolve(ui, repo, *pats, **opts):
6020 """redo merges or set/view the merge status of files
6019 """redo merges or set/view the merge status of files
6021
6020
6022 Merges with unresolved conflicts are often the result of
6021 Merges with unresolved conflicts are often the result of
6023 non-interactive merging using the ``internal:merge`` configuration
6022 non-interactive merging using the ``internal:merge`` configuration
6024 setting, or a command-line merge tool like ``diff3``. The resolve
6023 setting, or a command-line merge tool like ``diff3``. The resolve
6025 command is used to manage the files involved in a merge, after
6024 command is used to manage the files involved in a merge, after
6026 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
6025 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
6027 working directory must have two parents). See :hg:`help
6026 working directory must have two parents). See :hg:`help
6028 merge-tools` for information on configuring merge tools.
6027 merge-tools` for information on configuring merge tools.
6029
6028
6030 The resolve command can be used in the following ways:
6029 The resolve command can be used in the following ways:
6031
6030
6032 - :hg:`resolve [--re-merge] [--tool TOOL] FILE...`: attempt to re-merge
6031 - :hg:`resolve [--re-merge] [--tool TOOL] FILE...`: attempt to re-merge
6033 the specified files, discarding any previous merge attempts. Re-merging
6032 the specified files, discarding any previous merge attempts. Re-merging
6034 is not performed for files already marked as resolved. Use ``--all/-a``
6033 is not performed for files already marked as resolved. Use ``--all/-a``
6035 to select all unresolved files. ``--tool`` can be used to specify
6034 to select all unresolved files. ``--tool`` can be used to specify
6036 the merge tool used for the given files. It overrides the HGMERGE
6035 the merge tool used for the given files. It overrides the HGMERGE
6037 environment variable and your configuration files. Previous file
6036 environment variable and your configuration files. Previous file
6038 contents are saved with a ``.orig`` suffix.
6037 contents are saved with a ``.orig`` suffix.
6039
6038
6040 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
6039 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
6041 (e.g. after having manually fixed-up the files). The default is
6040 (e.g. after having manually fixed-up the files). The default is
6042 to mark all unresolved files.
6041 to mark all unresolved files.
6043
6042
6044 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
6043 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
6045 default is to mark all resolved files.
6044 default is to mark all resolved files.
6046
6045
6047 - :hg:`resolve -l`: list files which had or still have conflicts.
6046 - :hg:`resolve -l`: list files which had or still have conflicts.
6048 In the printed list, ``U`` = unresolved and ``R`` = resolved.
6047 In the printed list, ``U`` = unresolved and ``R`` = resolved.
6049 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
6048 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
6050 the list. See :hg:`help filesets` for details.
6049 the list. See :hg:`help filesets` for details.
6051
6050
6052 .. note::
6051 .. note::
6053
6052
6054 Mercurial will not let you commit files with unresolved merge
6053 Mercurial will not let you commit files with unresolved merge
6055 conflicts. You must use :hg:`resolve -m ...` before you can
6054 conflicts. You must use :hg:`resolve -m ...` before you can
6056 commit after a conflicting merge.
6055 commit after a conflicting merge.
6057
6056
6058 .. container:: verbose
6057 .. container:: verbose
6059
6058
6060 Template:
6059 Template:
6061
6060
6062 The following keywords are supported in addition to the common template
6061 The following keywords are supported in addition to the common template
6063 keywords and functions. See also :hg:`help templates`.
6062 keywords and functions. See also :hg:`help templates`.
6064
6063
6065 :mergestatus: String. Character denoting merge conflicts, ``U`` or ``R``.
6064 :mergestatus: String. Character denoting merge conflicts, ``U`` or ``R``.
6066 :path: String. Repository-absolute path of the file.
6065 :path: String. Repository-absolute path of the file.
6067
6066
6068 Returns 0 on success, 1 if any files fail a resolve attempt.
6067 Returns 0 on success, 1 if any files fail a resolve attempt.
6069 """
6068 """
6070
6069
6071 opts = pycompat.byteskwargs(opts)
6070 opts = pycompat.byteskwargs(opts)
6072 confirm = ui.configbool(b'commands', b'resolve.confirm')
6071 confirm = ui.configbool(b'commands', b'resolve.confirm')
6073 flaglist = b'all mark unmark list no_status re_merge'.split()
6072 flaglist = b'all mark unmark list no_status re_merge'.split()
6074 all, mark, unmark, show, nostatus, remerge = [opts.get(o) for o in flaglist]
6073 all, mark, unmark, show, nostatus, remerge = [opts.get(o) for o in flaglist]
6075
6074
6076 actioncount = len(list(filter(None, [show, mark, unmark, remerge])))
6075 actioncount = len(list(filter(None, [show, mark, unmark, remerge])))
6077 if actioncount > 1:
6076 if actioncount > 1:
6078 raise error.InputError(_(b"too many actions specified"))
6077 raise error.InputError(_(b"too many actions specified"))
6079 elif actioncount == 0 and ui.configbool(
6078 elif actioncount == 0 and ui.configbool(
6080 b'commands', b'resolve.explicit-re-merge'
6079 b'commands', b'resolve.explicit-re-merge'
6081 ):
6080 ):
6082 hint = _(b'use --mark, --unmark, --list or --re-merge')
6081 hint = _(b'use --mark, --unmark, --list or --re-merge')
6083 raise error.InputError(_(b'no action specified'), hint=hint)
6082 raise error.InputError(_(b'no action specified'), hint=hint)
6084 if pats and all:
6083 if pats and all:
6085 raise error.InputError(_(b"can't specify --all and patterns"))
6084 raise error.InputError(_(b"can't specify --all and patterns"))
6086 if not (all or pats or show or mark or unmark):
6085 if not (all or pats or show or mark or unmark):
6087 raise error.InputError(
6086 raise error.InputError(
6088 _(b'no files or directories specified'),
6087 _(b'no files or directories specified'),
6089 hint=b'use --all to re-merge all unresolved files',
6088 hint=b'use --all to re-merge all unresolved files',
6090 )
6089 )
6091
6090
6092 if confirm:
6091 if confirm:
6093 if all:
6092 if all:
6094 if ui.promptchoice(
6093 if ui.promptchoice(
6095 _(b're-merge all unresolved files (yn)?$$ &Yes $$ &No')
6094 _(b're-merge all unresolved files (yn)?$$ &Yes $$ &No')
6096 ):
6095 ):
6097 raise error.CanceledError(_(b'user quit'))
6096 raise error.CanceledError(_(b'user quit'))
6098 if mark and not pats:
6097 if mark and not pats:
6099 if ui.promptchoice(
6098 if ui.promptchoice(
6100 _(
6099 _(
6101 b'mark all unresolved files as resolved (yn)?'
6100 b'mark all unresolved files as resolved (yn)?'
6102 b'$$ &Yes $$ &No'
6101 b'$$ &Yes $$ &No'
6103 )
6102 )
6104 ):
6103 ):
6105 raise error.CanceledError(_(b'user quit'))
6104 raise error.CanceledError(_(b'user quit'))
6106 if unmark and not pats:
6105 if unmark and not pats:
6107 if ui.promptchoice(
6106 if ui.promptchoice(
6108 _(
6107 _(
6109 b'mark all resolved files as unresolved (yn)?'
6108 b'mark all resolved files as unresolved (yn)?'
6110 b'$$ &Yes $$ &No'
6109 b'$$ &Yes $$ &No'
6111 )
6110 )
6112 ):
6111 ):
6113 raise error.CanceledError(_(b'user quit'))
6112 raise error.CanceledError(_(b'user quit'))
6114
6113
6115 uipathfn = scmutil.getuipathfn(repo)
6114 uipathfn = scmutil.getuipathfn(repo)
6116
6115
6117 if show:
6116 if show:
6118 ui.pager(b'resolve')
6117 ui.pager(b'resolve')
6119 fm = ui.formatter(b'resolve', opts)
6118 fm = ui.formatter(b'resolve', opts)
6120 ms = mergestatemod.mergestate.read(repo)
6119 ms = mergestatemod.mergestate.read(repo)
6121 wctx = repo[None]
6120 wctx = repo[None]
6122 m = scmutil.match(wctx, pats, opts)
6121 m = scmutil.match(wctx, pats, opts)
6123
6122
6124 # Labels and keys based on merge state. Unresolved path conflicts show
6123 # Labels and keys based on merge state. Unresolved path conflicts show
6125 # as 'P'. Resolved path conflicts show as 'R', the same as normal
6124 # as 'P'. Resolved path conflicts show as 'R', the same as normal
6126 # resolved conflicts.
6125 # resolved conflicts.
6127 mergestateinfo = {
6126 mergestateinfo = {
6128 mergestatemod.MERGE_RECORD_UNRESOLVED: (
6127 mergestatemod.MERGE_RECORD_UNRESOLVED: (
6129 b'resolve.unresolved',
6128 b'resolve.unresolved',
6130 b'U',
6129 b'U',
6131 ),
6130 ),
6132 mergestatemod.MERGE_RECORD_RESOLVED: (b'resolve.resolved', b'R'),
6131 mergestatemod.MERGE_RECORD_RESOLVED: (b'resolve.resolved', b'R'),
6133 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH: (
6132 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH: (
6134 b'resolve.unresolved',
6133 b'resolve.unresolved',
6135 b'P',
6134 b'P',
6136 ),
6135 ),
6137 mergestatemod.MERGE_RECORD_RESOLVED_PATH: (
6136 mergestatemod.MERGE_RECORD_RESOLVED_PATH: (
6138 b'resolve.resolved',
6137 b'resolve.resolved',
6139 b'R',
6138 b'R',
6140 ),
6139 ),
6141 }
6140 }
6142
6141
6143 for f in ms:
6142 for f in ms:
6144 if not m(f):
6143 if not m(f):
6145 continue
6144 continue
6146
6145
6147 label, key = mergestateinfo[ms[f]]
6146 label, key = mergestateinfo[ms[f]]
6148 fm.startitem()
6147 fm.startitem()
6149 fm.context(ctx=wctx)
6148 fm.context(ctx=wctx)
6150 fm.condwrite(not nostatus, b'mergestatus', b'%s ', key, label=label)
6149 fm.condwrite(not nostatus, b'mergestatus', b'%s ', key, label=label)
6151 fm.data(path=f)
6150 fm.data(path=f)
6152 fm.plain(b'%s\n' % uipathfn(f), label=label)
6151 fm.plain(b'%s\n' % uipathfn(f), label=label)
6153 fm.end()
6152 fm.end()
6154 return 0
6153 return 0
6155
6154
6156 with repo.wlock():
6155 with repo.wlock():
6157 ms = mergestatemod.mergestate.read(repo)
6156 ms = mergestatemod.mergestate.read(repo)
6158
6157
6159 if not (ms.active() or repo.dirstate.p2() != repo.nullid):
6158 if not (ms.active() or repo.dirstate.p2() != repo.nullid):
6160 raise error.StateError(
6159 raise error.StateError(
6161 _(b'resolve command not applicable when not merging')
6160 _(b'resolve command not applicable when not merging')
6162 )
6161 )
6163
6162
6164 wctx = repo[None]
6163 wctx = repo[None]
6165 m = scmutil.match(wctx, pats, opts)
6164 m = scmutil.match(wctx, pats, opts)
6166 ret = 0
6165 ret = 0
6167 didwork = False
6166 didwork = False
6168
6167
6169 hasconflictmarkers = []
6168 hasconflictmarkers = []
6170 if mark:
6169 if mark:
6171 markcheck = ui.config(b'commands', b'resolve.mark-check')
6170 markcheck = ui.config(b'commands', b'resolve.mark-check')
6172 if markcheck not in [b'warn', b'abort']:
6171 if markcheck not in [b'warn', b'abort']:
6173 # Treat all invalid / unrecognized values as 'none'.
6172 # Treat all invalid / unrecognized values as 'none'.
6174 markcheck = False
6173 markcheck = False
6175 for f in ms:
6174 for f in ms:
6176 if not m(f):
6175 if not m(f):
6177 continue
6176 continue
6178
6177
6179 didwork = True
6178 didwork = True
6180
6179
6181 # path conflicts must be resolved manually
6180 # path conflicts must be resolved manually
6182 if ms[f] in (
6181 if ms[f] in (
6183 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH,
6182 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH,
6184 mergestatemod.MERGE_RECORD_RESOLVED_PATH,
6183 mergestatemod.MERGE_RECORD_RESOLVED_PATH,
6185 ):
6184 ):
6186 if mark:
6185 if mark:
6187 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED_PATH)
6186 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED_PATH)
6188 elif unmark:
6187 elif unmark:
6189 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED_PATH)
6188 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED_PATH)
6190 elif ms[f] == mergestatemod.MERGE_RECORD_UNRESOLVED_PATH:
6189 elif ms[f] == mergestatemod.MERGE_RECORD_UNRESOLVED_PATH:
6191 ui.warn(
6190 ui.warn(
6192 _(b'%s: path conflict must be resolved manually\n')
6191 _(b'%s: path conflict must be resolved manually\n')
6193 % uipathfn(f)
6192 % uipathfn(f)
6194 )
6193 )
6195 continue
6194 continue
6196
6195
6197 if mark:
6196 if mark:
6198 if markcheck:
6197 if markcheck:
6199 fdata = repo.wvfs.tryread(f)
6198 fdata = repo.wvfs.tryread(f)
6200 if (
6199 if (
6201 filemerge.hasconflictmarkers(fdata)
6200 filemerge.hasconflictmarkers(fdata)
6202 and ms[f] != mergestatemod.MERGE_RECORD_RESOLVED
6201 and ms[f] != mergestatemod.MERGE_RECORD_RESOLVED
6203 ):
6202 ):
6204 hasconflictmarkers.append(f)
6203 hasconflictmarkers.append(f)
6205 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED)
6204 ms.mark(f, mergestatemod.MERGE_RECORD_RESOLVED)
6206 elif unmark:
6205 elif unmark:
6207 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED)
6206 ms.mark(f, mergestatemod.MERGE_RECORD_UNRESOLVED)
6208 else:
6207 else:
6209 # backup pre-resolve (merge uses .orig for its own purposes)
6208 # backup pre-resolve (merge uses .orig for its own purposes)
6210 a = repo.wjoin(f)
6209 a = repo.wjoin(f)
6211 try:
6210 try:
6212 util.copyfile(a, a + b".resolve")
6211 util.copyfile(a, a + b".resolve")
6213 except FileNotFoundError:
6212 except FileNotFoundError:
6214 pass
6213 pass
6215
6214
6216 try:
6215 try:
6217 # preresolve file
6216 # preresolve file
6218 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
6217 overrides = {(b'ui', b'forcemerge'): opts.get(b'tool', b'')}
6219 with ui.configoverride(overrides, b'resolve'):
6218 with ui.configoverride(overrides, b'resolve'):
6220 r = ms.resolve(f, wctx)
6219 r = ms.resolve(f, wctx)
6221 if r:
6220 if r:
6222 ret = 1
6221 ret = 1
6223 finally:
6222 finally:
6224 ms.commit()
6223 ms.commit()
6225
6224
6226 # replace filemerge's .orig file with our resolve file
6225 # replace filemerge's .orig file with our resolve file
6227 try:
6226 try:
6228 util.rename(
6227 util.rename(
6229 a + b".resolve", scmutil.backuppath(ui, repo, f)
6228 a + b".resolve", scmutil.backuppath(ui, repo, f)
6230 )
6229 )
6231 except FileNotFoundError:
6230 except FileNotFoundError:
6232 pass
6231 pass
6233
6232
6234 if hasconflictmarkers:
6233 if hasconflictmarkers:
6235 ui.warn(
6234 ui.warn(
6236 _(
6235 _(
6237 b'warning: the following files still have conflict '
6236 b'warning: the following files still have conflict '
6238 b'markers:\n'
6237 b'markers:\n'
6239 )
6238 )
6240 + b''.join(
6239 + b''.join(
6241 b' ' + uipathfn(f) + b'\n' for f in hasconflictmarkers
6240 b' ' + uipathfn(f) + b'\n' for f in hasconflictmarkers
6242 )
6241 )
6243 )
6242 )
6244 if markcheck == b'abort' and not all and not pats:
6243 if markcheck == b'abort' and not all and not pats:
6245 raise error.StateError(
6244 raise error.StateError(
6246 _(b'conflict markers detected'),
6245 _(b'conflict markers detected'),
6247 hint=_(b'use --all to mark anyway'),
6246 hint=_(b'use --all to mark anyway'),
6248 )
6247 )
6249
6248
6250 ms.commit()
6249 ms.commit()
6251 branchmerge = repo.dirstate.p2() != repo.nullid
6250 branchmerge = repo.dirstate.p2() != repo.nullid
6252 # resolve is not doing a parent change here, however, `record updates`
6251 # resolve is not doing a parent change here, however, `record updates`
6253 # will call some dirstate API that at intended for parent changes call.
6252 # will call some dirstate API that at intended for parent changes call.
6254 # Ideally we would not need this and could implement a lighter version
6253 # Ideally we would not need this and could implement a lighter version
6255 # of the recordupdateslogic that will not have to deal with the part
6254 # of the recordupdateslogic that will not have to deal with the part
6256 # related to parent changes. However this would requires that:
6255 # related to parent changes. However this would requires that:
6257 # - we are sure we passed around enough information at update/merge
6256 # - we are sure we passed around enough information at update/merge
6258 # time to no longer needs it at `hg resolve time`
6257 # time to no longer needs it at `hg resolve time`
6259 # - we are sure we store that information well enough to be able to reuse it
6258 # - we are sure we store that information well enough to be able to reuse it
6260 # - we are the necessary logic to reuse it right.
6259 # - we are the necessary logic to reuse it right.
6261 #
6260 #
6262 # All this should eventually happens, but in the mean time, we use this
6261 # All this should eventually happens, but in the mean time, we use this
6263 # context manager slightly out of the context it should be.
6262 # context manager slightly out of the context it should be.
6264 with repo.dirstate.parentchange():
6263 with repo.dirstate.parentchange():
6265 mergestatemod.recordupdates(repo, ms.actions(), branchmerge, None)
6264 mergestatemod.recordupdates(repo, ms.actions(), branchmerge, None)
6266
6265
6267 if not didwork and pats:
6266 if not didwork and pats:
6268 hint = None
6267 hint = None
6269 if not any([p for p in pats if p.find(b':') >= 0]):
6268 if not any([p for p in pats if p.find(b':') >= 0]):
6270 pats = [b'path:%s' % p for p in pats]
6269 pats = [b'path:%s' % p for p in pats]
6271 m = scmutil.match(wctx, pats, opts)
6270 m = scmutil.match(wctx, pats, opts)
6272 for f in ms:
6271 for f in ms:
6273 if not m(f):
6272 if not m(f):
6274 continue
6273 continue
6275
6274
6276 def flag(o):
6275 def flag(o):
6277 if o == b're_merge':
6276 if o == b're_merge':
6278 return b'--re-merge '
6277 return b'--re-merge '
6279 return b'-%s ' % o[0:1]
6278 return b'-%s ' % o[0:1]
6280
6279
6281 flags = b''.join([flag(o) for o in flaglist if opts.get(o)])
6280 flags = b''.join([flag(o) for o in flaglist if opts.get(o)])
6282 hint = _(b"(try: hg resolve %s%s)\n") % (
6281 hint = _(b"(try: hg resolve %s%s)\n") % (
6283 flags,
6282 flags,
6284 b' '.join(pats),
6283 b' '.join(pats),
6285 )
6284 )
6286 break
6285 break
6287 ui.warn(_(b"arguments do not match paths that need resolving\n"))
6286 ui.warn(_(b"arguments do not match paths that need resolving\n"))
6288 if hint:
6287 if hint:
6289 ui.warn(hint)
6288 ui.warn(hint)
6290
6289
6291 unresolvedf = ms.unresolvedcount()
6290 unresolvedf = ms.unresolvedcount()
6292 if not unresolvedf:
6291 if not unresolvedf:
6293 ui.status(_(b'(no more unresolved files)\n'))
6292 ui.status(_(b'(no more unresolved files)\n'))
6294 cmdutil.checkafterresolved(repo)
6293 cmdutil.checkafterresolved(repo)
6295
6294
6296 return ret
6295 return ret
6297
6296
6298
6297
6299 @command(
6298 @command(
6300 b'revert',
6299 b'revert',
6301 [
6300 [
6302 (b'a', b'all', None, _(b'revert all changes when no arguments given')),
6301 (b'a', b'all', None, _(b'revert all changes when no arguments given')),
6303 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
6302 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
6304 (b'r', b'rev', b'', _(b'revert to the specified revision'), _(b'REV')),
6303 (b'r', b'rev', b'', _(b'revert to the specified revision'), _(b'REV')),
6305 (b'C', b'no-backup', None, _(b'do not save backup copies of files')),
6304 (b'C', b'no-backup', None, _(b'do not save backup copies of files')),
6306 (b'i', b'interactive', None, _(b'interactively select the changes')),
6305 (b'i', b'interactive', None, _(b'interactively select the changes')),
6307 ]
6306 ]
6308 + walkopts
6307 + walkopts
6309 + dryrunopts,
6308 + dryrunopts,
6310 _(b'[OPTION]... [-r REV] [NAME]...'),
6309 _(b'[OPTION]... [-r REV] [NAME]...'),
6311 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6310 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6312 )
6311 )
6313 def revert(ui, repo, *pats, **opts):
6312 def revert(ui, repo, *pats, **opts):
6314 """restore files to their checkout state
6313 """restore files to their checkout state
6315
6314
6316 .. note::
6315 .. note::
6317
6316
6318 To check out earlier revisions, you should use :hg:`update REV`.
6317 To check out earlier revisions, you should use :hg:`update REV`.
6319 To cancel an uncommitted merge (and lose your changes),
6318 To cancel an uncommitted merge (and lose your changes),
6320 use :hg:`merge --abort`.
6319 use :hg:`merge --abort`.
6321
6320
6322 With no revision specified, revert the specified files or directories
6321 With no revision specified, revert the specified files or directories
6323 to the contents they had in the parent of the working directory.
6322 to the contents they had in the parent of the working directory.
6324 This restores the contents of files to an unmodified
6323 This restores the contents of files to an unmodified
6325 state and unschedules adds, removes, copies, and renames. If the
6324 state and unschedules adds, removes, copies, and renames. If the
6326 working directory has two parents, you must explicitly specify a
6325 working directory has two parents, you must explicitly specify a
6327 revision.
6326 revision.
6328
6327
6329 Using the -r/--rev or -d/--date options, revert the given files or
6328 Using the -r/--rev or -d/--date options, revert the given files or
6330 directories to their states as of a specific revision. Because
6329 directories to their states as of a specific revision. Because
6331 revert does not change the working directory parents, this will
6330 revert does not change the working directory parents, this will
6332 cause these files to appear modified. This can be helpful to "back
6331 cause these files to appear modified. This can be helpful to "back
6333 out" some or all of an earlier change. See :hg:`backout` for a
6332 out" some or all of an earlier change. See :hg:`backout` for a
6334 related method.
6333 related method.
6335
6334
6336 Modified files are saved with a .orig suffix before reverting.
6335 Modified files are saved with a .orig suffix before reverting.
6337 To disable these backups, use --no-backup. It is possible to store
6336 To disable these backups, use --no-backup. It is possible to store
6338 the backup files in a custom directory relative to the root of the
6337 the backup files in a custom directory relative to the root of the
6339 repository by setting the ``ui.origbackuppath`` configuration
6338 repository by setting the ``ui.origbackuppath`` configuration
6340 option.
6339 option.
6341
6340
6342 See :hg:`help dates` for a list of formats valid for -d/--date.
6341 See :hg:`help dates` for a list of formats valid for -d/--date.
6343
6342
6344 See :hg:`help backout` for a way to reverse the effect of an
6343 See :hg:`help backout` for a way to reverse the effect of an
6345 earlier changeset.
6344 earlier changeset.
6346
6345
6347 Returns 0 on success.
6346 Returns 0 on success.
6348 """
6347 """
6349
6348
6350 opts = pycompat.byteskwargs(opts)
6349 opts = pycompat.byteskwargs(opts)
6351 if opts.get(b"date"):
6350 if opts.get(b"date"):
6352 cmdutil.check_incompatible_arguments(opts, b'date', [b'rev'])
6351 cmdutil.check_incompatible_arguments(opts, b'date', [b'rev'])
6353 opts[b"rev"] = cmdutil.finddate(ui, repo, opts[b"date"])
6352 opts[b"rev"] = cmdutil.finddate(ui, repo, opts[b"date"])
6354
6353
6355 parent, p2 = repo.dirstate.parents()
6354 parent, p2 = repo.dirstate.parents()
6356 if not opts.get(b'rev') and p2 != repo.nullid:
6355 if not opts.get(b'rev') and p2 != repo.nullid:
6357 # revert after merge is a trap for new users (issue2915)
6356 # revert after merge is a trap for new users (issue2915)
6358 raise error.InputError(
6357 raise error.InputError(
6359 _(b'uncommitted merge with no revision specified'),
6358 _(b'uncommitted merge with no revision specified'),
6360 hint=_(b"use 'hg update' or see 'hg help revert'"),
6359 hint=_(b"use 'hg update' or see 'hg help revert'"),
6361 )
6360 )
6362
6361
6363 rev = opts.get(b'rev')
6362 rev = opts.get(b'rev')
6364 if rev:
6363 if rev:
6365 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
6364 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
6366 ctx = logcmdutil.revsingle(repo, rev)
6365 ctx = logcmdutil.revsingle(repo, rev)
6367
6366
6368 if not (
6367 if not (
6369 pats
6368 pats
6370 or opts.get(b'include')
6369 or opts.get(b'include')
6371 or opts.get(b'exclude')
6370 or opts.get(b'exclude')
6372 or opts.get(b'all')
6371 or opts.get(b'all')
6373 or opts.get(b'interactive')
6372 or opts.get(b'interactive')
6374 ):
6373 ):
6375 msg = _(b"no files or directories specified")
6374 msg = _(b"no files or directories specified")
6376 if p2 != repo.nullid:
6375 if p2 != repo.nullid:
6377 hint = _(
6376 hint = _(
6378 b"uncommitted merge, use --all to discard all changes,"
6377 b"uncommitted merge, use --all to discard all changes,"
6379 b" or 'hg update -C .' to abort the merge"
6378 b" or 'hg update -C .' to abort the merge"
6380 )
6379 )
6381 raise error.InputError(msg, hint=hint)
6380 raise error.InputError(msg, hint=hint)
6382 dirty = any(repo.status())
6381 dirty = any(repo.status())
6383 node = ctx.node()
6382 node = ctx.node()
6384 if node != parent:
6383 if node != parent:
6385 if dirty:
6384 if dirty:
6386 hint = (
6385 hint = (
6387 _(
6386 _(
6388 b"uncommitted changes, use --all to discard all"
6387 b"uncommitted changes, use --all to discard all"
6389 b" changes, or 'hg update %d' to update"
6388 b" changes, or 'hg update %d' to update"
6390 )
6389 )
6391 % ctx.rev()
6390 % ctx.rev()
6392 )
6391 )
6393 else:
6392 else:
6394 hint = (
6393 hint = (
6395 _(
6394 _(
6396 b"use --all to revert all files,"
6395 b"use --all to revert all files,"
6397 b" or 'hg update %d' to update"
6396 b" or 'hg update %d' to update"
6398 )
6397 )
6399 % ctx.rev()
6398 % ctx.rev()
6400 )
6399 )
6401 elif dirty:
6400 elif dirty:
6402 hint = _(b"uncommitted changes, use --all to discard all changes")
6401 hint = _(b"uncommitted changes, use --all to discard all changes")
6403 else:
6402 else:
6404 hint = _(b"use --all to revert all files")
6403 hint = _(b"use --all to revert all files")
6405 raise error.InputError(msg, hint=hint)
6404 raise error.InputError(msg, hint=hint)
6406
6405
6407 return cmdutil.revert(ui, repo, ctx, *pats, **pycompat.strkwargs(opts))
6406 return cmdutil.revert(ui, repo, ctx, *pats, **pycompat.strkwargs(opts))
6408
6407
6409
6408
6410 @command(
6409 @command(
6411 b'rollback',
6410 b'rollback',
6412 dryrunopts + [(b'f', b'force', False, _(b'ignore safety measures'))],
6411 dryrunopts + [(b'f', b'force', False, _(b'ignore safety measures'))],
6413 helpcategory=command.CATEGORY_MAINTENANCE,
6412 helpcategory=command.CATEGORY_MAINTENANCE,
6414 )
6413 )
6415 def rollback(ui, repo, **opts):
6414 def rollback(ui, repo, **opts):
6416 """roll back the last transaction (DANGEROUS) (DEPRECATED)
6415 """roll back the last transaction (DANGEROUS) (DEPRECATED)
6417
6416
6418 Please use :hg:`commit --amend` instead of rollback to correct
6417 Please use :hg:`commit --amend` instead of rollback to correct
6419 mistakes in the last commit.
6418 mistakes in the last commit.
6420
6419
6421 This command should be used with care. There is only one level of
6420 This command should be used with care. There is only one level of
6422 rollback, and there is no way to undo a rollback. It will also
6421 rollback, and there is no way to undo a rollback. It will also
6423 restore the dirstate at the time of the last transaction, losing
6422 restore the dirstate at the time of the last transaction, losing
6424 any dirstate changes since that time. This command does not alter
6423 any dirstate changes since that time. This command does not alter
6425 the working directory.
6424 the working directory.
6426
6425
6427 Transactions are used to encapsulate the effects of all commands
6426 Transactions are used to encapsulate the effects of all commands
6428 that create new changesets or propagate existing changesets into a
6427 that create new changesets or propagate existing changesets into a
6429 repository.
6428 repository.
6430
6429
6431 .. container:: verbose
6430 .. container:: verbose
6432
6431
6433 For example, the following commands are transactional, and their
6432 For example, the following commands are transactional, and their
6434 effects can be rolled back:
6433 effects can be rolled back:
6435
6434
6436 - commit
6435 - commit
6437 - import
6436 - import
6438 - pull
6437 - pull
6439 - push (with this repository as the destination)
6438 - push (with this repository as the destination)
6440 - unbundle
6439 - unbundle
6441
6440
6442 To avoid permanent data loss, rollback will refuse to rollback a
6441 To avoid permanent data loss, rollback will refuse to rollback a
6443 commit transaction if it isn't checked out. Use --force to
6442 commit transaction if it isn't checked out. Use --force to
6444 override this protection.
6443 override this protection.
6445
6444
6446 The rollback command can be entirely disabled by setting the
6445 The rollback command can be entirely disabled by setting the
6447 ``ui.rollback`` configuration setting to false. If you're here
6446 ``ui.rollback`` configuration setting to false. If you're here
6448 because you want to use rollback and it's disabled, you can
6447 because you want to use rollback and it's disabled, you can
6449 re-enable the command by setting ``ui.rollback`` to true.
6448 re-enable the command by setting ``ui.rollback`` to true.
6450
6449
6451 This command is not intended for use on public repositories. Once
6450 This command is not intended for use on public repositories. Once
6452 changes are visible for pull by other users, rolling a transaction
6451 changes are visible for pull by other users, rolling a transaction
6453 back locally is ineffective (someone else may already have pulled
6452 back locally is ineffective (someone else may already have pulled
6454 the changes). Furthermore, a race is possible with readers of the
6453 the changes). Furthermore, a race is possible with readers of the
6455 repository; for example an in-progress pull from the repository
6454 repository; for example an in-progress pull from the repository
6456 may fail if a rollback is performed.
6455 may fail if a rollback is performed.
6457
6456
6458 Returns 0 on success, 1 if no rollback data is available.
6457 Returns 0 on success, 1 if no rollback data is available.
6459 """
6458 """
6460 if not ui.configbool(b'ui', b'rollback'):
6459 if not ui.configbool(b'ui', b'rollback'):
6461 raise error.Abort(
6460 raise error.Abort(
6462 _(b'rollback is disabled because it is unsafe'),
6461 _(b'rollback is disabled because it is unsafe'),
6463 hint=b'see `hg help -v rollback` for information',
6462 hint=b'see `hg help -v rollback` for information',
6464 )
6463 )
6465 return repo.rollback(dryrun=opts.get('dry_run'), force=opts.get('force'))
6464 return repo.rollback(dryrun=opts.get('dry_run'), force=opts.get('force'))
6466
6465
6467
6466
6468 @command(
6467 @command(
6469 b'root',
6468 b'root',
6470 [] + formatteropts,
6469 [] + formatteropts,
6471 intents={INTENT_READONLY},
6470 intents={INTENT_READONLY},
6472 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6471 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6473 )
6472 )
6474 def root(ui, repo, **opts):
6473 def root(ui, repo, **opts):
6475 """print the root (top) of the current working directory
6474 """print the root (top) of the current working directory
6476
6475
6477 Print the root directory of the current repository.
6476 Print the root directory of the current repository.
6478
6477
6479 .. container:: verbose
6478 .. container:: verbose
6480
6479
6481 Template:
6480 Template:
6482
6481
6483 The following keywords are supported in addition to the common template
6482 The following keywords are supported in addition to the common template
6484 keywords and functions. See also :hg:`help templates`.
6483 keywords and functions. See also :hg:`help templates`.
6485
6484
6486 :hgpath: String. Path to the .hg directory.
6485 :hgpath: String. Path to the .hg directory.
6487 :storepath: String. Path to the directory holding versioned data.
6486 :storepath: String. Path to the directory holding versioned data.
6488
6487
6489 Returns 0 on success.
6488 Returns 0 on success.
6490 """
6489 """
6491 opts = pycompat.byteskwargs(opts)
6490 opts = pycompat.byteskwargs(opts)
6492 with ui.formatter(b'root', opts) as fm:
6491 with ui.formatter(b'root', opts) as fm:
6493 fm.startitem()
6492 fm.startitem()
6494 fm.write(b'reporoot', b'%s\n', repo.root)
6493 fm.write(b'reporoot', b'%s\n', repo.root)
6495 fm.data(hgpath=repo.path, storepath=repo.spath)
6494 fm.data(hgpath=repo.path, storepath=repo.spath)
6496
6495
6497
6496
6498 @command(
6497 @command(
6499 b'serve',
6498 b'serve',
6500 [
6499 [
6501 (
6500 (
6502 b'A',
6501 b'A',
6503 b'accesslog',
6502 b'accesslog',
6504 b'',
6503 b'',
6505 _(b'name of access log file to write to'),
6504 _(b'name of access log file to write to'),
6506 _(b'FILE'),
6505 _(b'FILE'),
6507 ),
6506 ),
6508 (b'd', b'daemon', None, _(b'run server in background')),
6507 (b'd', b'daemon', None, _(b'run server in background')),
6509 (b'', b'daemon-postexec', [], _(b'used internally by daemon mode')),
6508 (b'', b'daemon-postexec', [], _(b'used internally by daemon mode')),
6510 (
6509 (
6511 b'E',
6510 b'E',
6512 b'errorlog',
6511 b'errorlog',
6513 b'',
6512 b'',
6514 _(b'name of error log file to write to'),
6513 _(b'name of error log file to write to'),
6515 _(b'FILE'),
6514 _(b'FILE'),
6516 ),
6515 ),
6517 # use string type, then we can check if something was passed
6516 # use string type, then we can check if something was passed
6518 (
6517 (
6519 b'p',
6518 b'p',
6520 b'port',
6519 b'port',
6521 b'',
6520 b'',
6522 _(b'port to listen on (default: 8000)'),
6521 _(b'port to listen on (default: 8000)'),
6523 _(b'PORT'),
6522 _(b'PORT'),
6524 ),
6523 ),
6525 (
6524 (
6526 b'a',
6525 b'a',
6527 b'address',
6526 b'address',
6528 b'',
6527 b'',
6529 _(b'address to listen on (default: all interfaces)'),
6528 _(b'address to listen on (default: all interfaces)'),
6530 _(b'ADDR'),
6529 _(b'ADDR'),
6531 ),
6530 ),
6532 (
6531 (
6533 b'',
6532 b'',
6534 b'prefix',
6533 b'prefix',
6535 b'',
6534 b'',
6536 _(b'prefix path to serve from (default: server root)'),
6535 _(b'prefix path to serve from (default: server root)'),
6537 _(b'PREFIX'),
6536 _(b'PREFIX'),
6538 ),
6537 ),
6539 (
6538 (
6540 b'n',
6539 b'n',
6541 b'name',
6540 b'name',
6542 b'',
6541 b'',
6543 _(b'name to show in web pages (default: working directory)'),
6542 _(b'name to show in web pages (default: working directory)'),
6544 _(b'NAME'),
6543 _(b'NAME'),
6545 ),
6544 ),
6546 (
6545 (
6547 b'',
6546 b'',
6548 b'web-conf',
6547 b'web-conf',
6549 b'',
6548 b'',
6550 _(b"name of the hgweb config file (see 'hg help hgweb')"),
6549 _(b"name of the hgweb config file (see 'hg help hgweb')"),
6551 _(b'FILE'),
6550 _(b'FILE'),
6552 ),
6551 ),
6553 (
6552 (
6554 b'',
6553 b'',
6555 b'webdir-conf',
6554 b'webdir-conf',
6556 b'',
6555 b'',
6557 _(b'name of the hgweb config file (DEPRECATED)'),
6556 _(b'name of the hgweb config file (DEPRECATED)'),
6558 _(b'FILE'),
6557 _(b'FILE'),
6559 ),
6558 ),
6560 (
6559 (
6561 b'',
6560 b'',
6562 b'pid-file',
6561 b'pid-file',
6563 b'',
6562 b'',
6564 _(b'name of file to write process ID to'),
6563 _(b'name of file to write process ID to'),
6565 _(b'FILE'),
6564 _(b'FILE'),
6566 ),
6565 ),
6567 (b'', b'stdio', None, _(b'for remote clients (ADVANCED)')),
6566 (b'', b'stdio', None, _(b'for remote clients (ADVANCED)')),
6568 (
6567 (
6569 b'',
6568 b'',
6570 b'cmdserver',
6569 b'cmdserver',
6571 b'',
6570 b'',
6572 _(b'for remote clients (ADVANCED)'),
6571 _(b'for remote clients (ADVANCED)'),
6573 _(b'MODE'),
6572 _(b'MODE'),
6574 ),
6573 ),
6575 (b't', b'templates', b'', _(b'web templates to use'), _(b'TEMPLATE')),
6574 (b't', b'templates', b'', _(b'web templates to use'), _(b'TEMPLATE')),
6576 (b'', b'style', b'', _(b'template style to use'), _(b'STYLE')),
6575 (b'', b'style', b'', _(b'template style to use'), _(b'STYLE')),
6577 (b'6', b'ipv6', None, _(b'use IPv6 in addition to IPv4')),
6576 (b'6', b'ipv6', None, _(b'use IPv6 in addition to IPv4')),
6578 (b'', b'certificate', b'', _(b'SSL certificate file'), _(b'FILE')),
6577 (b'', b'certificate', b'', _(b'SSL certificate file'), _(b'FILE')),
6579 (b'', b'print-url', None, _(b'start and print only the URL')),
6578 (b'', b'print-url', None, _(b'start and print only the URL')),
6580 ]
6579 ]
6581 + subrepoopts,
6580 + subrepoopts,
6582 _(b'[OPTION]...'),
6581 _(b'[OPTION]...'),
6583 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
6582 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
6584 helpbasic=True,
6583 helpbasic=True,
6585 optionalrepo=True,
6584 optionalrepo=True,
6586 )
6585 )
6587 def serve(ui, repo, **opts):
6586 def serve(ui, repo, **opts):
6588 """start stand-alone webserver
6587 """start stand-alone webserver
6589
6588
6590 Start a local HTTP repository browser and pull server. You can use
6589 Start a local HTTP repository browser and pull server. You can use
6591 this for ad-hoc sharing and browsing of repositories. It is
6590 this for ad-hoc sharing and browsing of repositories. It is
6592 recommended to use a real web server to serve a repository for
6591 recommended to use a real web server to serve a repository for
6593 longer periods of time.
6592 longer periods of time.
6594
6593
6595 Please note that the server does not implement access control.
6594 Please note that the server does not implement access control.
6596 This means that, by default, anybody can read from the server and
6595 This means that, by default, anybody can read from the server and
6597 nobody can write to it by default. Set the ``web.allow-push``
6596 nobody can write to it by default. Set the ``web.allow-push``
6598 option to ``*`` to allow everybody to push to the server. You
6597 option to ``*`` to allow everybody to push to the server. You
6599 should use a real web server if you need to authenticate users.
6598 should use a real web server if you need to authenticate users.
6600
6599
6601 By default, the server logs accesses to stdout and errors to
6600 By default, the server logs accesses to stdout and errors to
6602 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
6601 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
6603 files.
6602 files.
6604
6603
6605 To have the server choose a free port number to listen on, specify
6604 To have the server choose a free port number to listen on, specify
6606 a port number of 0; in this case, the server will print the port
6605 a port number of 0; in this case, the server will print the port
6607 number it uses.
6606 number it uses.
6608
6607
6609 Returns 0 on success.
6608 Returns 0 on success.
6610 """
6609 """
6611
6610
6612 cmdutil.check_incompatible_arguments(opts, 'stdio', ['cmdserver'])
6611 cmdutil.check_incompatible_arguments(opts, 'stdio', ['cmdserver'])
6613 opts = pycompat.byteskwargs(opts)
6612 opts = pycompat.byteskwargs(opts)
6614 if opts[b"print_url"] and ui.verbose:
6613 if opts[b"print_url"] and ui.verbose:
6615 raise error.InputError(_(b"cannot use --print-url with --verbose"))
6614 raise error.InputError(_(b"cannot use --print-url with --verbose"))
6616
6615
6617 if opts[b"stdio"]:
6616 if opts[b"stdio"]:
6618 if repo is None:
6617 if repo is None:
6619 raise error.RepoError(
6618 raise error.RepoError(
6620 _(b"there is no Mercurial repository here (.hg not found)")
6619 _(b"there is no Mercurial repository here (.hg not found)")
6621 )
6620 )
6622 s = wireprotoserver.sshserver(ui, repo)
6621 s = wireprotoserver.sshserver(ui, repo)
6623 s.serve_forever()
6622 s.serve_forever()
6624 return
6623 return
6625
6624
6626 service = server.createservice(ui, repo, opts)
6625 service = server.createservice(ui, repo, opts)
6627 return server.runservice(opts, initfn=service.init, runfn=service.run)
6626 return server.runservice(opts, initfn=service.init, runfn=service.run)
6628
6627
6629
6628
6630 @command(
6629 @command(
6631 b'shelve',
6630 b'shelve',
6632 [
6631 [
6633 (
6632 (
6634 b'A',
6633 b'A',
6635 b'addremove',
6634 b'addremove',
6636 None,
6635 None,
6637 _(b'mark new/missing files as added/removed before shelving'),
6636 _(b'mark new/missing files as added/removed before shelving'),
6638 ),
6637 ),
6639 (b'u', b'unknown', None, _(b'store unknown files in the shelve')),
6638 (b'u', b'unknown', None, _(b'store unknown files in the shelve')),
6640 (b'', b'cleanup', None, _(b'delete all shelved changes')),
6639 (b'', b'cleanup', None, _(b'delete all shelved changes')),
6641 (
6640 (
6642 b'',
6641 b'',
6643 b'date',
6642 b'date',
6644 b'',
6643 b'',
6645 _(b'shelve with the specified commit date'),
6644 _(b'shelve with the specified commit date'),
6646 _(b'DATE'),
6645 _(b'DATE'),
6647 ),
6646 ),
6648 (b'd', b'delete', None, _(b'delete the named shelved change(s)')),
6647 (b'd', b'delete', None, _(b'delete the named shelved change(s)')),
6649 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
6648 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
6650 (
6649 (
6651 b'k',
6650 b'k',
6652 b'keep',
6651 b'keep',
6653 False,
6652 False,
6654 _(b'shelve, but keep changes in the working directory'),
6653 _(b'shelve, but keep changes in the working directory'),
6655 ),
6654 ),
6656 (b'l', b'list', None, _(b'list current shelves')),
6655 (b'l', b'list', None, _(b'list current shelves')),
6657 (b'm', b'message', b'', _(b'use text as shelve message'), _(b'TEXT')),
6656 (b'm', b'message', b'', _(b'use text as shelve message'), _(b'TEXT')),
6658 (
6657 (
6659 b'n',
6658 b'n',
6660 b'name',
6659 b'name',
6661 b'',
6660 b'',
6662 _(b'use the given name for the shelved commit'),
6661 _(b'use the given name for the shelved commit'),
6663 _(b'NAME'),
6662 _(b'NAME'),
6664 ),
6663 ),
6665 (
6664 (
6666 b'p',
6665 b'p',
6667 b'patch',
6666 b'patch',
6668 None,
6667 None,
6669 _(
6668 _(
6670 b'output patches for changes (provide the names of the shelved '
6669 b'output patches for changes (provide the names of the shelved '
6671 b'changes as positional arguments)'
6670 b'changes as positional arguments)'
6672 ),
6671 ),
6673 ),
6672 ),
6674 (b'i', b'interactive', None, _(b'interactive mode')),
6673 (b'i', b'interactive', None, _(b'interactive mode')),
6675 (
6674 (
6676 b'',
6675 b'',
6677 b'stat',
6676 b'stat',
6678 None,
6677 None,
6679 _(
6678 _(
6680 b'output diffstat-style summary of changes (provide the names of '
6679 b'output diffstat-style summary of changes (provide the names of '
6681 b'the shelved changes as positional arguments)'
6680 b'the shelved changes as positional arguments)'
6682 ),
6681 ),
6683 ),
6682 ),
6684 ]
6683 ]
6685 + cmdutil.walkopts,
6684 + cmdutil.walkopts,
6686 _(b'hg shelve [OPTION]... [FILE]...'),
6685 _(b'hg shelve [OPTION]... [FILE]...'),
6687 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6686 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6688 )
6687 )
6689 def shelve(ui, repo, *pats, **opts):
6688 def shelve(ui, repo, *pats, **opts):
6690 """save and set aside changes from the working directory
6689 """save and set aside changes from the working directory
6691
6690
6692 Shelving takes files that "hg status" reports as not clean, saves
6691 Shelving takes files that "hg status" reports as not clean, saves
6693 the modifications to a bundle (a shelved change), and reverts the
6692 the modifications to a bundle (a shelved change), and reverts the
6694 files so that their state in the working directory becomes clean.
6693 files so that their state in the working directory becomes clean.
6695
6694
6696 To restore these changes to the working directory, using "hg
6695 To restore these changes to the working directory, using "hg
6697 unshelve"; this will work even if you switch to a different
6696 unshelve"; this will work even if you switch to a different
6698 commit.
6697 commit.
6699
6698
6700 When no files are specified, "hg shelve" saves all not-clean
6699 When no files are specified, "hg shelve" saves all not-clean
6701 files. If specific files or directories are named, only changes to
6700 files. If specific files or directories are named, only changes to
6702 those files are shelved.
6701 those files are shelved.
6703
6702
6704 In bare shelve (when no files are specified, without interactive,
6703 In bare shelve (when no files are specified, without interactive,
6705 include and exclude option), shelving remembers information if the
6704 include and exclude option), shelving remembers information if the
6706 working directory was on newly created branch, in other words working
6705 working directory was on newly created branch, in other words working
6707 directory was on different branch than its first parent. In this
6706 directory was on different branch than its first parent. In this
6708 situation unshelving restores branch information to the working directory.
6707 situation unshelving restores branch information to the working directory.
6709
6708
6710 Each shelved change has a name that makes it easier to find later.
6709 Each shelved change has a name that makes it easier to find later.
6711 The name of a shelved change defaults to being based on the active
6710 The name of a shelved change defaults to being based on the active
6712 bookmark, or if there is no active bookmark, the current named
6711 bookmark, or if there is no active bookmark, the current named
6713 branch. To specify a different name, use ``--name``.
6712 branch. To specify a different name, use ``--name``.
6714
6713
6715 To see a list of existing shelved changes, use the ``--list``
6714 To see a list of existing shelved changes, use the ``--list``
6716 option. For each shelved change, this will print its name, age,
6715 option. For each shelved change, this will print its name, age,
6717 and description; use ``--patch`` or ``--stat`` for more details.
6716 and description; use ``--patch`` or ``--stat`` for more details.
6718
6717
6719 To delete specific shelved changes, use ``--delete``. To delete
6718 To delete specific shelved changes, use ``--delete``. To delete
6720 all shelved changes, use ``--cleanup``.
6719 all shelved changes, use ``--cleanup``.
6721 """
6720 """
6722 opts = pycompat.byteskwargs(opts)
6721 opts = pycompat.byteskwargs(opts)
6723 allowables = [
6722 allowables = [
6724 (b'addremove', {b'create'}), # 'create' is pseudo action
6723 (b'addremove', {b'create'}), # 'create' is pseudo action
6725 (b'unknown', {b'create'}),
6724 (b'unknown', {b'create'}),
6726 (b'cleanup', {b'cleanup'}),
6725 (b'cleanup', {b'cleanup'}),
6727 # ('date', {'create'}), # ignored for passing '--date "0 0"' in tests
6726 # ('date', {'create'}), # ignored for passing '--date "0 0"' in tests
6728 (b'delete', {b'delete'}),
6727 (b'delete', {b'delete'}),
6729 (b'edit', {b'create'}),
6728 (b'edit', {b'create'}),
6730 (b'keep', {b'create'}),
6729 (b'keep', {b'create'}),
6731 (b'list', {b'list'}),
6730 (b'list', {b'list'}),
6732 (b'message', {b'create'}),
6731 (b'message', {b'create'}),
6733 (b'name', {b'create'}),
6732 (b'name', {b'create'}),
6734 (b'patch', {b'patch', b'list'}),
6733 (b'patch', {b'patch', b'list'}),
6735 (b'stat', {b'stat', b'list'}),
6734 (b'stat', {b'stat', b'list'}),
6736 ]
6735 ]
6737
6736
6738 def checkopt(opt):
6737 def checkopt(opt):
6739 if opts.get(opt):
6738 if opts.get(opt):
6740 for i, allowable in allowables:
6739 for i, allowable in allowables:
6741 if opts[i] and opt not in allowable:
6740 if opts[i] and opt not in allowable:
6742 raise error.InputError(
6741 raise error.InputError(
6743 _(
6742 _(
6744 b"options '--%s' and '--%s' may not be "
6743 b"options '--%s' and '--%s' may not be "
6745 b"used together"
6744 b"used together"
6746 )
6745 )
6747 % (opt, i)
6746 % (opt, i)
6748 )
6747 )
6749 return True
6748 return True
6750
6749
6751 if checkopt(b'cleanup'):
6750 if checkopt(b'cleanup'):
6752 if pats:
6751 if pats:
6753 raise error.InputError(
6752 raise error.InputError(
6754 _(b"cannot specify names when using '--cleanup'")
6753 _(b"cannot specify names when using '--cleanup'")
6755 )
6754 )
6756 return shelvemod.cleanupcmd(ui, repo)
6755 return shelvemod.cleanupcmd(ui, repo)
6757 elif checkopt(b'delete'):
6756 elif checkopt(b'delete'):
6758 return shelvemod.deletecmd(ui, repo, pats)
6757 return shelvemod.deletecmd(ui, repo, pats)
6759 elif checkopt(b'list'):
6758 elif checkopt(b'list'):
6760 return shelvemod.listcmd(ui, repo, pats, opts)
6759 return shelvemod.listcmd(ui, repo, pats, opts)
6761 elif checkopt(b'patch') or checkopt(b'stat'):
6760 elif checkopt(b'patch') or checkopt(b'stat'):
6762 return shelvemod.patchcmds(ui, repo, pats, opts)
6761 return shelvemod.patchcmds(ui, repo, pats, opts)
6763 else:
6762 else:
6764 return shelvemod.createcmd(ui, repo, pats, opts)
6763 return shelvemod.createcmd(ui, repo, pats, opts)
6765
6764
6766
6765
6767 _NOTTERSE = b'nothing'
6766 _NOTTERSE = b'nothing'
6768
6767
6769
6768
6770 @command(
6769 @command(
6771 b'status|st',
6770 b'status|st',
6772 [
6771 [
6773 (b'A', b'all', None, _(b'show status of all files')),
6772 (b'A', b'all', None, _(b'show status of all files')),
6774 (b'm', b'modified', None, _(b'show only modified files')),
6773 (b'm', b'modified', None, _(b'show only modified files')),
6775 (b'a', b'added', None, _(b'show only added files')),
6774 (b'a', b'added', None, _(b'show only added files')),
6776 (b'r', b'removed', None, _(b'show only removed files')),
6775 (b'r', b'removed', None, _(b'show only removed files')),
6777 (b'd', b'deleted', None, _(b'show only missing files')),
6776 (b'd', b'deleted', None, _(b'show only missing files')),
6778 (b'c', b'clean', None, _(b'show only files without changes')),
6777 (b'c', b'clean', None, _(b'show only files without changes')),
6779 (b'u', b'unknown', None, _(b'show only unknown (not tracked) files')),
6778 (b'u', b'unknown', None, _(b'show only unknown (not tracked) files')),
6780 (b'i', b'ignored', None, _(b'show only ignored files')),
6779 (b'i', b'ignored', None, _(b'show only ignored files')),
6781 (b'n', b'no-status', None, _(b'hide status prefix')),
6780 (b'n', b'no-status', None, _(b'hide status prefix')),
6782 (b't', b'terse', _NOTTERSE, _(b'show the terse output (EXPERIMENTAL)')),
6781 (b't', b'terse', _NOTTERSE, _(b'show the terse output (EXPERIMENTAL)')),
6783 (
6782 (
6784 b'C',
6783 b'C',
6785 b'copies',
6784 b'copies',
6786 None,
6785 None,
6787 _(b'show source of copied files (DEFAULT: ui.statuscopies)'),
6786 _(b'show source of copied files (DEFAULT: ui.statuscopies)'),
6788 ),
6787 ),
6789 (
6788 (
6790 b'0',
6789 b'0',
6791 b'print0',
6790 b'print0',
6792 None,
6791 None,
6793 _(b'end filenames with NUL, for use with xargs'),
6792 _(b'end filenames with NUL, for use with xargs'),
6794 ),
6793 ),
6795 (b'', b'rev', [], _(b'show difference from revision'), _(b'REV')),
6794 (b'', b'rev', [], _(b'show difference from revision'), _(b'REV')),
6796 (
6795 (
6797 b'',
6796 b'',
6798 b'change',
6797 b'change',
6799 b'',
6798 b'',
6800 _(b'list the changed files of a revision'),
6799 _(b'list the changed files of a revision'),
6801 _(b'REV'),
6800 _(b'REV'),
6802 ),
6801 ),
6803 ]
6802 ]
6804 + walkopts
6803 + walkopts
6805 + subrepoopts
6804 + subrepoopts
6806 + formatteropts,
6805 + formatteropts,
6807 _(b'[OPTION]... [FILE]...'),
6806 _(b'[OPTION]... [FILE]...'),
6808 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6807 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6809 helpbasic=True,
6808 helpbasic=True,
6810 inferrepo=True,
6809 inferrepo=True,
6811 intents={INTENT_READONLY},
6810 intents={INTENT_READONLY},
6812 )
6811 )
6813 def status(ui, repo, *pats, **opts):
6812 def status(ui, repo, *pats, **opts):
6814 """show changed files in the working directory
6813 """show changed files in the working directory
6815
6814
6816 Show status of files in the repository. If names are given, only
6815 Show status of files in the repository. If names are given, only
6817 files that match are shown. Files that are clean or ignored or
6816 files that match are shown. Files that are clean or ignored or
6818 the source of a copy/move operation, are not listed unless
6817 the source of a copy/move operation, are not listed unless
6819 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
6818 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
6820 Unless options described with "show only ..." are given, the
6819 Unless options described with "show only ..." are given, the
6821 options -mardu are used.
6820 options -mardu are used.
6822
6821
6823 Option -q/--quiet hides untracked (unknown and ignored) files
6822 Option -q/--quiet hides untracked (unknown and ignored) files
6824 unless explicitly requested with -u/--unknown or -i/--ignored.
6823 unless explicitly requested with -u/--unknown or -i/--ignored.
6825
6824
6826 .. note::
6825 .. note::
6827
6826
6828 :hg:`status` may appear to disagree with diff if permissions have
6827 :hg:`status` may appear to disagree with diff if permissions have
6829 changed or a merge has occurred. The standard diff format does
6828 changed or a merge has occurred. The standard diff format does
6830 not report permission changes and diff only reports changes
6829 not report permission changes and diff only reports changes
6831 relative to one merge parent.
6830 relative to one merge parent.
6832
6831
6833 If one revision is given, it is used as the base revision.
6832 If one revision is given, it is used as the base revision.
6834 If two revisions are given, the differences between them are
6833 If two revisions are given, the differences between them are
6835 shown. The --change option can also be used as a shortcut to list
6834 shown. The --change option can also be used as a shortcut to list
6836 the changed files of a revision from its first parent.
6835 the changed files of a revision from its first parent.
6837
6836
6838 The codes used to show the status of files are::
6837 The codes used to show the status of files are::
6839
6838
6840 M = modified
6839 M = modified
6841 A = added
6840 A = added
6842 R = removed
6841 R = removed
6843 C = clean
6842 C = clean
6844 ! = missing (deleted by non-hg command, but still tracked)
6843 ! = missing (deleted by non-hg command, but still tracked)
6845 ? = not tracked
6844 ? = not tracked
6846 I = ignored
6845 I = ignored
6847 = origin of the previous file (with --copies)
6846 = origin of the previous file (with --copies)
6848
6847
6849 .. container:: verbose
6848 .. container:: verbose
6850
6849
6851 The -t/--terse option abbreviates the output by showing only the directory
6850 The -t/--terse option abbreviates the output by showing only the directory
6852 name if all the files in it share the same status. The option takes an
6851 name if all the files in it share the same status. The option takes an
6853 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
6852 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
6854 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
6853 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
6855 for 'ignored' and 'c' for clean.
6854 for 'ignored' and 'c' for clean.
6856
6855
6857 It abbreviates only those statuses which are passed. Note that clean and
6856 It abbreviates only those statuses which are passed. Note that clean and
6858 ignored files are not displayed with '--terse ic' unless the -c/--clean
6857 ignored files are not displayed with '--terse ic' unless the -c/--clean
6859 and -i/--ignored options are also used.
6858 and -i/--ignored options are also used.
6860
6859
6861 The -v/--verbose option shows information when the repository is in an
6860 The -v/--verbose option shows information when the repository is in an
6862 unfinished merge, shelve, rebase state etc. You can have this behavior
6861 unfinished merge, shelve, rebase state etc. You can have this behavior
6863 turned on by default by enabling the ``commands.status.verbose`` option.
6862 turned on by default by enabling the ``commands.status.verbose`` option.
6864
6863
6865 You can skip displaying some of these states by setting
6864 You can skip displaying some of these states by setting
6866 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
6865 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
6867 'histedit', 'merge', 'rebase', or 'unshelve'.
6866 'histedit', 'merge', 'rebase', or 'unshelve'.
6868
6867
6869 Template:
6868 Template:
6870
6869
6871 The following keywords are supported in addition to the common template
6870 The following keywords are supported in addition to the common template
6872 keywords and functions. See also :hg:`help templates`.
6871 keywords and functions. See also :hg:`help templates`.
6873
6872
6874 :path: String. Repository-absolute path of the file.
6873 :path: String. Repository-absolute path of the file.
6875 :source: String. Repository-absolute path of the file originated from.
6874 :source: String. Repository-absolute path of the file originated from.
6876 Available if ``--copies`` is specified.
6875 Available if ``--copies`` is specified.
6877 :status: String. Character denoting file's status.
6876 :status: String. Character denoting file's status.
6878
6877
6879 Examples:
6878 Examples:
6880
6879
6881 - show changes in the working directory relative to a
6880 - show changes in the working directory relative to a
6882 changeset::
6881 changeset::
6883
6882
6884 hg status --rev 9353
6883 hg status --rev 9353
6885
6884
6886 - show changes in the working directory relative to the
6885 - show changes in the working directory relative to the
6887 current directory (see :hg:`help patterns` for more information)::
6886 current directory (see :hg:`help patterns` for more information)::
6888
6887
6889 hg status re:
6888 hg status re:
6890
6889
6891 - show all changes including copies in an existing changeset::
6890 - show all changes including copies in an existing changeset::
6892
6891
6893 hg status --copies --change 9353
6892 hg status --copies --change 9353
6894
6893
6895 - get a NUL separated list of added files, suitable for xargs::
6894 - get a NUL separated list of added files, suitable for xargs::
6896
6895
6897 hg status -an0
6896 hg status -an0
6898
6897
6899 - show more information about the repository status, abbreviating
6898 - show more information about the repository status, abbreviating
6900 added, removed, modified, deleted, and untracked paths::
6899 added, removed, modified, deleted, and untracked paths::
6901
6900
6902 hg status -v -t mardu
6901 hg status -v -t mardu
6903
6902
6904 Returns 0 on success.
6903 Returns 0 on success.
6905
6904
6906 """
6905 """
6907
6906
6908 cmdutil.check_at_most_one_arg(opts, 'rev', 'change')
6907 cmdutil.check_at_most_one_arg(opts, 'rev', 'change')
6909 opts = pycompat.byteskwargs(opts)
6908 opts = pycompat.byteskwargs(opts)
6910 revs = opts.get(b'rev', [])
6909 revs = opts.get(b'rev', [])
6911 change = opts.get(b'change', b'')
6910 change = opts.get(b'change', b'')
6912 terse = opts.get(b'terse', _NOTTERSE)
6911 terse = opts.get(b'terse', _NOTTERSE)
6913 if terse is _NOTTERSE:
6912 if terse is _NOTTERSE:
6914 if revs:
6913 if revs:
6915 terse = b''
6914 terse = b''
6916 else:
6915 else:
6917 terse = ui.config(b'commands', b'status.terse')
6916 terse = ui.config(b'commands', b'status.terse')
6918
6917
6919 if revs and terse:
6918 if revs and terse:
6920 msg = _(b'cannot use --terse with --rev')
6919 msg = _(b'cannot use --terse with --rev')
6921 raise error.InputError(msg)
6920 raise error.InputError(msg)
6922 elif change:
6921 elif change:
6923 repo = scmutil.unhidehashlikerevs(repo, [change], b'nowarn')
6922 repo = scmutil.unhidehashlikerevs(repo, [change], b'nowarn')
6924 ctx2 = logcmdutil.revsingle(repo, change, None)
6923 ctx2 = logcmdutil.revsingle(repo, change, None)
6925 ctx1 = ctx2.p1()
6924 ctx1 = ctx2.p1()
6926 else:
6925 else:
6927 repo = scmutil.unhidehashlikerevs(repo, revs, b'nowarn')
6926 repo = scmutil.unhidehashlikerevs(repo, revs, b'nowarn')
6928 ctx1, ctx2 = logcmdutil.revpair(repo, revs)
6927 ctx1, ctx2 = logcmdutil.revpair(repo, revs)
6929
6928
6930 forcerelativevalue = None
6929 forcerelativevalue = None
6931 if ui.hasconfig(b'commands', b'status.relative'):
6930 if ui.hasconfig(b'commands', b'status.relative'):
6932 forcerelativevalue = ui.configbool(b'commands', b'status.relative')
6931 forcerelativevalue = ui.configbool(b'commands', b'status.relative')
6933 uipathfn = scmutil.getuipathfn(
6932 uipathfn = scmutil.getuipathfn(
6934 repo,
6933 repo,
6935 legacyrelativevalue=bool(pats),
6934 legacyrelativevalue=bool(pats),
6936 forcerelativevalue=forcerelativevalue,
6935 forcerelativevalue=forcerelativevalue,
6937 )
6936 )
6938
6937
6939 if opts.get(b'print0'):
6938 if opts.get(b'print0'):
6940 end = b'\0'
6939 end = b'\0'
6941 else:
6940 else:
6942 end = b'\n'
6941 end = b'\n'
6943 states = b'modified added removed deleted unknown ignored clean'.split()
6942 states = b'modified added removed deleted unknown ignored clean'.split()
6944 show = [k for k in states if opts.get(k)]
6943 show = [k for k in states if opts.get(k)]
6945 if opts.get(b'all'):
6944 if opts.get(b'all'):
6946 show += ui.quiet and (states[:4] + [b'clean']) or states
6945 show += ui.quiet and (states[:4] + [b'clean']) or states
6947
6946
6948 if not show:
6947 if not show:
6949 if ui.quiet:
6948 if ui.quiet:
6950 show = states[:4]
6949 show = states[:4]
6951 else:
6950 else:
6952 show = states[:5]
6951 show = states[:5]
6953
6952
6954 m = scmutil.match(ctx2, pats, opts)
6953 m = scmutil.match(ctx2, pats, opts)
6955 if terse:
6954 if terse:
6956 # we need to compute clean and unknown to terse
6955 # we need to compute clean and unknown to terse
6957 stat = repo.status(
6956 stat = repo.status(
6958 ctx1.node(),
6957 ctx1.node(),
6959 ctx2.node(),
6958 ctx2.node(),
6960 m,
6959 m,
6961 b'ignored' in show or b'i' in terse,
6960 b'ignored' in show or b'i' in terse,
6962 clean=True,
6961 clean=True,
6963 unknown=True,
6962 unknown=True,
6964 listsubrepos=opts.get(b'subrepos'),
6963 listsubrepos=opts.get(b'subrepos'),
6965 )
6964 )
6966
6965
6967 stat = cmdutil.tersedir(stat, terse)
6966 stat = cmdutil.tersedir(stat, terse)
6968 else:
6967 else:
6969 stat = repo.status(
6968 stat = repo.status(
6970 ctx1.node(),
6969 ctx1.node(),
6971 ctx2.node(),
6970 ctx2.node(),
6972 m,
6971 m,
6973 b'ignored' in show,
6972 b'ignored' in show,
6974 b'clean' in show,
6973 b'clean' in show,
6975 b'unknown' in show,
6974 b'unknown' in show,
6976 opts.get(b'subrepos'),
6975 opts.get(b'subrepos'),
6977 )
6976 )
6978
6977
6979 changestates = zip(
6978 changestates = zip(
6980 states,
6979 states,
6981 pycompat.iterbytestr(b'MAR!?IC'),
6980 pycompat.iterbytestr(b'MAR!?IC'),
6982 [getattr(stat, s.decode('utf8')) for s in states],
6981 [getattr(stat, s.decode('utf8')) for s in states],
6983 )
6982 )
6984
6983
6985 copy = {}
6984 copy = {}
6986 show_copies = ui.configbool(b'ui', b'statuscopies')
6985 show_copies = ui.configbool(b'ui', b'statuscopies')
6987 if opts.get(b'copies') is not None:
6986 if opts.get(b'copies') is not None:
6988 show_copies = opts.get(b'copies')
6987 show_copies = opts.get(b'copies')
6989 show_copies = (show_copies or opts.get(b'all')) and not opts.get(
6988 show_copies = (show_copies or opts.get(b'all')) and not opts.get(
6990 b'no_status'
6989 b'no_status'
6991 )
6990 )
6992 if show_copies:
6991 if show_copies:
6993 copy = copies.pathcopies(ctx1, ctx2, m)
6992 copy = copies.pathcopies(ctx1, ctx2, m)
6994
6993
6995 morestatus = None
6994 morestatus = None
6996 if (
6995 if (
6997 (ui.verbose or ui.configbool(b'commands', b'status.verbose'))
6996 (ui.verbose or ui.configbool(b'commands', b'status.verbose'))
6998 and not ui.plain()
6997 and not ui.plain()
6999 and not opts.get(b'print0')
6998 and not opts.get(b'print0')
7000 ):
6999 ):
7001 morestatus = cmdutil.readmorestatus(repo)
7000 morestatus = cmdutil.readmorestatus(repo)
7002
7001
7003 ui.pager(b'status')
7002 ui.pager(b'status')
7004 fm = ui.formatter(b'status', opts)
7003 fm = ui.formatter(b'status', opts)
7005 fmt = b'%s' + end
7004 fmt = b'%s' + end
7006 showchar = not opts.get(b'no_status')
7005 showchar = not opts.get(b'no_status')
7007
7006
7008 for state, char, files in changestates:
7007 for state, char, files in changestates:
7009 if state in show:
7008 if state in show:
7010 label = b'status.' + state
7009 label = b'status.' + state
7011 for f in files:
7010 for f in files:
7012 fm.startitem()
7011 fm.startitem()
7013 fm.context(ctx=ctx2)
7012 fm.context(ctx=ctx2)
7014 fm.data(itemtype=b'file', path=f)
7013 fm.data(itemtype=b'file', path=f)
7015 fm.condwrite(showchar, b'status', b'%s ', char, label=label)
7014 fm.condwrite(showchar, b'status', b'%s ', char, label=label)
7016 fm.plain(fmt % uipathfn(f), label=label)
7015 fm.plain(fmt % uipathfn(f), label=label)
7017 if f in copy:
7016 if f in copy:
7018 fm.data(source=copy[f])
7017 fm.data(source=copy[f])
7019 fm.plain(
7018 fm.plain(
7020 (b' %s' + end) % uipathfn(copy[f]),
7019 (b' %s' + end) % uipathfn(copy[f]),
7021 label=b'status.copied',
7020 label=b'status.copied',
7022 )
7021 )
7023 if morestatus:
7022 if morestatus:
7024 morestatus.formatfile(f, fm)
7023 morestatus.formatfile(f, fm)
7025
7024
7026 if morestatus:
7025 if morestatus:
7027 morestatus.formatfooter(fm)
7026 morestatus.formatfooter(fm)
7028 fm.end()
7027 fm.end()
7029
7028
7030
7029
7031 @command(
7030 @command(
7032 b'summary|sum',
7031 b'summary|sum',
7033 [(b'', b'remote', None, _(b'check for push and pull'))],
7032 [(b'', b'remote', None, _(b'check for push and pull'))],
7034 b'[--remote]',
7033 b'[--remote]',
7035 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7034 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7036 helpbasic=True,
7035 helpbasic=True,
7037 intents={INTENT_READONLY},
7036 intents={INTENT_READONLY},
7038 )
7037 )
7039 def summary(ui, repo, **opts):
7038 def summary(ui, repo, **opts):
7040 """summarize working directory state
7039 """summarize working directory state
7041
7040
7042 This generates a brief summary of the working directory state,
7041 This generates a brief summary of the working directory state,
7043 including parents, branch, commit status, phase and available updates.
7042 including parents, branch, commit status, phase and available updates.
7044
7043
7045 With the --remote option, this will check the default paths for
7044 With the --remote option, this will check the default paths for
7046 incoming and outgoing changes. This can be time-consuming.
7045 incoming and outgoing changes. This can be time-consuming.
7047
7046
7048 Returns 0 on success.
7047 Returns 0 on success.
7049 """
7048 """
7050
7049
7051 opts = pycompat.byteskwargs(opts)
7050 opts = pycompat.byteskwargs(opts)
7052 ui.pager(b'summary')
7051 ui.pager(b'summary')
7053 ctx = repo[None]
7052 ctx = repo[None]
7054 parents = ctx.parents()
7053 parents = ctx.parents()
7055 pnode = parents[0].node()
7054 pnode = parents[0].node()
7056 marks = []
7055 marks = []
7057
7056
7058 try:
7057 try:
7059 ms = mergestatemod.mergestate.read(repo)
7058 ms = mergestatemod.mergestate.read(repo)
7060 except error.UnsupportedMergeRecords as e:
7059 except error.UnsupportedMergeRecords as e:
7061 s = b' '.join(e.recordtypes)
7060 s = b' '.join(e.recordtypes)
7062 ui.warn(
7061 ui.warn(
7063 _(b'warning: merge state has unsupported record types: %s\n') % s
7062 _(b'warning: merge state has unsupported record types: %s\n') % s
7064 )
7063 )
7065 unresolved = []
7064 unresolved = []
7066 else:
7065 else:
7067 unresolved = list(ms.unresolved())
7066 unresolved = list(ms.unresolved())
7068
7067
7069 for p in parents:
7068 for p in parents:
7070 # label with log.changeset (instead of log.parent) since this
7069 # label with log.changeset (instead of log.parent) since this
7071 # shows a working directory parent *changeset*:
7070 # shows a working directory parent *changeset*:
7072 # i18n: column positioning for "hg summary"
7071 # i18n: column positioning for "hg summary"
7073 ui.write(
7072 ui.write(
7074 _(b'parent: %d:%s ') % (p.rev(), p),
7073 _(b'parent: %d:%s ') % (p.rev(), p),
7075 label=logcmdutil.changesetlabels(p),
7074 label=logcmdutil.changesetlabels(p),
7076 )
7075 )
7077 ui.write(b' '.join(p.tags()), label=b'log.tag')
7076 ui.write(b' '.join(p.tags()), label=b'log.tag')
7078 if p.bookmarks():
7077 if p.bookmarks():
7079 marks.extend(p.bookmarks())
7078 marks.extend(p.bookmarks())
7080 if p.rev() == -1:
7079 if p.rev() == -1:
7081 if not len(repo):
7080 if not len(repo):
7082 ui.write(_(b' (empty repository)'))
7081 ui.write(_(b' (empty repository)'))
7083 else:
7082 else:
7084 ui.write(_(b' (no revision checked out)'))
7083 ui.write(_(b' (no revision checked out)'))
7085 if p.obsolete():
7084 if p.obsolete():
7086 ui.write(_(b' (obsolete)'))
7085 ui.write(_(b' (obsolete)'))
7087 if p.isunstable():
7086 if p.isunstable():
7088 instabilities = (
7087 instabilities = (
7089 ui.label(instability, b'trouble.%s' % instability)
7088 ui.label(instability, b'trouble.%s' % instability)
7090 for instability in p.instabilities()
7089 for instability in p.instabilities()
7091 )
7090 )
7092 ui.write(b' (' + b', '.join(instabilities) + b')')
7091 ui.write(b' (' + b', '.join(instabilities) + b')')
7093 ui.write(b'\n')
7092 ui.write(b'\n')
7094 if p.description():
7093 if p.description():
7095 ui.status(
7094 ui.status(
7096 b' ' + p.description().splitlines()[0].strip() + b'\n',
7095 b' ' + p.description().splitlines()[0].strip() + b'\n',
7097 label=b'log.summary',
7096 label=b'log.summary',
7098 )
7097 )
7099
7098
7100 branch = ctx.branch()
7099 branch = ctx.branch()
7101 bheads = repo.branchheads(branch)
7100 bheads = repo.branchheads(branch)
7102 # i18n: column positioning for "hg summary"
7101 # i18n: column positioning for "hg summary"
7103 m = _(b'branch: %s\n') % branch
7102 m = _(b'branch: %s\n') % branch
7104 if branch != b'default':
7103 if branch != b'default':
7105 ui.write(m, label=b'log.branch')
7104 ui.write(m, label=b'log.branch')
7106 else:
7105 else:
7107 ui.status(m, label=b'log.branch')
7106 ui.status(m, label=b'log.branch')
7108
7107
7109 if marks:
7108 if marks:
7110 active = repo._activebookmark
7109 active = repo._activebookmark
7111 # i18n: column positioning for "hg summary"
7110 # i18n: column positioning for "hg summary"
7112 ui.write(_(b'bookmarks:'), label=b'log.bookmark')
7111 ui.write(_(b'bookmarks:'), label=b'log.bookmark')
7113 if active is not None:
7112 if active is not None:
7114 if active in marks:
7113 if active in marks:
7115 ui.write(b' *' + active, label=bookmarks.activebookmarklabel)
7114 ui.write(b' *' + active, label=bookmarks.activebookmarklabel)
7116 marks.remove(active)
7115 marks.remove(active)
7117 else:
7116 else:
7118 ui.write(b' [%s]' % active, label=bookmarks.activebookmarklabel)
7117 ui.write(b' [%s]' % active, label=bookmarks.activebookmarklabel)
7119 for m in marks:
7118 for m in marks:
7120 ui.write(b' ' + m, label=b'log.bookmark')
7119 ui.write(b' ' + m, label=b'log.bookmark')
7121 ui.write(b'\n', label=b'log.bookmark')
7120 ui.write(b'\n', label=b'log.bookmark')
7122
7121
7123 status = repo.status(unknown=True)
7122 status = repo.status(unknown=True)
7124
7123
7125 c = repo.dirstate.copies()
7124 c = repo.dirstate.copies()
7126 copied, renamed = [], []
7125 copied, renamed = [], []
7127 for d, s in c.items():
7126 for d, s in c.items():
7128 if s in status.removed:
7127 if s in status.removed:
7129 status.removed.remove(s)
7128 status.removed.remove(s)
7130 renamed.append(d)
7129 renamed.append(d)
7131 else:
7130 else:
7132 copied.append(d)
7131 copied.append(d)
7133 if d in status.added:
7132 if d in status.added:
7134 status.added.remove(d)
7133 status.added.remove(d)
7135
7134
7136 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
7135 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
7137
7136
7138 labels = [
7137 labels = [
7139 (ui.label(_(b'%d modified'), b'status.modified'), status.modified),
7138 (ui.label(_(b'%d modified'), b'status.modified'), status.modified),
7140 (ui.label(_(b'%d added'), b'status.added'), status.added),
7139 (ui.label(_(b'%d added'), b'status.added'), status.added),
7141 (ui.label(_(b'%d removed'), b'status.removed'), status.removed),
7140 (ui.label(_(b'%d removed'), b'status.removed'), status.removed),
7142 (ui.label(_(b'%d renamed'), b'status.copied'), renamed),
7141 (ui.label(_(b'%d renamed'), b'status.copied'), renamed),
7143 (ui.label(_(b'%d copied'), b'status.copied'), copied),
7142 (ui.label(_(b'%d copied'), b'status.copied'), copied),
7144 (ui.label(_(b'%d deleted'), b'status.deleted'), status.deleted),
7143 (ui.label(_(b'%d deleted'), b'status.deleted'), status.deleted),
7145 (ui.label(_(b'%d unknown'), b'status.unknown'), status.unknown),
7144 (ui.label(_(b'%d unknown'), b'status.unknown'), status.unknown),
7146 (ui.label(_(b'%d unresolved'), b'resolve.unresolved'), unresolved),
7145 (ui.label(_(b'%d unresolved'), b'resolve.unresolved'), unresolved),
7147 (ui.label(_(b'%d subrepos'), b'status.modified'), subs),
7146 (ui.label(_(b'%d subrepos'), b'status.modified'), subs),
7148 ]
7147 ]
7149 t = []
7148 t = []
7150 for l, s in labels:
7149 for l, s in labels:
7151 if s:
7150 if s:
7152 t.append(l % len(s))
7151 t.append(l % len(s))
7153
7152
7154 t = b', '.join(t)
7153 t = b', '.join(t)
7155 cleanworkdir = False
7154 cleanworkdir = False
7156
7155
7157 if repo.vfs.exists(b'graftstate'):
7156 if repo.vfs.exists(b'graftstate'):
7158 t += _(b' (graft in progress)')
7157 t += _(b' (graft in progress)')
7159 if repo.vfs.exists(b'updatestate'):
7158 if repo.vfs.exists(b'updatestate'):
7160 t += _(b' (interrupted update)')
7159 t += _(b' (interrupted update)')
7161 elif len(parents) > 1:
7160 elif len(parents) > 1:
7162 t += _(b' (merge)')
7161 t += _(b' (merge)')
7163 elif branch != parents[0].branch():
7162 elif branch != parents[0].branch():
7164 t += _(b' (new branch)')
7163 t += _(b' (new branch)')
7165 elif parents[0].closesbranch() and pnode in repo.branchheads(
7164 elif parents[0].closesbranch() and pnode in repo.branchheads(
7166 branch, closed=True
7165 branch, closed=True
7167 ):
7166 ):
7168 t += _(b' (head closed)')
7167 t += _(b' (head closed)')
7169 elif not (
7168 elif not (
7170 status.modified
7169 status.modified
7171 or status.added
7170 or status.added
7172 or status.removed
7171 or status.removed
7173 or renamed
7172 or renamed
7174 or copied
7173 or copied
7175 or subs
7174 or subs
7176 ):
7175 ):
7177 t += _(b' (clean)')
7176 t += _(b' (clean)')
7178 cleanworkdir = True
7177 cleanworkdir = True
7179 elif pnode not in bheads:
7178 elif pnode not in bheads:
7180 t += _(b' (new branch head)')
7179 t += _(b' (new branch head)')
7181
7180
7182 if parents:
7181 if parents:
7183 pendingphase = max(p.phase() for p in parents)
7182 pendingphase = max(p.phase() for p in parents)
7184 else:
7183 else:
7185 pendingphase = phases.public
7184 pendingphase = phases.public
7186
7185
7187 if pendingphase > phases.newcommitphase(ui):
7186 if pendingphase > phases.newcommitphase(ui):
7188 t += b' (%s)' % phases.phasenames[pendingphase]
7187 t += b' (%s)' % phases.phasenames[pendingphase]
7189
7188
7190 if cleanworkdir:
7189 if cleanworkdir:
7191 # i18n: column positioning for "hg summary"
7190 # i18n: column positioning for "hg summary"
7192 ui.status(_(b'commit: %s\n') % t.strip())
7191 ui.status(_(b'commit: %s\n') % t.strip())
7193 else:
7192 else:
7194 # i18n: column positioning for "hg summary"
7193 # i18n: column positioning for "hg summary"
7195 ui.write(_(b'commit: %s\n') % t.strip())
7194 ui.write(_(b'commit: %s\n') % t.strip())
7196
7195
7197 # all ancestors of branch heads - all ancestors of parent = new csets
7196 # all ancestors of branch heads - all ancestors of parent = new csets
7198 new = len(
7197 new = len(
7199 repo.changelog.findmissing([pctx.node() for pctx in parents], bheads)
7198 repo.changelog.findmissing([pctx.node() for pctx in parents], bheads)
7200 )
7199 )
7201
7200
7202 if new == 0:
7201 if new == 0:
7203 # i18n: column positioning for "hg summary"
7202 # i18n: column positioning for "hg summary"
7204 ui.status(_(b'update: (current)\n'))
7203 ui.status(_(b'update: (current)\n'))
7205 elif pnode not in bheads:
7204 elif pnode not in bheads:
7206 # i18n: column positioning for "hg summary"
7205 # i18n: column positioning for "hg summary"
7207 ui.write(_(b'update: %d new changesets (update)\n') % new)
7206 ui.write(_(b'update: %d new changesets (update)\n') % new)
7208 else:
7207 else:
7209 # i18n: column positioning for "hg summary"
7208 # i18n: column positioning for "hg summary"
7210 ui.write(
7209 ui.write(
7211 _(b'update: %d new changesets, %d branch heads (merge)\n')
7210 _(b'update: %d new changesets, %d branch heads (merge)\n')
7212 % (new, len(bheads))
7211 % (new, len(bheads))
7213 )
7212 )
7214
7213
7215 t = []
7214 t = []
7216 draft = len(repo.revs(b'draft()'))
7215 draft = len(repo.revs(b'draft()'))
7217 if draft:
7216 if draft:
7218 t.append(_(b'%d draft') % draft)
7217 t.append(_(b'%d draft') % draft)
7219 secret = len(repo.revs(b'secret()'))
7218 secret = len(repo.revs(b'secret()'))
7220 if secret:
7219 if secret:
7221 t.append(_(b'%d secret') % secret)
7220 t.append(_(b'%d secret') % secret)
7222
7221
7223 if draft or secret:
7222 if draft or secret:
7224 ui.status(_(b'phases: %s\n') % b', '.join(t))
7223 ui.status(_(b'phases: %s\n') % b', '.join(t))
7225
7224
7226 if obsolete.isenabled(repo, obsolete.createmarkersopt):
7225 if obsolete.isenabled(repo, obsolete.createmarkersopt):
7227 for trouble in (b"orphan", b"contentdivergent", b"phasedivergent"):
7226 for trouble in (b"orphan", b"contentdivergent", b"phasedivergent"):
7228 numtrouble = len(repo.revs(trouble + b"()"))
7227 numtrouble = len(repo.revs(trouble + b"()"))
7229 # We write all the possibilities to ease translation
7228 # We write all the possibilities to ease translation
7230 troublemsg = {
7229 troublemsg = {
7231 b"orphan": _(b"orphan: %d changesets"),
7230 b"orphan": _(b"orphan: %d changesets"),
7232 b"contentdivergent": _(b"content-divergent: %d changesets"),
7231 b"contentdivergent": _(b"content-divergent: %d changesets"),
7233 b"phasedivergent": _(b"phase-divergent: %d changesets"),
7232 b"phasedivergent": _(b"phase-divergent: %d changesets"),
7234 }
7233 }
7235 if numtrouble > 0:
7234 if numtrouble > 0:
7236 ui.status(troublemsg[trouble] % numtrouble + b"\n")
7235 ui.status(troublemsg[trouble] % numtrouble + b"\n")
7237
7236
7238 cmdutil.summaryhooks(ui, repo)
7237 cmdutil.summaryhooks(ui, repo)
7239
7238
7240 if opts.get(b'remote'):
7239 if opts.get(b'remote'):
7241 needsincoming, needsoutgoing = True, True
7240 needsincoming, needsoutgoing = True, True
7242 else:
7241 else:
7243 needsincoming, needsoutgoing = False, False
7242 needsincoming, needsoutgoing = False, False
7244 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
7243 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
7245 if i:
7244 if i:
7246 needsincoming = True
7245 needsincoming = True
7247 if o:
7246 if o:
7248 needsoutgoing = True
7247 needsoutgoing = True
7249 if not needsincoming and not needsoutgoing:
7248 if not needsincoming and not needsoutgoing:
7250 return
7249 return
7251
7250
7252 def getincoming():
7251 def getincoming():
7253 # XXX We should actually skip this if no default is specified, instead
7252 # XXX We should actually skip this if no default is specified, instead
7254 # of passing "default" which will resolve as "./default/" if no default
7253 # of passing "default" which will resolve as "./default/" if no default
7255 # path is defined.
7254 # path is defined.
7256 source, branches = urlutil.get_unique_pull_path(
7255 source, branches = urlutil.get_unique_pull_path(
7257 b'summary', repo, ui, b'default'
7256 b'summary', repo, ui, b'default'
7258 )
7257 )
7259 sbranch = branches[0]
7258 sbranch = branches[0]
7260 try:
7259 try:
7261 other = hg.peer(repo, {}, source)
7260 other = hg.peer(repo, {}, source)
7262 except error.RepoError:
7261 except error.RepoError:
7263 if opts.get(b'remote'):
7262 if opts.get(b'remote'):
7264 raise
7263 raise
7265 return source, sbranch, None, None, None
7264 return source, sbranch, None, None, None
7266 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
7265 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
7267 if revs:
7266 if revs:
7268 revs = [other.lookup(rev) for rev in revs]
7267 revs = [other.lookup(rev) for rev in revs]
7269 ui.debug(b'comparing with %s\n' % urlutil.hidepassword(source))
7268 ui.debug(b'comparing with %s\n' % urlutil.hidepassword(source))
7270 with repo.ui.silent():
7269 with repo.ui.silent():
7271 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
7270 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
7272 return source, sbranch, other, commoninc, commoninc[1]
7271 return source, sbranch, other, commoninc, commoninc[1]
7273
7272
7274 if needsincoming:
7273 if needsincoming:
7275 source, sbranch, sother, commoninc, incoming = getincoming()
7274 source, sbranch, sother, commoninc, incoming = getincoming()
7276 else:
7275 else:
7277 source = sbranch = sother = commoninc = incoming = None
7276 source = sbranch = sother = commoninc = incoming = None
7278
7277
7279 def getoutgoing():
7278 def getoutgoing():
7280 # XXX We should actually skip this if no default is specified, instead
7279 # XXX We should actually skip this if no default is specified, instead
7281 # of passing "default" which will resolve as "./default/" if no default
7280 # of passing "default" which will resolve as "./default/" if no default
7282 # path is defined.
7281 # path is defined.
7283 d = None
7282 d = None
7284 if b'default-push' in ui.paths:
7283 if b'default-push' in ui.paths:
7285 d = b'default-push'
7284 d = b'default-push'
7286 elif b'default' in ui.paths:
7285 elif b'default' in ui.paths:
7287 d = b'default'
7286 d = b'default'
7288 path = None
7287 path = None
7289 if d is not None:
7288 if d is not None:
7290 path = urlutil.get_unique_push_path(b'summary', repo, ui, d)
7289 path = urlutil.get_unique_push_path(b'summary', repo, ui, d)
7291 dest = path.loc
7290 dest = path.loc
7292 dbranch = path.branch
7291 dbranch = path.branch
7293 else:
7292 else:
7294 dest = b'default'
7293 dest = b'default'
7295 dbranch = None
7294 dbranch = None
7296 revs, checkout = hg.addbranchrevs(repo, repo, (dbranch, []), None)
7295 revs, checkout = hg.addbranchrevs(repo, repo, (dbranch, []), None)
7297 if source != dest:
7296 if source != dest:
7298 try:
7297 try:
7299 dother = hg.peer(repo, {}, path if path is not None else dest)
7298 dother = hg.peer(repo, {}, path if path is not None else dest)
7300 except error.RepoError:
7299 except error.RepoError:
7301 if opts.get(b'remote'):
7300 if opts.get(b'remote'):
7302 raise
7301 raise
7303 return dest, dbranch, None, None
7302 return dest, dbranch, None, None
7304 ui.debug(b'comparing with %s\n' % urlutil.hidepassword(dest))
7303 ui.debug(b'comparing with %s\n' % urlutil.hidepassword(dest))
7305 elif sother is None:
7304 elif sother is None:
7306 # there is no explicit destination peer, but source one is invalid
7305 # there is no explicit destination peer, but source one is invalid
7307 return dest, dbranch, None, None
7306 return dest, dbranch, None, None
7308 else:
7307 else:
7309 dother = sother
7308 dother = sother
7310 if source != dest or (sbranch is not None and sbranch != dbranch):
7309 if source != dest or (sbranch is not None and sbranch != dbranch):
7311 common = None
7310 common = None
7312 else:
7311 else:
7313 common = commoninc
7312 common = commoninc
7314 if revs:
7313 if revs:
7315 revs = [repo.lookup(rev) for rev in revs]
7314 revs = [repo.lookup(rev) for rev in revs]
7316 with repo.ui.silent():
7315 with repo.ui.silent():
7317 outgoing = discovery.findcommonoutgoing(
7316 outgoing = discovery.findcommonoutgoing(
7318 repo, dother, onlyheads=revs, commoninc=common
7317 repo, dother, onlyheads=revs, commoninc=common
7319 )
7318 )
7320 return dest, dbranch, dother, outgoing
7319 return dest, dbranch, dother, outgoing
7321
7320
7322 if needsoutgoing:
7321 if needsoutgoing:
7323 dest, dbranch, dother, outgoing = getoutgoing()
7322 dest, dbranch, dother, outgoing = getoutgoing()
7324 else:
7323 else:
7325 dest = dbranch = dother = outgoing = None
7324 dest = dbranch = dother = outgoing = None
7326
7325
7327 if opts.get(b'remote'):
7326 if opts.get(b'remote'):
7328 # Help pytype. --remote sets both `needsincoming` and `needsoutgoing`.
7327 # Help pytype. --remote sets both `needsincoming` and `needsoutgoing`.
7329 # The former always sets `sother` (or raises an exception if it can't);
7328 # The former always sets `sother` (or raises an exception if it can't);
7330 # the latter always sets `outgoing`.
7329 # the latter always sets `outgoing`.
7331 assert sother is not None
7330 assert sother is not None
7332 assert outgoing is not None
7331 assert outgoing is not None
7333
7332
7334 t = []
7333 t = []
7335 if incoming:
7334 if incoming:
7336 t.append(_(b'1 or more incoming'))
7335 t.append(_(b'1 or more incoming'))
7337 o = outgoing.missing
7336 o = outgoing.missing
7338 if o:
7337 if o:
7339 t.append(_(b'%d outgoing') % len(o))
7338 t.append(_(b'%d outgoing') % len(o))
7340 other = dother or sother
7339 other = dother or sother
7341 if b'bookmarks' in other.listkeys(b'namespaces'):
7340 if b'bookmarks' in other.listkeys(b'namespaces'):
7342 counts = bookmarks.summary(repo, other)
7341 counts = bookmarks.summary(repo, other)
7343 if counts[0] > 0:
7342 if counts[0] > 0:
7344 t.append(_(b'%d incoming bookmarks') % counts[0])
7343 t.append(_(b'%d incoming bookmarks') % counts[0])
7345 if counts[1] > 0:
7344 if counts[1] > 0:
7346 t.append(_(b'%d outgoing bookmarks') % counts[1])
7345 t.append(_(b'%d outgoing bookmarks') % counts[1])
7347
7346
7348 if t:
7347 if t:
7349 # i18n: column positioning for "hg summary"
7348 # i18n: column positioning for "hg summary"
7350 ui.write(_(b'remote: %s\n') % (b', '.join(t)))
7349 ui.write(_(b'remote: %s\n') % (b', '.join(t)))
7351 else:
7350 else:
7352 # i18n: column positioning for "hg summary"
7351 # i18n: column positioning for "hg summary"
7353 ui.status(_(b'remote: (synced)\n'))
7352 ui.status(_(b'remote: (synced)\n'))
7354
7353
7355 cmdutil.summaryremotehooks(
7354 cmdutil.summaryremotehooks(
7356 ui,
7355 ui,
7357 repo,
7356 repo,
7358 opts,
7357 opts,
7359 (
7358 (
7360 (source, sbranch, sother, commoninc),
7359 (source, sbranch, sother, commoninc),
7361 (dest, dbranch, dother, outgoing),
7360 (dest, dbranch, dother, outgoing),
7362 ),
7361 ),
7363 )
7362 )
7364
7363
7365
7364
7366 @command(
7365 @command(
7367 b'tag',
7366 b'tag',
7368 [
7367 [
7369 (b'f', b'force', None, _(b'force tag')),
7368 (b'f', b'force', None, _(b'force tag')),
7370 (b'l', b'local', None, _(b'make the tag local')),
7369 (b'l', b'local', None, _(b'make the tag local')),
7371 (b'r', b'rev', b'', _(b'revision to tag'), _(b'REV')),
7370 (b'r', b'rev', b'', _(b'revision to tag'), _(b'REV')),
7372 (b'', b'remove', None, _(b'remove a tag')),
7371 (b'', b'remove', None, _(b'remove a tag')),
7373 # -l/--local is already there, commitopts cannot be used
7372 # -l/--local is already there, commitopts cannot be used
7374 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
7373 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
7375 (b'm', b'message', b'', _(b'use text as commit message'), _(b'TEXT')),
7374 (b'm', b'message', b'', _(b'use text as commit message'), _(b'TEXT')),
7376 ]
7375 ]
7377 + commitopts2,
7376 + commitopts2,
7378 _(b'[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'),
7377 _(b'[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'),
7379 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7378 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7380 )
7379 )
7381 def tag(ui, repo, name1, *names, **opts):
7380 def tag(ui, repo, name1, *names, **opts):
7382 """add one or more tags for the current or given revision
7381 """add one or more tags for the current or given revision
7383
7382
7384 Name a particular revision using <name>.
7383 Name a particular revision using <name>.
7385
7384
7386 Tags are used to name particular revisions of the repository and are
7385 Tags are used to name particular revisions of the repository and are
7387 very useful to compare different revisions, to go back to significant
7386 very useful to compare different revisions, to go back to significant
7388 earlier versions or to mark branch points as releases, etc. Changing
7387 earlier versions or to mark branch points as releases, etc. Changing
7389 an existing tag is normally disallowed; use -f/--force to override.
7388 an existing tag is normally disallowed; use -f/--force to override.
7390
7389
7391 If no revision is given, the parent of the working directory is
7390 If no revision is given, the parent of the working directory is
7392 used.
7391 used.
7393
7392
7394 To facilitate version control, distribution, and merging of tags,
7393 To facilitate version control, distribution, and merging of tags,
7395 they are stored as a file named ".hgtags" which is managed similarly
7394 they are stored as a file named ".hgtags" which is managed similarly
7396 to other project files and can be hand-edited if necessary. This
7395 to other project files and can be hand-edited if necessary. This
7397 also means that tagging creates a new commit. The file
7396 also means that tagging creates a new commit. The file
7398 ".hg/localtags" is used for local tags (not shared among
7397 ".hg/localtags" is used for local tags (not shared among
7399 repositories).
7398 repositories).
7400
7399
7401 Tag commits are usually made at the head of a branch. If the parent
7400 Tag commits are usually made at the head of a branch. If the parent
7402 of the working directory is not a branch head, :hg:`tag` aborts; use
7401 of the working directory is not a branch head, :hg:`tag` aborts; use
7403 -f/--force to force the tag commit to be based on a non-head
7402 -f/--force to force the tag commit to be based on a non-head
7404 changeset.
7403 changeset.
7405
7404
7406 See :hg:`help dates` for a list of formats valid for -d/--date.
7405 See :hg:`help dates` for a list of formats valid for -d/--date.
7407
7406
7408 Since tag names have priority over branch names during revision
7407 Since tag names have priority over branch names during revision
7409 lookup, using an existing branch name as a tag name is discouraged.
7408 lookup, using an existing branch name as a tag name is discouraged.
7410
7409
7411 Returns 0 on success.
7410 Returns 0 on success.
7412 """
7411 """
7413 cmdutil.check_incompatible_arguments(opts, 'remove', ['rev'])
7412 cmdutil.check_incompatible_arguments(opts, 'remove', ['rev'])
7414 opts = pycompat.byteskwargs(opts)
7413 opts = pycompat.byteskwargs(opts)
7415 with repo.wlock(), repo.lock():
7414 with repo.wlock(), repo.lock():
7416 rev_ = b"."
7415 rev_ = b"."
7417 names = [t.strip() for t in (name1,) + names]
7416 names = [t.strip() for t in (name1,) + names]
7418 if len(names) != len(set(names)):
7417 if len(names) != len(set(names)):
7419 raise error.InputError(_(b'tag names must be unique'))
7418 raise error.InputError(_(b'tag names must be unique'))
7420 for n in names:
7419 for n in names:
7421 scmutil.checknewlabel(repo, n, b'tag')
7420 scmutil.checknewlabel(repo, n, b'tag')
7422 if not n:
7421 if not n:
7423 raise error.InputError(
7422 raise error.InputError(
7424 _(b'tag names cannot consist entirely of whitespace')
7423 _(b'tag names cannot consist entirely of whitespace')
7425 )
7424 )
7426 if opts.get(b'rev'):
7425 if opts.get(b'rev'):
7427 rev_ = opts[b'rev']
7426 rev_ = opts[b'rev']
7428 message = opts.get(b'message')
7427 message = opts.get(b'message')
7429 if opts.get(b'remove'):
7428 if opts.get(b'remove'):
7430 if opts.get(b'local'):
7429 if opts.get(b'local'):
7431 expectedtype = b'local'
7430 expectedtype = b'local'
7432 else:
7431 else:
7433 expectedtype = b'global'
7432 expectedtype = b'global'
7434
7433
7435 for n in names:
7434 for n in names:
7436 if repo.tagtype(n) == b'global':
7435 if repo.tagtype(n) == b'global':
7437 alltags = tagsmod.findglobaltags(ui, repo)
7436 alltags = tagsmod.findglobaltags(ui, repo)
7438 if alltags[n][0] == repo.nullid:
7437 if alltags[n][0] == repo.nullid:
7439 raise error.InputError(
7438 raise error.InputError(
7440 _(b"tag '%s' is already removed") % n
7439 _(b"tag '%s' is already removed") % n
7441 )
7440 )
7442 if not repo.tagtype(n):
7441 if not repo.tagtype(n):
7443 raise error.InputError(_(b"tag '%s' does not exist") % n)
7442 raise error.InputError(_(b"tag '%s' does not exist") % n)
7444 if repo.tagtype(n) != expectedtype:
7443 if repo.tagtype(n) != expectedtype:
7445 if expectedtype == b'global':
7444 if expectedtype == b'global':
7446 raise error.InputError(
7445 raise error.InputError(
7447 _(b"tag '%s' is not a global tag") % n
7446 _(b"tag '%s' is not a global tag") % n
7448 )
7447 )
7449 else:
7448 else:
7450 raise error.InputError(
7449 raise error.InputError(
7451 _(b"tag '%s' is not a local tag") % n
7450 _(b"tag '%s' is not a local tag") % n
7452 )
7451 )
7453 rev_ = b'null'
7452 rev_ = b'null'
7454 if not message:
7453 if not message:
7455 # we don't translate commit messages
7454 # we don't translate commit messages
7456 message = b'Removed tag %s' % b', '.join(names)
7455 message = b'Removed tag %s' % b', '.join(names)
7457 elif not opts.get(b'force'):
7456 elif not opts.get(b'force'):
7458 for n in names:
7457 for n in names:
7459 if n in repo.tags():
7458 if n in repo.tags():
7460 raise error.InputError(
7459 raise error.InputError(
7461 _(b"tag '%s' already exists (use -f to force)") % n
7460 _(b"tag '%s' already exists (use -f to force)") % n
7462 )
7461 )
7463 if not opts.get(b'local'):
7462 if not opts.get(b'local'):
7464 p1, p2 = repo.dirstate.parents()
7463 p1, p2 = repo.dirstate.parents()
7465 if p2 != repo.nullid:
7464 if p2 != repo.nullid:
7466 raise error.StateError(_(b'uncommitted merge'))
7465 raise error.StateError(_(b'uncommitted merge'))
7467 bheads = repo.branchheads()
7466 bheads = repo.branchheads()
7468 if not opts.get(b'force') and bheads and p1 not in bheads:
7467 if not opts.get(b'force') and bheads and p1 not in bheads:
7469 raise error.InputError(
7468 raise error.InputError(
7470 _(
7469 _(
7471 b'working directory is not at a branch head '
7470 b'working directory is not at a branch head '
7472 b'(use -f to force)'
7471 b'(use -f to force)'
7473 )
7472 )
7474 )
7473 )
7475 node = logcmdutil.revsingle(repo, rev_).node()
7474 node = logcmdutil.revsingle(repo, rev_).node()
7476
7475
7477 if not message:
7476 if not message:
7478 # we don't translate commit messages
7477 # we don't translate commit messages
7479 message = b'Added tag %s for changeset %s' % (
7478 message = b'Added tag %s for changeset %s' % (
7480 b', '.join(names),
7479 b', '.join(names),
7481 short(node),
7480 short(node),
7482 )
7481 )
7483
7482
7484 date = opts.get(b'date')
7483 date = opts.get(b'date')
7485 if date:
7484 if date:
7486 date = dateutil.parsedate(date)
7485 date = dateutil.parsedate(date)
7487
7486
7488 if opts.get(b'remove'):
7487 if opts.get(b'remove'):
7489 editform = b'tag.remove'
7488 editform = b'tag.remove'
7490 else:
7489 else:
7491 editform = b'tag.add'
7490 editform = b'tag.add'
7492 editor = cmdutil.getcommiteditor(
7491 editor = cmdutil.getcommiteditor(
7493 editform=editform, **pycompat.strkwargs(opts)
7492 editform=editform, **pycompat.strkwargs(opts)
7494 )
7493 )
7495
7494
7496 # don't allow tagging the null rev
7495 # don't allow tagging the null rev
7497 if (
7496 if (
7498 not opts.get(b'remove')
7497 not opts.get(b'remove')
7499 and logcmdutil.revsingle(repo, rev_).rev() == nullrev
7498 and logcmdutil.revsingle(repo, rev_).rev() == nullrev
7500 ):
7499 ):
7501 raise error.InputError(_(b"cannot tag null revision"))
7500 raise error.InputError(_(b"cannot tag null revision"))
7502
7501
7503 tagsmod.tag(
7502 tagsmod.tag(
7504 repo,
7503 repo,
7505 names,
7504 names,
7506 node,
7505 node,
7507 message,
7506 message,
7508 opts.get(b'local'),
7507 opts.get(b'local'),
7509 opts.get(b'user'),
7508 opts.get(b'user'),
7510 date,
7509 date,
7511 editor=editor,
7510 editor=editor,
7512 )
7511 )
7513
7512
7514
7513
7515 @command(
7514 @command(
7516 b'tags',
7515 b'tags',
7517 formatteropts,
7516 formatteropts,
7518 b'',
7517 b'',
7519 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7518 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
7520 intents={INTENT_READONLY},
7519 intents={INTENT_READONLY},
7521 )
7520 )
7522 def tags(ui, repo, **opts):
7521 def tags(ui, repo, **opts):
7523 """list repository tags
7522 """list repository tags
7524
7523
7525 This lists both regular and local tags. When the -v/--verbose
7524 This lists both regular and local tags. When the -v/--verbose
7526 switch is used, a third column "local" is printed for local tags.
7525 switch is used, a third column "local" is printed for local tags.
7527 When the -q/--quiet switch is used, only the tag name is printed.
7526 When the -q/--quiet switch is used, only the tag name is printed.
7528
7527
7529 .. container:: verbose
7528 .. container:: verbose
7530
7529
7531 Template:
7530 Template:
7532
7531
7533 The following keywords are supported in addition to the common template
7532 The following keywords are supported in addition to the common template
7534 keywords and functions such as ``{tag}``. See also
7533 keywords and functions such as ``{tag}``. See also
7535 :hg:`help templates`.
7534 :hg:`help templates`.
7536
7535
7537 :type: String. ``local`` for local tags.
7536 :type: String. ``local`` for local tags.
7538
7537
7539 Returns 0 on success.
7538 Returns 0 on success.
7540 """
7539 """
7541
7540
7542 opts = pycompat.byteskwargs(opts)
7541 opts = pycompat.byteskwargs(opts)
7543 ui.pager(b'tags')
7542 ui.pager(b'tags')
7544 fm = ui.formatter(b'tags', opts)
7543 fm = ui.formatter(b'tags', opts)
7545 hexfunc = fm.hexfunc
7544 hexfunc = fm.hexfunc
7546
7545
7547 for t, n in reversed(repo.tagslist()):
7546 for t, n in reversed(repo.tagslist()):
7548 hn = hexfunc(n)
7547 hn = hexfunc(n)
7549 label = b'tags.normal'
7548 label = b'tags.normal'
7550 tagtype = repo.tagtype(t)
7549 tagtype = repo.tagtype(t)
7551 if not tagtype or tagtype == b'global':
7550 if not tagtype or tagtype == b'global':
7552 tagtype = b''
7551 tagtype = b''
7553 else:
7552 else:
7554 label = b'tags.' + tagtype
7553 label = b'tags.' + tagtype
7555
7554
7556 fm.startitem()
7555 fm.startitem()
7557 fm.context(repo=repo)
7556 fm.context(repo=repo)
7558 fm.write(b'tag', b'%s', t, label=label)
7557 fm.write(b'tag', b'%s', t, label=label)
7559 fmt = b" " * (30 - encoding.colwidth(t)) + b' %5d:%s'
7558 fmt = b" " * (30 - encoding.colwidth(t)) + b' %5d:%s'
7560 fm.condwrite(
7559 fm.condwrite(
7561 not ui.quiet,
7560 not ui.quiet,
7562 b'rev node',
7561 b'rev node',
7563 fmt,
7562 fmt,
7564 repo.changelog.rev(n),
7563 repo.changelog.rev(n),
7565 hn,
7564 hn,
7566 label=label,
7565 label=label,
7567 )
7566 )
7568 fm.condwrite(
7567 fm.condwrite(
7569 ui.verbose and tagtype, b'type', b' %s', tagtype, label=label
7568 ui.verbose and tagtype, b'type', b' %s', tagtype, label=label
7570 )
7569 )
7571 fm.plain(b'\n')
7570 fm.plain(b'\n')
7572 fm.end()
7571 fm.end()
7573
7572
7574
7573
7575 @command(
7574 @command(
7576 b'tip',
7575 b'tip',
7577 [
7576 [
7578 (b'p', b'patch', None, _(b'show patch')),
7577 (b'p', b'patch', None, _(b'show patch')),
7579 (b'g', b'git', None, _(b'use git extended diff format')),
7578 (b'g', b'git', None, _(b'use git extended diff format')),
7580 ]
7579 ]
7581 + templateopts,
7580 + templateopts,
7582 _(b'[-p] [-g]'),
7581 _(b'[-p] [-g]'),
7583 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
7582 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
7584 )
7583 )
7585 def tip(ui, repo, **opts):
7584 def tip(ui, repo, **opts):
7586 """show the tip revision (DEPRECATED)
7585 """show the tip revision (DEPRECATED)
7587
7586
7588 The tip revision (usually just called the tip) is the changeset
7587 The tip revision (usually just called the tip) is the changeset
7589 most recently added to the repository (and therefore the most
7588 most recently added to the repository (and therefore the most
7590 recently changed head).
7589 recently changed head).
7591
7590
7592 If you have just made a commit, that commit will be the tip. If
7591 If you have just made a commit, that commit will be the tip. If
7593 you have just pulled changes from another repository, the tip of
7592 you have just pulled changes from another repository, the tip of
7594 that repository becomes the current tip. The "tip" tag is special
7593 that repository becomes the current tip. The "tip" tag is special
7595 and cannot be renamed or assigned to a different changeset.
7594 and cannot be renamed or assigned to a different changeset.
7596
7595
7597 This command is deprecated, please use :hg:`heads` instead.
7596 This command is deprecated, please use :hg:`heads` instead.
7598
7597
7599 Returns 0 on success.
7598 Returns 0 on success.
7600 """
7599 """
7601 opts = pycompat.byteskwargs(opts)
7600 opts = pycompat.byteskwargs(opts)
7602 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
7601 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
7603 displayer.show(repo[b'tip'])
7602 displayer.show(repo[b'tip'])
7604 displayer.close()
7603 displayer.close()
7605
7604
7606
7605
7607 @command(
7606 @command(
7608 b'unbundle',
7607 b'unbundle',
7609 [
7608 [
7610 (
7609 (
7611 b'u',
7610 b'u',
7612 b'update',
7611 b'update',
7613 None,
7612 None,
7614 _(b'update to new branch head if changesets were unbundled'),
7613 _(b'update to new branch head if changesets were unbundled'),
7615 )
7614 )
7616 ],
7615 ],
7617 _(b'[-u] FILE...'),
7616 _(b'[-u] FILE...'),
7618 helpcategory=command.CATEGORY_IMPORT_EXPORT,
7617 helpcategory=command.CATEGORY_IMPORT_EXPORT,
7619 )
7618 )
7620 def unbundle(ui, repo, fname1, *fnames, **opts):
7619 def unbundle(ui, repo, fname1, *fnames, **opts):
7621 """apply one or more bundle files
7620 """apply one or more bundle files
7622
7621
7623 Apply one or more bundle files generated by :hg:`bundle`.
7622 Apply one or more bundle files generated by :hg:`bundle`.
7624
7623
7625 Returns 0 on success, 1 if an update has unresolved files.
7624 Returns 0 on success, 1 if an update has unresolved files.
7626 """
7625 """
7627 fnames = (fname1,) + fnames
7626 fnames = (fname1,) + fnames
7628
7627
7629 with repo.lock():
7628 with repo.lock():
7630 for fname in fnames:
7629 for fname in fnames:
7631 f = hg.openpath(ui, fname)
7630 f = hg.openpath(ui, fname)
7632 gen = exchange.readbundle(ui, f, fname)
7631 gen = exchange.readbundle(ui, f, fname)
7633 if isinstance(gen, streamclone.streamcloneapplier):
7632 if isinstance(gen, streamclone.streamcloneapplier):
7634 raise error.InputError(
7633 raise error.InputError(
7635 _(
7634 _(
7636 b'packed bundles cannot be applied with '
7635 b'packed bundles cannot be applied with '
7637 b'"hg unbundle"'
7636 b'"hg unbundle"'
7638 ),
7637 ),
7639 hint=_(b'use "hg debugapplystreamclonebundle"'),
7638 hint=_(b'use "hg debugapplystreamclonebundle"'),
7640 )
7639 )
7641 url = b'bundle:' + fname
7640 url = b'bundle:' + fname
7642 try:
7641 try:
7643 txnname = b'unbundle'
7642 txnname = b'unbundle'
7644 if not isinstance(gen, bundle2.unbundle20):
7643 if not isinstance(gen, bundle2.unbundle20):
7645 txnname = b'unbundle\n%s' % urlutil.hidepassword(url)
7644 txnname = b'unbundle\n%s' % urlutil.hidepassword(url)
7646 with repo.transaction(txnname) as tr:
7645 with repo.transaction(txnname) as tr:
7647 op = bundle2.applybundle(
7646 op = bundle2.applybundle(
7648 repo, gen, tr, source=b'unbundle', url=url
7647 repo, gen, tr, source=b'unbundle', url=url
7649 )
7648 )
7650 except error.BundleUnknownFeatureError as exc:
7649 except error.BundleUnknownFeatureError as exc:
7651 raise error.Abort(
7650 raise error.Abort(
7652 _(b'%s: unknown bundle feature, %s') % (fname, exc),
7651 _(b'%s: unknown bundle feature, %s') % (fname, exc),
7653 hint=_(
7652 hint=_(
7654 b"see https://mercurial-scm.org/"
7653 b"see https://mercurial-scm.org/"
7655 b"wiki/BundleFeature for more "
7654 b"wiki/BundleFeature for more "
7656 b"information"
7655 b"information"
7657 ),
7656 ),
7658 )
7657 )
7659 modheads = bundle2.combinechangegroupresults(op)
7658 modheads = bundle2.combinechangegroupresults(op)
7660
7659
7661 if postincoming(ui, repo, modheads, opts.get('update'), None, None):
7660 if postincoming(ui, repo, modheads, opts.get('update'), None, None):
7662 return 1
7661 return 1
7663 else:
7662 else:
7664 return 0
7663 return 0
7665
7664
7666
7665
7667 @command(
7666 @command(
7668 b'unshelve',
7667 b'unshelve',
7669 [
7668 [
7670 (b'a', b'abort', None, _(b'abort an incomplete unshelve operation')),
7669 (b'a', b'abort', None, _(b'abort an incomplete unshelve operation')),
7671 (
7670 (
7672 b'c',
7671 b'c',
7673 b'continue',
7672 b'continue',
7674 None,
7673 None,
7675 _(b'continue an incomplete unshelve operation'),
7674 _(b'continue an incomplete unshelve operation'),
7676 ),
7675 ),
7677 (b'i', b'interactive', None, _(b'use interactive mode (EXPERIMENTAL)')),
7676 (b'i', b'interactive', None, _(b'use interactive mode (EXPERIMENTAL)')),
7678 (b'k', b'keep', None, _(b'keep shelve after unshelving')),
7677 (b'k', b'keep', None, _(b'keep shelve after unshelving')),
7679 (
7678 (
7680 b'n',
7679 b'n',
7681 b'name',
7680 b'name',
7682 b'',
7681 b'',
7683 _(b'restore shelved change with given name'),
7682 _(b'restore shelved change with given name'),
7684 _(b'NAME'),
7683 _(b'NAME'),
7685 ),
7684 ),
7686 (b't', b'tool', b'', _(b'specify merge tool')),
7685 (b't', b'tool', b'', _(b'specify merge tool')),
7687 (
7686 (
7688 b'',
7687 b'',
7689 b'date',
7688 b'date',
7690 b'',
7689 b'',
7691 _(b'set date for temporary commits (DEPRECATED)'),
7690 _(b'set date for temporary commits (DEPRECATED)'),
7692 _(b'DATE'),
7691 _(b'DATE'),
7693 ),
7692 ),
7694 ],
7693 ],
7695 _(b'hg unshelve [OPTION]... [[-n] SHELVED]'),
7694 _(b'hg unshelve [OPTION]... [[-n] SHELVED]'),
7696 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7695 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7697 )
7696 )
7698 def unshelve(ui, repo, *shelved, **opts):
7697 def unshelve(ui, repo, *shelved, **opts):
7699 """restore a shelved change to the working directory
7698 """restore a shelved change to the working directory
7700
7699
7701 This command accepts an optional name of a shelved change to
7700 This command accepts an optional name of a shelved change to
7702 restore. If none is given, the most recent shelved change is used.
7701 restore. If none is given, the most recent shelved change is used.
7703
7702
7704 If a shelved change is applied successfully, the bundle that
7703 If a shelved change is applied successfully, the bundle that
7705 contains the shelved changes is moved to a backup location
7704 contains the shelved changes is moved to a backup location
7706 (.hg/shelve-backup).
7705 (.hg/shelve-backup).
7707
7706
7708 Since you can restore a shelved change on top of an arbitrary
7707 Since you can restore a shelved change on top of an arbitrary
7709 commit, it is possible that unshelving will result in a conflict
7708 commit, it is possible that unshelving will result in a conflict
7710 between your changes and the commits you are unshelving onto. If
7709 between your changes and the commits you are unshelving onto. If
7711 this occurs, you must resolve the conflict, then use
7710 this occurs, you must resolve the conflict, then use
7712 ``--continue`` to complete the unshelve operation. (The bundle
7711 ``--continue`` to complete the unshelve operation. (The bundle
7713 will not be moved until you successfully complete the unshelve.)
7712 will not be moved until you successfully complete the unshelve.)
7714
7713
7715 (Alternatively, you can use ``--abort`` to abandon an unshelve
7714 (Alternatively, you can use ``--abort`` to abandon an unshelve
7716 that causes a conflict. This reverts the unshelved changes, and
7715 that causes a conflict. This reverts the unshelved changes, and
7717 leaves the bundle in place.)
7716 leaves the bundle in place.)
7718
7717
7719 If bare shelved change (without interactive, include and exclude
7718 If bare shelved change (without interactive, include and exclude
7720 option) was done on newly created branch it would restore branch
7719 option) was done on newly created branch it would restore branch
7721 information to the working directory.
7720 information to the working directory.
7722
7721
7723 After a successful unshelve, the shelved changes are stored in a
7722 After a successful unshelve, the shelved changes are stored in a
7724 backup directory. Only the N most recent backups are kept. N
7723 backup directory. Only the N most recent backups are kept. N
7725 defaults to 10 but can be overridden using the ``shelve.maxbackups``
7724 defaults to 10 but can be overridden using the ``shelve.maxbackups``
7726 configuration option.
7725 configuration option.
7727
7726
7728 .. container:: verbose
7727 .. container:: verbose
7729
7728
7730 Timestamp in seconds is used to decide order of backups. More
7729 Timestamp in seconds is used to decide order of backups. More
7731 than ``maxbackups`` backups are kept, if same timestamp
7730 than ``maxbackups`` backups are kept, if same timestamp
7732 prevents from deciding exact order of them, for safety.
7731 prevents from deciding exact order of them, for safety.
7733
7732
7734 Selected changes can be unshelved with ``--interactive`` flag.
7733 Selected changes can be unshelved with ``--interactive`` flag.
7735 The working directory is updated with the selected changes, and
7734 The working directory is updated with the selected changes, and
7736 only the unselected changes remain shelved.
7735 only the unselected changes remain shelved.
7737 Note: The whole shelve is applied to working directory first before
7736 Note: The whole shelve is applied to working directory first before
7738 running interactively. So, this will bring up all the conflicts between
7737 running interactively. So, this will bring up all the conflicts between
7739 working directory and the shelve, irrespective of which changes will be
7738 working directory and the shelve, irrespective of which changes will be
7740 unshelved.
7739 unshelved.
7741 """
7740 """
7742 with repo.wlock():
7741 with repo.wlock():
7743 return shelvemod.unshelvecmd(ui, repo, *shelved, **opts)
7742 return shelvemod.unshelvecmd(ui, repo, *shelved, **opts)
7744
7743
7745
7744
7746 statemod.addunfinished(
7745 statemod.addunfinished(
7747 b'unshelve',
7746 b'unshelve',
7748 fname=b'shelvedstate',
7747 fname=b'shelvedstate',
7749 continueflag=True,
7748 continueflag=True,
7750 abortfunc=shelvemod.hgabortunshelve,
7749 abortfunc=shelvemod.hgabortunshelve,
7751 continuefunc=shelvemod.hgcontinueunshelve,
7750 continuefunc=shelvemod.hgcontinueunshelve,
7752 cmdmsg=_(b'unshelve already in progress'),
7751 cmdmsg=_(b'unshelve already in progress'),
7753 )
7752 )
7754
7753
7755
7754
7756 @command(
7755 @command(
7757 b'update|up|checkout|co',
7756 b'update|up|checkout|co',
7758 [
7757 [
7759 (b'C', b'clean', None, _(b'discard uncommitted changes (no backup)')),
7758 (b'C', b'clean', None, _(b'discard uncommitted changes (no backup)')),
7760 (b'c', b'check', None, _(b'require clean working directory')),
7759 (b'c', b'check', None, _(b'require clean working directory')),
7761 (b'm', b'merge', None, _(b'merge uncommitted changes')),
7760 (b'm', b'merge', None, _(b'merge uncommitted changes')),
7762 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
7761 (b'd', b'date', b'', _(b'tipmost revision matching date'), _(b'DATE')),
7763 (b'r', b'rev', b'', _(b'revision'), _(b'REV')),
7762 (b'r', b'rev', b'', _(b'revision'), _(b'REV')),
7764 ]
7763 ]
7765 + mergetoolopts,
7764 + mergetoolopts,
7766 _(b'[-C|-c|-m] [-d DATE] [[-r] REV]'),
7765 _(b'[-C|-c|-m] [-d DATE] [[-r] REV]'),
7767 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7766 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
7768 helpbasic=True,
7767 helpbasic=True,
7769 )
7768 )
7770 def update(ui, repo, node=None, **opts):
7769 def update(ui, repo, node=None, **opts):
7771 """update working directory (or switch revisions)
7770 """update working directory (or switch revisions)
7772
7771
7773 Update the repository's working directory to the specified
7772 Update the repository's working directory to the specified
7774 changeset. If no changeset is specified, update to the tip of the
7773 changeset. If no changeset is specified, update to the tip of the
7775 current named branch and move the active bookmark (see :hg:`help
7774 current named branch and move the active bookmark (see :hg:`help
7776 bookmarks`).
7775 bookmarks`).
7777
7776
7778 Update sets the working directory's parent revision to the specified
7777 Update sets the working directory's parent revision to the specified
7779 changeset (see :hg:`help parents`).
7778 changeset (see :hg:`help parents`).
7780
7779
7781 If the changeset is not a descendant or ancestor of the working
7780 If the changeset is not a descendant or ancestor of the working
7782 directory's parent and there are uncommitted changes, the update is
7781 directory's parent and there are uncommitted changes, the update is
7783 aborted. With the -c/--check option, the working directory is checked
7782 aborted. With the -c/--check option, the working directory is checked
7784 for uncommitted changes; if none are found, the working directory is
7783 for uncommitted changes; if none are found, the working directory is
7785 updated to the specified changeset.
7784 updated to the specified changeset.
7786
7785
7787 .. container:: verbose
7786 .. container:: verbose
7788
7787
7789 The -C/--clean, -c/--check, and -m/--merge options control what
7788 The -C/--clean, -c/--check, and -m/--merge options control what
7790 happens if the working directory contains uncommitted changes.
7789 happens if the working directory contains uncommitted changes.
7791 At most of one of them can be specified.
7790 At most of one of them can be specified.
7792
7791
7793 1. If no option is specified, and if
7792 1. If no option is specified, and if
7794 the requested changeset is an ancestor or descendant of
7793 the requested changeset is an ancestor or descendant of
7795 the working directory's parent, the uncommitted changes
7794 the working directory's parent, the uncommitted changes
7796 are merged into the requested changeset and the merged
7795 are merged into the requested changeset and the merged
7797 result is left uncommitted. If the requested changeset is
7796 result is left uncommitted. If the requested changeset is
7798 not an ancestor or descendant (that is, it is on another
7797 not an ancestor or descendant (that is, it is on another
7799 branch), the update is aborted and the uncommitted changes
7798 branch), the update is aborted and the uncommitted changes
7800 are preserved.
7799 are preserved.
7801
7800
7802 2. With the -m/--merge option, the update is allowed even if the
7801 2. With the -m/--merge option, the update is allowed even if the
7803 requested changeset is not an ancestor or descendant of
7802 requested changeset is not an ancestor or descendant of
7804 the working directory's parent.
7803 the working directory's parent.
7805
7804
7806 3. With the -c/--check option, the update is aborted and the
7805 3. With the -c/--check option, the update is aborted and the
7807 uncommitted changes are preserved.
7806 uncommitted changes are preserved.
7808
7807
7809 4. With the -C/--clean option, uncommitted changes are discarded and
7808 4. With the -C/--clean option, uncommitted changes are discarded and
7810 the working directory is updated to the requested changeset.
7809 the working directory is updated to the requested changeset.
7811
7810
7812 To cancel an uncommitted merge (and lose your changes), use
7811 To cancel an uncommitted merge (and lose your changes), use
7813 :hg:`merge --abort`.
7812 :hg:`merge --abort`.
7814
7813
7815 Use null as the changeset to remove the working directory (like
7814 Use null as the changeset to remove the working directory (like
7816 :hg:`clone -U`).
7815 :hg:`clone -U`).
7817
7816
7818 If you want to revert just one file to an older revision, use
7817 If you want to revert just one file to an older revision, use
7819 :hg:`revert [-r REV] NAME`.
7818 :hg:`revert [-r REV] NAME`.
7820
7819
7821 See :hg:`help dates` for a list of formats valid for -d/--date.
7820 See :hg:`help dates` for a list of formats valid for -d/--date.
7822
7821
7823 Returns 0 on success, 1 if there are unresolved files.
7822 Returns 0 on success, 1 if there are unresolved files.
7824 """
7823 """
7825 cmdutil.check_at_most_one_arg(opts, 'clean', 'check', 'merge')
7824 cmdutil.check_at_most_one_arg(opts, 'clean', 'check', 'merge')
7826 rev = opts.get('rev')
7825 rev = opts.get('rev')
7827 date = opts.get('date')
7826 date = opts.get('date')
7828 clean = opts.get('clean')
7827 clean = opts.get('clean')
7829 check = opts.get('check')
7828 check = opts.get('check')
7830 merge = opts.get('merge')
7829 merge = opts.get('merge')
7831 if rev and node:
7830 if rev and node:
7832 raise error.InputError(_(b"please specify just one revision"))
7831 raise error.InputError(_(b"please specify just one revision"))
7833
7832
7834 if ui.configbool(b'commands', b'update.requiredest'):
7833 if ui.configbool(b'commands', b'update.requiredest'):
7835 if not node and not rev and not date:
7834 if not node and not rev and not date:
7836 raise error.InputError(
7835 raise error.InputError(
7837 _(b'you must specify a destination'),
7836 _(b'you must specify a destination'),
7838 hint=_(b'for example: hg update ".::"'),
7837 hint=_(b'for example: hg update ".::"'),
7839 )
7838 )
7840
7839
7841 if rev is None or rev == b'':
7840 if rev is None or rev == b'':
7842 rev = node
7841 rev = node
7843
7842
7844 if date and rev is not None:
7843 if date and rev is not None:
7845 raise error.InputError(_(b"you can't specify a revision and a date"))
7844 raise error.InputError(_(b"you can't specify a revision and a date"))
7846
7845
7847 updatecheck = None
7846 updatecheck = None
7848 if check or merge is not None and not merge:
7847 if check or merge is not None and not merge:
7849 updatecheck = b'abort'
7848 updatecheck = b'abort'
7850 elif merge or check is not None and not check:
7849 elif merge or check is not None and not check:
7851 updatecheck = b'none'
7850 updatecheck = b'none'
7852
7851
7853 with repo.wlock():
7852 with repo.wlock():
7854 cmdutil.clearunfinished(repo)
7853 cmdutil.clearunfinished(repo)
7855 if date:
7854 if date:
7856 rev = cmdutil.finddate(ui, repo, date)
7855 rev = cmdutil.finddate(ui, repo, date)
7857
7856
7858 # if we defined a bookmark, we have to remember the original name
7857 # if we defined a bookmark, we have to remember the original name
7859 brev = rev
7858 brev = rev
7860 if rev:
7859 if rev:
7861 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
7860 repo = scmutil.unhidehashlikerevs(repo, [rev], b'nowarn')
7862 ctx = logcmdutil.revsingle(repo, rev, default=None)
7861 ctx = logcmdutil.revsingle(repo, rev, default=None)
7863 rev = ctx.rev()
7862 rev = ctx.rev()
7864 hidden = ctx.hidden()
7863 hidden = ctx.hidden()
7865 overrides = {(b'ui', b'forcemerge'): opts.get('tool', b'')}
7864 overrides = {(b'ui', b'forcemerge'): opts.get('tool', b'')}
7866 with ui.configoverride(overrides, b'update'):
7865 with ui.configoverride(overrides, b'update'):
7867 ret = hg.updatetotally(
7866 ret = hg.updatetotally(
7868 ui, repo, rev, brev, clean=clean, updatecheck=updatecheck
7867 ui, repo, rev, brev, clean=clean, updatecheck=updatecheck
7869 )
7868 )
7870 if hidden:
7869 if hidden:
7871 ctxstr = ctx.hex()[:12]
7870 ctxstr = ctx.hex()[:12]
7872 ui.warn(_(b"updated to hidden changeset %s\n") % ctxstr)
7871 ui.warn(_(b"updated to hidden changeset %s\n") % ctxstr)
7873
7872
7874 if ctx.obsolete():
7873 if ctx.obsolete():
7875 obsfatemsg = obsutil._getfilteredreason(repo, ctxstr, ctx)
7874 obsfatemsg = obsutil._getfilteredreason(repo, ctxstr, ctx)
7876 ui.warn(b"(%s)\n" % obsfatemsg)
7875 ui.warn(b"(%s)\n" % obsfatemsg)
7877 return ret
7876 return ret
7878
7877
7879
7878
7880 @command(
7879 @command(
7881 b'verify',
7880 b'verify',
7882 [(b'', b'full', False, b'perform more checks (EXPERIMENTAL)')],
7881 [(b'', b'full', False, b'perform more checks (EXPERIMENTAL)')],
7883 helpcategory=command.CATEGORY_MAINTENANCE,
7882 helpcategory=command.CATEGORY_MAINTENANCE,
7884 )
7883 )
7885 def verify(ui, repo, **opts):
7884 def verify(ui, repo, **opts):
7886 """verify the integrity of the repository
7885 """verify the integrity of the repository
7887
7886
7888 Verify the integrity of the current repository.
7887 Verify the integrity of the current repository.
7889
7888
7890 This will perform an extensive check of the repository's
7889 This will perform an extensive check of the repository's
7891 integrity, validating the hashes and checksums of each entry in
7890 integrity, validating the hashes and checksums of each entry in
7892 the changelog, manifest, and tracked files, as well as the
7891 the changelog, manifest, and tracked files, as well as the
7893 integrity of their crosslinks and indices.
7892 integrity of their crosslinks and indices.
7894
7893
7895 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
7894 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
7896 for more information about recovery from corruption of the
7895 for more information about recovery from corruption of the
7897 repository.
7896 repository.
7898
7897
7899 Returns 0 on success, 1 if errors are encountered.
7898 Returns 0 on success, 1 if errors are encountered.
7900 """
7899 """
7901 opts = pycompat.byteskwargs(opts)
7900 opts = pycompat.byteskwargs(opts)
7902
7901
7903 level = None
7902 level = None
7904 if opts[b'full']:
7903 if opts[b'full']:
7905 level = verifymod.VERIFY_FULL
7904 level = verifymod.VERIFY_FULL
7906 return hg.verify(repo, level)
7905 return hg.verify(repo, level)
7907
7906
7908
7907
7909 @command(
7908 @command(
7910 b'version',
7909 b'version',
7911 [] + formatteropts,
7910 [] + formatteropts,
7912 helpcategory=command.CATEGORY_HELP,
7911 helpcategory=command.CATEGORY_HELP,
7913 norepo=True,
7912 norepo=True,
7914 intents={INTENT_READONLY},
7913 intents={INTENT_READONLY},
7915 )
7914 )
7916 def version_(ui, **opts):
7915 def version_(ui, **opts):
7917 """output version and copyright information
7916 """output version and copyright information
7918
7917
7919 .. container:: verbose
7918 .. container:: verbose
7920
7919
7921 Template:
7920 Template:
7922
7921
7923 The following keywords are supported. See also :hg:`help templates`.
7922 The following keywords are supported. See also :hg:`help templates`.
7924
7923
7925 :extensions: List of extensions.
7924 :extensions: List of extensions.
7926 :ver: String. Version number.
7925 :ver: String. Version number.
7927
7926
7928 And each entry of ``{extensions}`` provides the following sub-keywords
7927 And each entry of ``{extensions}`` provides the following sub-keywords
7929 in addition to ``{ver}``.
7928 in addition to ``{ver}``.
7930
7929
7931 :bundled: Boolean. True if included in the release.
7930 :bundled: Boolean. True if included in the release.
7932 :name: String. Extension name.
7931 :name: String. Extension name.
7933 """
7932 """
7934 opts = pycompat.byteskwargs(opts)
7933 opts = pycompat.byteskwargs(opts)
7935 if ui.verbose:
7934 if ui.verbose:
7936 ui.pager(b'version')
7935 ui.pager(b'version')
7937 fm = ui.formatter(b"version", opts)
7936 fm = ui.formatter(b"version", opts)
7938 fm.startitem()
7937 fm.startitem()
7939 fm.write(
7938 fm.write(
7940 b"ver", _(b"Mercurial Distributed SCM (version %s)\n"), util.version()
7939 b"ver", _(b"Mercurial Distributed SCM (version %s)\n"), util.version()
7941 )
7940 )
7942 license = _(
7941 license = _(
7943 b"(see https://mercurial-scm.org for more information)\n"
7942 b"(see https://mercurial-scm.org for more information)\n"
7944 b"\nCopyright (C) 2005-2022 Olivia Mackall and others\n"
7943 b"\nCopyright (C) 2005-2022 Olivia Mackall and others\n"
7945 b"This is free software; see the source for copying conditions. "
7944 b"This is free software; see the source for copying conditions. "
7946 b"There is NO\nwarranty; "
7945 b"There is NO\nwarranty; "
7947 b"not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
7946 b"not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
7948 )
7947 )
7949 if not ui.quiet:
7948 if not ui.quiet:
7950 fm.plain(license)
7949 fm.plain(license)
7951
7950
7952 if ui.verbose:
7951 if ui.verbose:
7953 fm.plain(_(b"\nEnabled extensions:\n\n"))
7952 fm.plain(_(b"\nEnabled extensions:\n\n"))
7954 # format names and versions into columns
7953 # format names and versions into columns
7955 names = []
7954 names = []
7956 vers = []
7955 vers = []
7957 isinternals = []
7956 isinternals = []
7958 for name, module in sorted(extensions.extensions()):
7957 for name, module in sorted(extensions.extensions()):
7959 names.append(name)
7958 names.append(name)
7960 vers.append(extensions.moduleversion(module) or None)
7959 vers.append(extensions.moduleversion(module) or None)
7961 isinternals.append(extensions.ismoduleinternal(module))
7960 isinternals.append(extensions.ismoduleinternal(module))
7962 fn = fm.nested(b"extensions", tmpl=b'{name}\n')
7961 fn = fm.nested(b"extensions", tmpl=b'{name}\n')
7963 if names:
7962 if names:
7964 namefmt = b" %%-%ds " % max(len(n) for n in names)
7963 namefmt = b" %%-%ds " % max(len(n) for n in names)
7965 places = [_(b"external"), _(b"internal")]
7964 places = [_(b"external"), _(b"internal")]
7966 for n, v, p in zip(names, vers, isinternals):
7965 for n, v, p in zip(names, vers, isinternals):
7967 fn.startitem()
7966 fn.startitem()
7968 fn.condwrite(ui.verbose, b"name", namefmt, n)
7967 fn.condwrite(ui.verbose, b"name", namefmt, n)
7969 if ui.verbose:
7968 if ui.verbose:
7970 fn.plain(b"%s " % places[p])
7969 fn.plain(b"%s " % places[p])
7971 fn.data(bundled=p)
7970 fn.data(bundled=p)
7972 fn.condwrite(ui.verbose and v, b"ver", b"%s", v)
7971 fn.condwrite(ui.verbose and v, b"ver", b"%s", v)
7973 if ui.verbose:
7972 if ui.verbose:
7974 fn.plain(b"\n")
7973 fn.plain(b"\n")
7975 fn.end()
7974 fn.end()
7976 fm.end()
7975 fm.end()
7977
7976
7978
7977
7979 def loadcmdtable(ui, name, cmdtable):
7978 def loadcmdtable(ui, name, cmdtable):
7980 """Load command functions from specified cmdtable"""
7979 """Load command functions from specified cmdtable"""
7981 overrides = [cmd for cmd in cmdtable if cmd in table]
7980 overrides = [cmd for cmd in cmdtable if cmd in table]
7982 if overrides:
7981 if overrides:
7983 ui.warn(
7982 ui.warn(
7984 _(b"extension '%s' overrides commands: %s\n")
7983 _(b"extension '%s' overrides commands: %s\n")
7985 % (name, b" ".join(overrides))
7984 % (name, b" ".join(overrides))
7986 )
7985 )
7987 table.update(cmdtable)
7986 table.update(cmdtable)
General Comments 0
You need to be logged in to leave comments. Login now