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