##// END OF EJS Templates
help: add a mechanism to change flags' help depending on config...
Valentin Gatien-Baron -
r44777:142d2a4c default
parent child Browse files
Show More
@@ -1,4065 +1,4065 b''
1 # cmdutil.py - help for command processing in mercurial
1 # cmdutil.py - help for command processing in mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import copy as copymod
10 import copy as copymod
11 import errno
11 import errno
12 import os
12 import os
13 import re
13 import re
14
14
15 from .i18n import _
15 from .i18n import _
16 from .node import (
16 from .node import (
17 hex,
17 hex,
18 nullid,
18 nullid,
19 nullrev,
19 nullrev,
20 short,
20 short,
21 )
21 )
22 from .pycompat import (
22 from .pycompat import (
23 getattr,
23 getattr,
24 open,
24 open,
25 setattr,
25 setattr,
26 )
26 )
27 from .thirdparty import attr
27 from .thirdparty import attr
28
28
29 from . import (
29 from . import (
30 bookmarks,
30 bookmarks,
31 changelog,
31 changelog,
32 copies,
32 copies,
33 crecord as crecordmod,
33 crecord as crecordmod,
34 dirstateguard,
34 dirstateguard,
35 encoding,
35 encoding,
36 error,
36 error,
37 formatter,
37 formatter,
38 logcmdutil,
38 logcmdutil,
39 match as matchmod,
39 match as matchmod,
40 merge as mergemod,
40 merge as mergemod,
41 mergeutil,
41 mergeutil,
42 obsolete,
42 obsolete,
43 patch,
43 patch,
44 pathutil,
44 pathutil,
45 phases,
45 phases,
46 pycompat,
46 pycompat,
47 repair,
47 repair,
48 revlog,
48 revlog,
49 rewriteutil,
49 rewriteutil,
50 scmutil,
50 scmutil,
51 smartset,
51 smartset,
52 state as statemod,
52 state as statemod,
53 subrepoutil,
53 subrepoutil,
54 templatekw,
54 templatekw,
55 templater,
55 templater,
56 util,
56 util,
57 vfs as vfsmod,
57 vfs as vfsmod,
58 )
58 )
59
59
60 from .utils import (
60 from .utils import (
61 dateutil,
61 dateutil,
62 stringutil,
62 stringutil,
63 )
63 )
64
64
65 if pycompat.TYPE_CHECKING:
65 if pycompat.TYPE_CHECKING:
66 from typing import (
66 from typing import (
67 Any,
67 Any,
68 Dict,
68 Dict,
69 )
69 )
70
70
71 for t in (Any, Dict):
71 for t in (Any, Dict):
72 assert t
72 assert t
73
73
74 stringio = util.stringio
74 stringio = util.stringio
75
75
76 # templates of common command options
76 # templates of common command options
77
77
78 dryrunopts = [
78 dryrunopts = [
79 (b'n', b'dry-run', None, _(b'do not perform actions, just print output')),
79 (b'n', b'dry-run', None, _(b'do not perform actions, just print output')),
80 ]
80 ]
81
81
82 confirmopts = [
82 confirmopts = [
83 (b'', b'confirm', None, _(b'ask before applying actions')),
83 (b'', b'confirm', None, _(b'ask before applying actions')),
84 ]
84 ]
85
85
86 remoteopts = [
86 remoteopts = [
87 (b'e', b'ssh', b'', _(b'specify ssh command to use'), _(b'CMD')),
87 (b'e', b'ssh', b'', _(b'specify ssh command to use'), _(b'CMD')),
88 (
88 (
89 b'',
89 b'',
90 b'remotecmd',
90 b'remotecmd',
91 b'',
91 b'',
92 _(b'specify hg command to run on the remote side'),
92 _(b'specify hg command to run on the remote side'),
93 _(b'CMD'),
93 _(b'CMD'),
94 ),
94 ),
95 (
95 (
96 b'',
96 b'',
97 b'insecure',
97 b'insecure',
98 None,
98 None,
99 _(b'do not verify server certificate (ignoring web.cacerts config)'),
99 _(b'do not verify server certificate (ignoring web.cacerts config)'),
100 ),
100 ),
101 ]
101 ]
102
102
103 walkopts = [
103 walkopts = [
104 (
104 (
105 b'I',
105 b'I',
106 b'include',
106 b'include',
107 [],
107 [],
108 _(b'include names matching the given patterns'),
108 _(b'include names matching the given patterns'),
109 _(b'PATTERN'),
109 _(b'PATTERN'),
110 ),
110 ),
111 (
111 (
112 b'X',
112 b'X',
113 b'exclude',
113 b'exclude',
114 [],
114 [],
115 _(b'exclude names matching the given patterns'),
115 _(b'exclude names matching the given patterns'),
116 _(b'PATTERN'),
116 _(b'PATTERN'),
117 ),
117 ),
118 ]
118 ]
119
119
120 commitopts = [
120 commitopts = [
121 (b'm', b'message', b'', _(b'use text as commit message'), _(b'TEXT')),
121 (b'm', b'message', b'', _(b'use text as commit message'), _(b'TEXT')),
122 (b'l', b'logfile', b'', _(b'read commit message from file'), _(b'FILE')),
122 (b'l', b'logfile', b'', _(b'read commit message from file'), _(b'FILE')),
123 ]
123 ]
124
124
125 commitopts2 = [
125 commitopts2 = [
126 (
126 (
127 b'd',
127 b'd',
128 b'date',
128 b'date',
129 b'',
129 b'',
130 _(b'record the specified date as commit date'),
130 _(b'record the specified date as commit date'),
131 _(b'DATE'),
131 _(b'DATE'),
132 ),
132 ),
133 (
133 (
134 b'u',
134 b'u',
135 b'user',
135 b'user',
136 b'',
136 b'',
137 _(b'record the specified user as committer'),
137 _(b'record the specified user as committer'),
138 _(b'USER'),
138 _(b'USER'),
139 ),
139 ),
140 ]
140 ]
141
141
142 commitopts3 = [
142 commitopts3 = [
143 (b'D', b'currentdate', None, _(b'record the current date as commit date')),
143 (b'D', b'currentdate', None, _(b'record the current date as commit date')),
144 (b'U', b'currentuser', None, _(b'record the current user as committer')),
144 (b'U', b'currentuser', None, _(b'record the current user as committer')),
145 ]
145 ]
146
146
147 formatteropts = [
147 formatteropts = [
148 (b'T', b'template', b'', _(b'display with template'), _(b'TEMPLATE')),
148 (b'T', b'template', b'', _(b'display with template'), _(b'TEMPLATE')),
149 ]
149 ]
150
150
151 templateopts = [
151 templateopts = [
152 (
152 (
153 b'',
153 b'',
154 b'style',
154 b'style',
155 b'',
155 b'',
156 _(b'display using template map file (DEPRECATED)'),
156 _(b'display using template map file (DEPRECATED)'),
157 _(b'STYLE'),
157 _(b'STYLE'),
158 ),
158 ),
159 (b'T', b'template', b'', _(b'display with template'), _(b'TEMPLATE')),
159 (b'T', b'template', b'', _(b'display with template'), _(b'TEMPLATE')),
160 ]
160 ]
161
161
162 logopts = [
162 logopts = [
163 (b'p', b'patch', None, _(b'show patch')),
163 (b'p', b'patch', None, _(b'show patch')),
164 (b'g', b'git', None, _(b'use git extended diff format')),
164 (b'g', b'git', None, _(b'use git extended diff format')),
165 (b'l', b'limit', b'', _(b'limit number of changes displayed'), _(b'NUM')),
165 (b'l', b'limit', b'', _(b'limit number of changes displayed'), _(b'NUM')),
166 (b'M', b'no-merges', None, _(b'do not show merges')),
166 (b'M', b'no-merges', None, _(b'do not show merges')),
167 (b'', b'stat', None, _(b'output diffstat-style summary of changes')),
167 (b'', b'stat', None, _(b'output diffstat-style summary of changes')),
168 (b'G', b'graph', None, _(b"show the revision DAG")),
168 (b'G', b'graph', None, _(b"show the revision DAG")),
169 ] + templateopts
169 ] + templateopts
170
170
171 diffopts = [
171 diffopts = [
172 (b'a', b'text', None, _(b'treat all files as text')),
172 (b'a', b'text', None, _(b'treat all files as text')),
173 (b'g', b'git', None, _(b'use git extended diff format')),
173 (b'g', b'git', None, _(b'use git extended diff format (DEFAULT: diff.git)')),
174 (b'', b'binary', None, _(b'generate binary diffs in git mode (default)')),
174 (b'', b'binary', None, _(b'generate binary diffs in git mode (default)')),
175 (b'', b'nodates', None, _(b'omit dates from diff headers')),
175 (b'', b'nodates', None, _(b'omit dates from diff headers')),
176 ]
176 ]
177
177
178 diffwsopts = [
178 diffwsopts = [
179 (
179 (
180 b'w',
180 b'w',
181 b'ignore-all-space',
181 b'ignore-all-space',
182 None,
182 None,
183 _(b'ignore white space when comparing lines'),
183 _(b'ignore white space when comparing lines'),
184 ),
184 ),
185 (
185 (
186 b'b',
186 b'b',
187 b'ignore-space-change',
187 b'ignore-space-change',
188 None,
188 None,
189 _(b'ignore changes in the amount of white space'),
189 _(b'ignore changes in the amount of white space'),
190 ),
190 ),
191 (
191 (
192 b'B',
192 b'B',
193 b'ignore-blank-lines',
193 b'ignore-blank-lines',
194 None,
194 None,
195 _(b'ignore changes whose lines are all blank'),
195 _(b'ignore changes whose lines are all blank'),
196 ),
196 ),
197 (
197 (
198 b'Z',
198 b'Z',
199 b'ignore-space-at-eol',
199 b'ignore-space-at-eol',
200 None,
200 None,
201 _(b'ignore changes in whitespace at EOL'),
201 _(b'ignore changes in whitespace at EOL'),
202 ),
202 ),
203 ]
203 ]
204
204
205 diffopts2 = (
205 diffopts2 = (
206 [
206 [
207 (b'', b'noprefix', None, _(b'omit a/ and b/ prefixes from filenames')),
207 (b'', b'noprefix', None, _(b'omit a/ and b/ prefixes from filenames')),
208 (
208 (
209 b'p',
209 b'p',
210 b'show-function',
210 b'show-function',
211 None,
211 None,
212 _(b'show which function each change is in'),
212 _(b'show which function each change is in'),
213 ),
213 ),
214 (b'', b'reverse', None, _(b'produce a diff that undoes the changes')),
214 (b'', b'reverse', None, _(b'produce a diff that undoes the changes')),
215 ]
215 ]
216 + diffwsopts
216 + diffwsopts
217 + [
217 + [
218 (
218 (
219 b'U',
219 b'U',
220 b'unified',
220 b'unified',
221 b'',
221 b'',
222 _(b'number of lines of context to show'),
222 _(b'number of lines of context to show'),
223 _(b'NUM'),
223 _(b'NUM'),
224 ),
224 ),
225 (b'', b'stat', None, _(b'output diffstat-style summary of changes')),
225 (b'', b'stat', None, _(b'output diffstat-style summary of changes')),
226 (
226 (
227 b'',
227 b'',
228 b'root',
228 b'root',
229 b'',
229 b'',
230 _(b'produce diffs relative to subdirectory'),
230 _(b'produce diffs relative to subdirectory'),
231 _(b'DIR'),
231 _(b'DIR'),
232 ),
232 ),
233 ]
233 ]
234 )
234 )
235
235
236 mergetoolopts = [
236 mergetoolopts = [
237 (b't', b'tool', b'', _(b'specify merge tool'), _(b'TOOL')),
237 (b't', b'tool', b'', _(b'specify merge tool'), _(b'TOOL')),
238 ]
238 ]
239
239
240 similarityopts = [
240 similarityopts = [
241 (
241 (
242 b's',
242 b's',
243 b'similarity',
243 b'similarity',
244 b'',
244 b'',
245 _(b'guess renamed files by similarity (0<=s<=100)'),
245 _(b'guess renamed files by similarity (0<=s<=100)'),
246 _(b'SIMILARITY'),
246 _(b'SIMILARITY'),
247 )
247 )
248 ]
248 ]
249
249
250 subrepoopts = [(b'S', b'subrepos', None, _(b'recurse into subrepositories'))]
250 subrepoopts = [(b'S', b'subrepos', None, _(b'recurse into subrepositories'))]
251
251
252 debugrevlogopts = [
252 debugrevlogopts = [
253 (b'c', b'changelog', False, _(b'open changelog')),
253 (b'c', b'changelog', False, _(b'open changelog')),
254 (b'm', b'manifest', False, _(b'open manifest')),
254 (b'm', b'manifest', False, _(b'open manifest')),
255 (b'', b'dir', b'', _(b'open directory manifest')),
255 (b'', b'dir', b'', _(b'open directory manifest')),
256 ]
256 ]
257
257
258 # special string such that everything below this line will be ingored in the
258 # special string such that everything below this line will be ingored in the
259 # editor text
259 # editor text
260 _linebelow = b"^HG: ------------------------ >8 ------------------------$"
260 _linebelow = b"^HG: ------------------------ >8 ------------------------$"
261
261
262
262
263 def check_at_most_one_arg(opts, *args):
263 def check_at_most_one_arg(opts, *args):
264 """abort if more than one of the arguments are in opts
264 """abort if more than one of the arguments are in opts
265
265
266 Returns the unique argument or None if none of them were specified.
266 Returns the unique argument or None if none of them were specified.
267 """
267 """
268
268
269 def to_display(name):
269 def to_display(name):
270 return pycompat.sysbytes(name).replace(b'_', b'-')
270 return pycompat.sysbytes(name).replace(b'_', b'-')
271
271
272 previous = None
272 previous = None
273 for x in args:
273 for x in args:
274 if opts.get(x):
274 if opts.get(x):
275 if previous:
275 if previous:
276 raise error.Abort(
276 raise error.Abort(
277 _(b'cannot specify both --%s and --%s')
277 _(b'cannot specify both --%s and --%s')
278 % (to_display(previous), to_display(x))
278 % (to_display(previous), to_display(x))
279 )
279 )
280 previous = x
280 previous = x
281 return previous
281 return previous
282
282
283
283
284 def check_incompatible_arguments(opts, first, others):
284 def check_incompatible_arguments(opts, first, others):
285 """abort if the first argument is given along with any of the others
285 """abort if the first argument is given along with any of the others
286
286
287 Unlike check_at_most_one_arg(), `others` are not mutually exclusive
287 Unlike check_at_most_one_arg(), `others` are not mutually exclusive
288 among themselves, and they're passed as a single collection.
288 among themselves, and they're passed as a single collection.
289 """
289 """
290 for other in others:
290 for other in others:
291 check_at_most_one_arg(opts, first, other)
291 check_at_most_one_arg(opts, first, other)
292
292
293
293
294 def resolvecommitoptions(ui, opts):
294 def resolvecommitoptions(ui, opts):
295 """modify commit options dict to handle related options
295 """modify commit options dict to handle related options
296
296
297 The return value indicates that ``rewrite.update-timestamp`` is the reason
297 The return value indicates that ``rewrite.update-timestamp`` is the reason
298 the ``date`` option is set.
298 the ``date`` option is set.
299 """
299 """
300 check_at_most_one_arg(opts, b'date', b'currentdate')
300 check_at_most_one_arg(opts, b'date', b'currentdate')
301 check_at_most_one_arg(opts, b'user', b'currentuser')
301 check_at_most_one_arg(opts, b'user', b'currentuser')
302
302
303 datemaydiffer = False # date-only change should be ignored?
303 datemaydiffer = False # date-only change should be ignored?
304
304
305 if opts.get(b'currentdate'):
305 if opts.get(b'currentdate'):
306 opts[b'date'] = b'%d %d' % dateutil.makedate()
306 opts[b'date'] = b'%d %d' % dateutil.makedate()
307 elif (
307 elif (
308 not opts.get(b'date')
308 not opts.get(b'date')
309 and ui.configbool(b'rewrite', b'update-timestamp')
309 and ui.configbool(b'rewrite', b'update-timestamp')
310 and opts.get(b'currentdate') is None
310 and opts.get(b'currentdate') is None
311 ):
311 ):
312 opts[b'date'] = b'%d %d' % dateutil.makedate()
312 opts[b'date'] = b'%d %d' % dateutil.makedate()
313 datemaydiffer = True
313 datemaydiffer = True
314
314
315 if opts.get(b'currentuser'):
315 if opts.get(b'currentuser'):
316 opts[b'user'] = ui.username()
316 opts[b'user'] = ui.username()
317
317
318 return datemaydiffer
318 return datemaydiffer
319
319
320
320
321 def checknotesize(ui, opts):
321 def checknotesize(ui, opts):
322 """ make sure note is of valid format """
322 """ make sure note is of valid format """
323
323
324 note = opts.get(b'note')
324 note = opts.get(b'note')
325 if not note:
325 if not note:
326 return
326 return
327
327
328 if len(note) > 255:
328 if len(note) > 255:
329 raise error.Abort(_(b"cannot store a note of more than 255 bytes"))
329 raise error.Abort(_(b"cannot store a note of more than 255 bytes"))
330 if b'\n' in note:
330 if b'\n' in note:
331 raise error.Abort(_(b"note cannot contain a newline"))
331 raise error.Abort(_(b"note cannot contain a newline"))
332
332
333
333
334 def ishunk(x):
334 def ishunk(x):
335 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
335 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
336 return isinstance(x, hunkclasses)
336 return isinstance(x, hunkclasses)
337
337
338
338
339 def newandmodified(chunks, originalchunks):
339 def newandmodified(chunks, originalchunks):
340 newlyaddedandmodifiedfiles = set()
340 newlyaddedandmodifiedfiles = set()
341 alsorestore = set()
341 alsorestore = set()
342 for chunk in chunks:
342 for chunk in chunks:
343 if (
343 if (
344 ishunk(chunk)
344 ishunk(chunk)
345 and chunk.header.isnewfile()
345 and chunk.header.isnewfile()
346 and chunk not in originalchunks
346 and chunk not in originalchunks
347 ):
347 ):
348 newlyaddedandmodifiedfiles.add(chunk.header.filename())
348 newlyaddedandmodifiedfiles.add(chunk.header.filename())
349 alsorestore.update(
349 alsorestore.update(
350 set(chunk.header.files()) - {chunk.header.filename()}
350 set(chunk.header.files()) - {chunk.header.filename()}
351 )
351 )
352 return newlyaddedandmodifiedfiles, alsorestore
352 return newlyaddedandmodifiedfiles, alsorestore
353
353
354
354
355 def parsealiases(cmd):
355 def parsealiases(cmd):
356 return cmd.split(b"|")
356 return cmd.split(b"|")
357
357
358
358
359 def setupwrapcolorwrite(ui):
359 def setupwrapcolorwrite(ui):
360 # wrap ui.write so diff output can be labeled/colorized
360 # wrap ui.write so diff output can be labeled/colorized
361 def wrapwrite(orig, *args, **kw):
361 def wrapwrite(orig, *args, **kw):
362 label = kw.pop('label', b'')
362 label = kw.pop('label', b'')
363 for chunk, l in patch.difflabel(lambda: args):
363 for chunk, l in patch.difflabel(lambda: args):
364 orig(chunk, label=label + l)
364 orig(chunk, label=label + l)
365
365
366 oldwrite = ui.write
366 oldwrite = ui.write
367
367
368 def wrap(*args, **kwargs):
368 def wrap(*args, **kwargs):
369 return wrapwrite(oldwrite, *args, **kwargs)
369 return wrapwrite(oldwrite, *args, **kwargs)
370
370
371 setattr(ui, 'write', wrap)
371 setattr(ui, 'write', wrap)
372 return oldwrite
372 return oldwrite
373
373
374
374
375 def filterchunks(ui, originalhunks, usecurses, testfile, match, operation=None):
375 def filterchunks(ui, originalhunks, usecurses, testfile, match, operation=None):
376 try:
376 try:
377 if usecurses:
377 if usecurses:
378 if testfile:
378 if testfile:
379 recordfn = crecordmod.testdecorator(
379 recordfn = crecordmod.testdecorator(
380 testfile, crecordmod.testchunkselector
380 testfile, crecordmod.testchunkselector
381 )
381 )
382 else:
382 else:
383 recordfn = crecordmod.chunkselector
383 recordfn = crecordmod.chunkselector
384
384
385 return crecordmod.filterpatch(
385 return crecordmod.filterpatch(
386 ui, originalhunks, recordfn, operation
386 ui, originalhunks, recordfn, operation
387 )
387 )
388 except crecordmod.fallbackerror as e:
388 except crecordmod.fallbackerror as e:
389 ui.warn(b'%s\n' % e)
389 ui.warn(b'%s\n' % e)
390 ui.warn(_(b'falling back to text mode\n'))
390 ui.warn(_(b'falling back to text mode\n'))
391
391
392 return patch.filterpatch(ui, originalhunks, match, operation)
392 return patch.filterpatch(ui, originalhunks, match, operation)
393
393
394
394
395 def recordfilter(ui, originalhunks, match, operation=None):
395 def recordfilter(ui, originalhunks, match, operation=None):
396 """ Prompts the user to filter the originalhunks and return a list of
396 """ Prompts the user to filter the originalhunks and return a list of
397 selected hunks.
397 selected hunks.
398 *operation* is used for to build ui messages to indicate the user what
398 *operation* is used for to build ui messages to indicate the user what
399 kind of filtering they are doing: reverting, committing, shelving, etc.
399 kind of filtering they are doing: reverting, committing, shelving, etc.
400 (see patch.filterpatch).
400 (see patch.filterpatch).
401 """
401 """
402 usecurses = crecordmod.checkcurses(ui)
402 usecurses = crecordmod.checkcurses(ui)
403 testfile = ui.config(b'experimental', b'crecordtest')
403 testfile = ui.config(b'experimental', b'crecordtest')
404 oldwrite = setupwrapcolorwrite(ui)
404 oldwrite = setupwrapcolorwrite(ui)
405 try:
405 try:
406 newchunks, newopts = filterchunks(
406 newchunks, newopts = filterchunks(
407 ui, originalhunks, usecurses, testfile, match, operation
407 ui, originalhunks, usecurses, testfile, match, operation
408 )
408 )
409 finally:
409 finally:
410 ui.write = oldwrite
410 ui.write = oldwrite
411 return newchunks, newopts
411 return newchunks, newopts
412
412
413
413
414 def dorecord(
414 def dorecord(
415 ui, repo, commitfunc, cmdsuggest, backupall, filterfn, *pats, **opts
415 ui, repo, commitfunc, cmdsuggest, backupall, filterfn, *pats, **opts
416 ):
416 ):
417 opts = pycompat.byteskwargs(opts)
417 opts = pycompat.byteskwargs(opts)
418 if not ui.interactive():
418 if not ui.interactive():
419 if cmdsuggest:
419 if cmdsuggest:
420 msg = _(b'running non-interactively, use %s instead') % cmdsuggest
420 msg = _(b'running non-interactively, use %s instead') % cmdsuggest
421 else:
421 else:
422 msg = _(b'running non-interactively')
422 msg = _(b'running non-interactively')
423 raise error.Abort(msg)
423 raise error.Abort(msg)
424
424
425 # make sure username is set before going interactive
425 # make sure username is set before going interactive
426 if not opts.get(b'user'):
426 if not opts.get(b'user'):
427 ui.username() # raise exception, username not provided
427 ui.username() # raise exception, username not provided
428
428
429 def recordfunc(ui, repo, message, match, opts):
429 def recordfunc(ui, repo, message, match, opts):
430 """This is generic record driver.
430 """This is generic record driver.
431
431
432 Its job is to interactively filter local changes, and
432 Its job is to interactively filter local changes, and
433 accordingly prepare working directory into a state in which the
433 accordingly prepare working directory into a state in which the
434 job can be delegated to a non-interactive commit command such as
434 job can be delegated to a non-interactive commit command such as
435 'commit' or 'qrefresh'.
435 'commit' or 'qrefresh'.
436
436
437 After the actual job is done by non-interactive command, the
437 After the actual job is done by non-interactive command, the
438 working directory is restored to its original state.
438 working directory is restored to its original state.
439
439
440 In the end we'll record interesting changes, and everything else
440 In the end we'll record interesting changes, and everything else
441 will be left in place, so the user can continue working.
441 will be left in place, so the user can continue working.
442 """
442 """
443 if not opts.get(b'interactive-unshelve'):
443 if not opts.get(b'interactive-unshelve'):
444 checkunfinished(repo, commit=True)
444 checkunfinished(repo, commit=True)
445 wctx = repo[None]
445 wctx = repo[None]
446 merge = len(wctx.parents()) > 1
446 merge = len(wctx.parents()) > 1
447 if merge:
447 if merge:
448 raise error.Abort(
448 raise error.Abort(
449 _(
449 _(
450 b'cannot partially commit a merge '
450 b'cannot partially commit a merge '
451 b'(use "hg commit" instead)'
451 b'(use "hg commit" instead)'
452 )
452 )
453 )
453 )
454
454
455 def fail(f, msg):
455 def fail(f, msg):
456 raise error.Abort(b'%s: %s' % (f, msg))
456 raise error.Abort(b'%s: %s' % (f, msg))
457
457
458 force = opts.get(b'force')
458 force = opts.get(b'force')
459 if not force:
459 if not force:
460 match = matchmod.badmatch(match, fail)
460 match = matchmod.badmatch(match, fail)
461
461
462 status = repo.status(match=match)
462 status = repo.status(match=match)
463
463
464 overrides = {(b'ui', b'commitsubrepos'): True}
464 overrides = {(b'ui', b'commitsubrepos'): True}
465
465
466 with repo.ui.configoverride(overrides, b'record'):
466 with repo.ui.configoverride(overrides, b'record'):
467 # subrepoutil.precommit() modifies the status
467 # subrepoutil.precommit() modifies the status
468 tmpstatus = scmutil.status(
468 tmpstatus = scmutil.status(
469 copymod.copy(status.modified),
469 copymod.copy(status.modified),
470 copymod.copy(status.added),
470 copymod.copy(status.added),
471 copymod.copy(status.removed),
471 copymod.copy(status.removed),
472 copymod.copy(status.deleted),
472 copymod.copy(status.deleted),
473 copymod.copy(status.unknown),
473 copymod.copy(status.unknown),
474 copymod.copy(status.ignored),
474 copymod.copy(status.ignored),
475 copymod.copy(status.clean), # pytype: disable=wrong-arg-count
475 copymod.copy(status.clean), # pytype: disable=wrong-arg-count
476 )
476 )
477
477
478 # Force allows -X subrepo to skip the subrepo.
478 # Force allows -X subrepo to skip the subrepo.
479 subs, commitsubs, newstate = subrepoutil.precommit(
479 subs, commitsubs, newstate = subrepoutil.precommit(
480 repo.ui, wctx, tmpstatus, match, force=True
480 repo.ui, wctx, tmpstatus, match, force=True
481 )
481 )
482 for s in subs:
482 for s in subs:
483 if s in commitsubs:
483 if s in commitsubs:
484 dirtyreason = wctx.sub(s).dirtyreason(True)
484 dirtyreason = wctx.sub(s).dirtyreason(True)
485 raise error.Abort(dirtyreason)
485 raise error.Abort(dirtyreason)
486
486
487 if not force:
487 if not force:
488 repo.checkcommitpatterns(wctx, match, status, fail)
488 repo.checkcommitpatterns(wctx, match, status, fail)
489 diffopts = patch.difffeatureopts(
489 diffopts = patch.difffeatureopts(
490 ui,
490 ui,
491 opts=opts,
491 opts=opts,
492 whitespace=True,
492 whitespace=True,
493 section=b'commands',
493 section=b'commands',
494 configprefix=b'commit.interactive.',
494 configprefix=b'commit.interactive.',
495 )
495 )
496 diffopts.nodates = True
496 diffopts.nodates = True
497 diffopts.git = True
497 diffopts.git = True
498 diffopts.showfunc = True
498 diffopts.showfunc = True
499 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
499 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
500 originalchunks = patch.parsepatch(originaldiff)
500 originalchunks = patch.parsepatch(originaldiff)
501 match = scmutil.match(repo[None], pats)
501 match = scmutil.match(repo[None], pats)
502
502
503 # 1. filter patch, since we are intending to apply subset of it
503 # 1. filter patch, since we are intending to apply subset of it
504 try:
504 try:
505 chunks, newopts = filterfn(ui, originalchunks, match)
505 chunks, newopts = filterfn(ui, originalchunks, match)
506 except error.PatchError as err:
506 except error.PatchError as err:
507 raise error.Abort(_(b'error parsing patch: %s') % err)
507 raise error.Abort(_(b'error parsing patch: %s') % err)
508 opts.update(newopts)
508 opts.update(newopts)
509
509
510 # We need to keep a backup of files that have been newly added and
510 # We need to keep a backup of files that have been newly added and
511 # modified during the recording process because there is a previous
511 # modified during the recording process because there is a previous
512 # version without the edit in the workdir. We also will need to restore
512 # version without the edit in the workdir. We also will need to restore
513 # files that were the sources of renames so that the patch application
513 # files that were the sources of renames so that the patch application
514 # works.
514 # works.
515 newlyaddedandmodifiedfiles, alsorestore = newandmodified(
515 newlyaddedandmodifiedfiles, alsorestore = newandmodified(
516 chunks, originalchunks
516 chunks, originalchunks
517 )
517 )
518 contenders = set()
518 contenders = set()
519 for h in chunks:
519 for h in chunks:
520 try:
520 try:
521 contenders.update(set(h.files()))
521 contenders.update(set(h.files()))
522 except AttributeError:
522 except AttributeError:
523 pass
523 pass
524
524
525 changed = status.modified + status.added + status.removed
525 changed = status.modified + status.added + status.removed
526 newfiles = [f for f in changed if f in contenders]
526 newfiles = [f for f in changed if f in contenders]
527 if not newfiles:
527 if not newfiles:
528 ui.status(_(b'no changes to record\n'))
528 ui.status(_(b'no changes to record\n'))
529 return 0
529 return 0
530
530
531 modified = set(status.modified)
531 modified = set(status.modified)
532
532
533 # 2. backup changed files, so we can restore them in the end
533 # 2. backup changed files, so we can restore them in the end
534
534
535 if backupall:
535 if backupall:
536 tobackup = changed
536 tobackup = changed
537 else:
537 else:
538 tobackup = [
538 tobackup = [
539 f
539 f
540 for f in newfiles
540 for f in newfiles
541 if f in modified or f in newlyaddedandmodifiedfiles
541 if f in modified or f in newlyaddedandmodifiedfiles
542 ]
542 ]
543 backups = {}
543 backups = {}
544 if tobackup:
544 if tobackup:
545 backupdir = repo.vfs.join(b'record-backups')
545 backupdir = repo.vfs.join(b'record-backups')
546 try:
546 try:
547 os.mkdir(backupdir)
547 os.mkdir(backupdir)
548 except OSError as err:
548 except OSError as err:
549 if err.errno != errno.EEXIST:
549 if err.errno != errno.EEXIST:
550 raise
550 raise
551 try:
551 try:
552 # backup continues
552 # backup continues
553 for f in tobackup:
553 for f in tobackup:
554 fd, tmpname = pycompat.mkstemp(
554 fd, tmpname = pycompat.mkstemp(
555 prefix=f.replace(b'/', b'_') + b'.', dir=backupdir
555 prefix=f.replace(b'/', b'_') + b'.', dir=backupdir
556 )
556 )
557 os.close(fd)
557 os.close(fd)
558 ui.debug(b'backup %r as %r\n' % (f, tmpname))
558 ui.debug(b'backup %r as %r\n' % (f, tmpname))
559 util.copyfile(repo.wjoin(f), tmpname, copystat=True)
559 util.copyfile(repo.wjoin(f), tmpname, copystat=True)
560 backups[f] = tmpname
560 backups[f] = tmpname
561
561
562 fp = stringio()
562 fp = stringio()
563 for c in chunks:
563 for c in chunks:
564 fname = c.filename()
564 fname = c.filename()
565 if fname in backups:
565 if fname in backups:
566 c.write(fp)
566 c.write(fp)
567 dopatch = fp.tell()
567 dopatch = fp.tell()
568 fp.seek(0)
568 fp.seek(0)
569
569
570 # 2.5 optionally review / modify patch in text editor
570 # 2.5 optionally review / modify patch in text editor
571 if opts.get(b'review', False):
571 if opts.get(b'review', False):
572 patchtext = (
572 patchtext = (
573 crecordmod.diffhelptext
573 crecordmod.diffhelptext
574 + crecordmod.patchhelptext
574 + crecordmod.patchhelptext
575 + fp.read()
575 + fp.read()
576 )
576 )
577 reviewedpatch = ui.edit(
577 reviewedpatch = ui.edit(
578 patchtext, b"", action=b"diff", repopath=repo.path
578 patchtext, b"", action=b"diff", repopath=repo.path
579 )
579 )
580 fp.truncate(0)
580 fp.truncate(0)
581 fp.write(reviewedpatch)
581 fp.write(reviewedpatch)
582 fp.seek(0)
582 fp.seek(0)
583
583
584 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
584 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
585 # 3a. apply filtered patch to clean repo (clean)
585 # 3a. apply filtered patch to clean repo (clean)
586 if backups:
586 if backups:
587 m = scmutil.matchfiles(repo, set(backups.keys()) | alsorestore)
587 m = scmutil.matchfiles(repo, set(backups.keys()) | alsorestore)
588 mergemod.revert_to(repo[b'.'], matcher=m)
588 mergemod.revert_to(repo[b'.'], matcher=m)
589
589
590 # 3b. (apply)
590 # 3b. (apply)
591 if dopatch:
591 if dopatch:
592 try:
592 try:
593 ui.debug(b'applying patch\n')
593 ui.debug(b'applying patch\n')
594 ui.debug(fp.getvalue())
594 ui.debug(fp.getvalue())
595 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
595 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
596 except error.PatchError as err:
596 except error.PatchError as err:
597 raise error.Abort(pycompat.bytestr(err))
597 raise error.Abort(pycompat.bytestr(err))
598 del fp
598 del fp
599
599
600 # 4. We prepared working directory according to filtered
600 # 4. We prepared working directory according to filtered
601 # patch. Now is the time to delegate the job to
601 # patch. Now is the time to delegate the job to
602 # commit/qrefresh or the like!
602 # commit/qrefresh or the like!
603
603
604 # Make all of the pathnames absolute.
604 # Make all of the pathnames absolute.
605 newfiles = [repo.wjoin(nf) for nf in newfiles]
605 newfiles = [repo.wjoin(nf) for nf in newfiles]
606 return commitfunc(ui, repo, *newfiles, **pycompat.strkwargs(opts))
606 return commitfunc(ui, repo, *newfiles, **pycompat.strkwargs(opts))
607 finally:
607 finally:
608 # 5. finally restore backed-up files
608 # 5. finally restore backed-up files
609 try:
609 try:
610 dirstate = repo.dirstate
610 dirstate = repo.dirstate
611 for realname, tmpname in pycompat.iteritems(backups):
611 for realname, tmpname in pycompat.iteritems(backups):
612 ui.debug(b'restoring %r to %r\n' % (tmpname, realname))
612 ui.debug(b'restoring %r to %r\n' % (tmpname, realname))
613
613
614 if dirstate[realname] == b'n':
614 if dirstate[realname] == b'n':
615 # without normallookup, restoring timestamp
615 # without normallookup, restoring timestamp
616 # may cause partially committed files
616 # may cause partially committed files
617 # to be treated as unmodified
617 # to be treated as unmodified
618 dirstate.normallookup(realname)
618 dirstate.normallookup(realname)
619
619
620 # copystat=True here and above are a hack to trick any
620 # copystat=True here and above are a hack to trick any
621 # editors that have f open that we haven't modified them.
621 # editors that have f open that we haven't modified them.
622 #
622 #
623 # Also note that this racy as an editor could notice the
623 # Also note that this racy as an editor could notice the
624 # file's mtime before we've finished writing it.
624 # file's mtime before we've finished writing it.
625 util.copyfile(tmpname, repo.wjoin(realname), copystat=True)
625 util.copyfile(tmpname, repo.wjoin(realname), copystat=True)
626 os.unlink(tmpname)
626 os.unlink(tmpname)
627 if tobackup:
627 if tobackup:
628 os.rmdir(backupdir)
628 os.rmdir(backupdir)
629 except OSError:
629 except OSError:
630 pass
630 pass
631
631
632 def recordinwlock(ui, repo, message, match, opts):
632 def recordinwlock(ui, repo, message, match, opts):
633 with repo.wlock():
633 with repo.wlock():
634 return recordfunc(ui, repo, message, match, opts)
634 return recordfunc(ui, repo, message, match, opts)
635
635
636 return commit(ui, repo, recordinwlock, pats, opts)
636 return commit(ui, repo, recordinwlock, pats, opts)
637
637
638
638
639 class dirnode(object):
639 class dirnode(object):
640 """
640 """
641 Represent a directory in user working copy with information required for
641 Represent a directory in user working copy with information required for
642 the purpose of tersing its status.
642 the purpose of tersing its status.
643
643
644 path is the path to the directory, without a trailing '/'
644 path is the path to the directory, without a trailing '/'
645
645
646 statuses is a set of statuses of all files in this directory (this includes
646 statuses is a set of statuses of all files in this directory (this includes
647 all the files in all the subdirectories too)
647 all the files in all the subdirectories too)
648
648
649 files is a list of files which are direct child of this directory
649 files is a list of files which are direct child of this directory
650
650
651 subdirs is a dictionary of sub-directory name as the key and it's own
651 subdirs is a dictionary of sub-directory name as the key and it's own
652 dirnode object as the value
652 dirnode object as the value
653 """
653 """
654
654
655 def __init__(self, dirpath):
655 def __init__(self, dirpath):
656 self.path = dirpath
656 self.path = dirpath
657 self.statuses = set()
657 self.statuses = set()
658 self.files = []
658 self.files = []
659 self.subdirs = {}
659 self.subdirs = {}
660
660
661 def _addfileindir(self, filename, status):
661 def _addfileindir(self, filename, status):
662 """Add a file in this directory as a direct child."""
662 """Add a file in this directory as a direct child."""
663 self.files.append((filename, status))
663 self.files.append((filename, status))
664
664
665 def addfile(self, filename, status):
665 def addfile(self, filename, status):
666 """
666 """
667 Add a file to this directory or to its direct parent directory.
667 Add a file to this directory or to its direct parent directory.
668
668
669 If the file is not direct child of this directory, we traverse to the
669 If the file is not direct child of this directory, we traverse to the
670 directory of which this file is a direct child of and add the file
670 directory of which this file is a direct child of and add the file
671 there.
671 there.
672 """
672 """
673
673
674 # the filename contains a path separator, it means it's not the direct
674 # the filename contains a path separator, it means it's not the direct
675 # child of this directory
675 # child of this directory
676 if b'/' in filename:
676 if b'/' in filename:
677 subdir, filep = filename.split(b'/', 1)
677 subdir, filep = filename.split(b'/', 1)
678
678
679 # does the dirnode object for subdir exists
679 # does the dirnode object for subdir exists
680 if subdir not in self.subdirs:
680 if subdir not in self.subdirs:
681 subdirpath = pathutil.join(self.path, subdir)
681 subdirpath = pathutil.join(self.path, subdir)
682 self.subdirs[subdir] = dirnode(subdirpath)
682 self.subdirs[subdir] = dirnode(subdirpath)
683
683
684 # try adding the file in subdir
684 # try adding the file in subdir
685 self.subdirs[subdir].addfile(filep, status)
685 self.subdirs[subdir].addfile(filep, status)
686
686
687 else:
687 else:
688 self._addfileindir(filename, status)
688 self._addfileindir(filename, status)
689
689
690 if status not in self.statuses:
690 if status not in self.statuses:
691 self.statuses.add(status)
691 self.statuses.add(status)
692
692
693 def iterfilepaths(self):
693 def iterfilepaths(self):
694 """Yield (status, path) for files directly under this directory."""
694 """Yield (status, path) for files directly under this directory."""
695 for f, st in self.files:
695 for f, st in self.files:
696 yield st, pathutil.join(self.path, f)
696 yield st, pathutil.join(self.path, f)
697
697
698 def tersewalk(self, terseargs):
698 def tersewalk(self, terseargs):
699 """
699 """
700 Yield (status, path) obtained by processing the status of this
700 Yield (status, path) obtained by processing the status of this
701 dirnode.
701 dirnode.
702
702
703 terseargs is the string of arguments passed by the user with `--terse`
703 terseargs is the string of arguments passed by the user with `--terse`
704 flag.
704 flag.
705
705
706 Following are the cases which can happen:
706 Following are the cases which can happen:
707
707
708 1) All the files in the directory (including all the files in its
708 1) All the files in the directory (including all the files in its
709 subdirectories) share the same status and the user has asked us to terse
709 subdirectories) share the same status and the user has asked us to terse
710 that status. -> yield (status, dirpath). dirpath will end in '/'.
710 that status. -> yield (status, dirpath). dirpath will end in '/'.
711
711
712 2) Otherwise, we do following:
712 2) Otherwise, we do following:
713
713
714 a) Yield (status, filepath) for all the files which are in this
714 a) Yield (status, filepath) for all the files which are in this
715 directory (only the ones in this directory, not the subdirs)
715 directory (only the ones in this directory, not the subdirs)
716
716
717 b) Recurse the function on all the subdirectories of this
717 b) Recurse the function on all the subdirectories of this
718 directory
718 directory
719 """
719 """
720
720
721 if len(self.statuses) == 1:
721 if len(self.statuses) == 1:
722 onlyst = self.statuses.pop()
722 onlyst = self.statuses.pop()
723
723
724 # Making sure we terse only when the status abbreviation is
724 # Making sure we terse only when the status abbreviation is
725 # passed as terse argument
725 # passed as terse argument
726 if onlyst in terseargs:
726 if onlyst in terseargs:
727 yield onlyst, self.path + b'/'
727 yield onlyst, self.path + b'/'
728 return
728 return
729
729
730 # add the files to status list
730 # add the files to status list
731 for st, fpath in self.iterfilepaths():
731 for st, fpath in self.iterfilepaths():
732 yield st, fpath
732 yield st, fpath
733
733
734 # recurse on the subdirs
734 # recurse on the subdirs
735 for dirobj in self.subdirs.values():
735 for dirobj in self.subdirs.values():
736 for st, fpath in dirobj.tersewalk(terseargs):
736 for st, fpath in dirobj.tersewalk(terseargs):
737 yield st, fpath
737 yield st, fpath
738
738
739
739
740 def tersedir(statuslist, terseargs):
740 def tersedir(statuslist, terseargs):
741 """
741 """
742 Terse the status if all the files in a directory shares the same status.
742 Terse the status if all the files in a directory shares the same status.
743
743
744 statuslist is scmutil.status() object which contains a list of files for
744 statuslist is scmutil.status() object which contains a list of files for
745 each status.
745 each status.
746 terseargs is string which is passed by the user as the argument to `--terse`
746 terseargs is string which is passed by the user as the argument to `--terse`
747 flag.
747 flag.
748
748
749 The function makes a tree of objects of dirnode class, and at each node it
749 The function makes a tree of objects of dirnode class, and at each node it
750 stores the information required to know whether we can terse a certain
750 stores the information required to know whether we can terse a certain
751 directory or not.
751 directory or not.
752 """
752 """
753 # the order matters here as that is used to produce final list
753 # the order matters here as that is used to produce final list
754 allst = (b'm', b'a', b'r', b'd', b'u', b'i', b'c')
754 allst = (b'm', b'a', b'r', b'd', b'u', b'i', b'c')
755
755
756 # checking the argument validity
756 # checking the argument validity
757 for s in pycompat.bytestr(terseargs):
757 for s in pycompat.bytestr(terseargs):
758 if s not in allst:
758 if s not in allst:
759 raise error.Abort(_(b"'%s' not recognized") % s)
759 raise error.Abort(_(b"'%s' not recognized") % s)
760
760
761 # creating a dirnode object for the root of the repo
761 # creating a dirnode object for the root of the repo
762 rootobj = dirnode(b'')
762 rootobj = dirnode(b'')
763 pstatus = (
763 pstatus = (
764 b'modified',
764 b'modified',
765 b'added',
765 b'added',
766 b'deleted',
766 b'deleted',
767 b'clean',
767 b'clean',
768 b'unknown',
768 b'unknown',
769 b'ignored',
769 b'ignored',
770 b'removed',
770 b'removed',
771 )
771 )
772
772
773 tersedict = {}
773 tersedict = {}
774 for attrname in pstatus:
774 for attrname in pstatus:
775 statuschar = attrname[0:1]
775 statuschar = attrname[0:1]
776 for f in getattr(statuslist, attrname):
776 for f in getattr(statuslist, attrname):
777 rootobj.addfile(f, statuschar)
777 rootobj.addfile(f, statuschar)
778 tersedict[statuschar] = []
778 tersedict[statuschar] = []
779
779
780 # we won't be tersing the root dir, so add files in it
780 # we won't be tersing the root dir, so add files in it
781 for st, fpath in rootobj.iterfilepaths():
781 for st, fpath in rootobj.iterfilepaths():
782 tersedict[st].append(fpath)
782 tersedict[st].append(fpath)
783
783
784 # process each sub-directory and build tersedict
784 # process each sub-directory and build tersedict
785 for subdir in rootobj.subdirs.values():
785 for subdir in rootobj.subdirs.values():
786 for st, f in subdir.tersewalk(terseargs):
786 for st, f in subdir.tersewalk(terseargs):
787 tersedict[st].append(f)
787 tersedict[st].append(f)
788
788
789 tersedlist = []
789 tersedlist = []
790 for st in allst:
790 for st in allst:
791 tersedict[st].sort()
791 tersedict[st].sort()
792 tersedlist.append(tersedict[st])
792 tersedlist.append(tersedict[st])
793
793
794 return scmutil.status(*tersedlist)
794 return scmutil.status(*tersedlist)
795
795
796
796
797 def _commentlines(raw):
797 def _commentlines(raw):
798 '''Surround lineswith a comment char and a new line'''
798 '''Surround lineswith a comment char and a new line'''
799 lines = raw.splitlines()
799 lines = raw.splitlines()
800 commentedlines = [b'# %s' % line for line in lines]
800 commentedlines = [b'# %s' % line for line in lines]
801 return b'\n'.join(commentedlines) + b'\n'
801 return b'\n'.join(commentedlines) + b'\n'
802
802
803
803
804 @attr.s(frozen=True)
804 @attr.s(frozen=True)
805 class morestatus(object):
805 class morestatus(object):
806 reporoot = attr.ib()
806 reporoot = attr.ib()
807 unfinishedop = attr.ib()
807 unfinishedop = attr.ib()
808 unfinishedmsg = attr.ib()
808 unfinishedmsg = attr.ib()
809 activemerge = attr.ib()
809 activemerge = attr.ib()
810 unresolvedpaths = attr.ib()
810 unresolvedpaths = attr.ib()
811 _formattedpaths = attr.ib(init=False, default=set())
811 _formattedpaths = attr.ib(init=False, default=set())
812 _label = b'status.morestatus'
812 _label = b'status.morestatus'
813
813
814 def formatfile(self, path, fm):
814 def formatfile(self, path, fm):
815 self._formattedpaths.add(path)
815 self._formattedpaths.add(path)
816 if self.activemerge and path in self.unresolvedpaths:
816 if self.activemerge and path in self.unresolvedpaths:
817 fm.data(unresolved=True)
817 fm.data(unresolved=True)
818
818
819 def formatfooter(self, fm):
819 def formatfooter(self, fm):
820 if self.unfinishedop or self.unfinishedmsg:
820 if self.unfinishedop or self.unfinishedmsg:
821 fm.startitem()
821 fm.startitem()
822 fm.data(itemtype=b'morestatus')
822 fm.data(itemtype=b'morestatus')
823
823
824 if self.unfinishedop:
824 if self.unfinishedop:
825 fm.data(unfinished=self.unfinishedop)
825 fm.data(unfinished=self.unfinishedop)
826 statemsg = (
826 statemsg = (
827 _(b'The repository is in an unfinished *%s* state.')
827 _(b'The repository is in an unfinished *%s* state.')
828 % self.unfinishedop
828 % self.unfinishedop
829 )
829 )
830 fm.plain(b'%s\n' % _commentlines(statemsg), label=self._label)
830 fm.plain(b'%s\n' % _commentlines(statemsg), label=self._label)
831 if self.unfinishedmsg:
831 if self.unfinishedmsg:
832 fm.data(unfinishedmsg=self.unfinishedmsg)
832 fm.data(unfinishedmsg=self.unfinishedmsg)
833
833
834 # May also start new data items.
834 # May also start new data items.
835 self._formatconflicts(fm)
835 self._formatconflicts(fm)
836
836
837 if self.unfinishedmsg:
837 if self.unfinishedmsg:
838 fm.plain(
838 fm.plain(
839 b'%s\n' % _commentlines(self.unfinishedmsg), label=self._label
839 b'%s\n' % _commentlines(self.unfinishedmsg), label=self._label
840 )
840 )
841
841
842 def _formatconflicts(self, fm):
842 def _formatconflicts(self, fm):
843 if not self.activemerge:
843 if not self.activemerge:
844 return
844 return
845
845
846 if self.unresolvedpaths:
846 if self.unresolvedpaths:
847 mergeliststr = b'\n'.join(
847 mergeliststr = b'\n'.join(
848 [
848 [
849 b' %s'
849 b' %s'
850 % util.pathto(self.reporoot, encoding.getcwd(), path)
850 % util.pathto(self.reporoot, encoding.getcwd(), path)
851 for path in self.unresolvedpaths
851 for path in self.unresolvedpaths
852 ]
852 ]
853 )
853 )
854 msg = (
854 msg = (
855 _(
855 _(
856 '''Unresolved merge conflicts:
856 '''Unresolved merge conflicts:
857
857
858 %s
858 %s
859
859
860 To mark files as resolved: hg resolve --mark FILE'''
860 To mark files as resolved: hg resolve --mark FILE'''
861 )
861 )
862 % mergeliststr
862 % mergeliststr
863 )
863 )
864
864
865 # If any paths with unresolved conflicts were not previously
865 # If any paths with unresolved conflicts were not previously
866 # formatted, output them now.
866 # formatted, output them now.
867 for f in self.unresolvedpaths:
867 for f in self.unresolvedpaths:
868 if f in self._formattedpaths:
868 if f in self._formattedpaths:
869 # Already output.
869 # Already output.
870 continue
870 continue
871 fm.startitem()
871 fm.startitem()
872 # We can't claim to know the status of the file - it may just
872 # We can't claim to know the status of the file - it may just
873 # have been in one of the states that were not requested for
873 # have been in one of the states that were not requested for
874 # display, so it could be anything.
874 # display, so it could be anything.
875 fm.data(itemtype=b'file', path=f, unresolved=True)
875 fm.data(itemtype=b'file', path=f, unresolved=True)
876
876
877 else:
877 else:
878 msg = _(b'No unresolved merge conflicts.')
878 msg = _(b'No unresolved merge conflicts.')
879
879
880 fm.plain(b'%s\n' % _commentlines(msg), label=self._label)
880 fm.plain(b'%s\n' % _commentlines(msg), label=self._label)
881
881
882
882
883 def readmorestatus(repo):
883 def readmorestatus(repo):
884 """Returns a morestatus object if the repo has unfinished state."""
884 """Returns a morestatus object if the repo has unfinished state."""
885 statetuple = statemod.getrepostate(repo)
885 statetuple = statemod.getrepostate(repo)
886 mergestate = mergemod.mergestate.read(repo)
886 mergestate = mergemod.mergestate.read(repo)
887 activemerge = mergestate.active()
887 activemerge = mergestate.active()
888 if not statetuple and not activemerge:
888 if not statetuple and not activemerge:
889 return None
889 return None
890
890
891 unfinishedop = unfinishedmsg = unresolved = None
891 unfinishedop = unfinishedmsg = unresolved = None
892 if statetuple:
892 if statetuple:
893 unfinishedop, unfinishedmsg = statetuple
893 unfinishedop, unfinishedmsg = statetuple
894 if activemerge:
894 if activemerge:
895 unresolved = sorted(mergestate.unresolved())
895 unresolved = sorted(mergestate.unresolved())
896 return morestatus(
896 return morestatus(
897 repo.root, unfinishedop, unfinishedmsg, activemerge, unresolved
897 repo.root, unfinishedop, unfinishedmsg, activemerge, unresolved
898 )
898 )
899
899
900
900
901 def findpossible(cmd, table, strict=False):
901 def findpossible(cmd, table, strict=False):
902 """
902 """
903 Return cmd -> (aliases, command table entry)
903 Return cmd -> (aliases, command table entry)
904 for each matching command.
904 for each matching command.
905 Return debug commands (or their aliases) only if no normal command matches.
905 Return debug commands (or their aliases) only if no normal command matches.
906 """
906 """
907 choice = {}
907 choice = {}
908 debugchoice = {}
908 debugchoice = {}
909
909
910 if cmd in table:
910 if cmd in table:
911 # short-circuit exact matches, "log" alias beats "log|history"
911 # short-circuit exact matches, "log" alias beats "log|history"
912 keys = [cmd]
912 keys = [cmd]
913 else:
913 else:
914 keys = table.keys()
914 keys = table.keys()
915
915
916 allcmds = []
916 allcmds = []
917 for e in keys:
917 for e in keys:
918 aliases = parsealiases(e)
918 aliases = parsealiases(e)
919 allcmds.extend(aliases)
919 allcmds.extend(aliases)
920 found = None
920 found = None
921 if cmd in aliases:
921 if cmd in aliases:
922 found = cmd
922 found = cmd
923 elif not strict:
923 elif not strict:
924 for a in aliases:
924 for a in aliases:
925 if a.startswith(cmd):
925 if a.startswith(cmd):
926 found = a
926 found = a
927 break
927 break
928 if found is not None:
928 if found is not None:
929 if aliases[0].startswith(b"debug") or found.startswith(b"debug"):
929 if aliases[0].startswith(b"debug") or found.startswith(b"debug"):
930 debugchoice[found] = (aliases, table[e])
930 debugchoice[found] = (aliases, table[e])
931 else:
931 else:
932 choice[found] = (aliases, table[e])
932 choice[found] = (aliases, table[e])
933
933
934 if not choice and debugchoice:
934 if not choice and debugchoice:
935 choice = debugchoice
935 choice = debugchoice
936
936
937 return choice, allcmds
937 return choice, allcmds
938
938
939
939
940 def findcmd(cmd, table, strict=True):
940 def findcmd(cmd, table, strict=True):
941 """Return (aliases, command table entry) for command string."""
941 """Return (aliases, command table entry) for command string."""
942 choice, allcmds = findpossible(cmd, table, strict)
942 choice, allcmds = findpossible(cmd, table, strict)
943
943
944 if cmd in choice:
944 if cmd in choice:
945 return choice[cmd]
945 return choice[cmd]
946
946
947 if len(choice) > 1:
947 if len(choice) > 1:
948 clist = sorted(choice)
948 clist = sorted(choice)
949 raise error.AmbiguousCommand(cmd, clist)
949 raise error.AmbiguousCommand(cmd, clist)
950
950
951 if choice:
951 if choice:
952 return list(choice.values())[0]
952 return list(choice.values())[0]
953
953
954 raise error.UnknownCommand(cmd, allcmds)
954 raise error.UnknownCommand(cmd, allcmds)
955
955
956
956
957 def changebranch(ui, repo, revs, label):
957 def changebranch(ui, repo, revs, label):
958 """ Change the branch name of given revs to label """
958 """ Change the branch name of given revs to label """
959
959
960 with repo.wlock(), repo.lock(), repo.transaction(b'branches'):
960 with repo.wlock(), repo.lock(), repo.transaction(b'branches'):
961 # abort in case of uncommitted merge or dirty wdir
961 # abort in case of uncommitted merge or dirty wdir
962 bailifchanged(repo)
962 bailifchanged(repo)
963 revs = scmutil.revrange(repo, revs)
963 revs = scmutil.revrange(repo, revs)
964 if not revs:
964 if not revs:
965 raise error.Abort(b"empty revision set")
965 raise error.Abort(b"empty revision set")
966 roots = repo.revs(b'roots(%ld)', revs)
966 roots = repo.revs(b'roots(%ld)', revs)
967 if len(roots) > 1:
967 if len(roots) > 1:
968 raise error.Abort(
968 raise error.Abort(
969 _(b"cannot change branch of non-linear revisions")
969 _(b"cannot change branch of non-linear revisions")
970 )
970 )
971 rewriteutil.precheck(repo, revs, b'change branch of')
971 rewriteutil.precheck(repo, revs, b'change branch of')
972
972
973 root = repo[roots.first()]
973 root = repo[roots.first()]
974 rpb = {parent.branch() for parent in root.parents()}
974 rpb = {parent.branch() for parent in root.parents()}
975 if label not in rpb and label in repo.branchmap():
975 if label not in rpb and label in repo.branchmap():
976 raise error.Abort(_(b"a branch of the same name already exists"))
976 raise error.Abort(_(b"a branch of the same name already exists"))
977
977
978 if repo.revs(b'obsolete() and %ld', revs):
978 if repo.revs(b'obsolete() and %ld', revs):
979 raise error.Abort(
979 raise error.Abort(
980 _(b"cannot change branch of a obsolete changeset")
980 _(b"cannot change branch of a obsolete changeset")
981 )
981 )
982
982
983 # make sure only topological heads
983 # make sure only topological heads
984 if repo.revs(b'heads(%ld) - head()', revs):
984 if repo.revs(b'heads(%ld) - head()', revs):
985 raise error.Abort(_(b"cannot change branch in middle of a stack"))
985 raise error.Abort(_(b"cannot change branch in middle of a stack"))
986
986
987 replacements = {}
987 replacements = {}
988 # avoid import cycle mercurial.cmdutil -> mercurial.context ->
988 # avoid import cycle mercurial.cmdutil -> mercurial.context ->
989 # mercurial.subrepo -> mercurial.cmdutil
989 # mercurial.subrepo -> mercurial.cmdutil
990 from . import context
990 from . import context
991
991
992 for rev in revs:
992 for rev in revs:
993 ctx = repo[rev]
993 ctx = repo[rev]
994 oldbranch = ctx.branch()
994 oldbranch = ctx.branch()
995 # check if ctx has same branch
995 # check if ctx has same branch
996 if oldbranch == label:
996 if oldbranch == label:
997 continue
997 continue
998
998
999 def filectxfn(repo, newctx, path):
999 def filectxfn(repo, newctx, path):
1000 try:
1000 try:
1001 return ctx[path]
1001 return ctx[path]
1002 except error.ManifestLookupError:
1002 except error.ManifestLookupError:
1003 return None
1003 return None
1004
1004
1005 ui.debug(
1005 ui.debug(
1006 b"changing branch of '%s' from '%s' to '%s'\n"
1006 b"changing branch of '%s' from '%s' to '%s'\n"
1007 % (hex(ctx.node()), oldbranch, label)
1007 % (hex(ctx.node()), oldbranch, label)
1008 )
1008 )
1009 extra = ctx.extra()
1009 extra = ctx.extra()
1010 extra[b'branch_change'] = hex(ctx.node())
1010 extra[b'branch_change'] = hex(ctx.node())
1011 # While changing branch of set of linear commits, make sure that
1011 # While changing branch of set of linear commits, make sure that
1012 # we base our commits on new parent rather than old parent which
1012 # we base our commits on new parent rather than old parent which
1013 # was obsoleted while changing the branch
1013 # was obsoleted while changing the branch
1014 p1 = ctx.p1().node()
1014 p1 = ctx.p1().node()
1015 p2 = ctx.p2().node()
1015 p2 = ctx.p2().node()
1016 if p1 in replacements:
1016 if p1 in replacements:
1017 p1 = replacements[p1][0]
1017 p1 = replacements[p1][0]
1018 if p2 in replacements:
1018 if p2 in replacements:
1019 p2 = replacements[p2][0]
1019 p2 = replacements[p2][0]
1020
1020
1021 mc = context.memctx(
1021 mc = context.memctx(
1022 repo,
1022 repo,
1023 (p1, p2),
1023 (p1, p2),
1024 ctx.description(),
1024 ctx.description(),
1025 ctx.files(),
1025 ctx.files(),
1026 filectxfn,
1026 filectxfn,
1027 user=ctx.user(),
1027 user=ctx.user(),
1028 date=ctx.date(),
1028 date=ctx.date(),
1029 extra=extra,
1029 extra=extra,
1030 branch=label,
1030 branch=label,
1031 )
1031 )
1032
1032
1033 newnode = repo.commitctx(mc)
1033 newnode = repo.commitctx(mc)
1034 replacements[ctx.node()] = (newnode,)
1034 replacements[ctx.node()] = (newnode,)
1035 ui.debug(b'new node id is %s\n' % hex(newnode))
1035 ui.debug(b'new node id is %s\n' % hex(newnode))
1036
1036
1037 # create obsmarkers and move bookmarks
1037 # create obsmarkers and move bookmarks
1038 scmutil.cleanupnodes(
1038 scmutil.cleanupnodes(
1039 repo, replacements, b'branch-change', fixphase=True
1039 repo, replacements, b'branch-change', fixphase=True
1040 )
1040 )
1041
1041
1042 # move the working copy too
1042 # move the working copy too
1043 wctx = repo[None]
1043 wctx = repo[None]
1044 # in-progress merge is a bit too complex for now.
1044 # in-progress merge is a bit too complex for now.
1045 if len(wctx.parents()) == 1:
1045 if len(wctx.parents()) == 1:
1046 newid = replacements.get(wctx.p1().node())
1046 newid = replacements.get(wctx.p1().node())
1047 if newid is not None:
1047 if newid is not None:
1048 # avoid import cycle mercurial.cmdutil -> mercurial.hg ->
1048 # avoid import cycle mercurial.cmdutil -> mercurial.hg ->
1049 # mercurial.cmdutil
1049 # mercurial.cmdutil
1050 from . import hg
1050 from . import hg
1051
1051
1052 hg.update(repo, newid[0], quietempty=True)
1052 hg.update(repo, newid[0], quietempty=True)
1053
1053
1054 ui.status(_(b"changed branch on %d changesets\n") % len(replacements))
1054 ui.status(_(b"changed branch on %d changesets\n") % len(replacements))
1055
1055
1056
1056
1057 def findrepo(p):
1057 def findrepo(p):
1058 while not os.path.isdir(os.path.join(p, b".hg")):
1058 while not os.path.isdir(os.path.join(p, b".hg")):
1059 oldp, p = p, os.path.dirname(p)
1059 oldp, p = p, os.path.dirname(p)
1060 if p == oldp:
1060 if p == oldp:
1061 return None
1061 return None
1062
1062
1063 return p
1063 return p
1064
1064
1065
1065
1066 def bailifchanged(repo, merge=True, hint=None):
1066 def bailifchanged(repo, merge=True, hint=None):
1067 """ enforce the precondition that working directory must be clean.
1067 """ enforce the precondition that working directory must be clean.
1068
1068
1069 'merge' can be set to false if a pending uncommitted merge should be
1069 'merge' can be set to false if a pending uncommitted merge should be
1070 ignored (such as when 'update --check' runs).
1070 ignored (such as when 'update --check' runs).
1071
1071
1072 'hint' is the usual hint given to Abort exception.
1072 'hint' is the usual hint given to Abort exception.
1073 """
1073 """
1074
1074
1075 if merge and repo.dirstate.p2() != nullid:
1075 if merge and repo.dirstate.p2() != nullid:
1076 raise error.Abort(_(b'outstanding uncommitted merge'), hint=hint)
1076 raise error.Abort(_(b'outstanding uncommitted merge'), hint=hint)
1077 st = repo.status()
1077 st = repo.status()
1078 if st.modified or st.added or st.removed or st.deleted:
1078 if st.modified or st.added or st.removed or st.deleted:
1079 raise error.Abort(_(b'uncommitted changes'), hint=hint)
1079 raise error.Abort(_(b'uncommitted changes'), hint=hint)
1080 ctx = repo[None]
1080 ctx = repo[None]
1081 for s in sorted(ctx.substate):
1081 for s in sorted(ctx.substate):
1082 ctx.sub(s).bailifchanged(hint=hint)
1082 ctx.sub(s).bailifchanged(hint=hint)
1083
1083
1084
1084
1085 def logmessage(ui, opts):
1085 def logmessage(ui, opts):
1086 """ get the log message according to -m and -l option """
1086 """ get the log message according to -m and -l option """
1087
1087
1088 check_at_most_one_arg(opts, b'message', b'logfile')
1088 check_at_most_one_arg(opts, b'message', b'logfile')
1089
1089
1090 message = opts.get(b'message')
1090 message = opts.get(b'message')
1091 logfile = opts.get(b'logfile')
1091 logfile = opts.get(b'logfile')
1092
1092
1093 if not message and logfile:
1093 if not message and logfile:
1094 try:
1094 try:
1095 if isstdiofilename(logfile):
1095 if isstdiofilename(logfile):
1096 message = ui.fin.read()
1096 message = ui.fin.read()
1097 else:
1097 else:
1098 message = b'\n'.join(util.readfile(logfile).splitlines())
1098 message = b'\n'.join(util.readfile(logfile).splitlines())
1099 except IOError as inst:
1099 except IOError as inst:
1100 raise error.Abort(
1100 raise error.Abort(
1101 _(b"can't read commit message '%s': %s")
1101 _(b"can't read commit message '%s': %s")
1102 % (logfile, encoding.strtolocal(inst.strerror))
1102 % (logfile, encoding.strtolocal(inst.strerror))
1103 )
1103 )
1104 return message
1104 return message
1105
1105
1106
1106
1107 def mergeeditform(ctxorbool, baseformname):
1107 def mergeeditform(ctxorbool, baseformname):
1108 """return appropriate editform name (referencing a committemplate)
1108 """return appropriate editform name (referencing a committemplate)
1109
1109
1110 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
1110 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
1111 merging is committed.
1111 merging is committed.
1112
1112
1113 This returns baseformname with '.merge' appended if it is a merge,
1113 This returns baseformname with '.merge' appended if it is a merge,
1114 otherwise '.normal' is appended.
1114 otherwise '.normal' is appended.
1115 """
1115 """
1116 if isinstance(ctxorbool, bool):
1116 if isinstance(ctxorbool, bool):
1117 if ctxorbool:
1117 if ctxorbool:
1118 return baseformname + b".merge"
1118 return baseformname + b".merge"
1119 elif len(ctxorbool.parents()) > 1:
1119 elif len(ctxorbool.parents()) > 1:
1120 return baseformname + b".merge"
1120 return baseformname + b".merge"
1121
1121
1122 return baseformname + b".normal"
1122 return baseformname + b".normal"
1123
1123
1124
1124
1125 def getcommiteditor(
1125 def getcommiteditor(
1126 edit=False, finishdesc=None, extramsg=None, editform=b'', **opts
1126 edit=False, finishdesc=None, extramsg=None, editform=b'', **opts
1127 ):
1127 ):
1128 """get appropriate commit message editor according to '--edit' option
1128 """get appropriate commit message editor according to '--edit' option
1129
1129
1130 'finishdesc' is a function to be called with edited commit message
1130 'finishdesc' is a function to be called with edited commit message
1131 (= 'description' of the new changeset) just after editing, but
1131 (= 'description' of the new changeset) just after editing, but
1132 before checking empty-ness. It should return actual text to be
1132 before checking empty-ness. It should return actual text to be
1133 stored into history. This allows to change description before
1133 stored into history. This allows to change description before
1134 storing.
1134 storing.
1135
1135
1136 'extramsg' is a extra message to be shown in the editor instead of
1136 'extramsg' is a extra message to be shown in the editor instead of
1137 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
1137 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
1138 is automatically added.
1138 is automatically added.
1139
1139
1140 'editform' is a dot-separated list of names, to distinguish
1140 'editform' is a dot-separated list of names, to distinguish
1141 the purpose of commit text editing.
1141 the purpose of commit text editing.
1142
1142
1143 'getcommiteditor' returns 'commitforceeditor' regardless of
1143 'getcommiteditor' returns 'commitforceeditor' regardless of
1144 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
1144 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
1145 they are specific for usage in MQ.
1145 they are specific for usage in MQ.
1146 """
1146 """
1147 if edit or finishdesc or extramsg:
1147 if edit or finishdesc or extramsg:
1148 return lambda r, c, s: commitforceeditor(
1148 return lambda r, c, s: commitforceeditor(
1149 r, c, s, finishdesc=finishdesc, extramsg=extramsg, editform=editform
1149 r, c, s, finishdesc=finishdesc, extramsg=extramsg, editform=editform
1150 )
1150 )
1151 elif editform:
1151 elif editform:
1152 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
1152 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
1153 else:
1153 else:
1154 return commiteditor
1154 return commiteditor
1155
1155
1156
1156
1157 def _escapecommandtemplate(tmpl):
1157 def _escapecommandtemplate(tmpl):
1158 parts = []
1158 parts = []
1159 for typ, start, end in templater.scantemplate(tmpl, raw=True):
1159 for typ, start, end in templater.scantemplate(tmpl, raw=True):
1160 if typ == b'string':
1160 if typ == b'string':
1161 parts.append(stringutil.escapestr(tmpl[start:end]))
1161 parts.append(stringutil.escapestr(tmpl[start:end]))
1162 else:
1162 else:
1163 parts.append(tmpl[start:end])
1163 parts.append(tmpl[start:end])
1164 return b''.join(parts)
1164 return b''.join(parts)
1165
1165
1166
1166
1167 def rendercommandtemplate(ui, tmpl, props):
1167 def rendercommandtemplate(ui, tmpl, props):
1168 r"""Expand a literal template 'tmpl' in a way suitable for command line
1168 r"""Expand a literal template 'tmpl' in a way suitable for command line
1169
1169
1170 '\' in outermost string is not taken as an escape character because it
1170 '\' in outermost string is not taken as an escape character because it
1171 is a directory separator on Windows.
1171 is a directory separator on Windows.
1172
1172
1173 >>> from . import ui as uimod
1173 >>> from . import ui as uimod
1174 >>> ui = uimod.ui()
1174 >>> ui = uimod.ui()
1175 >>> rendercommandtemplate(ui, b'c:\\{path}', {b'path': b'foo'})
1175 >>> rendercommandtemplate(ui, b'c:\\{path}', {b'path': b'foo'})
1176 'c:\\foo'
1176 'c:\\foo'
1177 >>> rendercommandtemplate(ui, b'{"c:\\{path}"}', {'path': b'foo'})
1177 >>> rendercommandtemplate(ui, b'{"c:\\{path}"}', {'path': b'foo'})
1178 'c:{path}'
1178 'c:{path}'
1179 """
1179 """
1180 if not tmpl:
1180 if not tmpl:
1181 return tmpl
1181 return tmpl
1182 t = formatter.maketemplater(ui, _escapecommandtemplate(tmpl))
1182 t = formatter.maketemplater(ui, _escapecommandtemplate(tmpl))
1183 return t.renderdefault(props)
1183 return t.renderdefault(props)
1184
1184
1185
1185
1186 def rendertemplate(ctx, tmpl, props=None):
1186 def rendertemplate(ctx, tmpl, props=None):
1187 """Expand a literal template 'tmpl' byte-string against one changeset
1187 """Expand a literal template 'tmpl' byte-string against one changeset
1188
1188
1189 Each props item must be a stringify-able value or a callable returning
1189 Each props item must be a stringify-able value or a callable returning
1190 such value, i.e. no bare list nor dict should be passed.
1190 such value, i.e. no bare list nor dict should be passed.
1191 """
1191 """
1192 repo = ctx.repo()
1192 repo = ctx.repo()
1193 tres = formatter.templateresources(repo.ui, repo)
1193 tres = formatter.templateresources(repo.ui, repo)
1194 t = formatter.maketemplater(
1194 t = formatter.maketemplater(
1195 repo.ui, tmpl, defaults=templatekw.keywords, resources=tres
1195 repo.ui, tmpl, defaults=templatekw.keywords, resources=tres
1196 )
1196 )
1197 mapping = {b'ctx': ctx}
1197 mapping = {b'ctx': ctx}
1198 if props:
1198 if props:
1199 mapping.update(props)
1199 mapping.update(props)
1200 return t.renderdefault(mapping)
1200 return t.renderdefault(mapping)
1201
1201
1202
1202
1203 def _buildfntemplate(pat, total=None, seqno=None, revwidth=None, pathname=None):
1203 def _buildfntemplate(pat, total=None, seqno=None, revwidth=None, pathname=None):
1204 r"""Convert old-style filename format string to template string
1204 r"""Convert old-style filename format string to template string
1205
1205
1206 >>> _buildfntemplate(b'foo-%b-%n.patch', seqno=0)
1206 >>> _buildfntemplate(b'foo-%b-%n.patch', seqno=0)
1207 'foo-{reporoot|basename}-{seqno}.patch'
1207 'foo-{reporoot|basename}-{seqno}.patch'
1208 >>> _buildfntemplate(b'%R{tags % "{tag}"}%H')
1208 >>> _buildfntemplate(b'%R{tags % "{tag}"}%H')
1209 '{rev}{tags % "{tag}"}{node}'
1209 '{rev}{tags % "{tag}"}{node}'
1210
1210
1211 '\' in outermost strings has to be escaped because it is a directory
1211 '\' in outermost strings has to be escaped because it is a directory
1212 separator on Windows:
1212 separator on Windows:
1213
1213
1214 >>> _buildfntemplate(b'c:\\tmp\\%R\\%n.patch', seqno=0)
1214 >>> _buildfntemplate(b'c:\\tmp\\%R\\%n.patch', seqno=0)
1215 'c:\\\\tmp\\\\{rev}\\\\{seqno}.patch'
1215 'c:\\\\tmp\\\\{rev}\\\\{seqno}.patch'
1216 >>> _buildfntemplate(b'\\\\foo\\bar.patch')
1216 >>> _buildfntemplate(b'\\\\foo\\bar.patch')
1217 '\\\\\\\\foo\\\\bar.patch'
1217 '\\\\\\\\foo\\\\bar.patch'
1218 >>> _buildfntemplate(b'\\{tags % "{tag}"}')
1218 >>> _buildfntemplate(b'\\{tags % "{tag}"}')
1219 '\\\\{tags % "{tag}"}'
1219 '\\\\{tags % "{tag}"}'
1220
1220
1221 but inner strings follow the template rules (i.e. '\' is taken as an
1221 but inner strings follow the template rules (i.e. '\' is taken as an
1222 escape character):
1222 escape character):
1223
1223
1224 >>> _buildfntemplate(br'{"c:\tmp"}', seqno=0)
1224 >>> _buildfntemplate(br'{"c:\tmp"}', seqno=0)
1225 '{"c:\\tmp"}'
1225 '{"c:\\tmp"}'
1226 """
1226 """
1227 expander = {
1227 expander = {
1228 b'H': b'{node}',
1228 b'H': b'{node}',
1229 b'R': b'{rev}',
1229 b'R': b'{rev}',
1230 b'h': b'{node|short}',
1230 b'h': b'{node|short}',
1231 b'm': br'{sub(r"[^\w]", "_", desc|firstline)}',
1231 b'm': br'{sub(r"[^\w]", "_", desc|firstline)}',
1232 b'r': b'{if(revwidth, pad(rev, revwidth, "0", left=True), rev)}',
1232 b'r': b'{if(revwidth, pad(rev, revwidth, "0", left=True), rev)}',
1233 b'%': b'%',
1233 b'%': b'%',
1234 b'b': b'{reporoot|basename}',
1234 b'b': b'{reporoot|basename}',
1235 }
1235 }
1236 if total is not None:
1236 if total is not None:
1237 expander[b'N'] = b'{total}'
1237 expander[b'N'] = b'{total}'
1238 if seqno is not None:
1238 if seqno is not None:
1239 expander[b'n'] = b'{seqno}'
1239 expander[b'n'] = b'{seqno}'
1240 if total is not None and seqno is not None:
1240 if total is not None and seqno is not None:
1241 expander[b'n'] = b'{pad(seqno, total|stringify|count, "0", left=True)}'
1241 expander[b'n'] = b'{pad(seqno, total|stringify|count, "0", left=True)}'
1242 if pathname is not None:
1242 if pathname is not None:
1243 expander[b's'] = b'{pathname|basename}'
1243 expander[b's'] = b'{pathname|basename}'
1244 expander[b'd'] = b'{if(pathname|dirname, pathname|dirname, ".")}'
1244 expander[b'd'] = b'{if(pathname|dirname, pathname|dirname, ".")}'
1245 expander[b'p'] = b'{pathname}'
1245 expander[b'p'] = b'{pathname}'
1246
1246
1247 newname = []
1247 newname = []
1248 for typ, start, end in templater.scantemplate(pat, raw=True):
1248 for typ, start, end in templater.scantemplate(pat, raw=True):
1249 if typ != b'string':
1249 if typ != b'string':
1250 newname.append(pat[start:end])
1250 newname.append(pat[start:end])
1251 continue
1251 continue
1252 i = start
1252 i = start
1253 while i < end:
1253 while i < end:
1254 n = pat.find(b'%', i, end)
1254 n = pat.find(b'%', i, end)
1255 if n < 0:
1255 if n < 0:
1256 newname.append(stringutil.escapestr(pat[i:end]))
1256 newname.append(stringutil.escapestr(pat[i:end]))
1257 break
1257 break
1258 newname.append(stringutil.escapestr(pat[i:n]))
1258 newname.append(stringutil.escapestr(pat[i:n]))
1259 if n + 2 > end:
1259 if n + 2 > end:
1260 raise error.Abort(
1260 raise error.Abort(
1261 _(b"incomplete format spec in output filename")
1261 _(b"incomplete format spec in output filename")
1262 )
1262 )
1263 c = pat[n + 1 : n + 2]
1263 c = pat[n + 1 : n + 2]
1264 i = n + 2
1264 i = n + 2
1265 try:
1265 try:
1266 newname.append(expander[c])
1266 newname.append(expander[c])
1267 except KeyError:
1267 except KeyError:
1268 raise error.Abort(
1268 raise error.Abort(
1269 _(b"invalid format spec '%%%s' in output filename") % c
1269 _(b"invalid format spec '%%%s' in output filename") % c
1270 )
1270 )
1271 return b''.join(newname)
1271 return b''.join(newname)
1272
1272
1273
1273
1274 def makefilename(ctx, pat, **props):
1274 def makefilename(ctx, pat, **props):
1275 if not pat:
1275 if not pat:
1276 return pat
1276 return pat
1277 tmpl = _buildfntemplate(pat, **props)
1277 tmpl = _buildfntemplate(pat, **props)
1278 # BUG: alias expansion shouldn't be made against template fragments
1278 # BUG: alias expansion shouldn't be made against template fragments
1279 # rewritten from %-format strings, but we have no easy way to partially
1279 # rewritten from %-format strings, but we have no easy way to partially
1280 # disable the expansion.
1280 # disable the expansion.
1281 return rendertemplate(ctx, tmpl, pycompat.byteskwargs(props))
1281 return rendertemplate(ctx, tmpl, pycompat.byteskwargs(props))
1282
1282
1283
1283
1284 def isstdiofilename(pat):
1284 def isstdiofilename(pat):
1285 """True if the given pat looks like a filename denoting stdin/stdout"""
1285 """True if the given pat looks like a filename denoting stdin/stdout"""
1286 return not pat or pat == b'-'
1286 return not pat or pat == b'-'
1287
1287
1288
1288
1289 class _unclosablefile(object):
1289 class _unclosablefile(object):
1290 def __init__(self, fp):
1290 def __init__(self, fp):
1291 self._fp = fp
1291 self._fp = fp
1292
1292
1293 def close(self):
1293 def close(self):
1294 pass
1294 pass
1295
1295
1296 def __iter__(self):
1296 def __iter__(self):
1297 return iter(self._fp)
1297 return iter(self._fp)
1298
1298
1299 def __getattr__(self, attr):
1299 def __getattr__(self, attr):
1300 return getattr(self._fp, attr)
1300 return getattr(self._fp, attr)
1301
1301
1302 def __enter__(self):
1302 def __enter__(self):
1303 return self
1303 return self
1304
1304
1305 def __exit__(self, exc_type, exc_value, exc_tb):
1305 def __exit__(self, exc_type, exc_value, exc_tb):
1306 pass
1306 pass
1307
1307
1308
1308
1309 def makefileobj(ctx, pat, mode=b'wb', **props):
1309 def makefileobj(ctx, pat, mode=b'wb', **props):
1310 writable = mode not in (b'r', b'rb')
1310 writable = mode not in (b'r', b'rb')
1311
1311
1312 if isstdiofilename(pat):
1312 if isstdiofilename(pat):
1313 repo = ctx.repo()
1313 repo = ctx.repo()
1314 if writable:
1314 if writable:
1315 fp = repo.ui.fout
1315 fp = repo.ui.fout
1316 else:
1316 else:
1317 fp = repo.ui.fin
1317 fp = repo.ui.fin
1318 return _unclosablefile(fp)
1318 return _unclosablefile(fp)
1319 fn = makefilename(ctx, pat, **props)
1319 fn = makefilename(ctx, pat, **props)
1320 return open(fn, mode)
1320 return open(fn, mode)
1321
1321
1322
1322
1323 def openstorage(repo, cmd, file_, opts, returnrevlog=False):
1323 def openstorage(repo, cmd, file_, opts, returnrevlog=False):
1324 """opens the changelog, manifest, a filelog or a given revlog"""
1324 """opens the changelog, manifest, a filelog or a given revlog"""
1325 cl = opts[b'changelog']
1325 cl = opts[b'changelog']
1326 mf = opts[b'manifest']
1326 mf = opts[b'manifest']
1327 dir = opts[b'dir']
1327 dir = opts[b'dir']
1328 msg = None
1328 msg = None
1329 if cl and mf:
1329 if cl and mf:
1330 msg = _(b'cannot specify --changelog and --manifest at the same time')
1330 msg = _(b'cannot specify --changelog and --manifest at the same time')
1331 elif cl and dir:
1331 elif cl and dir:
1332 msg = _(b'cannot specify --changelog and --dir at the same time')
1332 msg = _(b'cannot specify --changelog and --dir at the same time')
1333 elif cl or mf or dir:
1333 elif cl or mf or dir:
1334 if file_:
1334 if file_:
1335 msg = _(b'cannot specify filename with --changelog or --manifest')
1335 msg = _(b'cannot specify filename with --changelog or --manifest')
1336 elif not repo:
1336 elif not repo:
1337 msg = _(
1337 msg = _(
1338 b'cannot specify --changelog or --manifest or --dir '
1338 b'cannot specify --changelog or --manifest or --dir '
1339 b'without a repository'
1339 b'without a repository'
1340 )
1340 )
1341 if msg:
1341 if msg:
1342 raise error.Abort(msg)
1342 raise error.Abort(msg)
1343
1343
1344 r = None
1344 r = None
1345 if repo:
1345 if repo:
1346 if cl:
1346 if cl:
1347 r = repo.unfiltered().changelog
1347 r = repo.unfiltered().changelog
1348 elif dir:
1348 elif dir:
1349 if b'treemanifest' not in repo.requirements:
1349 if b'treemanifest' not in repo.requirements:
1350 raise error.Abort(
1350 raise error.Abort(
1351 _(
1351 _(
1352 b"--dir can only be used on repos with "
1352 b"--dir can only be used on repos with "
1353 b"treemanifest enabled"
1353 b"treemanifest enabled"
1354 )
1354 )
1355 )
1355 )
1356 if not dir.endswith(b'/'):
1356 if not dir.endswith(b'/'):
1357 dir = dir + b'/'
1357 dir = dir + b'/'
1358 dirlog = repo.manifestlog.getstorage(dir)
1358 dirlog = repo.manifestlog.getstorage(dir)
1359 if len(dirlog):
1359 if len(dirlog):
1360 r = dirlog
1360 r = dirlog
1361 elif mf:
1361 elif mf:
1362 r = repo.manifestlog.getstorage(b'')
1362 r = repo.manifestlog.getstorage(b'')
1363 elif file_:
1363 elif file_:
1364 filelog = repo.file(file_)
1364 filelog = repo.file(file_)
1365 if len(filelog):
1365 if len(filelog):
1366 r = filelog
1366 r = filelog
1367
1367
1368 # Not all storage may be revlogs. If requested, try to return an actual
1368 # Not all storage may be revlogs. If requested, try to return an actual
1369 # revlog instance.
1369 # revlog instance.
1370 if returnrevlog:
1370 if returnrevlog:
1371 if isinstance(r, revlog.revlog):
1371 if isinstance(r, revlog.revlog):
1372 pass
1372 pass
1373 elif util.safehasattr(r, b'_revlog'):
1373 elif util.safehasattr(r, b'_revlog'):
1374 r = r._revlog # pytype: disable=attribute-error
1374 r = r._revlog # pytype: disable=attribute-error
1375 elif r is not None:
1375 elif r is not None:
1376 raise error.Abort(_(b'%r does not appear to be a revlog') % r)
1376 raise error.Abort(_(b'%r does not appear to be a revlog') % r)
1377
1377
1378 if not r:
1378 if not r:
1379 if not returnrevlog:
1379 if not returnrevlog:
1380 raise error.Abort(_(b'cannot give path to non-revlog'))
1380 raise error.Abort(_(b'cannot give path to non-revlog'))
1381
1381
1382 if not file_:
1382 if not file_:
1383 raise error.CommandError(cmd, _(b'invalid arguments'))
1383 raise error.CommandError(cmd, _(b'invalid arguments'))
1384 if not os.path.isfile(file_):
1384 if not os.path.isfile(file_):
1385 raise error.Abort(_(b"revlog '%s' not found") % file_)
1385 raise error.Abort(_(b"revlog '%s' not found") % file_)
1386 r = revlog.revlog(
1386 r = revlog.revlog(
1387 vfsmod.vfs(encoding.getcwd(), audit=False), file_[:-2] + b".i"
1387 vfsmod.vfs(encoding.getcwd(), audit=False), file_[:-2] + b".i"
1388 )
1388 )
1389 return r
1389 return r
1390
1390
1391
1391
1392 def openrevlog(repo, cmd, file_, opts):
1392 def openrevlog(repo, cmd, file_, opts):
1393 """Obtain a revlog backing storage of an item.
1393 """Obtain a revlog backing storage of an item.
1394
1394
1395 This is similar to ``openstorage()`` except it always returns a revlog.
1395 This is similar to ``openstorage()`` except it always returns a revlog.
1396
1396
1397 In most cases, a caller cares about the main storage object - not the
1397 In most cases, a caller cares about the main storage object - not the
1398 revlog backing it. Therefore, this function should only be used by code
1398 revlog backing it. Therefore, this function should only be used by code
1399 that needs to examine low-level revlog implementation details. e.g. debug
1399 that needs to examine low-level revlog implementation details. e.g. debug
1400 commands.
1400 commands.
1401 """
1401 """
1402 return openstorage(repo, cmd, file_, opts, returnrevlog=True)
1402 return openstorage(repo, cmd, file_, opts, returnrevlog=True)
1403
1403
1404
1404
1405 def copy(ui, repo, pats, opts, rename=False):
1405 def copy(ui, repo, pats, opts, rename=False):
1406 # called with the repo lock held
1406 # called with the repo lock held
1407 #
1407 #
1408 # hgsep => pathname that uses "/" to separate directories
1408 # hgsep => pathname that uses "/" to separate directories
1409 # ossep => pathname that uses os.sep to separate directories
1409 # ossep => pathname that uses os.sep to separate directories
1410 cwd = repo.getcwd()
1410 cwd = repo.getcwd()
1411 targets = {}
1411 targets = {}
1412 after = opts.get(b"after")
1412 after = opts.get(b"after")
1413 dryrun = opts.get(b"dry_run")
1413 dryrun = opts.get(b"dry_run")
1414 wctx = repo[None]
1414 wctx = repo[None]
1415
1415
1416 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
1416 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
1417
1417
1418 def walkpat(pat):
1418 def walkpat(pat):
1419 srcs = []
1419 srcs = []
1420 if after:
1420 if after:
1421 badstates = b'?'
1421 badstates = b'?'
1422 else:
1422 else:
1423 badstates = b'?r'
1423 badstates = b'?r'
1424 m = scmutil.match(wctx, [pat], opts, globbed=True)
1424 m = scmutil.match(wctx, [pat], opts, globbed=True)
1425 for abs in wctx.walk(m):
1425 for abs in wctx.walk(m):
1426 state = repo.dirstate[abs]
1426 state = repo.dirstate[abs]
1427 rel = uipathfn(abs)
1427 rel = uipathfn(abs)
1428 exact = m.exact(abs)
1428 exact = m.exact(abs)
1429 if state in badstates:
1429 if state in badstates:
1430 if exact and state == b'?':
1430 if exact and state == b'?':
1431 ui.warn(_(b'%s: not copying - file is not managed\n') % rel)
1431 ui.warn(_(b'%s: not copying - file is not managed\n') % rel)
1432 if exact and state == b'r':
1432 if exact and state == b'r':
1433 ui.warn(
1433 ui.warn(
1434 _(
1434 _(
1435 b'%s: not copying - file has been marked for'
1435 b'%s: not copying - file has been marked for'
1436 b' remove\n'
1436 b' remove\n'
1437 )
1437 )
1438 % rel
1438 % rel
1439 )
1439 )
1440 continue
1440 continue
1441 # abs: hgsep
1441 # abs: hgsep
1442 # rel: ossep
1442 # rel: ossep
1443 srcs.append((abs, rel, exact))
1443 srcs.append((abs, rel, exact))
1444 return srcs
1444 return srcs
1445
1445
1446 # abssrc: hgsep
1446 # abssrc: hgsep
1447 # relsrc: ossep
1447 # relsrc: ossep
1448 # otarget: ossep
1448 # otarget: ossep
1449 def copyfile(abssrc, relsrc, otarget, exact):
1449 def copyfile(abssrc, relsrc, otarget, exact):
1450 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
1450 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
1451 if b'/' in abstarget:
1451 if b'/' in abstarget:
1452 # We cannot normalize abstarget itself, this would prevent
1452 # We cannot normalize abstarget itself, this would prevent
1453 # case only renames, like a => A.
1453 # case only renames, like a => A.
1454 abspath, absname = abstarget.rsplit(b'/', 1)
1454 abspath, absname = abstarget.rsplit(b'/', 1)
1455 abstarget = repo.dirstate.normalize(abspath) + b'/' + absname
1455 abstarget = repo.dirstate.normalize(abspath) + b'/' + absname
1456 reltarget = repo.pathto(abstarget, cwd)
1456 reltarget = repo.pathto(abstarget, cwd)
1457 target = repo.wjoin(abstarget)
1457 target = repo.wjoin(abstarget)
1458 src = repo.wjoin(abssrc)
1458 src = repo.wjoin(abssrc)
1459 state = repo.dirstate[abstarget]
1459 state = repo.dirstate[abstarget]
1460
1460
1461 scmutil.checkportable(ui, abstarget)
1461 scmutil.checkportable(ui, abstarget)
1462
1462
1463 # check for collisions
1463 # check for collisions
1464 prevsrc = targets.get(abstarget)
1464 prevsrc = targets.get(abstarget)
1465 if prevsrc is not None:
1465 if prevsrc is not None:
1466 ui.warn(
1466 ui.warn(
1467 _(b'%s: not overwriting - %s collides with %s\n')
1467 _(b'%s: not overwriting - %s collides with %s\n')
1468 % (
1468 % (
1469 reltarget,
1469 reltarget,
1470 repo.pathto(abssrc, cwd),
1470 repo.pathto(abssrc, cwd),
1471 repo.pathto(prevsrc, cwd),
1471 repo.pathto(prevsrc, cwd),
1472 )
1472 )
1473 )
1473 )
1474 return True # report a failure
1474 return True # report a failure
1475
1475
1476 # check for overwrites
1476 # check for overwrites
1477 exists = os.path.lexists(target)
1477 exists = os.path.lexists(target)
1478 samefile = False
1478 samefile = False
1479 if exists and abssrc != abstarget:
1479 if exists and abssrc != abstarget:
1480 if repo.dirstate.normalize(abssrc) == repo.dirstate.normalize(
1480 if repo.dirstate.normalize(abssrc) == repo.dirstate.normalize(
1481 abstarget
1481 abstarget
1482 ):
1482 ):
1483 if not rename:
1483 if not rename:
1484 ui.warn(_(b"%s: can't copy - same file\n") % reltarget)
1484 ui.warn(_(b"%s: can't copy - same file\n") % reltarget)
1485 return True # report a failure
1485 return True # report a failure
1486 exists = False
1486 exists = False
1487 samefile = True
1487 samefile = True
1488
1488
1489 if not after and exists or after and state in b'mn':
1489 if not after and exists or after and state in b'mn':
1490 if not opts[b'force']:
1490 if not opts[b'force']:
1491 if state in b'mn':
1491 if state in b'mn':
1492 msg = _(b'%s: not overwriting - file already committed\n')
1492 msg = _(b'%s: not overwriting - file already committed\n')
1493 if after:
1493 if after:
1494 flags = b'--after --force'
1494 flags = b'--after --force'
1495 else:
1495 else:
1496 flags = b'--force'
1496 flags = b'--force'
1497 if rename:
1497 if rename:
1498 hint = (
1498 hint = (
1499 _(
1499 _(
1500 b"('hg rename %s' to replace the file by "
1500 b"('hg rename %s' to replace the file by "
1501 b'recording a rename)\n'
1501 b'recording a rename)\n'
1502 )
1502 )
1503 % flags
1503 % flags
1504 )
1504 )
1505 else:
1505 else:
1506 hint = (
1506 hint = (
1507 _(
1507 _(
1508 b"('hg copy %s' to replace the file by "
1508 b"('hg copy %s' to replace the file by "
1509 b'recording a copy)\n'
1509 b'recording a copy)\n'
1510 )
1510 )
1511 % flags
1511 % flags
1512 )
1512 )
1513 else:
1513 else:
1514 msg = _(b'%s: not overwriting - file exists\n')
1514 msg = _(b'%s: not overwriting - file exists\n')
1515 if rename:
1515 if rename:
1516 hint = _(
1516 hint = _(
1517 b"('hg rename --after' to record the rename)\n"
1517 b"('hg rename --after' to record the rename)\n"
1518 )
1518 )
1519 else:
1519 else:
1520 hint = _(b"('hg copy --after' to record the copy)\n")
1520 hint = _(b"('hg copy --after' to record the copy)\n")
1521 ui.warn(msg % reltarget)
1521 ui.warn(msg % reltarget)
1522 ui.warn(hint)
1522 ui.warn(hint)
1523 return True # report a failure
1523 return True # report a failure
1524
1524
1525 if after:
1525 if after:
1526 if not exists:
1526 if not exists:
1527 if rename:
1527 if rename:
1528 ui.warn(
1528 ui.warn(
1529 _(b'%s: not recording move - %s does not exist\n')
1529 _(b'%s: not recording move - %s does not exist\n')
1530 % (relsrc, reltarget)
1530 % (relsrc, reltarget)
1531 )
1531 )
1532 else:
1532 else:
1533 ui.warn(
1533 ui.warn(
1534 _(b'%s: not recording copy - %s does not exist\n')
1534 _(b'%s: not recording copy - %s does not exist\n')
1535 % (relsrc, reltarget)
1535 % (relsrc, reltarget)
1536 )
1536 )
1537 return True # report a failure
1537 return True # report a failure
1538 elif not dryrun:
1538 elif not dryrun:
1539 try:
1539 try:
1540 if exists:
1540 if exists:
1541 os.unlink(target)
1541 os.unlink(target)
1542 targetdir = os.path.dirname(target) or b'.'
1542 targetdir = os.path.dirname(target) or b'.'
1543 if not os.path.isdir(targetdir):
1543 if not os.path.isdir(targetdir):
1544 os.makedirs(targetdir)
1544 os.makedirs(targetdir)
1545 if samefile:
1545 if samefile:
1546 tmp = target + b"~hgrename"
1546 tmp = target + b"~hgrename"
1547 os.rename(src, tmp)
1547 os.rename(src, tmp)
1548 os.rename(tmp, target)
1548 os.rename(tmp, target)
1549 else:
1549 else:
1550 # Preserve stat info on renames, not on copies; this matches
1550 # Preserve stat info on renames, not on copies; this matches
1551 # Linux CLI behavior.
1551 # Linux CLI behavior.
1552 util.copyfile(src, target, copystat=rename)
1552 util.copyfile(src, target, copystat=rename)
1553 srcexists = True
1553 srcexists = True
1554 except IOError as inst:
1554 except IOError as inst:
1555 if inst.errno == errno.ENOENT:
1555 if inst.errno == errno.ENOENT:
1556 ui.warn(_(b'%s: deleted in working directory\n') % relsrc)
1556 ui.warn(_(b'%s: deleted in working directory\n') % relsrc)
1557 srcexists = False
1557 srcexists = False
1558 else:
1558 else:
1559 ui.warn(
1559 ui.warn(
1560 _(b'%s: cannot copy - %s\n')
1560 _(b'%s: cannot copy - %s\n')
1561 % (relsrc, encoding.strtolocal(inst.strerror))
1561 % (relsrc, encoding.strtolocal(inst.strerror))
1562 )
1562 )
1563 return True # report a failure
1563 return True # report a failure
1564
1564
1565 if ui.verbose or not exact:
1565 if ui.verbose or not exact:
1566 if rename:
1566 if rename:
1567 ui.status(_(b'moving %s to %s\n') % (relsrc, reltarget))
1567 ui.status(_(b'moving %s to %s\n') % (relsrc, reltarget))
1568 else:
1568 else:
1569 ui.status(_(b'copying %s to %s\n') % (relsrc, reltarget))
1569 ui.status(_(b'copying %s to %s\n') % (relsrc, reltarget))
1570
1570
1571 targets[abstarget] = abssrc
1571 targets[abstarget] = abssrc
1572
1572
1573 # fix up dirstate
1573 # fix up dirstate
1574 scmutil.dirstatecopy(
1574 scmutil.dirstatecopy(
1575 ui, repo, wctx, abssrc, abstarget, dryrun=dryrun, cwd=cwd
1575 ui, repo, wctx, abssrc, abstarget, dryrun=dryrun, cwd=cwd
1576 )
1576 )
1577 if rename and not dryrun:
1577 if rename and not dryrun:
1578 if not after and srcexists and not samefile:
1578 if not after and srcexists and not samefile:
1579 rmdir = repo.ui.configbool(b'experimental', b'removeemptydirs')
1579 rmdir = repo.ui.configbool(b'experimental', b'removeemptydirs')
1580 repo.wvfs.unlinkpath(abssrc, rmdir=rmdir)
1580 repo.wvfs.unlinkpath(abssrc, rmdir=rmdir)
1581 wctx.forget([abssrc])
1581 wctx.forget([abssrc])
1582
1582
1583 # pat: ossep
1583 # pat: ossep
1584 # dest ossep
1584 # dest ossep
1585 # srcs: list of (hgsep, hgsep, ossep, bool)
1585 # srcs: list of (hgsep, hgsep, ossep, bool)
1586 # return: function that takes hgsep and returns ossep
1586 # return: function that takes hgsep and returns ossep
1587 def targetpathfn(pat, dest, srcs):
1587 def targetpathfn(pat, dest, srcs):
1588 if os.path.isdir(pat):
1588 if os.path.isdir(pat):
1589 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1589 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1590 abspfx = util.localpath(abspfx)
1590 abspfx = util.localpath(abspfx)
1591 if destdirexists:
1591 if destdirexists:
1592 striplen = len(os.path.split(abspfx)[0])
1592 striplen = len(os.path.split(abspfx)[0])
1593 else:
1593 else:
1594 striplen = len(abspfx)
1594 striplen = len(abspfx)
1595 if striplen:
1595 if striplen:
1596 striplen += len(pycompat.ossep)
1596 striplen += len(pycompat.ossep)
1597 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1597 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1598 elif destdirexists:
1598 elif destdirexists:
1599 res = lambda p: os.path.join(
1599 res = lambda p: os.path.join(
1600 dest, os.path.basename(util.localpath(p))
1600 dest, os.path.basename(util.localpath(p))
1601 )
1601 )
1602 else:
1602 else:
1603 res = lambda p: dest
1603 res = lambda p: dest
1604 return res
1604 return res
1605
1605
1606 # pat: ossep
1606 # pat: ossep
1607 # dest ossep
1607 # dest ossep
1608 # srcs: list of (hgsep, hgsep, ossep, bool)
1608 # srcs: list of (hgsep, hgsep, ossep, bool)
1609 # return: function that takes hgsep and returns ossep
1609 # return: function that takes hgsep and returns ossep
1610 def targetpathafterfn(pat, dest, srcs):
1610 def targetpathafterfn(pat, dest, srcs):
1611 if matchmod.patkind(pat):
1611 if matchmod.patkind(pat):
1612 # a mercurial pattern
1612 # a mercurial pattern
1613 res = lambda p: os.path.join(
1613 res = lambda p: os.path.join(
1614 dest, os.path.basename(util.localpath(p))
1614 dest, os.path.basename(util.localpath(p))
1615 )
1615 )
1616 else:
1616 else:
1617 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1617 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1618 if len(abspfx) < len(srcs[0][0]):
1618 if len(abspfx) < len(srcs[0][0]):
1619 # A directory. Either the target path contains the last
1619 # A directory. Either the target path contains the last
1620 # component of the source path or it does not.
1620 # component of the source path or it does not.
1621 def evalpath(striplen):
1621 def evalpath(striplen):
1622 score = 0
1622 score = 0
1623 for s in srcs:
1623 for s in srcs:
1624 t = os.path.join(dest, util.localpath(s[0])[striplen:])
1624 t = os.path.join(dest, util.localpath(s[0])[striplen:])
1625 if os.path.lexists(t):
1625 if os.path.lexists(t):
1626 score += 1
1626 score += 1
1627 return score
1627 return score
1628
1628
1629 abspfx = util.localpath(abspfx)
1629 abspfx = util.localpath(abspfx)
1630 striplen = len(abspfx)
1630 striplen = len(abspfx)
1631 if striplen:
1631 if striplen:
1632 striplen += len(pycompat.ossep)
1632 striplen += len(pycompat.ossep)
1633 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1633 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1634 score = evalpath(striplen)
1634 score = evalpath(striplen)
1635 striplen1 = len(os.path.split(abspfx)[0])
1635 striplen1 = len(os.path.split(abspfx)[0])
1636 if striplen1:
1636 if striplen1:
1637 striplen1 += len(pycompat.ossep)
1637 striplen1 += len(pycompat.ossep)
1638 if evalpath(striplen1) > score:
1638 if evalpath(striplen1) > score:
1639 striplen = striplen1
1639 striplen = striplen1
1640 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1640 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1641 else:
1641 else:
1642 # a file
1642 # a file
1643 if destdirexists:
1643 if destdirexists:
1644 res = lambda p: os.path.join(
1644 res = lambda p: os.path.join(
1645 dest, os.path.basename(util.localpath(p))
1645 dest, os.path.basename(util.localpath(p))
1646 )
1646 )
1647 else:
1647 else:
1648 res = lambda p: dest
1648 res = lambda p: dest
1649 return res
1649 return res
1650
1650
1651 pats = scmutil.expandpats(pats)
1651 pats = scmutil.expandpats(pats)
1652 if not pats:
1652 if not pats:
1653 raise error.Abort(_(b'no source or destination specified'))
1653 raise error.Abort(_(b'no source or destination specified'))
1654 if len(pats) == 1:
1654 if len(pats) == 1:
1655 raise error.Abort(_(b'no destination specified'))
1655 raise error.Abort(_(b'no destination specified'))
1656 dest = pats.pop()
1656 dest = pats.pop()
1657 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
1657 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
1658 if not destdirexists:
1658 if not destdirexists:
1659 if len(pats) > 1 or matchmod.patkind(pats[0]):
1659 if len(pats) > 1 or matchmod.patkind(pats[0]):
1660 raise error.Abort(
1660 raise error.Abort(
1661 _(
1661 _(
1662 b'with multiple sources, destination must be an '
1662 b'with multiple sources, destination must be an '
1663 b'existing directory'
1663 b'existing directory'
1664 )
1664 )
1665 )
1665 )
1666 if util.endswithsep(dest):
1666 if util.endswithsep(dest):
1667 raise error.Abort(_(b'destination %s is not a directory') % dest)
1667 raise error.Abort(_(b'destination %s is not a directory') % dest)
1668
1668
1669 tfn = targetpathfn
1669 tfn = targetpathfn
1670 if after:
1670 if after:
1671 tfn = targetpathafterfn
1671 tfn = targetpathafterfn
1672 copylist = []
1672 copylist = []
1673 for pat in pats:
1673 for pat in pats:
1674 srcs = walkpat(pat)
1674 srcs = walkpat(pat)
1675 if not srcs:
1675 if not srcs:
1676 continue
1676 continue
1677 copylist.append((tfn(pat, dest, srcs), srcs))
1677 copylist.append((tfn(pat, dest, srcs), srcs))
1678 if not copylist:
1678 if not copylist:
1679 raise error.Abort(_(b'no files to copy'))
1679 raise error.Abort(_(b'no files to copy'))
1680
1680
1681 errors = 0
1681 errors = 0
1682 for targetpath, srcs in copylist:
1682 for targetpath, srcs in copylist:
1683 for abssrc, relsrc, exact in srcs:
1683 for abssrc, relsrc, exact in srcs:
1684 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
1684 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
1685 errors += 1
1685 errors += 1
1686
1686
1687 return errors != 0
1687 return errors != 0
1688
1688
1689
1689
1690 ## facility to let extension process additional data into an import patch
1690 ## facility to let extension process additional data into an import patch
1691 # list of identifier to be executed in order
1691 # list of identifier to be executed in order
1692 extrapreimport = [] # run before commit
1692 extrapreimport = [] # run before commit
1693 extrapostimport = [] # run after commit
1693 extrapostimport = [] # run after commit
1694 # mapping from identifier to actual import function
1694 # mapping from identifier to actual import function
1695 #
1695 #
1696 # 'preimport' are run before the commit is made and are provided the following
1696 # 'preimport' are run before the commit is made and are provided the following
1697 # arguments:
1697 # arguments:
1698 # - repo: the localrepository instance,
1698 # - repo: the localrepository instance,
1699 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
1699 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
1700 # - extra: the future extra dictionary of the changeset, please mutate it,
1700 # - extra: the future extra dictionary of the changeset, please mutate it,
1701 # - opts: the import options.
1701 # - opts: the import options.
1702 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
1702 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
1703 # mutation of in memory commit and more. Feel free to rework the code to get
1703 # mutation of in memory commit and more. Feel free to rework the code to get
1704 # there.
1704 # there.
1705 extrapreimportmap = {}
1705 extrapreimportmap = {}
1706 # 'postimport' are run after the commit is made and are provided the following
1706 # 'postimport' are run after the commit is made and are provided the following
1707 # argument:
1707 # argument:
1708 # - ctx: the changectx created by import.
1708 # - ctx: the changectx created by import.
1709 extrapostimportmap = {}
1709 extrapostimportmap = {}
1710
1710
1711
1711
1712 def tryimportone(ui, repo, patchdata, parents, opts, msgs, updatefunc):
1712 def tryimportone(ui, repo, patchdata, parents, opts, msgs, updatefunc):
1713 """Utility function used by commands.import to import a single patch
1713 """Utility function used by commands.import to import a single patch
1714
1714
1715 This function is explicitly defined here to help the evolve extension to
1715 This function is explicitly defined here to help the evolve extension to
1716 wrap this part of the import logic.
1716 wrap this part of the import logic.
1717
1717
1718 The API is currently a bit ugly because it a simple code translation from
1718 The API is currently a bit ugly because it a simple code translation from
1719 the import command. Feel free to make it better.
1719 the import command. Feel free to make it better.
1720
1720
1721 :patchdata: a dictionary containing parsed patch data (such as from
1721 :patchdata: a dictionary containing parsed patch data (such as from
1722 ``patch.extract()``)
1722 ``patch.extract()``)
1723 :parents: nodes that will be parent of the created commit
1723 :parents: nodes that will be parent of the created commit
1724 :opts: the full dict of option passed to the import command
1724 :opts: the full dict of option passed to the import command
1725 :msgs: list to save commit message to.
1725 :msgs: list to save commit message to.
1726 (used in case we need to save it when failing)
1726 (used in case we need to save it when failing)
1727 :updatefunc: a function that update a repo to a given node
1727 :updatefunc: a function that update a repo to a given node
1728 updatefunc(<repo>, <node>)
1728 updatefunc(<repo>, <node>)
1729 """
1729 """
1730 # avoid cycle context -> subrepo -> cmdutil
1730 # avoid cycle context -> subrepo -> cmdutil
1731 from . import context
1731 from . import context
1732
1732
1733 tmpname = patchdata.get(b'filename')
1733 tmpname = patchdata.get(b'filename')
1734 message = patchdata.get(b'message')
1734 message = patchdata.get(b'message')
1735 user = opts.get(b'user') or patchdata.get(b'user')
1735 user = opts.get(b'user') or patchdata.get(b'user')
1736 date = opts.get(b'date') or patchdata.get(b'date')
1736 date = opts.get(b'date') or patchdata.get(b'date')
1737 branch = patchdata.get(b'branch')
1737 branch = patchdata.get(b'branch')
1738 nodeid = patchdata.get(b'nodeid')
1738 nodeid = patchdata.get(b'nodeid')
1739 p1 = patchdata.get(b'p1')
1739 p1 = patchdata.get(b'p1')
1740 p2 = patchdata.get(b'p2')
1740 p2 = patchdata.get(b'p2')
1741
1741
1742 nocommit = opts.get(b'no_commit')
1742 nocommit = opts.get(b'no_commit')
1743 importbranch = opts.get(b'import_branch')
1743 importbranch = opts.get(b'import_branch')
1744 update = not opts.get(b'bypass')
1744 update = not opts.get(b'bypass')
1745 strip = opts[b"strip"]
1745 strip = opts[b"strip"]
1746 prefix = opts[b"prefix"]
1746 prefix = opts[b"prefix"]
1747 sim = float(opts.get(b'similarity') or 0)
1747 sim = float(opts.get(b'similarity') or 0)
1748
1748
1749 if not tmpname:
1749 if not tmpname:
1750 return None, None, False
1750 return None, None, False
1751
1751
1752 rejects = False
1752 rejects = False
1753
1753
1754 cmdline_message = logmessage(ui, opts)
1754 cmdline_message = logmessage(ui, opts)
1755 if cmdline_message:
1755 if cmdline_message:
1756 # pickup the cmdline msg
1756 # pickup the cmdline msg
1757 message = cmdline_message
1757 message = cmdline_message
1758 elif message:
1758 elif message:
1759 # pickup the patch msg
1759 # pickup the patch msg
1760 message = message.strip()
1760 message = message.strip()
1761 else:
1761 else:
1762 # launch the editor
1762 # launch the editor
1763 message = None
1763 message = None
1764 ui.debug(b'message:\n%s\n' % (message or b''))
1764 ui.debug(b'message:\n%s\n' % (message or b''))
1765
1765
1766 if len(parents) == 1:
1766 if len(parents) == 1:
1767 parents.append(repo[nullid])
1767 parents.append(repo[nullid])
1768 if opts.get(b'exact'):
1768 if opts.get(b'exact'):
1769 if not nodeid or not p1:
1769 if not nodeid or not p1:
1770 raise error.Abort(_(b'not a Mercurial patch'))
1770 raise error.Abort(_(b'not a Mercurial patch'))
1771 p1 = repo[p1]
1771 p1 = repo[p1]
1772 p2 = repo[p2 or nullid]
1772 p2 = repo[p2 or nullid]
1773 elif p2:
1773 elif p2:
1774 try:
1774 try:
1775 p1 = repo[p1]
1775 p1 = repo[p1]
1776 p2 = repo[p2]
1776 p2 = repo[p2]
1777 # Without any options, consider p2 only if the
1777 # Without any options, consider p2 only if the
1778 # patch is being applied on top of the recorded
1778 # patch is being applied on top of the recorded
1779 # first parent.
1779 # first parent.
1780 if p1 != parents[0]:
1780 if p1 != parents[0]:
1781 p1 = parents[0]
1781 p1 = parents[0]
1782 p2 = repo[nullid]
1782 p2 = repo[nullid]
1783 except error.RepoError:
1783 except error.RepoError:
1784 p1, p2 = parents
1784 p1, p2 = parents
1785 if p2.node() == nullid:
1785 if p2.node() == nullid:
1786 ui.warn(
1786 ui.warn(
1787 _(
1787 _(
1788 b"warning: import the patch as a normal revision\n"
1788 b"warning: import the patch as a normal revision\n"
1789 b"(use --exact to import the patch as a merge)\n"
1789 b"(use --exact to import the patch as a merge)\n"
1790 )
1790 )
1791 )
1791 )
1792 else:
1792 else:
1793 p1, p2 = parents
1793 p1, p2 = parents
1794
1794
1795 n = None
1795 n = None
1796 if update:
1796 if update:
1797 if p1 != parents[0]:
1797 if p1 != parents[0]:
1798 updatefunc(repo, p1.node())
1798 updatefunc(repo, p1.node())
1799 if p2 != parents[1]:
1799 if p2 != parents[1]:
1800 repo.setparents(p1.node(), p2.node())
1800 repo.setparents(p1.node(), p2.node())
1801
1801
1802 if opts.get(b'exact') or importbranch:
1802 if opts.get(b'exact') or importbranch:
1803 repo.dirstate.setbranch(branch or b'default')
1803 repo.dirstate.setbranch(branch or b'default')
1804
1804
1805 partial = opts.get(b'partial', False)
1805 partial = opts.get(b'partial', False)
1806 files = set()
1806 files = set()
1807 try:
1807 try:
1808 patch.patch(
1808 patch.patch(
1809 ui,
1809 ui,
1810 repo,
1810 repo,
1811 tmpname,
1811 tmpname,
1812 strip=strip,
1812 strip=strip,
1813 prefix=prefix,
1813 prefix=prefix,
1814 files=files,
1814 files=files,
1815 eolmode=None,
1815 eolmode=None,
1816 similarity=sim / 100.0,
1816 similarity=sim / 100.0,
1817 )
1817 )
1818 except error.PatchError as e:
1818 except error.PatchError as e:
1819 if not partial:
1819 if not partial:
1820 raise error.Abort(pycompat.bytestr(e))
1820 raise error.Abort(pycompat.bytestr(e))
1821 if partial:
1821 if partial:
1822 rejects = True
1822 rejects = True
1823
1823
1824 files = list(files)
1824 files = list(files)
1825 if nocommit:
1825 if nocommit:
1826 if message:
1826 if message:
1827 msgs.append(message)
1827 msgs.append(message)
1828 else:
1828 else:
1829 if opts.get(b'exact') or p2:
1829 if opts.get(b'exact') or p2:
1830 # If you got here, you either use --force and know what
1830 # If you got here, you either use --force and know what
1831 # you are doing or used --exact or a merge patch while
1831 # you are doing or used --exact or a merge patch while
1832 # being updated to its first parent.
1832 # being updated to its first parent.
1833 m = None
1833 m = None
1834 else:
1834 else:
1835 m = scmutil.matchfiles(repo, files or [])
1835 m = scmutil.matchfiles(repo, files or [])
1836 editform = mergeeditform(repo[None], b'import.normal')
1836 editform = mergeeditform(repo[None], b'import.normal')
1837 if opts.get(b'exact'):
1837 if opts.get(b'exact'):
1838 editor = None
1838 editor = None
1839 else:
1839 else:
1840 editor = getcommiteditor(
1840 editor = getcommiteditor(
1841 editform=editform, **pycompat.strkwargs(opts)
1841 editform=editform, **pycompat.strkwargs(opts)
1842 )
1842 )
1843 extra = {}
1843 extra = {}
1844 for idfunc in extrapreimport:
1844 for idfunc in extrapreimport:
1845 extrapreimportmap[idfunc](repo, patchdata, extra, opts)
1845 extrapreimportmap[idfunc](repo, patchdata, extra, opts)
1846 overrides = {}
1846 overrides = {}
1847 if partial:
1847 if partial:
1848 overrides[(b'ui', b'allowemptycommit')] = True
1848 overrides[(b'ui', b'allowemptycommit')] = True
1849 if opts.get(b'secret'):
1849 if opts.get(b'secret'):
1850 overrides[(b'phases', b'new-commit')] = b'secret'
1850 overrides[(b'phases', b'new-commit')] = b'secret'
1851 with repo.ui.configoverride(overrides, b'import'):
1851 with repo.ui.configoverride(overrides, b'import'):
1852 n = repo.commit(
1852 n = repo.commit(
1853 message, user, date, match=m, editor=editor, extra=extra
1853 message, user, date, match=m, editor=editor, extra=extra
1854 )
1854 )
1855 for idfunc in extrapostimport:
1855 for idfunc in extrapostimport:
1856 extrapostimportmap[idfunc](repo[n])
1856 extrapostimportmap[idfunc](repo[n])
1857 else:
1857 else:
1858 if opts.get(b'exact') or importbranch:
1858 if opts.get(b'exact') or importbranch:
1859 branch = branch or b'default'
1859 branch = branch or b'default'
1860 else:
1860 else:
1861 branch = p1.branch()
1861 branch = p1.branch()
1862 store = patch.filestore()
1862 store = patch.filestore()
1863 try:
1863 try:
1864 files = set()
1864 files = set()
1865 try:
1865 try:
1866 patch.patchrepo(
1866 patch.patchrepo(
1867 ui,
1867 ui,
1868 repo,
1868 repo,
1869 p1,
1869 p1,
1870 store,
1870 store,
1871 tmpname,
1871 tmpname,
1872 strip,
1872 strip,
1873 prefix,
1873 prefix,
1874 files,
1874 files,
1875 eolmode=None,
1875 eolmode=None,
1876 )
1876 )
1877 except error.PatchError as e:
1877 except error.PatchError as e:
1878 raise error.Abort(stringutil.forcebytestr(e))
1878 raise error.Abort(stringutil.forcebytestr(e))
1879 if opts.get(b'exact'):
1879 if opts.get(b'exact'):
1880 editor = None
1880 editor = None
1881 else:
1881 else:
1882 editor = getcommiteditor(editform=b'import.bypass')
1882 editor = getcommiteditor(editform=b'import.bypass')
1883 memctx = context.memctx(
1883 memctx = context.memctx(
1884 repo,
1884 repo,
1885 (p1.node(), p2.node()),
1885 (p1.node(), p2.node()),
1886 message,
1886 message,
1887 files=files,
1887 files=files,
1888 filectxfn=store,
1888 filectxfn=store,
1889 user=user,
1889 user=user,
1890 date=date,
1890 date=date,
1891 branch=branch,
1891 branch=branch,
1892 editor=editor,
1892 editor=editor,
1893 )
1893 )
1894 n = memctx.commit()
1894 n = memctx.commit()
1895 finally:
1895 finally:
1896 store.close()
1896 store.close()
1897 if opts.get(b'exact') and nocommit:
1897 if opts.get(b'exact') and nocommit:
1898 # --exact with --no-commit is still useful in that it does merge
1898 # --exact with --no-commit is still useful in that it does merge
1899 # and branch bits
1899 # and branch bits
1900 ui.warn(_(b"warning: can't check exact import with --no-commit\n"))
1900 ui.warn(_(b"warning: can't check exact import with --no-commit\n"))
1901 elif opts.get(b'exact') and (not n or hex(n) != nodeid):
1901 elif opts.get(b'exact') and (not n or hex(n) != nodeid):
1902 raise error.Abort(_(b'patch is damaged or loses information'))
1902 raise error.Abort(_(b'patch is damaged or loses information'))
1903 msg = _(b'applied to working directory')
1903 msg = _(b'applied to working directory')
1904 if n:
1904 if n:
1905 # i18n: refers to a short changeset id
1905 # i18n: refers to a short changeset id
1906 msg = _(b'created %s') % short(n)
1906 msg = _(b'created %s') % short(n)
1907 return msg, n, rejects
1907 return msg, n, rejects
1908
1908
1909
1909
1910 # facility to let extensions include additional data in an exported patch
1910 # facility to let extensions include additional data in an exported patch
1911 # list of identifiers to be executed in order
1911 # list of identifiers to be executed in order
1912 extraexport = []
1912 extraexport = []
1913 # mapping from identifier to actual export function
1913 # mapping from identifier to actual export function
1914 # function as to return a string to be added to the header or None
1914 # function as to return a string to be added to the header or None
1915 # it is given two arguments (sequencenumber, changectx)
1915 # it is given two arguments (sequencenumber, changectx)
1916 extraexportmap = {}
1916 extraexportmap = {}
1917
1917
1918
1918
1919 def _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts):
1919 def _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts):
1920 node = scmutil.binnode(ctx)
1920 node = scmutil.binnode(ctx)
1921 parents = [p.node() for p in ctx.parents() if p]
1921 parents = [p.node() for p in ctx.parents() if p]
1922 branch = ctx.branch()
1922 branch = ctx.branch()
1923 if switch_parent:
1923 if switch_parent:
1924 parents.reverse()
1924 parents.reverse()
1925
1925
1926 if parents:
1926 if parents:
1927 prev = parents[0]
1927 prev = parents[0]
1928 else:
1928 else:
1929 prev = nullid
1929 prev = nullid
1930
1930
1931 fm.context(ctx=ctx)
1931 fm.context(ctx=ctx)
1932 fm.plain(b'# HG changeset patch\n')
1932 fm.plain(b'# HG changeset patch\n')
1933 fm.write(b'user', b'# User %s\n', ctx.user())
1933 fm.write(b'user', b'# User %s\n', ctx.user())
1934 fm.plain(b'# Date %d %d\n' % ctx.date())
1934 fm.plain(b'# Date %d %d\n' % ctx.date())
1935 fm.write(b'date', b'# %s\n', fm.formatdate(ctx.date()))
1935 fm.write(b'date', b'# %s\n', fm.formatdate(ctx.date()))
1936 fm.condwrite(
1936 fm.condwrite(
1937 branch and branch != b'default', b'branch', b'# Branch %s\n', branch
1937 branch and branch != b'default', b'branch', b'# Branch %s\n', branch
1938 )
1938 )
1939 fm.write(b'node', b'# Node ID %s\n', hex(node))
1939 fm.write(b'node', b'# Node ID %s\n', hex(node))
1940 fm.plain(b'# Parent %s\n' % hex(prev))
1940 fm.plain(b'# Parent %s\n' % hex(prev))
1941 if len(parents) > 1:
1941 if len(parents) > 1:
1942 fm.plain(b'# Parent %s\n' % hex(parents[1]))
1942 fm.plain(b'# Parent %s\n' % hex(parents[1]))
1943 fm.data(parents=fm.formatlist(pycompat.maplist(hex, parents), name=b'node'))
1943 fm.data(parents=fm.formatlist(pycompat.maplist(hex, parents), name=b'node'))
1944
1944
1945 # TODO: redesign extraexportmap function to support formatter
1945 # TODO: redesign extraexportmap function to support formatter
1946 for headerid in extraexport:
1946 for headerid in extraexport:
1947 header = extraexportmap[headerid](seqno, ctx)
1947 header = extraexportmap[headerid](seqno, ctx)
1948 if header is not None:
1948 if header is not None:
1949 fm.plain(b'# %s\n' % header)
1949 fm.plain(b'# %s\n' % header)
1950
1950
1951 fm.write(b'desc', b'%s\n', ctx.description().rstrip())
1951 fm.write(b'desc', b'%s\n', ctx.description().rstrip())
1952 fm.plain(b'\n')
1952 fm.plain(b'\n')
1953
1953
1954 if fm.isplain():
1954 if fm.isplain():
1955 chunkiter = patch.diffui(repo, prev, node, match, opts=diffopts)
1955 chunkiter = patch.diffui(repo, prev, node, match, opts=diffopts)
1956 for chunk, label in chunkiter:
1956 for chunk, label in chunkiter:
1957 fm.plain(chunk, label=label)
1957 fm.plain(chunk, label=label)
1958 else:
1958 else:
1959 chunkiter = patch.diff(repo, prev, node, match, opts=diffopts)
1959 chunkiter = patch.diff(repo, prev, node, match, opts=diffopts)
1960 # TODO: make it structured?
1960 # TODO: make it structured?
1961 fm.data(diff=b''.join(chunkiter))
1961 fm.data(diff=b''.join(chunkiter))
1962
1962
1963
1963
1964 def _exportfile(repo, revs, fm, dest, switch_parent, diffopts, match):
1964 def _exportfile(repo, revs, fm, dest, switch_parent, diffopts, match):
1965 """Export changesets to stdout or a single file"""
1965 """Export changesets to stdout or a single file"""
1966 for seqno, rev in enumerate(revs, 1):
1966 for seqno, rev in enumerate(revs, 1):
1967 ctx = repo[rev]
1967 ctx = repo[rev]
1968 if not dest.startswith(b'<'):
1968 if not dest.startswith(b'<'):
1969 repo.ui.note(b"%s\n" % dest)
1969 repo.ui.note(b"%s\n" % dest)
1970 fm.startitem()
1970 fm.startitem()
1971 _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts)
1971 _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts)
1972
1972
1973
1973
1974 def _exportfntemplate(
1974 def _exportfntemplate(
1975 repo, revs, basefm, fntemplate, switch_parent, diffopts, match
1975 repo, revs, basefm, fntemplate, switch_parent, diffopts, match
1976 ):
1976 ):
1977 """Export changesets to possibly multiple files"""
1977 """Export changesets to possibly multiple files"""
1978 total = len(revs)
1978 total = len(revs)
1979 revwidth = max(len(str(rev)) for rev in revs)
1979 revwidth = max(len(str(rev)) for rev in revs)
1980 filemap = util.sortdict() # filename: [(seqno, rev), ...]
1980 filemap = util.sortdict() # filename: [(seqno, rev), ...]
1981
1981
1982 for seqno, rev in enumerate(revs, 1):
1982 for seqno, rev in enumerate(revs, 1):
1983 ctx = repo[rev]
1983 ctx = repo[rev]
1984 dest = makefilename(
1984 dest = makefilename(
1985 ctx, fntemplate, total=total, seqno=seqno, revwidth=revwidth
1985 ctx, fntemplate, total=total, seqno=seqno, revwidth=revwidth
1986 )
1986 )
1987 filemap.setdefault(dest, []).append((seqno, rev))
1987 filemap.setdefault(dest, []).append((seqno, rev))
1988
1988
1989 for dest in filemap:
1989 for dest in filemap:
1990 with formatter.maybereopen(basefm, dest) as fm:
1990 with formatter.maybereopen(basefm, dest) as fm:
1991 repo.ui.note(b"%s\n" % dest)
1991 repo.ui.note(b"%s\n" % dest)
1992 for seqno, rev in filemap[dest]:
1992 for seqno, rev in filemap[dest]:
1993 fm.startitem()
1993 fm.startitem()
1994 ctx = repo[rev]
1994 ctx = repo[rev]
1995 _exportsingle(
1995 _exportsingle(
1996 repo, ctx, fm, match, switch_parent, seqno, diffopts
1996 repo, ctx, fm, match, switch_parent, seqno, diffopts
1997 )
1997 )
1998
1998
1999
1999
2000 def _prefetchchangedfiles(repo, revs, match):
2000 def _prefetchchangedfiles(repo, revs, match):
2001 allfiles = set()
2001 allfiles = set()
2002 for rev in revs:
2002 for rev in revs:
2003 for file in repo[rev].files():
2003 for file in repo[rev].files():
2004 if not match or match(file):
2004 if not match or match(file):
2005 allfiles.add(file)
2005 allfiles.add(file)
2006 scmutil.prefetchfiles(repo, revs, scmutil.matchfiles(repo, allfiles))
2006 scmutil.prefetchfiles(repo, revs, scmutil.matchfiles(repo, allfiles))
2007
2007
2008
2008
2009 def export(
2009 def export(
2010 repo,
2010 repo,
2011 revs,
2011 revs,
2012 basefm,
2012 basefm,
2013 fntemplate=b'hg-%h.patch',
2013 fntemplate=b'hg-%h.patch',
2014 switch_parent=False,
2014 switch_parent=False,
2015 opts=None,
2015 opts=None,
2016 match=None,
2016 match=None,
2017 ):
2017 ):
2018 '''export changesets as hg patches
2018 '''export changesets as hg patches
2019
2019
2020 Args:
2020 Args:
2021 repo: The repository from which we're exporting revisions.
2021 repo: The repository from which we're exporting revisions.
2022 revs: A list of revisions to export as revision numbers.
2022 revs: A list of revisions to export as revision numbers.
2023 basefm: A formatter to which patches should be written.
2023 basefm: A formatter to which patches should be written.
2024 fntemplate: An optional string to use for generating patch file names.
2024 fntemplate: An optional string to use for generating patch file names.
2025 switch_parent: If True, show diffs against second parent when not nullid.
2025 switch_parent: If True, show diffs against second parent when not nullid.
2026 Default is false, which always shows diff against p1.
2026 Default is false, which always shows diff against p1.
2027 opts: diff options to use for generating the patch.
2027 opts: diff options to use for generating the patch.
2028 match: If specified, only export changes to files matching this matcher.
2028 match: If specified, only export changes to files matching this matcher.
2029
2029
2030 Returns:
2030 Returns:
2031 Nothing.
2031 Nothing.
2032
2032
2033 Side Effect:
2033 Side Effect:
2034 "HG Changeset Patch" data is emitted to one of the following
2034 "HG Changeset Patch" data is emitted to one of the following
2035 destinations:
2035 destinations:
2036 fntemplate specified: Each rev is written to a unique file named using
2036 fntemplate specified: Each rev is written to a unique file named using
2037 the given template.
2037 the given template.
2038 Otherwise: All revs will be written to basefm.
2038 Otherwise: All revs will be written to basefm.
2039 '''
2039 '''
2040 _prefetchchangedfiles(repo, revs, match)
2040 _prefetchchangedfiles(repo, revs, match)
2041
2041
2042 if not fntemplate:
2042 if not fntemplate:
2043 _exportfile(
2043 _exportfile(
2044 repo, revs, basefm, b'<unnamed>', switch_parent, opts, match
2044 repo, revs, basefm, b'<unnamed>', switch_parent, opts, match
2045 )
2045 )
2046 else:
2046 else:
2047 _exportfntemplate(
2047 _exportfntemplate(
2048 repo, revs, basefm, fntemplate, switch_parent, opts, match
2048 repo, revs, basefm, fntemplate, switch_parent, opts, match
2049 )
2049 )
2050
2050
2051
2051
2052 def exportfile(repo, revs, fp, switch_parent=False, opts=None, match=None):
2052 def exportfile(repo, revs, fp, switch_parent=False, opts=None, match=None):
2053 """Export changesets to the given file stream"""
2053 """Export changesets to the given file stream"""
2054 _prefetchchangedfiles(repo, revs, match)
2054 _prefetchchangedfiles(repo, revs, match)
2055
2055
2056 dest = getattr(fp, 'name', b'<unnamed>')
2056 dest = getattr(fp, 'name', b'<unnamed>')
2057 with formatter.formatter(repo.ui, fp, b'export', {}) as fm:
2057 with formatter.formatter(repo.ui, fp, b'export', {}) as fm:
2058 _exportfile(repo, revs, fm, dest, switch_parent, opts, match)
2058 _exportfile(repo, revs, fm, dest, switch_parent, opts, match)
2059
2059
2060
2060
2061 def showmarker(fm, marker, index=None):
2061 def showmarker(fm, marker, index=None):
2062 """utility function to display obsolescence marker in a readable way
2062 """utility function to display obsolescence marker in a readable way
2063
2063
2064 To be used by debug function."""
2064 To be used by debug function."""
2065 if index is not None:
2065 if index is not None:
2066 fm.write(b'index', b'%i ', index)
2066 fm.write(b'index', b'%i ', index)
2067 fm.write(b'prednode', b'%s ', hex(marker.prednode()))
2067 fm.write(b'prednode', b'%s ', hex(marker.prednode()))
2068 succs = marker.succnodes()
2068 succs = marker.succnodes()
2069 fm.condwrite(
2069 fm.condwrite(
2070 succs,
2070 succs,
2071 b'succnodes',
2071 b'succnodes',
2072 b'%s ',
2072 b'%s ',
2073 fm.formatlist(map(hex, succs), name=b'node'),
2073 fm.formatlist(map(hex, succs), name=b'node'),
2074 )
2074 )
2075 fm.write(b'flag', b'%X ', marker.flags())
2075 fm.write(b'flag', b'%X ', marker.flags())
2076 parents = marker.parentnodes()
2076 parents = marker.parentnodes()
2077 if parents is not None:
2077 if parents is not None:
2078 fm.write(
2078 fm.write(
2079 b'parentnodes',
2079 b'parentnodes',
2080 b'{%s} ',
2080 b'{%s} ',
2081 fm.formatlist(map(hex, parents), name=b'node', sep=b', '),
2081 fm.formatlist(map(hex, parents), name=b'node', sep=b', '),
2082 )
2082 )
2083 fm.write(b'date', b'(%s) ', fm.formatdate(marker.date()))
2083 fm.write(b'date', b'(%s) ', fm.formatdate(marker.date()))
2084 meta = marker.metadata().copy()
2084 meta = marker.metadata().copy()
2085 meta.pop(b'date', None)
2085 meta.pop(b'date', None)
2086 smeta = pycompat.rapply(pycompat.maybebytestr, meta)
2086 smeta = pycompat.rapply(pycompat.maybebytestr, meta)
2087 fm.write(
2087 fm.write(
2088 b'metadata', b'{%s}', fm.formatdict(smeta, fmt=b'%r: %r', sep=b', ')
2088 b'metadata', b'{%s}', fm.formatdict(smeta, fmt=b'%r: %r', sep=b', ')
2089 )
2089 )
2090 fm.plain(b'\n')
2090 fm.plain(b'\n')
2091
2091
2092
2092
2093 def finddate(ui, repo, date):
2093 def finddate(ui, repo, date):
2094 """Find the tipmost changeset that matches the given date spec"""
2094 """Find the tipmost changeset that matches the given date spec"""
2095
2095
2096 df = dateutil.matchdate(date)
2096 df = dateutil.matchdate(date)
2097 m = scmutil.matchall(repo)
2097 m = scmutil.matchall(repo)
2098 results = {}
2098 results = {}
2099
2099
2100 def prep(ctx, fns):
2100 def prep(ctx, fns):
2101 d = ctx.date()
2101 d = ctx.date()
2102 if df(d[0]):
2102 if df(d[0]):
2103 results[ctx.rev()] = d
2103 results[ctx.rev()] = d
2104
2104
2105 for ctx in walkchangerevs(repo, m, {b'rev': None}, prep):
2105 for ctx in walkchangerevs(repo, m, {b'rev': None}, prep):
2106 rev = ctx.rev()
2106 rev = ctx.rev()
2107 if rev in results:
2107 if rev in results:
2108 ui.status(
2108 ui.status(
2109 _(b"found revision %d from %s\n")
2109 _(b"found revision %d from %s\n")
2110 % (rev, dateutil.datestr(results[rev]))
2110 % (rev, dateutil.datestr(results[rev]))
2111 )
2111 )
2112 return b'%d' % rev
2112 return b'%d' % rev
2113
2113
2114 raise error.Abort(_(b"revision matching date not found"))
2114 raise error.Abort(_(b"revision matching date not found"))
2115
2115
2116
2116
2117 def increasingwindows(windowsize=8, sizelimit=512):
2117 def increasingwindows(windowsize=8, sizelimit=512):
2118 while True:
2118 while True:
2119 yield windowsize
2119 yield windowsize
2120 if windowsize < sizelimit:
2120 if windowsize < sizelimit:
2121 windowsize *= 2
2121 windowsize *= 2
2122
2122
2123
2123
2124 def _walkrevs(repo, opts):
2124 def _walkrevs(repo, opts):
2125 # Default --rev value depends on --follow but --follow behavior
2125 # Default --rev value depends on --follow but --follow behavior
2126 # depends on revisions resolved from --rev...
2126 # depends on revisions resolved from --rev...
2127 follow = opts.get(b'follow') or opts.get(b'follow_first')
2127 follow = opts.get(b'follow') or opts.get(b'follow_first')
2128 if opts.get(b'rev'):
2128 if opts.get(b'rev'):
2129 revs = scmutil.revrange(repo, opts[b'rev'])
2129 revs = scmutil.revrange(repo, opts[b'rev'])
2130 elif follow and repo.dirstate.p1() == nullid:
2130 elif follow and repo.dirstate.p1() == nullid:
2131 revs = smartset.baseset()
2131 revs = smartset.baseset()
2132 elif follow:
2132 elif follow:
2133 revs = repo.revs(b'reverse(:.)')
2133 revs = repo.revs(b'reverse(:.)')
2134 else:
2134 else:
2135 revs = smartset.spanset(repo)
2135 revs = smartset.spanset(repo)
2136 revs.reverse()
2136 revs.reverse()
2137 return revs
2137 return revs
2138
2138
2139
2139
2140 class FileWalkError(Exception):
2140 class FileWalkError(Exception):
2141 pass
2141 pass
2142
2142
2143
2143
2144 def walkfilerevs(repo, match, follow, revs, fncache):
2144 def walkfilerevs(repo, match, follow, revs, fncache):
2145 '''Walks the file history for the matched files.
2145 '''Walks the file history for the matched files.
2146
2146
2147 Returns the changeset revs that are involved in the file history.
2147 Returns the changeset revs that are involved in the file history.
2148
2148
2149 Throws FileWalkError if the file history can't be walked using
2149 Throws FileWalkError if the file history can't be walked using
2150 filelogs alone.
2150 filelogs alone.
2151 '''
2151 '''
2152 wanted = set()
2152 wanted = set()
2153 copies = []
2153 copies = []
2154 minrev, maxrev = min(revs), max(revs)
2154 minrev, maxrev = min(revs), max(revs)
2155
2155
2156 def filerevs(filelog, last):
2156 def filerevs(filelog, last):
2157 """
2157 """
2158 Only files, no patterns. Check the history of each file.
2158 Only files, no patterns. Check the history of each file.
2159
2159
2160 Examines filelog entries within minrev, maxrev linkrev range
2160 Examines filelog entries within minrev, maxrev linkrev range
2161 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
2161 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
2162 tuples in backwards order
2162 tuples in backwards order
2163 """
2163 """
2164 cl_count = len(repo)
2164 cl_count = len(repo)
2165 revs = []
2165 revs = []
2166 for j in pycompat.xrange(0, last + 1):
2166 for j in pycompat.xrange(0, last + 1):
2167 linkrev = filelog.linkrev(j)
2167 linkrev = filelog.linkrev(j)
2168 if linkrev < minrev:
2168 if linkrev < minrev:
2169 continue
2169 continue
2170 # only yield rev for which we have the changelog, it can
2170 # only yield rev for which we have the changelog, it can
2171 # happen while doing "hg log" during a pull or commit
2171 # happen while doing "hg log" during a pull or commit
2172 if linkrev >= cl_count:
2172 if linkrev >= cl_count:
2173 break
2173 break
2174
2174
2175 parentlinkrevs = []
2175 parentlinkrevs = []
2176 for p in filelog.parentrevs(j):
2176 for p in filelog.parentrevs(j):
2177 if p != nullrev:
2177 if p != nullrev:
2178 parentlinkrevs.append(filelog.linkrev(p))
2178 parentlinkrevs.append(filelog.linkrev(p))
2179 n = filelog.node(j)
2179 n = filelog.node(j)
2180 revs.append(
2180 revs.append(
2181 (linkrev, parentlinkrevs, follow and filelog.renamed(n))
2181 (linkrev, parentlinkrevs, follow and filelog.renamed(n))
2182 )
2182 )
2183
2183
2184 return reversed(revs)
2184 return reversed(revs)
2185
2185
2186 def iterfiles():
2186 def iterfiles():
2187 pctx = repo[b'.']
2187 pctx = repo[b'.']
2188 for filename in match.files():
2188 for filename in match.files():
2189 if follow:
2189 if follow:
2190 if filename not in pctx:
2190 if filename not in pctx:
2191 raise error.Abort(
2191 raise error.Abort(
2192 _(
2192 _(
2193 b'cannot follow file not in parent '
2193 b'cannot follow file not in parent '
2194 b'revision: "%s"'
2194 b'revision: "%s"'
2195 )
2195 )
2196 % filename
2196 % filename
2197 )
2197 )
2198 yield filename, pctx[filename].filenode()
2198 yield filename, pctx[filename].filenode()
2199 else:
2199 else:
2200 yield filename, None
2200 yield filename, None
2201 for filename_node in copies:
2201 for filename_node in copies:
2202 yield filename_node
2202 yield filename_node
2203
2203
2204 for file_, node in iterfiles():
2204 for file_, node in iterfiles():
2205 filelog = repo.file(file_)
2205 filelog = repo.file(file_)
2206 if not len(filelog):
2206 if not len(filelog):
2207 if node is None:
2207 if node is None:
2208 # A zero count may be a directory or deleted file, so
2208 # A zero count may be a directory or deleted file, so
2209 # try to find matching entries on the slow path.
2209 # try to find matching entries on the slow path.
2210 if follow:
2210 if follow:
2211 raise error.Abort(
2211 raise error.Abort(
2212 _(b'cannot follow nonexistent file: "%s"') % file_
2212 _(b'cannot follow nonexistent file: "%s"') % file_
2213 )
2213 )
2214 raise FileWalkError(b"Cannot walk via filelog")
2214 raise FileWalkError(b"Cannot walk via filelog")
2215 else:
2215 else:
2216 continue
2216 continue
2217
2217
2218 if node is None:
2218 if node is None:
2219 last = len(filelog) - 1
2219 last = len(filelog) - 1
2220 else:
2220 else:
2221 last = filelog.rev(node)
2221 last = filelog.rev(node)
2222
2222
2223 # keep track of all ancestors of the file
2223 # keep track of all ancestors of the file
2224 ancestors = {filelog.linkrev(last)}
2224 ancestors = {filelog.linkrev(last)}
2225
2225
2226 # iterate from latest to oldest revision
2226 # iterate from latest to oldest revision
2227 for rev, flparentlinkrevs, copied in filerevs(filelog, last):
2227 for rev, flparentlinkrevs, copied in filerevs(filelog, last):
2228 if not follow:
2228 if not follow:
2229 if rev > maxrev:
2229 if rev > maxrev:
2230 continue
2230 continue
2231 else:
2231 else:
2232 # Note that last might not be the first interesting
2232 # Note that last might not be the first interesting
2233 # rev to us:
2233 # rev to us:
2234 # if the file has been changed after maxrev, we'll
2234 # if the file has been changed after maxrev, we'll
2235 # have linkrev(last) > maxrev, and we still need
2235 # have linkrev(last) > maxrev, and we still need
2236 # to explore the file graph
2236 # to explore the file graph
2237 if rev not in ancestors:
2237 if rev not in ancestors:
2238 continue
2238 continue
2239 # XXX insert 1327 fix here
2239 # XXX insert 1327 fix here
2240 if flparentlinkrevs:
2240 if flparentlinkrevs:
2241 ancestors.update(flparentlinkrevs)
2241 ancestors.update(flparentlinkrevs)
2242
2242
2243 fncache.setdefault(rev, []).append(file_)
2243 fncache.setdefault(rev, []).append(file_)
2244 wanted.add(rev)
2244 wanted.add(rev)
2245 if copied:
2245 if copied:
2246 copies.append(copied)
2246 copies.append(copied)
2247
2247
2248 return wanted
2248 return wanted
2249
2249
2250
2250
2251 class _followfilter(object):
2251 class _followfilter(object):
2252 def __init__(self, repo, onlyfirst=False):
2252 def __init__(self, repo, onlyfirst=False):
2253 self.repo = repo
2253 self.repo = repo
2254 self.startrev = nullrev
2254 self.startrev = nullrev
2255 self.roots = set()
2255 self.roots = set()
2256 self.onlyfirst = onlyfirst
2256 self.onlyfirst = onlyfirst
2257
2257
2258 def match(self, rev):
2258 def match(self, rev):
2259 def realparents(rev):
2259 def realparents(rev):
2260 if self.onlyfirst:
2260 if self.onlyfirst:
2261 return self.repo.changelog.parentrevs(rev)[0:1]
2261 return self.repo.changelog.parentrevs(rev)[0:1]
2262 else:
2262 else:
2263 return filter(
2263 return filter(
2264 lambda x: x != nullrev, self.repo.changelog.parentrevs(rev)
2264 lambda x: x != nullrev, self.repo.changelog.parentrevs(rev)
2265 )
2265 )
2266
2266
2267 if self.startrev == nullrev:
2267 if self.startrev == nullrev:
2268 self.startrev = rev
2268 self.startrev = rev
2269 return True
2269 return True
2270
2270
2271 if rev > self.startrev:
2271 if rev > self.startrev:
2272 # forward: all descendants
2272 # forward: all descendants
2273 if not self.roots:
2273 if not self.roots:
2274 self.roots.add(self.startrev)
2274 self.roots.add(self.startrev)
2275 for parent in realparents(rev):
2275 for parent in realparents(rev):
2276 if parent in self.roots:
2276 if parent in self.roots:
2277 self.roots.add(rev)
2277 self.roots.add(rev)
2278 return True
2278 return True
2279 else:
2279 else:
2280 # backwards: all parents
2280 # backwards: all parents
2281 if not self.roots:
2281 if not self.roots:
2282 self.roots.update(realparents(self.startrev))
2282 self.roots.update(realparents(self.startrev))
2283 if rev in self.roots:
2283 if rev in self.roots:
2284 self.roots.remove(rev)
2284 self.roots.remove(rev)
2285 self.roots.update(realparents(rev))
2285 self.roots.update(realparents(rev))
2286 return True
2286 return True
2287
2287
2288 return False
2288 return False
2289
2289
2290
2290
2291 def walkchangerevs(repo, match, opts, prepare):
2291 def walkchangerevs(repo, match, opts, prepare):
2292 '''Iterate over files and the revs in which they changed.
2292 '''Iterate over files and the revs in which they changed.
2293
2293
2294 Callers most commonly need to iterate backwards over the history
2294 Callers most commonly need to iterate backwards over the history
2295 in which they are interested. Doing so has awful (quadratic-looking)
2295 in which they are interested. Doing so has awful (quadratic-looking)
2296 performance, so we use iterators in a "windowed" way.
2296 performance, so we use iterators in a "windowed" way.
2297
2297
2298 We walk a window of revisions in the desired order. Within the
2298 We walk a window of revisions in the desired order. Within the
2299 window, we first walk forwards to gather data, then in the desired
2299 window, we first walk forwards to gather data, then in the desired
2300 order (usually backwards) to display it.
2300 order (usually backwards) to display it.
2301
2301
2302 This function returns an iterator yielding contexts. Before
2302 This function returns an iterator yielding contexts. Before
2303 yielding each context, the iterator will first call the prepare
2303 yielding each context, the iterator will first call the prepare
2304 function on each context in the window in forward order.'''
2304 function on each context in the window in forward order.'''
2305
2305
2306 allfiles = opts.get(b'all_files')
2306 allfiles = opts.get(b'all_files')
2307 follow = opts.get(b'follow') or opts.get(b'follow_first')
2307 follow = opts.get(b'follow') or opts.get(b'follow_first')
2308 revs = _walkrevs(repo, opts)
2308 revs = _walkrevs(repo, opts)
2309 if not revs:
2309 if not revs:
2310 return []
2310 return []
2311 wanted = set()
2311 wanted = set()
2312 slowpath = match.anypats() or (not match.always() and opts.get(b'removed'))
2312 slowpath = match.anypats() or (not match.always() and opts.get(b'removed'))
2313 fncache = {}
2313 fncache = {}
2314 change = repo.__getitem__
2314 change = repo.__getitem__
2315
2315
2316 # First step is to fill wanted, the set of revisions that we want to yield.
2316 # First step is to fill wanted, the set of revisions that we want to yield.
2317 # When it does not induce extra cost, we also fill fncache for revisions in
2317 # When it does not induce extra cost, we also fill fncache for revisions in
2318 # wanted: a cache of filenames that were changed (ctx.files()) and that
2318 # wanted: a cache of filenames that were changed (ctx.files()) and that
2319 # match the file filtering conditions.
2319 # match the file filtering conditions.
2320
2320
2321 if match.always() or allfiles:
2321 if match.always() or allfiles:
2322 # No files, no patterns. Display all revs.
2322 # No files, no patterns. Display all revs.
2323 wanted = revs
2323 wanted = revs
2324 elif not slowpath:
2324 elif not slowpath:
2325 # We only have to read through the filelog to find wanted revisions
2325 # We only have to read through the filelog to find wanted revisions
2326
2326
2327 try:
2327 try:
2328 wanted = walkfilerevs(repo, match, follow, revs, fncache)
2328 wanted = walkfilerevs(repo, match, follow, revs, fncache)
2329 except FileWalkError:
2329 except FileWalkError:
2330 slowpath = True
2330 slowpath = True
2331
2331
2332 # We decided to fall back to the slowpath because at least one
2332 # We decided to fall back to the slowpath because at least one
2333 # of the paths was not a file. Check to see if at least one of them
2333 # of the paths was not a file. Check to see if at least one of them
2334 # existed in history, otherwise simply return
2334 # existed in history, otherwise simply return
2335 for path in match.files():
2335 for path in match.files():
2336 if path == b'.' or path in repo.store:
2336 if path == b'.' or path in repo.store:
2337 break
2337 break
2338 else:
2338 else:
2339 return []
2339 return []
2340
2340
2341 if slowpath:
2341 if slowpath:
2342 # We have to read the changelog to match filenames against
2342 # We have to read the changelog to match filenames against
2343 # changed files
2343 # changed files
2344
2344
2345 if follow:
2345 if follow:
2346 raise error.Abort(
2346 raise error.Abort(
2347 _(b'can only follow copies/renames for explicit filenames')
2347 _(b'can only follow copies/renames for explicit filenames')
2348 )
2348 )
2349
2349
2350 # The slow path checks files modified in every changeset.
2350 # The slow path checks files modified in every changeset.
2351 # This is really slow on large repos, so compute the set lazily.
2351 # This is really slow on large repos, so compute the set lazily.
2352 class lazywantedset(object):
2352 class lazywantedset(object):
2353 def __init__(self):
2353 def __init__(self):
2354 self.set = set()
2354 self.set = set()
2355 self.revs = set(revs)
2355 self.revs = set(revs)
2356
2356
2357 # No need to worry about locality here because it will be accessed
2357 # No need to worry about locality here because it will be accessed
2358 # in the same order as the increasing window below.
2358 # in the same order as the increasing window below.
2359 def __contains__(self, value):
2359 def __contains__(self, value):
2360 if value in self.set:
2360 if value in self.set:
2361 return True
2361 return True
2362 elif not value in self.revs:
2362 elif not value in self.revs:
2363 return False
2363 return False
2364 else:
2364 else:
2365 self.revs.discard(value)
2365 self.revs.discard(value)
2366 ctx = change(value)
2366 ctx = change(value)
2367 if allfiles:
2367 if allfiles:
2368 matches = list(ctx.manifest().walk(match))
2368 matches = list(ctx.manifest().walk(match))
2369 else:
2369 else:
2370 matches = [f for f in ctx.files() if match(f)]
2370 matches = [f for f in ctx.files() if match(f)]
2371 if matches:
2371 if matches:
2372 fncache[value] = matches
2372 fncache[value] = matches
2373 self.set.add(value)
2373 self.set.add(value)
2374 return True
2374 return True
2375 return False
2375 return False
2376
2376
2377 def discard(self, value):
2377 def discard(self, value):
2378 self.revs.discard(value)
2378 self.revs.discard(value)
2379 self.set.discard(value)
2379 self.set.discard(value)
2380
2380
2381 wanted = lazywantedset()
2381 wanted = lazywantedset()
2382
2382
2383 # it might be worthwhile to do this in the iterator if the rev range
2383 # it might be worthwhile to do this in the iterator if the rev range
2384 # is descending and the prune args are all within that range
2384 # is descending and the prune args are all within that range
2385 for rev in opts.get(b'prune', ()):
2385 for rev in opts.get(b'prune', ()):
2386 rev = repo[rev].rev()
2386 rev = repo[rev].rev()
2387 ff = _followfilter(repo)
2387 ff = _followfilter(repo)
2388 stop = min(revs[0], revs[-1])
2388 stop = min(revs[0], revs[-1])
2389 for x in pycompat.xrange(rev, stop - 1, -1):
2389 for x in pycompat.xrange(rev, stop - 1, -1):
2390 if ff.match(x):
2390 if ff.match(x):
2391 wanted = wanted - [x]
2391 wanted = wanted - [x]
2392
2392
2393 # Now that wanted is correctly initialized, we can iterate over the
2393 # Now that wanted is correctly initialized, we can iterate over the
2394 # revision range, yielding only revisions in wanted.
2394 # revision range, yielding only revisions in wanted.
2395 def iterate():
2395 def iterate():
2396 if follow and match.always():
2396 if follow and match.always():
2397 ff = _followfilter(repo, onlyfirst=opts.get(b'follow_first'))
2397 ff = _followfilter(repo, onlyfirst=opts.get(b'follow_first'))
2398
2398
2399 def want(rev):
2399 def want(rev):
2400 return ff.match(rev) and rev in wanted
2400 return ff.match(rev) and rev in wanted
2401
2401
2402 else:
2402 else:
2403
2403
2404 def want(rev):
2404 def want(rev):
2405 return rev in wanted
2405 return rev in wanted
2406
2406
2407 it = iter(revs)
2407 it = iter(revs)
2408 stopiteration = False
2408 stopiteration = False
2409 for windowsize in increasingwindows():
2409 for windowsize in increasingwindows():
2410 nrevs = []
2410 nrevs = []
2411 for i in pycompat.xrange(windowsize):
2411 for i in pycompat.xrange(windowsize):
2412 rev = next(it, None)
2412 rev = next(it, None)
2413 if rev is None:
2413 if rev is None:
2414 stopiteration = True
2414 stopiteration = True
2415 break
2415 break
2416 elif want(rev):
2416 elif want(rev):
2417 nrevs.append(rev)
2417 nrevs.append(rev)
2418 for rev in sorted(nrevs):
2418 for rev in sorted(nrevs):
2419 fns = fncache.get(rev)
2419 fns = fncache.get(rev)
2420 ctx = change(rev)
2420 ctx = change(rev)
2421 if not fns:
2421 if not fns:
2422
2422
2423 def fns_generator():
2423 def fns_generator():
2424 if allfiles:
2424 if allfiles:
2425
2425
2426 def bad(f, msg):
2426 def bad(f, msg):
2427 pass
2427 pass
2428
2428
2429 for f in ctx.matches(matchmod.badmatch(match, bad)):
2429 for f in ctx.matches(matchmod.badmatch(match, bad)):
2430 yield f
2430 yield f
2431 else:
2431 else:
2432 for f in ctx.files():
2432 for f in ctx.files():
2433 if match(f):
2433 if match(f):
2434 yield f
2434 yield f
2435
2435
2436 fns = fns_generator()
2436 fns = fns_generator()
2437 prepare(ctx, fns)
2437 prepare(ctx, fns)
2438 for rev in nrevs:
2438 for rev in nrevs:
2439 yield change(rev)
2439 yield change(rev)
2440
2440
2441 if stopiteration:
2441 if stopiteration:
2442 break
2442 break
2443
2443
2444 return iterate()
2444 return iterate()
2445
2445
2446
2446
2447 def add(ui, repo, match, prefix, uipathfn, explicitonly, **opts):
2447 def add(ui, repo, match, prefix, uipathfn, explicitonly, **opts):
2448 bad = []
2448 bad = []
2449
2449
2450 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2450 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2451 names = []
2451 names = []
2452 wctx = repo[None]
2452 wctx = repo[None]
2453 cca = None
2453 cca = None
2454 abort, warn = scmutil.checkportabilityalert(ui)
2454 abort, warn = scmutil.checkportabilityalert(ui)
2455 if abort or warn:
2455 if abort or warn:
2456 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2456 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2457
2457
2458 match = repo.narrowmatch(match, includeexact=True)
2458 match = repo.narrowmatch(match, includeexact=True)
2459 badmatch = matchmod.badmatch(match, badfn)
2459 badmatch = matchmod.badmatch(match, badfn)
2460 dirstate = repo.dirstate
2460 dirstate = repo.dirstate
2461 # We don't want to just call wctx.walk here, since it would return a lot of
2461 # We don't want to just call wctx.walk here, since it would return a lot of
2462 # clean files, which we aren't interested in and takes time.
2462 # clean files, which we aren't interested in and takes time.
2463 for f in sorted(
2463 for f in sorted(
2464 dirstate.walk(
2464 dirstate.walk(
2465 badmatch,
2465 badmatch,
2466 subrepos=sorted(wctx.substate),
2466 subrepos=sorted(wctx.substate),
2467 unknown=True,
2467 unknown=True,
2468 ignored=False,
2468 ignored=False,
2469 full=False,
2469 full=False,
2470 )
2470 )
2471 ):
2471 ):
2472 exact = match.exact(f)
2472 exact = match.exact(f)
2473 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2473 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2474 if cca:
2474 if cca:
2475 cca(f)
2475 cca(f)
2476 names.append(f)
2476 names.append(f)
2477 if ui.verbose or not exact:
2477 if ui.verbose or not exact:
2478 ui.status(
2478 ui.status(
2479 _(b'adding %s\n') % uipathfn(f), label=b'ui.addremove.added'
2479 _(b'adding %s\n') % uipathfn(f), label=b'ui.addremove.added'
2480 )
2480 )
2481
2481
2482 for subpath in sorted(wctx.substate):
2482 for subpath in sorted(wctx.substate):
2483 sub = wctx.sub(subpath)
2483 sub = wctx.sub(subpath)
2484 try:
2484 try:
2485 submatch = matchmod.subdirmatcher(subpath, match)
2485 submatch = matchmod.subdirmatcher(subpath, match)
2486 subprefix = repo.wvfs.reljoin(prefix, subpath)
2486 subprefix = repo.wvfs.reljoin(prefix, subpath)
2487 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2487 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2488 if opts.get('subrepos'):
2488 if opts.get('subrepos'):
2489 bad.extend(
2489 bad.extend(
2490 sub.add(ui, submatch, subprefix, subuipathfn, False, **opts)
2490 sub.add(ui, submatch, subprefix, subuipathfn, False, **opts)
2491 )
2491 )
2492 else:
2492 else:
2493 bad.extend(
2493 bad.extend(
2494 sub.add(ui, submatch, subprefix, subuipathfn, True, **opts)
2494 sub.add(ui, submatch, subprefix, subuipathfn, True, **opts)
2495 )
2495 )
2496 except error.LookupError:
2496 except error.LookupError:
2497 ui.status(
2497 ui.status(
2498 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2498 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2499 )
2499 )
2500
2500
2501 if not opts.get('dry_run'):
2501 if not opts.get('dry_run'):
2502 rejected = wctx.add(names, prefix)
2502 rejected = wctx.add(names, prefix)
2503 bad.extend(f for f in rejected if f in match.files())
2503 bad.extend(f for f in rejected if f in match.files())
2504 return bad
2504 return bad
2505
2505
2506
2506
2507 def addwebdirpath(repo, serverpath, webconf):
2507 def addwebdirpath(repo, serverpath, webconf):
2508 webconf[serverpath] = repo.root
2508 webconf[serverpath] = repo.root
2509 repo.ui.debug(b'adding %s = %s\n' % (serverpath, repo.root))
2509 repo.ui.debug(b'adding %s = %s\n' % (serverpath, repo.root))
2510
2510
2511 for r in repo.revs(b'filelog("path:.hgsub")'):
2511 for r in repo.revs(b'filelog("path:.hgsub")'):
2512 ctx = repo[r]
2512 ctx = repo[r]
2513 for subpath in ctx.substate:
2513 for subpath in ctx.substate:
2514 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2514 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2515
2515
2516
2516
2517 def forget(
2517 def forget(
2518 ui, repo, match, prefix, uipathfn, explicitonly, dryrun, interactive
2518 ui, repo, match, prefix, uipathfn, explicitonly, dryrun, interactive
2519 ):
2519 ):
2520 if dryrun and interactive:
2520 if dryrun and interactive:
2521 raise error.Abort(_(b"cannot specify both --dry-run and --interactive"))
2521 raise error.Abort(_(b"cannot specify both --dry-run and --interactive"))
2522 bad = []
2522 bad = []
2523 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2523 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2524 wctx = repo[None]
2524 wctx = repo[None]
2525 forgot = []
2525 forgot = []
2526
2526
2527 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2527 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2528 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2528 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2529 if explicitonly:
2529 if explicitonly:
2530 forget = [f for f in forget if match.exact(f)]
2530 forget = [f for f in forget if match.exact(f)]
2531
2531
2532 for subpath in sorted(wctx.substate):
2532 for subpath in sorted(wctx.substate):
2533 sub = wctx.sub(subpath)
2533 sub = wctx.sub(subpath)
2534 submatch = matchmod.subdirmatcher(subpath, match)
2534 submatch = matchmod.subdirmatcher(subpath, match)
2535 subprefix = repo.wvfs.reljoin(prefix, subpath)
2535 subprefix = repo.wvfs.reljoin(prefix, subpath)
2536 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2536 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2537 try:
2537 try:
2538 subbad, subforgot = sub.forget(
2538 subbad, subforgot = sub.forget(
2539 submatch,
2539 submatch,
2540 subprefix,
2540 subprefix,
2541 subuipathfn,
2541 subuipathfn,
2542 dryrun=dryrun,
2542 dryrun=dryrun,
2543 interactive=interactive,
2543 interactive=interactive,
2544 )
2544 )
2545 bad.extend([subpath + b'/' + f for f in subbad])
2545 bad.extend([subpath + b'/' + f for f in subbad])
2546 forgot.extend([subpath + b'/' + f for f in subforgot])
2546 forgot.extend([subpath + b'/' + f for f in subforgot])
2547 except error.LookupError:
2547 except error.LookupError:
2548 ui.status(
2548 ui.status(
2549 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2549 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2550 )
2550 )
2551
2551
2552 if not explicitonly:
2552 if not explicitonly:
2553 for f in match.files():
2553 for f in match.files():
2554 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2554 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2555 if f not in forgot:
2555 if f not in forgot:
2556 if repo.wvfs.exists(f):
2556 if repo.wvfs.exists(f):
2557 # Don't complain if the exact case match wasn't given.
2557 # Don't complain if the exact case match wasn't given.
2558 # But don't do this until after checking 'forgot', so
2558 # But don't do this until after checking 'forgot', so
2559 # that subrepo files aren't normalized, and this op is
2559 # that subrepo files aren't normalized, and this op is
2560 # purely from data cached by the status walk above.
2560 # purely from data cached by the status walk above.
2561 if repo.dirstate.normalize(f) in repo.dirstate:
2561 if repo.dirstate.normalize(f) in repo.dirstate:
2562 continue
2562 continue
2563 ui.warn(
2563 ui.warn(
2564 _(
2564 _(
2565 b'not removing %s: '
2565 b'not removing %s: '
2566 b'file is already untracked\n'
2566 b'file is already untracked\n'
2567 )
2567 )
2568 % uipathfn(f)
2568 % uipathfn(f)
2569 )
2569 )
2570 bad.append(f)
2570 bad.append(f)
2571
2571
2572 if interactive:
2572 if interactive:
2573 responses = _(
2573 responses = _(
2574 b'[Ynsa?]'
2574 b'[Ynsa?]'
2575 b'$$ &Yes, forget this file'
2575 b'$$ &Yes, forget this file'
2576 b'$$ &No, skip this file'
2576 b'$$ &No, skip this file'
2577 b'$$ &Skip remaining files'
2577 b'$$ &Skip remaining files'
2578 b'$$ Include &all remaining files'
2578 b'$$ Include &all remaining files'
2579 b'$$ &? (display help)'
2579 b'$$ &? (display help)'
2580 )
2580 )
2581 for filename in forget[:]:
2581 for filename in forget[:]:
2582 r = ui.promptchoice(
2582 r = ui.promptchoice(
2583 _(b'forget %s %s') % (uipathfn(filename), responses)
2583 _(b'forget %s %s') % (uipathfn(filename), responses)
2584 )
2584 )
2585 if r == 4: # ?
2585 if r == 4: # ?
2586 while r == 4:
2586 while r == 4:
2587 for c, t in ui.extractchoices(responses)[1]:
2587 for c, t in ui.extractchoices(responses)[1]:
2588 ui.write(b'%s - %s\n' % (c, encoding.lower(t)))
2588 ui.write(b'%s - %s\n' % (c, encoding.lower(t)))
2589 r = ui.promptchoice(
2589 r = ui.promptchoice(
2590 _(b'forget %s %s') % (uipathfn(filename), responses)
2590 _(b'forget %s %s') % (uipathfn(filename), responses)
2591 )
2591 )
2592 if r == 0: # yes
2592 if r == 0: # yes
2593 continue
2593 continue
2594 elif r == 1: # no
2594 elif r == 1: # no
2595 forget.remove(filename)
2595 forget.remove(filename)
2596 elif r == 2: # Skip
2596 elif r == 2: # Skip
2597 fnindex = forget.index(filename)
2597 fnindex = forget.index(filename)
2598 del forget[fnindex:]
2598 del forget[fnindex:]
2599 break
2599 break
2600 elif r == 3: # All
2600 elif r == 3: # All
2601 break
2601 break
2602
2602
2603 for f in forget:
2603 for f in forget:
2604 if ui.verbose or not match.exact(f) or interactive:
2604 if ui.verbose or not match.exact(f) or interactive:
2605 ui.status(
2605 ui.status(
2606 _(b'removing %s\n') % uipathfn(f), label=b'ui.addremove.removed'
2606 _(b'removing %s\n') % uipathfn(f), label=b'ui.addremove.removed'
2607 )
2607 )
2608
2608
2609 if not dryrun:
2609 if not dryrun:
2610 rejected = wctx.forget(forget, prefix)
2610 rejected = wctx.forget(forget, prefix)
2611 bad.extend(f for f in rejected if f in match.files())
2611 bad.extend(f for f in rejected if f in match.files())
2612 forgot.extend(f for f in forget if f not in rejected)
2612 forgot.extend(f for f in forget if f not in rejected)
2613 return bad, forgot
2613 return bad, forgot
2614
2614
2615
2615
2616 def files(ui, ctx, m, uipathfn, fm, fmt, subrepos):
2616 def files(ui, ctx, m, uipathfn, fm, fmt, subrepos):
2617 ret = 1
2617 ret = 1
2618
2618
2619 needsfctx = ui.verbose or {b'size', b'flags'} & fm.datahint()
2619 needsfctx = ui.verbose or {b'size', b'flags'} & fm.datahint()
2620 for f in ctx.matches(m):
2620 for f in ctx.matches(m):
2621 fm.startitem()
2621 fm.startitem()
2622 fm.context(ctx=ctx)
2622 fm.context(ctx=ctx)
2623 if needsfctx:
2623 if needsfctx:
2624 fc = ctx[f]
2624 fc = ctx[f]
2625 fm.write(b'size flags', b'% 10d % 1s ', fc.size(), fc.flags())
2625 fm.write(b'size flags', b'% 10d % 1s ', fc.size(), fc.flags())
2626 fm.data(path=f)
2626 fm.data(path=f)
2627 fm.plain(fmt % uipathfn(f))
2627 fm.plain(fmt % uipathfn(f))
2628 ret = 0
2628 ret = 0
2629
2629
2630 for subpath in sorted(ctx.substate):
2630 for subpath in sorted(ctx.substate):
2631 submatch = matchmod.subdirmatcher(subpath, m)
2631 submatch = matchmod.subdirmatcher(subpath, m)
2632 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2632 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2633 if subrepos or m.exact(subpath) or any(submatch.files()):
2633 if subrepos or m.exact(subpath) or any(submatch.files()):
2634 sub = ctx.sub(subpath)
2634 sub = ctx.sub(subpath)
2635 try:
2635 try:
2636 recurse = m.exact(subpath) or subrepos
2636 recurse = m.exact(subpath) or subrepos
2637 if (
2637 if (
2638 sub.printfiles(ui, submatch, subuipathfn, fm, fmt, recurse)
2638 sub.printfiles(ui, submatch, subuipathfn, fm, fmt, recurse)
2639 == 0
2639 == 0
2640 ):
2640 ):
2641 ret = 0
2641 ret = 0
2642 except error.LookupError:
2642 except error.LookupError:
2643 ui.status(
2643 ui.status(
2644 _(b"skipping missing subrepository: %s\n")
2644 _(b"skipping missing subrepository: %s\n")
2645 % uipathfn(subpath)
2645 % uipathfn(subpath)
2646 )
2646 )
2647
2647
2648 return ret
2648 return ret
2649
2649
2650
2650
2651 def remove(
2651 def remove(
2652 ui, repo, m, prefix, uipathfn, after, force, subrepos, dryrun, warnings=None
2652 ui, repo, m, prefix, uipathfn, after, force, subrepos, dryrun, warnings=None
2653 ):
2653 ):
2654 ret = 0
2654 ret = 0
2655 s = repo.status(match=m, clean=True)
2655 s = repo.status(match=m, clean=True)
2656 modified, added, deleted, clean = s.modified, s.added, s.deleted, s.clean
2656 modified, added, deleted, clean = s.modified, s.added, s.deleted, s.clean
2657
2657
2658 wctx = repo[None]
2658 wctx = repo[None]
2659
2659
2660 if warnings is None:
2660 if warnings is None:
2661 warnings = []
2661 warnings = []
2662 warn = True
2662 warn = True
2663 else:
2663 else:
2664 warn = False
2664 warn = False
2665
2665
2666 subs = sorted(wctx.substate)
2666 subs = sorted(wctx.substate)
2667 progress = ui.makeprogress(
2667 progress = ui.makeprogress(
2668 _(b'searching'), total=len(subs), unit=_(b'subrepos')
2668 _(b'searching'), total=len(subs), unit=_(b'subrepos')
2669 )
2669 )
2670 for subpath in subs:
2670 for subpath in subs:
2671 submatch = matchmod.subdirmatcher(subpath, m)
2671 submatch = matchmod.subdirmatcher(subpath, m)
2672 subprefix = repo.wvfs.reljoin(prefix, subpath)
2672 subprefix = repo.wvfs.reljoin(prefix, subpath)
2673 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2673 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2674 if subrepos or m.exact(subpath) or any(submatch.files()):
2674 if subrepos or m.exact(subpath) or any(submatch.files()):
2675 progress.increment()
2675 progress.increment()
2676 sub = wctx.sub(subpath)
2676 sub = wctx.sub(subpath)
2677 try:
2677 try:
2678 if sub.removefiles(
2678 if sub.removefiles(
2679 submatch,
2679 submatch,
2680 subprefix,
2680 subprefix,
2681 subuipathfn,
2681 subuipathfn,
2682 after,
2682 after,
2683 force,
2683 force,
2684 subrepos,
2684 subrepos,
2685 dryrun,
2685 dryrun,
2686 warnings,
2686 warnings,
2687 ):
2687 ):
2688 ret = 1
2688 ret = 1
2689 except error.LookupError:
2689 except error.LookupError:
2690 warnings.append(
2690 warnings.append(
2691 _(b"skipping missing subrepository: %s\n")
2691 _(b"skipping missing subrepository: %s\n")
2692 % uipathfn(subpath)
2692 % uipathfn(subpath)
2693 )
2693 )
2694 progress.complete()
2694 progress.complete()
2695
2695
2696 # warn about failure to delete explicit files/dirs
2696 # warn about failure to delete explicit files/dirs
2697 deleteddirs = pathutil.dirs(deleted)
2697 deleteddirs = pathutil.dirs(deleted)
2698 files = m.files()
2698 files = m.files()
2699 progress = ui.makeprogress(
2699 progress = ui.makeprogress(
2700 _(b'deleting'), total=len(files), unit=_(b'files')
2700 _(b'deleting'), total=len(files), unit=_(b'files')
2701 )
2701 )
2702 for f in files:
2702 for f in files:
2703
2703
2704 def insubrepo():
2704 def insubrepo():
2705 for subpath in wctx.substate:
2705 for subpath in wctx.substate:
2706 if f.startswith(subpath + b'/'):
2706 if f.startswith(subpath + b'/'):
2707 return True
2707 return True
2708 return False
2708 return False
2709
2709
2710 progress.increment()
2710 progress.increment()
2711 isdir = f in deleteddirs or wctx.hasdir(f)
2711 isdir = f in deleteddirs or wctx.hasdir(f)
2712 if f in repo.dirstate or isdir or f == b'.' or insubrepo() or f in subs:
2712 if f in repo.dirstate or isdir or f == b'.' or insubrepo() or f in subs:
2713 continue
2713 continue
2714
2714
2715 if repo.wvfs.exists(f):
2715 if repo.wvfs.exists(f):
2716 if repo.wvfs.isdir(f):
2716 if repo.wvfs.isdir(f):
2717 warnings.append(
2717 warnings.append(
2718 _(b'not removing %s: no tracked files\n') % uipathfn(f)
2718 _(b'not removing %s: no tracked files\n') % uipathfn(f)
2719 )
2719 )
2720 else:
2720 else:
2721 warnings.append(
2721 warnings.append(
2722 _(b'not removing %s: file is untracked\n') % uipathfn(f)
2722 _(b'not removing %s: file is untracked\n') % uipathfn(f)
2723 )
2723 )
2724 # missing files will generate a warning elsewhere
2724 # missing files will generate a warning elsewhere
2725 ret = 1
2725 ret = 1
2726 progress.complete()
2726 progress.complete()
2727
2727
2728 if force:
2728 if force:
2729 list = modified + deleted + clean + added
2729 list = modified + deleted + clean + added
2730 elif after:
2730 elif after:
2731 list = deleted
2731 list = deleted
2732 remaining = modified + added + clean
2732 remaining = modified + added + clean
2733 progress = ui.makeprogress(
2733 progress = ui.makeprogress(
2734 _(b'skipping'), total=len(remaining), unit=_(b'files')
2734 _(b'skipping'), total=len(remaining), unit=_(b'files')
2735 )
2735 )
2736 for f in remaining:
2736 for f in remaining:
2737 progress.increment()
2737 progress.increment()
2738 if ui.verbose or (f in files):
2738 if ui.verbose or (f in files):
2739 warnings.append(
2739 warnings.append(
2740 _(b'not removing %s: file still exists\n') % uipathfn(f)
2740 _(b'not removing %s: file still exists\n') % uipathfn(f)
2741 )
2741 )
2742 ret = 1
2742 ret = 1
2743 progress.complete()
2743 progress.complete()
2744 else:
2744 else:
2745 list = deleted + clean
2745 list = deleted + clean
2746 progress = ui.makeprogress(
2746 progress = ui.makeprogress(
2747 _(b'skipping'), total=(len(modified) + len(added)), unit=_(b'files')
2747 _(b'skipping'), total=(len(modified) + len(added)), unit=_(b'files')
2748 )
2748 )
2749 for f in modified:
2749 for f in modified:
2750 progress.increment()
2750 progress.increment()
2751 warnings.append(
2751 warnings.append(
2752 _(
2752 _(
2753 b'not removing %s: file is modified (use -f'
2753 b'not removing %s: file is modified (use -f'
2754 b' to force removal)\n'
2754 b' to force removal)\n'
2755 )
2755 )
2756 % uipathfn(f)
2756 % uipathfn(f)
2757 )
2757 )
2758 ret = 1
2758 ret = 1
2759 for f in added:
2759 for f in added:
2760 progress.increment()
2760 progress.increment()
2761 warnings.append(
2761 warnings.append(
2762 _(
2762 _(
2763 b"not removing %s: file has been marked for add"
2763 b"not removing %s: file has been marked for add"
2764 b" (use 'hg forget' to undo add)\n"
2764 b" (use 'hg forget' to undo add)\n"
2765 )
2765 )
2766 % uipathfn(f)
2766 % uipathfn(f)
2767 )
2767 )
2768 ret = 1
2768 ret = 1
2769 progress.complete()
2769 progress.complete()
2770
2770
2771 list = sorted(list)
2771 list = sorted(list)
2772 progress = ui.makeprogress(
2772 progress = ui.makeprogress(
2773 _(b'deleting'), total=len(list), unit=_(b'files')
2773 _(b'deleting'), total=len(list), unit=_(b'files')
2774 )
2774 )
2775 for f in list:
2775 for f in list:
2776 if ui.verbose or not m.exact(f):
2776 if ui.verbose or not m.exact(f):
2777 progress.increment()
2777 progress.increment()
2778 ui.status(
2778 ui.status(
2779 _(b'removing %s\n') % uipathfn(f), label=b'ui.addremove.removed'
2779 _(b'removing %s\n') % uipathfn(f), label=b'ui.addremove.removed'
2780 )
2780 )
2781 progress.complete()
2781 progress.complete()
2782
2782
2783 if not dryrun:
2783 if not dryrun:
2784 with repo.wlock():
2784 with repo.wlock():
2785 if not after:
2785 if not after:
2786 for f in list:
2786 for f in list:
2787 if f in added:
2787 if f in added:
2788 continue # we never unlink added files on remove
2788 continue # we never unlink added files on remove
2789 rmdir = repo.ui.configbool(
2789 rmdir = repo.ui.configbool(
2790 b'experimental', b'removeemptydirs'
2790 b'experimental', b'removeemptydirs'
2791 )
2791 )
2792 repo.wvfs.unlinkpath(f, ignoremissing=True, rmdir=rmdir)
2792 repo.wvfs.unlinkpath(f, ignoremissing=True, rmdir=rmdir)
2793 repo[None].forget(list)
2793 repo[None].forget(list)
2794
2794
2795 if warn:
2795 if warn:
2796 for warning in warnings:
2796 for warning in warnings:
2797 ui.warn(warning)
2797 ui.warn(warning)
2798
2798
2799 return ret
2799 return ret
2800
2800
2801
2801
2802 def _catfmtneedsdata(fm):
2802 def _catfmtneedsdata(fm):
2803 return not fm.datahint() or b'data' in fm.datahint()
2803 return not fm.datahint() or b'data' in fm.datahint()
2804
2804
2805
2805
2806 def _updatecatformatter(fm, ctx, matcher, path, decode):
2806 def _updatecatformatter(fm, ctx, matcher, path, decode):
2807 """Hook for adding data to the formatter used by ``hg cat``.
2807 """Hook for adding data to the formatter used by ``hg cat``.
2808
2808
2809 Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call
2809 Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call
2810 this method first."""
2810 this method first."""
2811
2811
2812 # data() can be expensive to fetch (e.g. lfs), so don't fetch it if it
2812 # data() can be expensive to fetch (e.g. lfs), so don't fetch it if it
2813 # wasn't requested.
2813 # wasn't requested.
2814 data = b''
2814 data = b''
2815 if _catfmtneedsdata(fm):
2815 if _catfmtneedsdata(fm):
2816 data = ctx[path].data()
2816 data = ctx[path].data()
2817 if decode:
2817 if decode:
2818 data = ctx.repo().wwritedata(path, data)
2818 data = ctx.repo().wwritedata(path, data)
2819 fm.startitem()
2819 fm.startitem()
2820 fm.context(ctx=ctx)
2820 fm.context(ctx=ctx)
2821 fm.write(b'data', b'%s', data)
2821 fm.write(b'data', b'%s', data)
2822 fm.data(path=path)
2822 fm.data(path=path)
2823
2823
2824
2824
2825 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
2825 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
2826 err = 1
2826 err = 1
2827 opts = pycompat.byteskwargs(opts)
2827 opts = pycompat.byteskwargs(opts)
2828
2828
2829 def write(path):
2829 def write(path):
2830 filename = None
2830 filename = None
2831 if fntemplate:
2831 if fntemplate:
2832 filename = makefilename(
2832 filename = makefilename(
2833 ctx, fntemplate, pathname=os.path.join(prefix, path)
2833 ctx, fntemplate, pathname=os.path.join(prefix, path)
2834 )
2834 )
2835 # attempt to create the directory if it does not already exist
2835 # attempt to create the directory if it does not already exist
2836 try:
2836 try:
2837 os.makedirs(os.path.dirname(filename))
2837 os.makedirs(os.path.dirname(filename))
2838 except OSError:
2838 except OSError:
2839 pass
2839 pass
2840 with formatter.maybereopen(basefm, filename) as fm:
2840 with formatter.maybereopen(basefm, filename) as fm:
2841 _updatecatformatter(fm, ctx, matcher, path, opts.get(b'decode'))
2841 _updatecatformatter(fm, ctx, matcher, path, opts.get(b'decode'))
2842
2842
2843 # Automation often uses hg cat on single files, so special case it
2843 # Automation often uses hg cat on single files, so special case it
2844 # for performance to avoid the cost of parsing the manifest.
2844 # for performance to avoid the cost of parsing the manifest.
2845 if len(matcher.files()) == 1 and not matcher.anypats():
2845 if len(matcher.files()) == 1 and not matcher.anypats():
2846 file = matcher.files()[0]
2846 file = matcher.files()[0]
2847 mfl = repo.manifestlog
2847 mfl = repo.manifestlog
2848 mfnode = ctx.manifestnode()
2848 mfnode = ctx.manifestnode()
2849 try:
2849 try:
2850 if mfnode and mfl[mfnode].find(file)[0]:
2850 if mfnode and mfl[mfnode].find(file)[0]:
2851 if _catfmtneedsdata(basefm):
2851 if _catfmtneedsdata(basefm):
2852 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2852 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2853 write(file)
2853 write(file)
2854 return 0
2854 return 0
2855 except KeyError:
2855 except KeyError:
2856 pass
2856 pass
2857
2857
2858 if _catfmtneedsdata(basefm):
2858 if _catfmtneedsdata(basefm):
2859 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2859 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2860
2860
2861 for abs in ctx.walk(matcher):
2861 for abs in ctx.walk(matcher):
2862 write(abs)
2862 write(abs)
2863 err = 0
2863 err = 0
2864
2864
2865 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
2865 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
2866 for subpath in sorted(ctx.substate):
2866 for subpath in sorted(ctx.substate):
2867 sub = ctx.sub(subpath)
2867 sub = ctx.sub(subpath)
2868 try:
2868 try:
2869 submatch = matchmod.subdirmatcher(subpath, matcher)
2869 submatch = matchmod.subdirmatcher(subpath, matcher)
2870 subprefix = os.path.join(prefix, subpath)
2870 subprefix = os.path.join(prefix, subpath)
2871 if not sub.cat(
2871 if not sub.cat(
2872 submatch,
2872 submatch,
2873 basefm,
2873 basefm,
2874 fntemplate,
2874 fntemplate,
2875 subprefix,
2875 subprefix,
2876 **pycompat.strkwargs(opts)
2876 **pycompat.strkwargs(opts)
2877 ):
2877 ):
2878 err = 0
2878 err = 0
2879 except error.RepoLookupError:
2879 except error.RepoLookupError:
2880 ui.status(
2880 ui.status(
2881 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2881 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2882 )
2882 )
2883
2883
2884 return err
2884 return err
2885
2885
2886
2886
2887 def commit(ui, repo, commitfunc, pats, opts):
2887 def commit(ui, repo, commitfunc, pats, opts):
2888 '''commit the specified files or all outstanding changes'''
2888 '''commit the specified files or all outstanding changes'''
2889 date = opts.get(b'date')
2889 date = opts.get(b'date')
2890 if date:
2890 if date:
2891 opts[b'date'] = dateutil.parsedate(date)
2891 opts[b'date'] = dateutil.parsedate(date)
2892 message = logmessage(ui, opts)
2892 message = logmessage(ui, opts)
2893 matcher = scmutil.match(repo[None], pats, opts)
2893 matcher = scmutil.match(repo[None], pats, opts)
2894
2894
2895 dsguard = None
2895 dsguard = None
2896 # extract addremove carefully -- this function can be called from a command
2896 # extract addremove carefully -- this function can be called from a command
2897 # that doesn't support addremove
2897 # that doesn't support addremove
2898 if opts.get(b'addremove'):
2898 if opts.get(b'addremove'):
2899 dsguard = dirstateguard.dirstateguard(repo, b'commit')
2899 dsguard = dirstateguard.dirstateguard(repo, b'commit')
2900 with dsguard or util.nullcontextmanager():
2900 with dsguard or util.nullcontextmanager():
2901 if dsguard:
2901 if dsguard:
2902 relative = scmutil.anypats(pats, opts)
2902 relative = scmutil.anypats(pats, opts)
2903 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
2903 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
2904 if scmutil.addremove(repo, matcher, b"", uipathfn, opts) != 0:
2904 if scmutil.addremove(repo, matcher, b"", uipathfn, opts) != 0:
2905 raise error.Abort(
2905 raise error.Abort(
2906 _(b"failed to mark all new/missing files as added/removed")
2906 _(b"failed to mark all new/missing files as added/removed")
2907 )
2907 )
2908
2908
2909 return commitfunc(ui, repo, message, matcher, opts)
2909 return commitfunc(ui, repo, message, matcher, opts)
2910
2910
2911
2911
2912 def samefile(f, ctx1, ctx2):
2912 def samefile(f, ctx1, ctx2):
2913 if f in ctx1.manifest():
2913 if f in ctx1.manifest():
2914 a = ctx1.filectx(f)
2914 a = ctx1.filectx(f)
2915 if f in ctx2.manifest():
2915 if f in ctx2.manifest():
2916 b = ctx2.filectx(f)
2916 b = ctx2.filectx(f)
2917 return not a.cmp(b) and a.flags() == b.flags()
2917 return not a.cmp(b) and a.flags() == b.flags()
2918 else:
2918 else:
2919 return False
2919 return False
2920 else:
2920 else:
2921 return f not in ctx2.manifest()
2921 return f not in ctx2.manifest()
2922
2922
2923
2923
2924 def amend(ui, repo, old, extra, pats, opts):
2924 def amend(ui, repo, old, extra, pats, opts):
2925 # avoid cycle context -> subrepo -> cmdutil
2925 # avoid cycle context -> subrepo -> cmdutil
2926 from . import context
2926 from . import context
2927
2927
2928 # amend will reuse the existing user if not specified, but the obsolete
2928 # amend will reuse the existing user if not specified, but the obsolete
2929 # marker creation requires that the current user's name is specified.
2929 # marker creation requires that the current user's name is specified.
2930 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2930 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2931 ui.username() # raise exception if username not set
2931 ui.username() # raise exception if username not set
2932
2932
2933 ui.note(_(b'amending changeset %s\n') % old)
2933 ui.note(_(b'amending changeset %s\n') % old)
2934 base = old.p1()
2934 base = old.p1()
2935
2935
2936 with repo.wlock(), repo.lock(), repo.transaction(b'amend'):
2936 with repo.wlock(), repo.lock(), repo.transaction(b'amend'):
2937 # Participating changesets:
2937 # Participating changesets:
2938 #
2938 #
2939 # wctx o - workingctx that contains changes from working copy
2939 # wctx o - workingctx that contains changes from working copy
2940 # | to go into amending commit
2940 # | to go into amending commit
2941 # |
2941 # |
2942 # old o - changeset to amend
2942 # old o - changeset to amend
2943 # |
2943 # |
2944 # base o - first parent of the changeset to amend
2944 # base o - first parent of the changeset to amend
2945 wctx = repo[None]
2945 wctx = repo[None]
2946
2946
2947 # Copy to avoid mutating input
2947 # Copy to avoid mutating input
2948 extra = extra.copy()
2948 extra = extra.copy()
2949 # Update extra dict from amended commit (e.g. to preserve graft
2949 # Update extra dict from amended commit (e.g. to preserve graft
2950 # source)
2950 # source)
2951 extra.update(old.extra())
2951 extra.update(old.extra())
2952
2952
2953 # Also update it from the from the wctx
2953 # Also update it from the from the wctx
2954 extra.update(wctx.extra())
2954 extra.update(wctx.extra())
2955
2955
2956 # date-only change should be ignored?
2956 # date-only change should be ignored?
2957 datemaydiffer = resolvecommitoptions(ui, opts)
2957 datemaydiffer = resolvecommitoptions(ui, opts)
2958
2958
2959 date = old.date()
2959 date = old.date()
2960 if opts.get(b'date'):
2960 if opts.get(b'date'):
2961 date = dateutil.parsedate(opts.get(b'date'))
2961 date = dateutil.parsedate(opts.get(b'date'))
2962 user = opts.get(b'user') or old.user()
2962 user = opts.get(b'user') or old.user()
2963
2963
2964 if len(old.parents()) > 1:
2964 if len(old.parents()) > 1:
2965 # ctx.files() isn't reliable for merges, so fall back to the
2965 # ctx.files() isn't reliable for merges, so fall back to the
2966 # slower repo.status() method
2966 # slower repo.status() method
2967 st = base.status(old)
2967 st = base.status(old)
2968 files = set(st.modified) | set(st.added) | set(st.removed)
2968 files = set(st.modified) | set(st.added) | set(st.removed)
2969 else:
2969 else:
2970 files = set(old.files())
2970 files = set(old.files())
2971
2971
2972 # add/remove the files to the working copy if the "addremove" option
2972 # add/remove the files to the working copy if the "addremove" option
2973 # was specified.
2973 # was specified.
2974 matcher = scmutil.match(wctx, pats, opts)
2974 matcher = scmutil.match(wctx, pats, opts)
2975 relative = scmutil.anypats(pats, opts)
2975 relative = scmutil.anypats(pats, opts)
2976 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
2976 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
2977 if opts.get(b'addremove') and scmutil.addremove(
2977 if opts.get(b'addremove') and scmutil.addremove(
2978 repo, matcher, b"", uipathfn, opts
2978 repo, matcher, b"", uipathfn, opts
2979 ):
2979 ):
2980 raise error.Abort(
2980 raise error.Abort(
2981 _(b"failed to mark all new/missing files as added/removed")
2981 _(b"failed to mark all new/missing files as added/removed")
2982 )
2982 )
2983
2983
2984 # Check subrepos. This depends on in-place wctx._status update in
2984 # Check subrepos. This depends on in-place wctx._status update in
2985 # subrepo.precommit(). To minimize the risk of this hack, we do
2985 # subrepo.precommit(). To minimize the risk of this hack, we do
2986 # nothing if .hgsub does not exist.
2986 # nothing if .hgsub does not exist.
2987 if b'.hgsub' in wctx or b'.hgsub' in old:
2987 if b'.hgsub' in wctx or b'.hgsub' in old:
2988 subs, commitsubs, newsubstate = subrepoutil.precommit(
2988 subs, commitsubs, newsubstate = subrepoutil.precommit(
2989 ui, wctx, wctx._status, matcher
2989 ui, wctx, wctx._status, matcher
2990 )
2990 )
2991 # amend should abort if commitsubrepos is enabled
2991 # amend should abort if commitsubrepos is enabled
2992 assert not commitsubs
2992 assert not commitsubs
2993 if subs:
2993 if subs:
2994 subrepoutil.writestate(repo, newsubstate)
2994 subrepoutil.writestate(repo, newsubstate)
2995
2995
2996 ms = mergemod.mergestate.read(repo)
2996 ms = mergemod.mergestate.read(repo)
2997 mergeutil.checkunresolved(ms)
2997 mergeutil.checkunresolved(ms)
2998
2998
2999 filestoamend = set(f for f in wctx.files() if matcher(f))
2999 filestoamend = set(f for f in wctx.files() if matcher(f))
3000
3000
3001 changes = len(filestoamend) > 0
3001 changes = len(filestoamend) > 0
3002 if changes:
3002 if changes:
3003 # Recompute copies (avoid recording a -> b -> a)
3003 # Recompute copies (avoid recording a -> b -> a)
3004 copied = copies.pathcopies(base, wctx, matcher)
3004 copied = copies.pathcopies(base, wctx, matcher)
3005 if old.p2:
3005 if old.p2:
3006 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
3006 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
3007
3007
3008 # Prune files which were reverted by the updates: if old
3008 # Prune files which were reverted by the updates: if old
3009 # introduced file X and the file was renamed in the working
3009 # introduced file X and the file was renamed in the working
3010 # copy, then those two files are the same and
3010 # copy, then those two files are the same and
3011 # we can discard X from our list of files. Likewise if X
3011 # we can discard X from our list of files. Likewise if X
3012 # was removed, it's no longer relevant. If X is missing (aka
3012 # was removed, it's no longer relevant. If X is missing (aka
3013 # deleted), old X must be preserved.
3013 # deleted), old X must be preserved.
3014 files.update(filestoamend)
3014 files.update(filestoamend)
3015 files = [
3015 files = [
3016 f
3016 f
3017 for f in files
3017 for f in files
3018 if (f not in filestoamend or not samefile(f, wctx, base))
3018 if (f not in filestoamend or not samefile(f, wctx, base))
3019 ]
3019 ]
3020
3020
3021 def filectxfn(repo, ctx_, path):
3021 def filectxfn(repo, ctx_, path):
3022 try:
3022 try:
3023 # If the file being considered is not amongst the files
3023 # If the file being considered is not amongst the files
3024 # to be amended, we should return the file context from the
3024 # to be amended, we should return the file context from the
3025 # old changeset. This avoids issues when only some files in
3025 # old changeset. This avoids issues when only some files in
3026 # the working copy are being amended but there are also
3026 # the working copy are being amended but there are also
3027 # changes to other files from the old changeset.
3027 # changes to other files from the old changeset.
3028 if path not in filestoamend:
3028 if path not in filestoamend:
3029 return old.filectx(path)
3029 return old.filectx(path)
3030
3030
3031 # Return None for removed files.
3031 # Return None for removed files.
3032 if path in wctx.removed():
3032 if path in wctx.removed():
3033 return None
3033 return None
3034
3034
3035 fctx = wctx[path]
3035 fctx = wctx[path]
3036 flags = fctx.flags()
3036 flags = fctx.flags()
3037 mctx = context.memfilectx(
3037 mctx = context.memfilectx(
3038 repo,
3038 repo,
3039 ctx_,
3039 ctx_,
3040 fctx.path(),
3040 fctx.path(),
3041 fctx.data(),
3041 fctx.data(),
3042 islink=b'l' in flags,
3042 islink=b'l' in flags,
3043 isexec=b'x' in flags,
3043 isexec=b'x' in flags,
3044 copysource=copied.get(path),
3044 copysource=copied.get(path),
3045 )
3045 )
3046 return mctx
3046 return mctx
3047 except KeyError:
3047 except KeyError:
3048 return None
3048 return None
3049
3049
3050 else:
3050 else:
3051 ui.note(_(b'copying changeset %s to %s\n') % (old, base))
3051 ui.note(_(b'copying changeset %s to %s\n') % (old, base))
3052
3052
3053 # Use version of files as in the old cset
3053 # Use version of files as in the old cset
3054 def filectxfn(repo, ctx_, path):
3054 def filectxfn(repo, ctx_, path):
3055 try:
3055 try:
3056 return old.filectx(path)
3056 return old.filectx(path)
3057 except KeyError:
3057 except KeyError:
3058 return None
3058 return None
3059
3059
3060 # See if we got a message from -m or -l, if not, open the editor with
3060 # See if we got a message from -m or -l, if not, open the editor with
3061 # the message of the changeset to amend.
3061 # the message of the changeset to amend.
3062 message = logmessage(ui, opts)
3062 message = logmessage(ui, opts)
3063
3063
3064 editform = mergeeditform(old, b'commit.amend')
3064 editform = mergeeditform(old, b'commit.amend')
3065
3065
3066 if not message:
3066 if not message:
3067 message = old.description()
3067 message = old.description()
3068 # Default if message isn't provided and --edit is not passed is to
3068 # Default if message isn't provided and --edit is not passed is to
3069 # invoke editor, but allow --no-edit. If somehow we don't have any
3069 # invoke editor, but allow --no-edit. If somehow we don't have any
3070 # description, let's always start the editor.
3070 # description, let's always start the editor.
3071 doedit = not message or opts.get(b'edit') in [True, None]
3071 doedit = not message or opts.get(b'edit') in [True, None]
3072 else:
3072 else:
3073 # Default if message is provided is to not invoke editor, but allow
3073 # Default if message is provided is to not invoke editor, but allow
3074 # --edit.
3074 # --edit.
3075 doedit = opts.get(b'edit') is True
3075 doedit = opts.get(b'edit') is True
3076 editor = getcommiteditor(edit=doedit, editform=editform)
3076 editor = getcommiteditor(edit=doedit, editform=editform)
3077
3077
3078 pureextra = extra.copy()
3078 pureextra = extra.copy()
3079 extra[b'amend_source'] = old.hex()
3079 extra[b'amend_source'] = old.hex()
3080
3080
3081 new = context.memctx(
3081 new = context.memctx(
3082 repo,
3082 repo,
3083 parents=[base.node(), old.p2().node()],
3083 parents=[base.node(), old.p2().node()],
3084 text=message,
3084 text=message,
3085 files=files,
3085 files=files,
3086 filectxfn=filectxfn,
3086 filectxfn=filectxfn,
3087 user=user,
3087 user=user,
3088 date=date,
3088 date=date,
3089 extra=extra,
3089 extra=extra,
3090 editor=editor,
3090 editor=editor,
3091 )
3091 )
3092
3092
3093 newdesc = changelog.stripdesc(new.description())
3093 newdesc = changelog.stripdesc(new.description())
3094 if (
3094 if (
3095 (not changes)
3095 (not changes)
3096 and newdesc == old.description()
3096 and newdesc == old.description()
3097 and user == old.user()
3097 and user == old.user()
3098 and (date == old.date() or datemaydiffer)
3098 and (date == old.date() or datemaydiffer)
3099 and pureextra == old.extra()
3099 and pureextra == old.extra()
3100 ):
3100 ):
3101 # nothing changed. continuing here would create a new node
3101 # nothing changed. continuing here would create a new node
3102 # anyway because of the amend_source noise.
3102 # anyway because of the amend_source noise.
3103 #
3103 #
3104 # This not what we expect from amend.
3104 # This not what we expect from amend.
3105 return old.node()
3105 return old.node()
3106
3106
3107 commitphase = None
3107 commitphase = None
3108 if opts.get(b'secret'):
3108 if opts.get(b'secret'):
3109 commitphase = phases.secret
3109 commitphase = phases.secret
3110 newid = repo.commitctx(new)
3110 newid = repo.commitctx(new)
3111
3111
3112 # Reroute the working copy parent to the new changeset
3112 # Reroute the working copy parent to the new changeset
3113 repo.setparents(newid, nullid)
3113 repo.setparents(newid, nullid)
3114 mapping = {old.node(): (newid,)}
3114 mapping = {old.node(): (newid,)}
3115 obsmetadata = None
3115 obsmetadata = None
3116 if opts.get(b'note'):
3116 if opts.get(b'note'):
3117 obsmetadata = {b'note': encoding.fromlocal(opts[b'note'])}
3117 obsmetadata = {b'note': encoding.fromlocal(opts[b'note'])}
3118 backup = ui.configbool(b'rewrite', b'backup-bundle')
3118 backup = ui.configbool(b'rewrite', b'backup-bundle')
3119 scmutil.cleanupnodes(
3119 scmutil.cleanupnodes(
3120 repo,
3120 repo,
3121 mapping,
3121 mapping,
3122 b'amend',
3122 b'amend',
3123 metadata=obsmetadata,
3123 metadata=obsmetadata,
3124 fixphase=True,
3124 fixphase=True,
3125 targetphase=commitphase,
3125 targetphase=commitphase,
3126 backup=backup,
3126 backup=backup,
3127 )
3127 )
3128
3128
3129 # Fixing the dirstate because localrepo.commitctx does not update
3129 # Fixing the dirstate because localrepo.commitctx does not update
3130 # it. This is rather convenient because we did not need to update
3130 # it. This is rather convenient because we did not need to update
3131 # the dirstate for all the files in the new commit which commitctx
3131 # the dirstate for all the files in the new commit which commitctx
3132 # could have done if it updated the dirstate. Now, we can
3132 # could have done if it updated the dirstate. Now, we can
3133 # selectively update the dirstate only for the amended files.
3133 # selectively update the dirstate only for the amended files.
3134 dirstate = repo.dirstate
3134 dirstate = repo.dirstate
3135
3135
3136 # Update the state of the files which were added and modified in the
3136 # Update the state of the files which were added and modified in the
3137 # amend to "normal" in the dirstate. We need to use "normallookup" since
3137 # amend to "normal" in the dirstate. We need to use "normallookup" since
3138 # the files may have changed since the command started; using "normal"
3138 # the files may have changed since the command started; using "normal"
3139 # would mark them as clean but with uncommitted contents.
3139 # would mark them as clean but with uncommitted contents.
3140 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
3140 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
3141 for f in normalfiles:
3141 for f in normalfiles:
3142 dirstate.normallookup(f)
3142 dirstate.normallookup(f)
3143
3143
3144 # Update the state of files which were removed in the amend
3144 # Update the state of files which were removed in the amend
3145 # to "removed" in the dirstate.
3145 # to "removed" in the dirstate.
3146 removedfiles = set(wctx.removed()) & filestoamend
3146 removedfiles = set(wctx.removed()) & filestoamend
3147 for f in removedfiles:
3147 for f in removedfiles:
3148 dirstate.drop(f)
3148 dirstate.drop(f)
3149
3149
3150 return newid
3150 return newid
3151
3151
3152
3152
3153 def commiteditor(repo, ctx, subs, editform=b''):
3153 def commiteditor(repo, ctx, subs, editform=b''):
3154 if ctx.description():
3154 if ctx.description():
3155 return ctx.description()
3155 return ctx.description()
3156 return commitforceeditor(
3156 return commitforceeditor(
3157 repo, ctx, subs, editform=editform, unchangedmessagedetection=True
3157 repo, ctx, subs, editform=editform, unchangedmessagedetection=True
3158 )
3158 )
3159
3159
3160
3160
3161 def commitforceeditor(
3161 def commitforceeditor(
3162 repo,
3162 repo,
3163 ctx,
3163 ctx,
3164 subs,
3164 subs,
3165 finishdesc=None,
3165 finishdesc=None,
3166 extramsg=None,
3166 extramsg=None,
3167 editform=b'',
3167 editform=b'',
3168 unchangedmessagedetection=False,
3168 unchangedmessagedetection=False,
3169 ):
3169 ):
3170 if not extramsg:
3170 if not extramsg:
3171 extramsg = _(b"Leave message empty to abort commit.")
3171 extramsg = _(b"Leave message empty to abort commit.")
3172
3172
3173 forms = [e for e in editform.split(b'.') if e]
3173 forms = [e for e in editform.split(b'.') if e]
3174 forms.insert(0, b'changeset')
3174 forms.insert(0, b'changeset')
3175 templatetext = None
3175 templatetext = None
3176 while forms:
3176 while forms:
3177 ref = b'.'.join(forms)
3177 ref = b'.'.join(forms)
3178 if repo.ui.config(b'committemplate', ref):
3178 if repo.ui.config(b'committemplate', ref):
3179 templatetext = committext = buildcommittemplate(
3179 templatetext = committext = buildcommittemplate(
3180 repo, ctx, subs, extramsg, ref
3180 repo, ctx, subs, extramsg, ref
3181 )
3181 )
3182 break
3182 break
3183 forms.pop()
3183 forms.pop()
3184 else:
3184 else:
3185 committext = buildcommittext(repo, ctx, subs, extramsg)
3185 committext = buildcommittext(repo, ctx, subs, extramsg)
3186
3186
3187 # run editor in the repository root
3187 # run editor in the repository root
3188 olddir = encoding.getcwd()
3188 olddir = encoding.getcwd()
3189 os.chdir(repo.root)
3189 os.chdir(repo.root)
3190
3190
3191 # make in-memory changes visible to external process
3191 # make in-memory changes visible to external process
3192 tr = repo.currenttransaction()
3192 tr = repo.currenttransaction()
3193 repo.dirstate.write(tr)
3193 repo.dirstate.write(tr)
3194 pending = tr and tr.writepending() and repo.root
3194 pending = tr and tr.writepending() and repo.root
3195
3195
3196 editortext = repo.ui.edit(
3196 editortext = repo.ui.edit(
3197 committext,
3197 committext,
3198 ctx.user(),
3198 ctx.user(),
3199 ctx.extra(),
3199 ctx.extra(),
3200 editform=editform,
3200 editform=editform,
3201 pending=pending,
3201 pending=pending,
3202 repopath=repo.path,
3202 repopath=repo.path,
3203 action=b'commit',
3203 action=b'commit',
3204 )
3204 )
3205 text = editortext
3205 text = editortext
3206
3206
3207 # strip away anything below this special string (used for editors that want
3207 # strip away anything below this special string (used for editors that want
3208 # to display the diff)
3208 # to display the diff)
3209 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
3209 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
3210 if stripbelow:
3210 if stripbelow:
3211 text = text[: stripbelow.start()]
3211 text = text[: stripbelow.start()]
3212
3212
3213 text = re.sub(b"(?m)^HG:.*(\n|$)", b"", text)
3213 text = re.sub(b"(?m)^HG:.*(\n|$)", b"", text)
3214 os.chdir(olddir)
3214 os.chdir(olddir)
3215
3215
3216 if finishdesc:
3216 if finishdesc:
3217 text = finishdesc(text)
3217 text = finishdesc(text)
3218 if not text.strip():
3218 if not text.strip():
3219 raise error.Abort(_(b"empty commit message"))
3219 raise error.Abort(_(b"empty commit message"))
3220 if unchangedmessagedetection and editortext == templatetext:
3220 if unchangedmessagedetection and editortext == templatetext:
3221 raise error.Abort(_(b"commit message unchanged"))
3221 raise error.Abort(_(b"commit message unchanged"))
3222
3222
3223 return text
3223 return text
3224
3224
3225
3225
3226 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
3226 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
3227 ui = repo.ui
3227 ui = repo.ui
3228 spec = formatter.templatespec(ref, None, None)
3228 spec = formatter.templatespec(ref, None, None)
3229 t = logcmdutil.changesettemplater(ui, repo, spec)
3229 t = logcmdutil.changesettemplater(ui, repo, spec)
3230 t.t.cache.update(
3230 t.t.cache.update(
3231 (k, templater.unquotestring(v))
3231 (k, templater.unquotestring(v))
3232 for k, v in repo.ui.configitems(b'committemplate')
3232 for k, v in repo.ui.configitems(b'committemplate')
3233 )
3233 )
3234
3234
3235 if not extramsg:
3235 if not extramsg:
3236 extramsg = b'' # ensure that extramsg is string
3236 extramsg = b'' # ensure that extramsg is string
3237
3237
3238 ui.pushbuffer()
3238 ui.pushbuffer()
3239 t.show(ctx, extramsg=extramsg)
3239 t.show(ctx, extramsg=extramsg)
3240 return ui.popbuffer()
3240 return ui.popbuffer()
3241
3241
3242
3242
3243 def hgprefix(msg):
3243 def hgprefix(msg):
3244 return b"\n".join([b"HG: %s" % a for a in msg.split(b"\n") if a])
3244 return b"\n".join([b"HG: %s" % a for a in msg.split(b"\n") if a])
3245
3245
3246
3246
3247 def buildcommittext(repo, ctx, subs, extramsg):
3247 def buildcommittext(repo, ctx, subs, extramsg):
3248 edittext = []
3248 edittext = []
3249 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
3249 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
3250 if ctx.description():
3250 if ctx.description():
3251 edittext.append(ctx.description())
3251 edittext.append(ctx.description())
3252 edittext.append(b"")
3252 edittext.append(b"")
3253 edittext.append(b"") # Empty line between message and comments.
3253 edittext.append(b"") # Empty line between message and comments.
3254 edittext.append(
3254 edittext.append(
3255 hgprefix(
3255 hgprefix(
3256 _(
3256 _(
3257 b"Enter commit message."
3257 b"Enter commit message."
3258 b" Lines beginning with 'HG:' are removed."
3258 b" Lines beginning with 'HG:' are removed."
3259 )
3259 )
3260 )
3260 )
3261 )
3261 )
3262 edittext.append(hgprefix(extramsg))
3262 edittext.append(hgprefix(extramsg))
3263 edittext.append(b"HG: --")
3263 edittext.append(b"HG: --")
3264 edittext.append(hgprefix(_(b"user: %s") % ctx.user()))
3264 edittext.append(hgprefix(_(b"user: %s") % ctx.user()))
3265 if ctx.p2():
3265 if ctx.p2():
3266 edittext.append(hgprefix(_(b"branch merge")))
3266 edittext.append(hgprefix(_(b"branch merge")))
3267 if ctx.branch():
3267 if ctx.branch():
3268 edittext.append(hgprefix(_(b"branch '%s'") % ctx.branch()))
3268 edittext.append(hgprefix(_(b"branch '%s'") % ctx.branch()))
3269 if bookmarks.isactivewdirparent(repo):
3269 if bookmarks.isactivewdirparent(repo):
3270 edittext.append(hgprefix(_(b"bookmark '%s'") % repo._activebookmark))
3270 edittext.append(hgprefix(_(b"bookmark '%s'") % repo._activebookmark))
3271 edittext.extend([hgprefix(_(b"subrepo %s") % s) for s in subs])
3271 edittext.extend([hgprefix(_(b"subrepo %s") % s) for s in subs])
3272 edittext.extend([hgprefix(_(b"added %s") % f) for f in added])
3272 edittext.extend([hgprefix(_(b"added %s") % f) for f in added])
3273 edittext.extend([hgprefix(_(b"changed %s") % f) for f in modified])
3273 edittext.extend([hgprefix(_(b"changed %s") % f) for f in modified])
3274 edittext.extend([hgprefix(_(b"removed %s") % f) for f in removed])
3274 edittext.extend([hgprefix(_(b"removed %s") % f) for f in removed])
3275 if not added and not modified and not removed:
3275 if not added and not modified and not removed:
3276 edittext.append(hgprefix(_(b"no files changed")))
3276 edittext.append(hgprefix(_(b"no files changed")))
3277 edittext.append(b"")
3277 edittext.append(b"")
3278
3278
3279 return b"\n".join(edittext)
3279 return b"\n".join(edittext)
3280
3280
3281
3281
3282 def commitstatus(repo, node, branch, bheads=None, opts=None):
3282 def commitstatus(repo, node, branch, bheads=None, opts=None):
3283 if opts is None:
3283 if opts is None:
3284 opts = {}
3284 opts = {}
3285 ctx = repo[node]
3285 ctx = repo[node]
3286 parents = ctx.parents()
3286 parents = ctx.parents()
3287
3287
3288 if (
3288 if (
3289 not opts.get(b'amend')
3289 not opts.get(b'amend')
3290 and bheads
3290 and bheads
3291 and node not in bheads
3291 and node not in bheads
3292 and not [
3292 and not [
3293 x for x in parents if x.node() in bheads and x.branch() == branch
3293 x for x in parents if x.node() in bheads and x.branch() == branch
3294 ]
3294 ]
3295 ):
3295 ):
3296 repo.ui.status(_(b'created new head\n'))
3296 repo.ui.status(_(b'created new head\n'))
3297 # The message is not printed for initial roots. For the other
3297 # The message is not printed for initial roots. For the other
3298 # changesets, it is printed in the following situations:
3298 # changesets, it is printed in the following situations:
3299 #
3299 #
3300 # Par column: for the 2 parents with ...
3300 # Par column: for the 2 parents with ...
3301 # N: null or no parent
3301 # N: null or no parent
3302 # B: parent is on another named branch
3302 # B: parent is on another named branch
3303 # C: parent is a regular non head changeset
3303 # C: parent is a regular non head changeset
3304 # H: parent was a branch head of the current branch
3304 # H: parent was a branch head of the current branch
3305 # Msg column: whether we print "created new head" message
3305 # Msg column: whether we print "created new head" message
3306 # In the following, it is assumed that there already exists some
3306 # In the following, it is assumed that there already exists some
3307 # initial branch heads of the current branch, otherwise nothing is
3307 # initial branch heads of the current branch, otherwise nothing is
3308 # printed anyway.
3308 # printed anyway.
3309 #
3309 #
3310 # Par Msg Comment
3310 # Par Msg Comment
3311 # N N y additional topo root
3311 # N N y additional topo root
3312 #
3312 #
3313 # B N y additional branch root
3313 # B N y additional branch root
3314 # C N y additional topo head
3314 # C N y additional topo head
3315 # H N n usual case
3315 # H N n usual case
3316 #
3316 #
3317 # B B y weird additional branch root
3317 # B B y weird additional branch root
3318 # C B y branch merge
3318 # C B y branch merge
3319 # H B n merge with named branch
3319 # H B n merge with named branch
3320 #
3320 #
3321 # C C y additional head from merge
3321 # C C y additional head from merge
3322 # C H n merge with a head
3322 # C H n merge with a head
3323 #
3323 #
3324 # H H n head merge: head count decreases
3324 # H H n head merge: head count decreases
3325
3325
3326 if not opts.get(b'close_branch'):
3326 if not opts.get(b'close_branch'):
3327 for r in parents:
3327 for r in parents:
3328 if r.closesbranch() and r.branch() == branch:
3328 if r.closesbranch() and r.branch() == branch:
3329 repo.ui.status(
3329 repo.ui.status(
3330 _(b'reopening closed branch head %d\n') % r.rev()
3330 _(b'reopening closed branch head %d\n') % r.rev()
3331 )
3331 )
3332
3332
3333 if repo.ui.debugflag:
3333 if repo.ui.debugflag:
3334 repo.ui.write(
3334 repo.ui.write(
3335 _(b'committed changeset %d:%s\n') % (ctx.rev(), ctx.hex())
3335 _(b'committed changeset %d:%s\n') % (ctx.rev(), ctx.hex())
3336 )
3336 )
3337 elif repo.ui.verbose:
3337 elif repo.ui.verbose:
3338 repo.ui.write(_(b'committed changeset %d:%s\n') % (ctx.rev(), ctx))
3338 repo.ui.write(_(b'committed changeset %d:%s\n') % (ctx.rev(), ctx))
3339
3339
3340
3340
3341 def postcommitstatus(repo, pats, opts):
3341 def postcommitstatus(repo, pats, opts):
3342 return repo.status(match=scmutil.match(repo[None], pats, opts))
3342 return repo.status(match=scmutil.match(repo[None], pats, opts))
3343
3343
3344
3344
3345 def revert(ui, repo, ctx, parents, *pats, **opts):
3345 def revert(ui, repo, ctx, parents, *pats, **opts):
3346 opts = pycompat.byteskwargs(opts)
3346 opts = pycompat.byteskwargs(opts)
3347 parent, p2 = parents
3347 parent, p2 = parents
3348 node = ctx.node()
3348 node = ctx.node()
3349
3349
3350 mf = ctx.manifest()
3350 mf = ctx.manifest()
3351 if node == p2:
3351 if node == p2:
3352 parent = p2
3352 parent = p2
3353
3353
3354 # need all matching names in dirstate and manifest of target rev,
3354 # need all matching names in dirstate and manifest of target rev,
3355 # so have to walk both. do not print errors if files exist in one
3355 # so have to walk both. do not print errors if files exist in one
3356 # but not other. in both cases, filesets should be evaluated against
3356 # but not other. in both cases, filesets should be evaluated against
3357 # workingctx to get consistent result (issue4497). this means 'set:**'
3357 # workingctx to get consistent result (issue4497). this means 'set:**'
3358 # cannot be used to select missing files from target rev.
3358 # cannot be used to select missing files from target rev.
3359
3359
3360 # `names` is a mapping for all elements in working copy and target revision
3360 # `names` is a mapping for all elements in working copy and target revision
3361 # The mapping is in the form:
3361 # The mapping is in the form:
3362 # <abs path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
3362 # <abs path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
3363 names = {}
3363 names = {}
3364 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
3364 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
3365
3365
3366 with repo.wlock():
3366 with repo.wlock():
3367 ## filling of the `names` mapping
3367 ## filling of the `names` mapping
3368 # walk dirstate to fill `names`
3368 # walk dirstate to fill `names`
3369
3369
3370 interactive = opts.get(b'interactive', False)
3370 interactive = opts.get(b'interactive', False)
3371 wctx = repo[None]
3371 wctx = repo[None]
3372 m = scmutil.match(wctx, pats, opts)
3372 m = scmutil.match(wctx, pats, opts)
3373
3373
3374 # we'll need this later
3374 # we'll need this later
3375 targetsubs = sorted(s for s in wctx.substate if m(s))
3375 targetsubs = sorted(s for s in wctx.substate if m(s))
3376
3376
3377 if not m.always():
3377 if not m.always():
3378 matcher = matchmod.badmatch(m, lambda x, y: False)
3378 matcher = matchmod.badmatch(m, lambda x, y: False)
3379 for abs in wctx.walk(matcher):
3379 for abs in wctx.walk(matcher):
3380 names[abs] = m.exact(abs)
3380 names[abs] = m.exact(abs)
3381
3381
3382 # walk target manifest to fill `names`
3382 # walk target manifest to fill `names`
3383
3383
3384 def badfn(path, msg):
3384 def badfn(path, msg):
3385 if path in names:
3385 if path in names:
3386 return
3386 return
3387 if path in ctx.substate:
3387 if path in ctx.substate:
3388 return
3388 return
3389 path_ = path + b'/'
3389 path_ = path + b'/'
3390 for f in names:
3390 for f in names:
3391 if f.startswith(path_):
3391 if f.startswith(path_):
3392 return
3392 return
3393 ui.warn(b"%s: %s\n" % (uipathfn(path), msg))
3393 ui.warn(b"%s: %s\n" % (uipathfn(path), msg))
3394
3394
3395 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
3395 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
3396 if abs not in names:
3396 if abs not in names:
3397 names[abs] = m.exact(abs)
3397 names[abs] = m.exact(abs)
3398
3398
3399 # Find status of all file in `names`.
3399 # Find status of all file in `names`.
3400 m = scmutil.matchfiles(repo, names)
3400 m = scmutil.matchfiles(repo, names)
3401
3401
3402 changes = repo.status(
3402 changes = repo.status(
3403 node1=node, match=m, unknown=True, ignored=True, clean=True
3403 node1=node, match=m, unknown=True, ignored=True, clean=True
3404 )
3404 )
3405 else:
3405 else:
3406 changes = repo.status(node1=node, match=m)
3406 changes = repo.status(node1=node, match=m)
3407 for kind in changes:
3407 for kind in changes:
3408 for abs in kind:
3408 for abs in kind:
3409 names[abs] = m.exact(abs)
3409 names[abs] = m.exact(abs)
3410
3410
3411 m = scmutil.matchfiles(repo, names)
3411 m = scmutil.matchfiles(repo, names)
3412
3412
3413 modified = set(changes.modified)
3413 modified = set(changes.modified)
3414 added = set(changes.added)
3414 added = set(changes.added)
3415 removed = set(changes.removed)
3415 removed = set(changes.removed)
3416 _deleted = set(changes.deleted)
3416 _deleted = set(changes.deleted)
3417 unknown = set(changes.unknown)
3417 unknown = set(changes.unknown)
3418 unknown.update(changes.ignored)
3418 unknown.update(changes.ignored)
3419 clean = set(changes.clean)
3419 clean = set(changes.clean)
3420 modadded = set()
3420 modadded = set()
3421
3421
3422 # We need to account for the state of the file in the dirstate,
3422 # We need to account for the state of the file in the dirstate,
3423 # even when we revert against something else than parent. This will
3423 # even when we revert against something else than parent. This will
3424 # slightly alter the behavior of revert (doing back up or not, delete
3424 # slightly alter the behavior of revert (doing back up or not, delete
3425 # or just forget etc).
3425 # or just forget etc).
3426 if parent == node:
3426 if parent == node:
3427 dsmodified = modified
3427 dsmodified = modified
3428 dsadded = added
3428 dsadded = added
3429 dsremoved = removed
3429 dsremoved = removed
3430 # store all local modifications, useful later for rename detection
3430 # store all local modifications, useful later for rename detection
3431 localchanges = dsmodified | dsadded
3431 localchanges = dsmodified | dsadded
3432 modified, added, removed = set(), set(), set()
3432 modified, added, removed = set(), set(), set()
3433 else:
3433 else:
3434 changes = repo.status(node1=parent, match=m)
3434 changes = repo.status(node1=parent, match=m)
3435 dsmodified = set(changes.modified)
3435 dsmodified = set(changes.modified)
3436 dsadded = set(changes.added)
3436 dsadded = set(changes.added)
3437 dsremoved = set(changes.removed)
3437 dsremoved = set(changes.removed)
3438 # store all local modifications, useful later for rename detection
3438 # store all local modifications, useful later for rename detection
3439 localchanges = dsmodified | dsadded
3439 localchanges = dsmodified | dsadded
3440
3440
3441 # only take into account for removes between wc and target
3441 # only take into account for removes between wc and target
3442 clean |= dsremoved - removed
3442 clean |= dsremoved - removed
3443 dsremoved &= removed
3443 dsremoved &= removed
3444 # distinct between dirstate remove and other
3444 # distinct between dirstate remove and other
3445 removed -= dsremoved
3445 removed -= dsremoved
3446
3446
3447 modadded = added & dsmodified
3447 modadded = added & dsmodified
3448 added -= modadded
3448 added -= modadded
3449
3449
3450 # tell newly modified apart.
3450 # tell newly modified apart.
3451 dsmodified &= modified
3451 dsmodified &= modified
3452 dsmodified |= modified & dsadded # dirstate added may need backup
3452 dsmodified |= modified & dsadded # dirstate added may need backup
3453 modified -= dsmodified
3453 modified -= dsmodified
3454
3454
3455 # We need to wait for some post-processing to update this set
3455 # We need to wait for some post-processing to update this set
3456 # before making the distinction. The dirstate will be used for
3456 # before making the distinction. The dirstate will be used for
3457 # that purpose.
3457 # that purpose.
3458 dsadded = added
3458 dsadded = added
3459
3459
3460 # in case of merge, files that are actually added can be reported as
3460 # in case of merge, files that are actually added can be reported as
3461 # modified, we need to post process the result
3461 # modified, we need to post process the result
3462 if p2 != nullid:
3462 if p2 != nullid:
3463 mergeadd = set(dsmodified)
3463 mergeadd = set(dsmodified)
3464 for path in dsmodified:
3464 for path in dsmodified:
3465 if path in mf:
3465 if path in mf:
3466 mergeadd.remove(path)
3466 mergeadd.remove(path)
3467 dsadded |= mergeadd
3467 dsadded |= mergeadd
3468 dsmodified -= mergeadd
3468 dsmodified -= mergeadd
3469
3469
3470 # if f is a rename, update `names` to also revert the source
3470 # if f is a rename, update `names` to also revert the source
3471 for f in localchanges:
3471 for f in localchanges:
3472 src = repo.dirstate.copied(f)
3472 src = repo.dirstate.copied(f)
3473 # XXX should we check for rename down to target node?
3473 # XXX should we check for rename down to target node?
3474 if src and src not in names and repo.dirstate[src] == b'r':
3474 if src and src not in names and repo.dirstate[src] == b'r':
3475 dsremoved.add(src)
3475 dsremoved.add(src)
3476 names[src] = True
3476 names[src] = True
3477
3477
3478 # determine the exact nature of the deleted changesets
3478 # determine the exact nature of the deleted changesets
3479 deladded = set(_deleted)
3479 deladded = set(_deleted)
3480 for path in _deleted:
3480 for path in _deleted:
3481 if path in mf:
3481 if path in mf:
3482 deladded.remove(path)
3482 deladded.remove(path)
3483 deleted = _deleted - deladded
3483 deleted = _deleted - deladded
3484
3484
3485 # distinguish between file to forget and the other
3485 # distinguish between file to forget and the other
3486 added = set()
3486 added = set()
3487 for abs in dsadded:
3487 for abs in dsadded:
3488 if repo.dirstate[abs] != b'a':
3488 if repo.dirstate[abs] != b'a':
3489 added.add(abs)
3489 added.add(abs)
3490 dsadded -= added
3490 dsadded -= added
3491
3491
3492 for abs in deladded:
3492 for abs in deladded:
3493 if repo.dirstate[abs] == b'a':
3493 if repo.dirstate[abs] == b'a':
3494 dsadded.add(abs)
3494 dsadded.add(abs)
3495 deladded -= dsadded
3495 deladded -= dsadded
3496
3496
3497 # For files marked as removed, we check if an unknown file is present at
3497 # For files marked as removed, we check if an unknown file is present at
3498 # the same path. If a such file exists it may need to be backed up.
3498 # the same path. If a such file exists it may need to be backed up.
3499 # Making the distinction at this stage helps have simpler backup
3499 # Making the distinction at this stage helps have simpler backup
3500 # logic.
3500 # logic.
3501 removunk = set()
3501 removunk = set()
3502 for abs in removed:
3502 for abs in removed:
3503 target = repo.wjoin(abs)
3503 target = repo.wjoin(abs)
3504 if os.path.lexists(target):
3504 if os.path.lexists(target):
3505 removunk.add(abs)
3505 removunk.add(abs)
3506 removed -= removunk
3506 removed -= removunk
3507
3507
3508 dsremovunk = set()
3508 dsremovunk = set()
3509 for abs in dsremoved:
3509 for abs in dsremoved:
3510 target = repo.wjoin(abs)
3510 target = repo.wjoin(abs)
3511 if os.path.lexists(target):
3511 if os.path.lexists(target):
3512 dsremovunk.add(abs)
3512 dsremovunk.add(abs)
3513 dsremoved -= dsremovunk
3513 dsremoved -= dsremovunk
3514
3514
3515 # action to be actually performed by revert
3515 # action to be actually performed by revert
3516 # (<list of file>, message>) tuple
3516 # (<list of file>, message>) tuple
3517 actions = {
3517 actions = {
3518 b'revert': ([], _(b'reverting %s\n')),
3518 b'revert': ([], _(b'reverting %s\n')),
3519 b'add': ([], _(b'adding %s\n')),
3519 b'add': ([], _(b'adding %s\n')),
3520 b'remove': ([], _(b'removing %s\n')),
3520 b'remove': ([], _(b'removing %s\n')),
3521 b'drop': ([], _(b'removing %s\n')),
3521 b'drop': ([], _(b'removing %s\n')),
3522 b'forget': ([], _(b'forgetting %s\n')),
3522 b'forget': ([], _(b'forgetting %s\n')),
3523 b'undelete': ([], _(b'undeleting %s\n')),
3523 b'undelete': ([], _(b'undeleting %s\n')),
3524 b'noop': (None, _(b'no changes needed to %s\n')),
3524 b'noop': (None, _(b'no changes needed to %s\n')),
3525 b'unknown': (None, _(b'file not managed: %s\n')),
3525 b'unknown': (None, _(b'file not managed: %s\n')),
3526 }
3526 }
3527
3527
3528 # "constant" that convey the backup strategy.
3528 # "constant" that convey the backup strategy.
3529 # All set to `discard` if `no-backup` is set do avoid checking
3529 # All set to `discard` if `no-backup` is set do avoid checking
3530 # no_backup lower in the code.
3530 # no_backup lower in the code.
3531 # These values are ordered for comparison purposes
3531 # These values are ordered for comparison purposes
3532 backupinteractive = 3 # do backup if interactively modified
3532 backupinteractive = 3 # do backup if interactively modified
3533 backup = 2 # unconditionally do backup
3533 backup = 2 # unconditionally do backup
3534 check = 1 # check if the existing file differs from target
3534 check = 1 # check if the existing file differs from target
3535 discard = 0 # never do backup
3535 discard = 0 # never do backup
3536 if opts.get(b'no_backup'):
3536 if opts.get(b'no_backup'):
3537 backupinteractive = backup = check = discard
3537 backupinteractive = backup = check = discard
3538 if interactive:
3538 if interactive:
3539 dsmodifiedbackup = backupinteractive
3539 dsmodifiedbackup = backupinteractive
3540 else:
3540 else:
3541 dsmodifiedbackup = backup
3541 dsmodifiedbackup = backup
3542 tobackup = set()
3542 tobackup = set()
3543
3543
3544 backupanddel = actions[b'remove']
3544 backupanddel = actions[b'remove']
3545 if not opts.get(b'no_backup'):
3545 if not opts.get(b'no_backup'):
3546 backupanddel = actions[b'drop']
3546 backupanddel = actions[b'drop']
3547
3547
3548 disptable = (
3548 disptable = (
3549 # dispatch table:
3549 # dispatch table:
3550 # file state
3550 # file state
3551 # action
3551 # action
3552 # make backup
3552 # make backup
3553 ## Sets that results that will change file on disk
3553 ## Sets that results that will change file on disk
3554 # Modified compared to target, no local change
3554 # Modified compared to target, no local change
3555 (modified, actions[b'revert'], discard),
3555 (modified, actions[b'revert'], discard),
3556 # Modified compared to target, but local file is deleted
3556 # Modified compared to target, but local file is deleted
3557 (deleted, actions[b'revert'], discard),
3557 (deleted, actions[b'revert'], discard),
3558 # Modified compared to target, local change
3558 # Modified compared to target, local change
3559 (dsmodified, actions[b'revert'], dsmodifiedbackup),
3559 (dsmodified, actions[b'revert'], dsmodifiedbackup),
3560 # Added since target
3560 # Added since target
3561 (added, actions[b'remove'], discard),
3561 (added, actions[b'remove'], discard),
3562 # Added in working directory
3562 # Added in working directory
3563 (dsadded, actions[b'forget'], discard),
3563 (dsadded, actions[b'forget'], discard),
3564 # Added since target, have local modification
3564 # Added since target, have local modification
3565 (modadded, backupanddel, backup),
3565 (modadded, backupanddel, backup),
3566 # Added since target but file is missing in working directory
3566 # Added since target but file is missing in working directory
3567 (deladded, actions[b'drop'], discard),
3567 (deladded, actions[b'drop'], discard),
3568 # Removed since target, before working copy parent
3568 # Removed since target, before working copy parent
3569 (removed, actions[b'add'], discard),
3569 (removed, actions[b'add'], discard),
3570 # Same as `removed` but an unknown file exists at the same path
3570 # Same as `removed` but an unknown file exists at the same path
3571 (removunk, actions[b'add'], check),
3571 (removunk, actions[b'add'], check),
3572 # Removed since targe, marked as such in working copy parent
3572 # Removed since targe, marked as such in working copy parent
3573 (dsremoved, actions[b'undelete'], discard),
3573 (dsremoved, actions[b'undelete'], discard),
3574 # Same as `dsremoved` but an unknown file exists at the same path
3574 # Same as `dsremoved` but an unknown file exists at the same path
3575 (dsremovunk, actions[b'undelete'], check),
3575 (dsremovunk, actions[b'undelete'], check),
3576 ## the following sets does not result in any file changes
3576 ## the following sets does not result in any file changes
3577 # File with no modification
3577 # File with no modification
3578 (clean, actions[b'noop'], discard),
3578 (clean, actions[b'noop'], discard),
3579 # Existing file, not tracked anywhere
3579 # Existing file, not tracked anywhere
3580 (unknown, actions[b'unknown'], discard),
3580 (unknown, actions[b'unknown'], discard),
3581 )
3581 )
3582
3582
3583 for abs, exact in sorted(names.items()):
3583 for abs, exact in sorted(names.items()):
3584 # target file to be touch on disk (relative to cwd)
3584 # target file to be touch on disk (relative to cwd)
3585 target = repo.wjoin(abs)
3585 target = repo.wjoin(abs)
3586 # search the entry in the dispatch table.
3586 # search the entry in the dispatch table.
3587 # if the file is in any of these sets, it was touched in the working
3587 # if the file is in any of these sets, it was touched in the working
3588 # directory parent and we are sure it needs to be reverted.
3588 # directory parent and we are sure it needs to be reverted.
3589 for table, (xlist, msg), dobackup in disptable:
3589 for table, (xlist, msg), dobackup in disptable:
3590 if abs not in table:
3590 if abs not in table:
3591 continue
3591 continue
3592 if xlist is not None:
3592 if xlist is not None:
3593 xlist.append(abs)
3593 xlist.append(abs)
3594 if dobackup:
3594 if dobackup:
3595 # If in interactive mode, don't automatically create
3595 # If in interactive mode, don't automatically create
3596 # .orig files (issue4793)
3596 # .orig files (issue4793)
3597 if dobackup == backupinteractive:
3597 if dobackup == backupinteractive:
3598 tobackup.add(abs)
3598 tobackup.add(abs)
3599 elif backup <= dobackup or wctx[abs].cmp(ctx[abs]):
3599 elif backup <= dobackup or wctx[abs].cmp(ctx[abs]):
3600 absbakname = scmutil.backuppath(ui, repo, abs)
3600 absbakname = scmutil.backuppath(ui, repo, abs)
3601 bakname = os.path.relpath(
3601 bakname = os.path.relpath(
3602 absbakname, start=repo.root
3602 absbakname, start=repo.root
3603 )
3603 )
3604 ui.note(
3604 ui.note(
3605 _(b'saving current version of %s as %s\n')
3605 _(b'saving current version of %s as %s\n')
3606 % (uipathfn(abs), uipathfn(bakname))
3606 % (uipathfn(abs), uipathfn(bakname))
3607 )
3607 )
3608 if not opts.get(b'dry_run'):
3608 if not opts.get(b'dry_run'):
3609 if interactive:
3609 if interactive:
3610 util.copyfile(target, absbakname)
3610 util.copyfile(target, absbakname)
3611 else:
3611 else:
3612 util.rename(target, absbakname)
3612 util.rename(target, absbakname)
3613 if opts.get(b'dry_run'):
3613 if opts.get(b'dry_run'):
3614 if ui.verbose or not exact:
3614 if ui.verbose or not exact:
3615 ui.status(msg % uipathfn(abs))
3615 ui.status(msg % uipathfn(abs))
3616 elif exact:
3616 elif exact:
3617 ui.warn(msg % uipathfn(abs))
3617 ui.warn(msg % uipathfn(abs))
3618 break
3618 break
3619
3619
3620 if not opts.get(b'dry_run'):
3620 if not opts.get(b'dry_run'):
3621 needdata = (b'revert', b'add', b'undelete')
3621 needdata = (b'revert', b'add', b'undelete')
3622 oplist = [actions[name][0] for name in needdata]
3622 oplist = [actions[name][0] for name in needdata]
3623 prefetch = scmutil.prefetchfiles
3623 prefetch = scmutil.prefetchfiles
3624 matchfiles = scmutil.matchfiles
3624 matchfiles = scmutil.matchfiles
3625 prefetch(
3625 prefetch(
3626 repo,
3626 repo,
3627 [ctx.rev()],
3627 [ctx.rev()],
3628 matchfiles(repo, [f for sublist in oplist for f in sublist]),
3628 matchfiles(repo, [f for sublist in oplist for f in sublist]),
3629 )
3629 )
3630 match = scmutil.match(repo[None], pats)
3630 match = scmutil.match(repo[None], pats)
3631 _performrevert(
3631 _performrevert(
3632 repo,
3632 repo,
3633 parents,
3633 parents,
3634 ctx,
3634 ctx,
3635 names,
3635 names,
3636 uipathfn,
3636 uipathfn,
3637 actions,
3637 actions,
3638 match,
3638 match,
3639 interactive,
3639 interactive,
3640 tobackup,
3640 tobackup,
3641 )
3641 )
3642
3642
3643 if targetsubs:
3643 if targetsubs:
3644 # Revert the subrepos on the revert list
3644 # Revert the subrepos on the revert list
3645 for sub in targetsubs:
3645 for sub in targetsubs:
3646 try:
3646 try:
3647 wctx.sub(sub).revert(
3647 wctx.sub(sub).revert(
3648 ctx.substate[sub], *pats, **pycompat.strkwargs(opts)
3648 ctx.substate[sub], *pats, **pycompat.strkwargs(opts)
3649 )
3649 )
3650 except KeyError:
3650 except KeyError:
3651 raise error.Abort(
3651 raise error.Abort(
3652 b"subrepository '%s' does not exist in %s!"
3652 b"subrepository '%s' does not exist in %s!"
3653 % (sub, short(ctx.node()))
3653 % (sub, short(ctx.node()))
3654 )
3654 )
3655
3655
3656
3656
3657 def _performrevert(
3657 def _performrevert(
3658 repo,
3658 repo,
3659 parents,
3659 parents,
3660 ctx,
3660 ctx,
3661 names,
3661 names,
3662 uipathfn,
3662 uipathfn,
3663 actions,
3663 actions,
3664 match,
3664 match,
3665 interactive=False,
3665 interactive=False,
3666 tobackup=None,
3666 tobackup=None,
3667 ):
3667 ):
3668 """function that actually perform all the actions computed for revert
3668 """function that actually perform all the actions computed for revert
3669
3669
3670 This is an independent function to let extension to plug in and react to
3670 This is an independent function to let extension to plug in and react to
3671 the imminent revert.
3671 the imminent revert.
3672
3672
3673 Make sure you have the working directory locked when calling this function.
3673 Make sure you have the working directory locked when calling this function.
3674 """
3674 """
3675 parent, p2 = parents
3675 parent, p2 = parents
3676 node = ctx.node()
3676 node = ctx.node()
3677 excluded_files = []
3677 excluded_files = []
3678
3678
3679 def checkout(f):
3679 def checkout(f):
3680 fc = ctx[f]
3680 fc = ctx[f]
3681 repo.wwrite(f, fc.data(), fc.flags())
3681 repo.wwrite(f, fc.data(), fc.flags())
3682
3682
3683 def doremove(f):
3683 def doremove(f):
3684 try:
3684 try:
3685 rmdir = repo.ui.configbool(b'experimental', b'removeemptydirs')
3685 rmdir = repo.ui.configbool(b'experimental', b'removeemptydirs')
3686 repo.wvfs.unlinkpath(f, rmdir=rmdir)
3686 repo.wvfs.unlinkpath(f, rmdir=rmdir)
3687 except OSError:
3687 except OSError:
3688 pass
3688 pass
3689 repo.dirstate.remove(f)
3689 repo.dirstate.remove(f)
3690
3690
3691 def prntstatusmsg(action, f):
3691 def prntstatusmsg(action, f):
3692 exact = names[f]
3692 exact = names[f]
3693 if repo.ui.verbose or not exact:
3693 if repo.ui.verbose or not exact:
3694 repo.ui.status(actions[action][1] % uipathfn(f))
3694 repo.ui.status(actions[action][1] % uipathfn(f))
3695
3695
3696 audit_path = pathutil.pathauditor(repo.root, cached=True)
3696 audit_path = pathutil.pathauditor(repo.root, cached=True)
3697 for f in actions[b'forget'][0]:
3697 for f in actions[b'forget'][0]:
3698 if interactive:
3698 if interactive:
3699 choice = repo.ui.promptchoice(
3699 choice = repo.ui.promptchoice(
3700 _(b"forget added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f)
3700 _(b"forget added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f)
3701 )
3701 )
3702 if choice == 0:
3702 if choice == 0:
3703 prntstatusmsg(b'forget', f)
3703 prntstatusmsg(b'forget', f)
3704 repo.dirstate.drop(f)
3704 repo.dirstate.drop(f)
3705 else:
3705 else:
3706 excluded_files.append(f)
3706 excluded_files.append(f)
3707 else:
3707 else:
3708 prntstatusmsg(b'forget', f)
3708 prntstatusmsg(b'forget', f)
3709 repo.dirstate.drop(f)
3709 repo.dirstate.drop(f)
3710 for f in actions[b'remove'][0]:
3710 for f in actions[b'remove'][0]:
3711 audit_path(f)
3711 audit_path(f)
3712 if interactive:
3712 if interactive:
3713 choice = repo.ui.promptchoice(
3713 choice = repo.ui.promptchoice(
3714 _(b"remove added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f)
3714 _(b"remove added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f)
3715 )
3715 )
3716 if choice == 0:
3716 if choice == 0:
3717 prntstatusmsg(b'remove', f)
3717 prntstatusmsg(b'remove', f)
3718 doremove(f)
3718 doremove(f)
3719 else:
3719 else:
3720 excluded_files.append(f)
3720 excluded_files.append(f)
3721 else:
3721 else:
3722 prntstatusmsg(b'remove', f)
3722 prntstatusmsg(b'remove', f)
3723 doremove(f)
3723 doremove(f)
3724 for f in actions[b'drop'][0]:
3724 for f in actions[b'drop'][0]:
3725 audit_path(f)
3725 audit_path(f)
3726 prntstatusmsg(b'drop', f)
3726 prntstatusmsg(b'drop', f)
3727 repo.dirstate.remove(f)
3727 repo.dirstate.remove(f)
3728
3728
3729 normal = None
3729 normal = None
3730 if node == parent:
3730 if node == parent:
3731 # We're reverting to our parent. If possible, we'd like status
3731 # We're reverting to our parent. If possible, we'd like status
3732 # to report the file as clean. We have to use normallookup for
3732 # to report the file as clean. We have to use normallookup for
3733 # merges to avoid losing information about merged/dirty files.
3733 # merges to avoid losing information about merged/dirty files.
3734 if p2 != nullid:
3734 if p2 != nullid:
3735 normal = repo.dirstate.normallookup
3735 normal = repo.dirstate.normallookup
3736 else:
3736 else:
3737 normal = repo.dirstate.normal
3737 normal = repo.dirstate.normal
3738
3738
3739 newlyaddedandmodifiedfiles = set()
3739 newlyaddedandmodifiedfiles = set()
3740 if interactive:
3740 if interactive:
3741 # Prompt the user for changes to revert
3741 # Prompt the user for changes to revert
3742 torevert = [f for f in actions[b'revert'][0] if f not in excluded_files]
3742 torevert = [f for f in actions[b'revert'][0] if f not in excluded_files]
3743 m = scmutil.matchfiles(repo, torevert)
3743 m = scmutil.matchfiles(repo, torevert)
3744 diffopts = patch.difffeatureopts(
3744 diffopts = patch.difffeatureopts(
3745 repo.ui,
3745 repo.ui,
3746 whitespace=True,
3746 whitespace=True,
3747 section=b'commands',
3747 section=b'commands',
3748 configprefix=b'revert.interactive.',
3748 configprefix=b'revert.interactive.',
3749 )
3749 )
3750 diffopts.nodates = True
3750 diffopts.nodates = True
3751 diffopts.git = True
3751 diffopts.git = True
3752 operation = b'apply'
3752 operation = b'apply'
3753 if node == parent:
3753 if node == parent:
3754 if repo.ui.configbool(
3754 if repo.ui.configbool(
3755 b'experimental', b'revert.interactive.select-to-keep'
3755 b'experimental', b'revert.interactive.select-to-keep'
3756 ):
3756 ):
3757 operation = b'keep'
3757 operation = b'keep'
3758 else:
3758 else:
3759 operation = b'discard'
3759 operation = b'discard'
3760
3760
3761 if operation == b'apply':
3761 if operation == b'apply':
3762 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3762 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3763 else:
3763 else:
3764 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3764 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3765 originalchunks = patch.parsepatch(diff)
3765 originalchunks = patch.parsepatch(diff)
3766
3766
3767 try:
3767 try:
3768
3768
3769 chunks, opts = recordfilter(
3769 chunks, opts = recordfilter(
3770 repo.ui, originalchunks, match, operation=operation
3770 repo.ui, originalchunks, match, operation=operation
3771 )
3771 )
3772 if operation == b'discard':
3772 if operation == b'discard':
3773 chunks = patch.reversehunks(chunks)
3773 chunks = patch.reversehunks(chunks)
3774
3774
3775 except error.PatchError as err:
3775 except error.PatchError as err:
3776 raise error.Abort(_(b'error parsing patch: %s') % err)
3776 raise error.Abort(_(b'error parsing patch: %s') % err)
3777
3777
3778 # FIXME: when doing an interactive revert of a copy, there's no way of
3778 # FIXME: when doing an interactive revert of a copy, there's no way of
3779 # performing a partial revert of the added file, the only option is
3779 # performing a partial revert of the added file, the only option is
3780 # "remove added file <name> (Yn)?", so we don't need to worry about the
3780 # "remove added file <name> (Yn)?", so we don't need to worry about the
3781 # alsorestore value. Ideally we'd be able to partially revert
3781 # alsorestore value. Ideally we'd be able to partially revert
3782 # copied/renamed files.
3782 # copied/renamed files.
3783 newlyaddedandmodifiedfiles, unusedalsorestore = newandmodified(
3783 newlyaddedandmodifiedfiles, unusedalsorestore = newandmodified(
3784 chunks, originalchunks
3784 chunks, originalchunks
3785 )
3785 )
3786 if tobackup is None:
3786 if tobackup is None:
3787 tobackup = set()
3787 tobackup = set()
3788 # Apply changes
3788 # Apply changes
3789 fp = stringio()
3789 fp = stringio()
3790 # chunks are serialized per file, but files aren't sorted
3790 # chunks are serialized per file, but files aren't sorted
3791 for f in sorted(set(c.header.filename() for c in chunks if ishunk(c))):
3791 for f in sorted(set(c.header.filename() for c in chunks if ishunk(c))):
3792 prntstatusmsg(b'revert', f)
3792 prntstatusmsg(b'revert', f)
3793 files = set()
3793 files = set()
3794 for c in chunks:
3794 for c in chunks:
3795 if ishunk(c):
3795 if ishunk(c):
3796 abs = c.header.filename()
3796 abs = c.header.filename()
3797 # Create a backup file only if this hunk should be backed up
3797 # Create a backup file only if this hunk should be backed up
3798 if c.header.filename() in tobackup:
3798 if c.header.filename() in tobackup:
3799 target = repo.wjoin(abs)
3799 target = repo.wjoin(abs)
3800 bakname = scmutil.backuppath(repo.ui, repo, abs)
3800 bakname = scmutil.backuppath(repo.ui, repo, abs)
3801 util.copyfile(target, bakname)
3801 util.copyfile(target, bakname)
3802 tobackup.remove(abs)
3802 tobackup.remove(abs)
3803 if abs not in files:
3803 if abs not in files:
3804 files.add(abs)
3804 files.add(abs)
3805 if operation == b'keep':
3805 if operation == b'keep':
3806 checkout(abs)
3806 checkout(abs)
3807 c.write(fp)
3807 c.write(fp)
3808 dopatch = fp.tell()
3808 dopatch = fp.tell()
3809 fp.seek(0)
3809 fp.seek(0)
3810 if dopatch:
3810 if dopatch:
3811 try:
3811 try:
3812 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3812 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3813 except error.PatchError as err:
3813 except error.PatchError as err:
3814 raise error.Abort(pycompat.bytestr(err))
3814 raise error.Abort(pycompat.bytestr(err))
3815 del fp
3815 del fp
3816 else:
3816 else:
3817 for f in actions[b'revert'][0]:
3817 for f in actions[b'revert'][0]:
3818 prntstatusmsg(b'revert', f)
3818 prntstatusmsg(b'revert', f)
3819 checkout(f)
3819 checkout(f)
3820 if normal:
3820 if normal:
3821 normal(f)
3821 normal(f)
3822
3822
3823 for f in actions[b'add'][0]:
3823 for f in actions[b'add'][0]:
3824 # Don't checkout modified files, they are already created by the diff
3824 # Don't checkout modified files, they are already created by the diff
3825 if f not in newlyaddedandmodifiedfiles:
3825 if f not in newlyaddedandmodifiedfiles:
3826 prntstatusmsg(b'add', f)
3826 prntstatusmsg(b'add', f)
3827 checkout(f)
3827 checkout(f)
3828 repo.dirstate.add(f)
3828 repo.dirstate.add(f)
3829
3829
3830 normal = repo.dirstate.normallookup
3830 normal = repo.dirstate.normallookup
3831 if node == parent and p2 == nullid:
3831 if node == parent and p2 == nullid:
3832 normal = repo.dirstate.normal
3832 normal = repo.dirstate.normal
3833 for f in actions[b'undelete'][0]:
3833 for f in actions[b'undelete'][0]:
3834 if interactive:
3834 if interactive:
3835 choice = repo.ui.promptchoice(
3835 choice = repo.ui.promptchoice(
3836 _(b"add back removed file %s (Yn)?$$ &Yes $$ &No") % f
3836 _(b"add back removed file %s (Yn)?$$ &Yes $$ &No") % f
3837 )
3837 )
3838 if choice == 0:
3838 if choice == 0:
3839 prntstatusmsg(b'undelete', f)
3839 prntstatusmsg(b'undelete', f)
3840 checkout(f)
3840 checkout(f)
3841 normal(f)
3841 normal(f)
3842 else:
3842 else:
3843 excluded_files.append(f)
3843 excluded_files.append(f)
3844 else:
3844 else:
3845 prntstatusmsg(b'undelete', f)
3845 prntstatusmsg(b'undelete', f)
3846 checkout(f)
3846 checkout(f)
3847 normal(f)
3847 normal(f)
3848
3848
3849 copied = copies.pathcopies(repo[parent], ctx)
3849 copied = copies.pathcopies(repo[parent], ctx)
3850
3850
3851 for f in (
3851 for f in (
3852 actions[b'add'][0] + actions[b'undelete'][0] + actions[b'revert'][0]
3852 actions[b'add'][0] + actions[b'undelete'][0] + actions[b'revert'][0]
3853 ):
3853 ):
3854 if f in copied:
3854 if f in copied:
3855 repo.dirstate.copy(copied[f], f)
3855 repo.dirstate.copy(copied[f], f)
3856
3856
3857
3857
3858 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3858 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3859 # commands.outgoing. "missing" is "missing" of the result of
3859 # commands.outgoing. "missing" is "missing" of the result of
3860 # "findcommonoutgoing()"
3860 # "findcommonoutgoing()"
3861 outgoinghooks = util.hooks()
3861 outgoinghooks = util.hooks()
3862
3862
3863 # a list of (ui, repo) functions called by commands.summary
3863 # a list of (ui, repo) functions called by commands.summary
3864 summaryhooks = util.hooks()
3864 summaryhooks = util.hooks()
3865
3865
3866 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3866 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3867 #
3867 #
3868 # functions should return tuple of booleans below, if 'changes' is None:
3868 # functions should return tuple of booleans below, if 'changes' is None:
3869 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3869 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3870 #
3870 #
3871 # otherwise, 'changes' is a tuple of tuples below:
3871 # otherwise, 'changes' is a tuple of tuples below:
3872 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3872 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3873 # - (desturl, destbranch, destpeer, outgoing)
3873 # - (desturl, destbranch, destpeer, outgoing)
3874 summaryremotehooks = util.hooks()
3874 summaryremotehooks = util.hooks()
3875
3875
3876
3876
3877 def checkunfinished(repo, commit=False, skipmerge=False):
3877 def checkunfinished(repo, commit=False, skipmerge=False):
3878 '''Look for an unfinished multistep operation, like graft, and abort
3878 '''Look for an unfinished multistep operation, like graft, and abort
3879 if found. It's probably good to check this right before
3879 if found. It's probably good to check this right before
3880 bailifchanged().
3880 bailifchanged().
3881 '''
3881 '''
3882 # Check for non-clearable states first, so things like rebase will take
3882 # Check for non-clearable states first, so things like rebase will take
3883 # precedence over update.
3883 # precedence over update.
3884 for state in statemod._unfinishedstates:
3884 for state in statemod._unfinishedstates:
3885 if (
3885 if (
3886 state._clearable
3886 state._clearable
3887 or (commit and state._allowcommit)
3887 or (commit and state._allowcommit)
3888 or state._reportonly
3888 or state._reportonly
3889 ):
3889 ):
3890 continue
3890 continue
3891 if state.isunfinished(repo):
3891 if state.isunfinished(repo):
3892 raise error.Abort(state.msg(), hint=state.hint())
3892 raise error.Abort(state.msg(), hint=state.hint())
3893
3893
3894 for s in statemod._unfinishedstates:
3894 for s in statemod._unfinishedstates:
3895 if (
3895 if (
3896 not s._clearable
3896 not s._clearable
3897 or (commit and s._allowcommit)
3897 or (commit and s._allowcommit)
3898 or (s._opname == b'merge' and skipmerge)
3898 or (s._opname == b'merge' and skipmerge)
3899 or s._reportonly
3899 or s._reportonly
3900 ):
3900 ):
3901 continue
3901 continue
3902 if s.isunfinished(repo):
3902 if s.isunfinished(repo):
3903 raise error.Abort(s.msg(), hint=s.hint())
3903 raise error.Abort(s.msg(), hint=s.hint())
3904
3904
3905
3905
3906 def clearunfinished(repo):
3906 def clearunfinished(repo):
3907 '''Check for unfinished operations (as above), and clear the ones
3907 '''Check for unfinished operations (as above), and clear the ones
3908 that are clearable.
3908 that are clearable.
3909 '''
3909 '''
3910 for state in statemod._unfinishedstates:
3910 for state in statemod._unfinishedstates:
3911 if state._reportonly:
3911 if state._reportonly:
3912 continue
3912 continue
3913 if not state._clearable and state.isunfinished(repo):
3913 if not state._clearable and state.isunfinished(repo):
3914 raise error.Abort(state.msg(), hint=state.hint())
3914 raise error.Abort(state.msg(), hint=state.hint())
3915
3915
3916 for s in statemod._unfinishedstates:
3916 for s in statemod._unfinishedstates:
3917 if s._opname == b'merge' or state._reportonly:
3917 if s._opname == b'merge' or state._reportonly:
3918 continue
3918 continue
3919 if s._clearable and s.isunfinished(repo):
3919 if s._clearable and s.isunfinished(repo):
3920 util.unlink(repo.vfs.join(s._fname))
3920 util.unlink(repo.vfs.join(s._fname))
3921
3921
3922
3922
3923 def getunfinishedstate(repo):
3923 def getunfinishedstate(repo):
3924 ''' Checks for unfinished operations and returns statecheck object
3924 ''' Checks for unfinished operations and returns statecheck object
3925 for it'''
3925 for it'''
3926 for state in statemod._unfinishedstates:
3926 for state in statemod._unfinishedstates:
3927 if state.isunfinished(repo):
3927 if state.isunfinished(repo):
3928 return state
3928 return state
3929 return None
3929 return None
3930
3930
3931
3931
3932 def howtocontinue(repo):
3932 def howtocontinue(repo):
3933 '''Check for an unfinished operation and return the command to finish
3933 '''Check for an unfinished operation and return the command to finish
3934 it.
3934 it.
3935
3935
3936 statemod._unfinishedstates list is checked for an unfinished operation
3936 statemod._unfinishedstates list is checked for an unfinished operation
3937 and the corresponding message to finish it is generated if a method to
3937 and the corresponding message to finish it is generated if a method to
3938 continue is supported by the operation.
3938 continue is supported by the operation.
3939
3939
3940 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3940 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3941 a boolean.
3941 a boolean.
3942 '''
3942 '''
3943 contmsg = _(b"continue: %s")
3943 contmsg = _(b"continue: %s")
3944 for state in statemod._unfinishedstates:
3944 for state in statemod._unfinishedstates:
3945 if not state._continueflag:
3945 if not state._continueflag:
3946 continue
3946 continue
3947 if state.isunfinished(repo):
3947 if state.isunfinished(repo):
3948 return contmsg % state.continuemsg(), True
3948 return contmsg % state.continuemsg(), True
3949 if repo[None].dirty(missing=True, merge=False, branch=False):
3949 if repo[None].dirty(missing=True, merge=False, branch=False):
3950 return contmsg % _(b"hg commit"), False
3950 return contmsg % _(b"hg commit"), False
3951 return None, None
3951 return None, None
3952
3952
3953
3953
3954 def checkafterresolved(repo):
3954 def checkafterresolved(repo):
3955 '''Inform the user about the next action after completing hg resolve
3955 '''Inform the user about the next action after completing hg resolve
3956
3956
3957 If there's a an unfinished operation that supports continue flag,
3957 If there's a an unfinished operation that supports continue flag,
3958 howtocontinue will yield repo.ui.warn as the reporter.
3958 howtocontinue will yield repo.ui.warn as the reporter.
3959
3959
3960 Otherwise, it will yield repo.ui.note.
3960 Otherwise, it will yield repo.ui.note.
3961 '''
3961 '''
3962 msg, warning = howtocontinue(repo)
3962 msg, warning = howtocontinue(repo)
3963 if msg is not None:
3963 if msg is not None:
3964 if warning:
3964 if warning:
3965 repo.ui.warn(b"%s\n" % msg)
3965 repo.ui.warn(b"%s\n" % msg)
3966 else:
3966 else:
3967 repo.ui.note(b"%s\n" % msg)
3967 repo.ui.note(b"%s\n" % msg)
3968
3968
3969
3969
3970 def wrongtooltocontinue(repo, task):
3970 def wrongtooltocontinue(repo, task):
3971 '''Raise an abort suggesting how to properly continue if there is an
3971 '''Raise an abort suggesting how to properly continue if there is an
3972 active task.
3972 active task.
3973
3973
3974 Uses howtocontinue() to find the active task.
3974 Uses howtocontinue() to find the active task.
3975
3975
3976 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3976 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3977 a hint.
3977 a hint.
3978 '''
3978 '''
3979 after = howtocontinue(repo)
3979 after = howtocontinue(repo)
3980 hint = None
3980 hint = None
3981 if after[1]:
3981 if after[1]:
3982 hint = after[0]
3982 hint = after[0]
3983 raise error.Abort(_(b'no %s in progress') % task, hint=hint)
3983 raise error.Abort(_(b'no %s in progress') % task, hint=hint)
3984
3984
3985
3985
3986 def abortgraft(ui, repo, graftstate):
3986 def abortgraft(ui, repo, graftstate):
3987 """abort the interrupted graft and rollbacks to the state before interrupted
3987 """abort the interrupted graft and rollbacks to the state before interrupted
3988 graft"""
3988 graft"""
3989 if not graftstate.exists():
3989 if not graftstate.exists():
3990 raise error.Abort(_(b"no interrupted graft to abort"))
3990 raise error.Abort(_(b"no interrupted graft to abort"))
3991 statedata = readgraftstate(repo, graftstate)
3991 statedata = readgraftstate(repo, graftstate)
3992 newnodes = statedata.get(b'newnodes')
3992 newnodes = statedata.get(b'newnodes')
3993 if newnodes is None:
3993 if newnodes is None:
3994 # and old graft state which does not have all the data required to abort
3994 # and old graft state which does not have all the data required to abort
3995 # the graft
3995 # the graft
3996 raise error.Abort(_(b"cannot abort using an old graftstate"))
3996 raise error.Abort(_(b"cannot abort using an old graftstate"))
3997
3997
3998 # changeset from which graft operation was started
3998 # changeset from which graft operation was started
3999 if len(newnodes) > 0:
3999 if len(newnodes) > 0:
4000 startctx = repo[newnodes[0]].p1()
4000 startctx = repo[newnodes[0]].p1()
4001 else:
4001 else:
4002 startctx = repo[b'.']
4002 startctx = repo[b'.']
4003 # whether to strip or not
4003 # whether to strip or not
4004 cleanup = False
4004 cleanup = False
4005 from . import hg
4005 from . import hg
4006
4006
4007 if newnodes:
4007 if newnodes:
4008 newnodes = [repo[r].rev() for r in newnodes]
4008 newnodes = [repo[r].rev() for r in newnodes]
4009 cleanup = True
4009 cleanup = True
4010 # checking that none of the newnodes turned public or is public
4010 # checking that none of the newnodes turned public or is public
4011 immutable = [c for c in newnodes if not repo[c].mutable()]
4011 immutable = [c for c in newnodes if not repo[c].mutable()]
4012 if immutable:
4012 if immutable:
4013 repo.ui.warn(
4013 repo.ui.warn(
4014 _(b"cannot clean up public changesets %s\n")
4014 _(b"cannot clean up public changesets %s\n")
4015 % b', '.join(bytes(repo[r]) for r in immutable),
4015 % b', '.join(bytes(repo[r]) for r in immutable),
4016 hint=_(b"see 'hg help phases' for details"),
4016 hint=_(b"see 'hg help phases' for details"),
4017 )
4017 )
4018 cleanup = False
4018 cleanup = False
4019
4019
4020 # checking that no new nodes are created on top of grafted revs
4020 # checking that no new nodes are created on top of grafted revs
4021 desc = set(repo.changelog.descendants(newnodes))
4021 desc = set(repo.changelog.descendants(newnodes))
4022 if desc - set(newnodes):
4022 if desc - set(newnodes):
4023 repo.ui.warn(
4023 repo.ui.warn(
4024 _(
4024 _(
4025 b"new changesets detected on destination "
4025 b"new changesets detected on destination "
4026 b"branch, can't strip\n"
4026 b"branch, can't strip\n"
4027 )
4027 )
4028 )
4028 )
4029 cleanup = False
4029 cleanup = False
4030
4030
4031 if cleanup:
4031 if cleanup:
4032 with repo.wlock(), repo.lock():
4032 with repo.wlock(), repo.lock():
4033 hg.updaterepo(repo, startctx.node(), overwrite=True)
4033 hg.updaterepo(repo, startctx.node(), overwrite=True)
4034 # stripping the new nodes created
4034 # stripping the new nodes created
4035 strippoints = [
4035 strippoints = [
4036 c.node() for c in repo.set(b"roots(%ld)", newnodes)
4036 c.node() for c in repo.set(b"roots(%ld)", newnodes)
4037 ]
4037 ]
4038 repair.strip(repo.ui, repo, strippoints, backup=False)
4038 repair.strip(repo.ui, repo, strippoints, backup=False)
4039
4039
4040 if not cleanup:
4040 if not cleanup:
4041 # we don't update to the startnode if we can't strip
4041 # we don't update to the startnode if we can't strip
4042 startctx = repo[b'.']
4042 startctx = repo[b'.']
4043 hg.updaterepo(repo, startctx.node(), overwrite=True)
4043 hg.updaterepo(repo, startctx.node(), overwrite=True)
4044
4044
4045 ui.status(_(b"graft aborted\n"))
4045 ui.status(_(b"graft aborted\n"))
4046 ui.status(_(b"working directory is now at %s\n") % startctx.hex()[:12])
4046 ui.status(_(b"working directory is now at %s\n") % startctx.hex()[:12])
4047 graftstate.delete()
4047 graftstate.delete()
4048 return 0
4048 return 0
4049
4049
4050
4050
4051 def readgraftstate(repo, graftstate):
4051 def readgraftstate(repo, graftstate):
4052 # type: (Any, statemod.cmdstate) -> Dict[bytes, Any]
4052 # type: (Any, statemod.cmdstate) -> Dict[bytes, Any]
4053 """read the graft state file and return a dict of the data stored in it"""
4053 """read the graft state file and return a dict of the data stored in it"""
4054 try:
4054 try:
4055 return graftstate.read()
4055 return graftstate.read()
4056 except error.CorruptedState:
4056 except error.CorruptedState:
4057 nodes = repo.vfs.read(b'graftstate').splitlines()
4057 nodes = repo.vfs.read(b'graftstate').splitlines()
4058 return {b'nodes': nodes}
4058 return {b'nodes': nodes}
4059
4059
4060
4060
4061 def hgabortgraft(ui, repo):
4061 def hgabortgraft(ui, repo):
4062 """ abort logic for aborting graft using 'hg abort'"""
4062 """ abort logic for aborting graft using 'hg abort'"""
4063 with repo.wlock():
4063 with repo.wlock():
4064 graftstate = statemod.cmdstate(repo, b'graftstate')
4064 graftstate = statemod.cmdstate(repo, b'graftstate')
4065 return abortgraft(ui, repo, graftstate)
4065 return abortgraft(ui, repo, graftstate)
@@ -1,1121 +1,1137 b''
1 # help.py - help data for mercurial
1 # help.py - help data for mercurial
2 #
2 #
3 # Copyright 2006 Matt Mackall <mpm@selenic.com>
3 # Copyright 2006 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import itertools
10 import itertools
11 import re
11 import re
12 import textwrap
12 import textwrap
13
13
14 from .i18n import (
14 from .i18n import (
15 _,
15 _,
16 gettext,
16 gettext,
17 )
17 )
18 from .pycompat import getattr
18 from .pycompat import getattr
19 from . import (
19 from . import (
20 cmdutil,
20 cmdutil,
21 encoding,
21 encoding,
22 error,
22 error,
23 extensions,
23 extensions,
24 fancyopts,
24 fancyopts,
25 filemerge,
25 filemerge,
26 fileset,
26 fileset,
27 minirst,
27 minirst,
28 pycompat,
28 pycompat,
29 registrar,
29 registrar,
30 revset,
30 revset,
31 templatefilters,
31 templatefilters,
32 templatefuncs,
32 templatefuncs,
33 templatekw,
33 templatekw,
34 ui as uimod,
34 ui as uimod,
35 util,
35 util,
36 )
36 )
37 from .hgweb import webcommands
37 from .hgweb import webcommands
38 from .utils import (
38 from .utils import (
39 compression,
39 compression,
40 resourceutil,
40 resourceutil,
41 )
41 )
42
42
43 _exclkeywords = {
43 _exclkeywords = {
44 b"(ADVANCED)",
44 b"(ADVANCED)",
45 b"(DEPRECATED)",
45 b"(DEPRECATED)",
46 b"(EXPERIMENTAL)",
46 b"(EXPERIMENTAL)",
47 # i18n: "(ADVANCED)" is a keyword, must be translated consistently
47 # i18n: "(ADVANCED)" is a keyword, must be translated consistently
48 _(b"(ADVANCED)"),
48 _(b"(ADVANCED)"),
49 # i18n: "(DEPRECATED)" is a keyword, must be translated consistently
49 # i18n: "(DEPRECATED)" is a keyword, must be translated consistently
50 _(b"(DEPRECATED)"),
50 _(b"(DEPRECATED)"),
51 # i18n: "(EXPERIMENTAL)" is a keyword, must be translated consistently
51 # i18n: "(EXPERIMENTAL)" is a keyword, must be translated consistently
52 _(b"(EXPERIMENTAL)"),
52 _(b"(EXPERIMENTAL)"),
53 }
53 }
54
54
55 # The order in which command categories will be displayed.
55 # The order in which command categories will be displayed.
56 # Extensions with custom categories should insert them into this list
56 # Extensions with custom categories should insert them into this list
57 # after/before the appropriate item, rather than replacing the list or
57 # after/before the appropriate item, rather than replacing the list or
58 # assuming absolute positions.
58 # assuming absolute positions.
59 CATEGORY_ORDER = [
59 CATEGORY_ORDER = [
60 registrar.command.CATEGORY_REPO_CREATION,
60 registrar.command.CATEGORY_REPO_CREATION,
61 registrar.command.CATEGORY_REMOTE_REPO_MANAGEMENT,
61 registrar.command.CATEGORY_REMOTE_REPO_MANAGEMENT,
62 registrar.command.CATEGORY_COMMITTING,
62 registrar.command.CATEGORY_COMMITTING,
63 registrar.command.CATEGORY_CHANGE_MANAGEMENT,
63 registrar.command.CATEGORY_CHANGE_MANAGEMENT,
64 registrar.command.CATEGORY_CHANGE_ORGANIZATION,
64 registrar.command.CATEGORY_CHANGE_ORGANIZATION,
65 registrar.command.CATEGORY_FILE_CONTENTS,
65 registrar.command.CATEGORY_FILE_CONTENTS,
66 registrar.command.CATEGORY_CHANGE_NAVIGATION,
66 registrar.command.CATEGORY_CHANGE_NAVIGATION,
67 registrar.command.CATEGORY_WORKING_DIRECTORY,
67 registrar.command.CATEGORY_WORKING_DIRECTORY,
68 registrar.command.CATEGORY_IMPORT_EXPORT,
68 registrar.command.CATEGORY_IMPORT_EXPORT,
69 registrar.command.CATEGORY_MAINTENANCE,
69 registrar.command.CATEGORY_MAINTENANCE,
70 registrar.command.CATEGORY_HELP,
70 registrar.command.CATEGORY_HELP,
71 registrar.command.CATEGORY_MISC,
71 registrar.command.CATEGORY_MISC,
72 registrar.command.CATEGORY_NONE,
72 registrar.command.CATEGORY_NONE,
73 ]
73 ]
74
74
75 # Human-readable category names. These are translated.
75 # Human-readable category names. These are translated.
76 # Extensions with custom categories should add their names here.
76 # Extensions with custom categories should add their names here.
77 CATEGORY_NAMES = {
77 CATEGORY_NAMES = {
78 registrar.command.CATEGORY_REPO_CREATION: b'Repository creation',
78 registrar.command.CATEGORY_REPO_CREATION: b'Repository creation',
79 registrar.command.CATEGORY_REMOTE_REPO_MANAGEMENT: b'Remote repository management',
79 registrar.command.CATEGORY_REMOTE_REPO_MANAGEMENT: b'Remote repository management',
80 registrar.command.CATEGORY_COMMITTING: b'Change creation',
80 registrar.command.CATEGORY_COMMITTING: b'Change creation',
81 registrar.command.CATEGORY_CHANGE_NAVIGATION: b'Change navigation',
81 registrar.command.CATEGORY_CHANGE_NAVIGATION: b'Change navigation',
82 registrar.command.CATEGORY_CHANGE_MANAGEMENT: b'Change manipulation',
82 registrar.command.CATEGORY_CHANGE_MANAGEMENT: b'Change manipulation',
83 registrar.command.CATEGORY_CHANGE_ORGANIZATION: b'Change organization',
83 registrar.command.CATEGORY_CHANGE_ORGANIZATION: b'Change organization',
84 registrar.command.CATEGORY_WORKING_DIRECTORY: b'Working directory management',
84 registrar.command.CATEGORY_WORKING_DIRECTORY: b'Working directory management',
85 registrar.command.CATEGORY_FILE_CONTENTS: b'File content management',
85 registrar.command.CATEGORY_FILE_CONTENTS: b'File content management',
86 registrar.command.CATEGORY_IMPORT_EXPORT: b'Change import/export',
86 registrar.command.CATEGORY_IMPORT_EXPORT: b'Change import/export',
87 registrar.command.CATEGORY_MAINTENANCE: b'Repository maintenance',
87 registrar.command.CATEGORY_MAINTENANCE: b'Repository maintenance',
88 registrar.command.CATEGORY_HELP: b'Help',
88 registrar.command.CATEGORY_HELP: b'Help',
89 registrar.command.CATEGORY_MISC: b'Miscellaneous commands',
89 registrar.command.CATEGORY_MISC: b'Miscellaneous commands',
90 registrar.command.CATEGORY_NONE: b'Uncategorized commands',
90 registrar.command.CATEGORY_NONE: b'Uncategorized commands',
91 }
91 }
92
92
93 # Topic categories.
93 # Topic categories.
94 TOPIC_CATEGORY_IDS = b'ids'
94 TOPIC_CATEGORY_IDS = b'ids'
95 TOPIC_CATEGORY_OUTPUT = b'output'
95 TOPIC_CATEGORY_OUTPUT = b'output'
96 TOPIC_CATEGORY_CONFIG = b'config'
96 TOPIC_CATEGORY_CONFIG = b'config'
97 TOPIC_CATEGORY_CONCEPTS = b'concepts'
97 TOPIC_CATEGORY_CONCEPTS = b'concepts'
98 TOPIC_CATEGORY_MISC = b'misc'
98 TOPIC_CATEGORY_MISC = b'misc'
99 TOPIC_CATEGORY_NONE = b'none'
99 TOPIC_CATEGORY_NONE = b'none'
100
100
101 # The order in which topic categories will be displayed.
101 # The order in which topic categories will be displayed.
102 # Extensions with custom categories should insert them into this list
102 # Extensions with custom categories should insert them into this list
103 # after/before the appropriate item, rather than replacing the list or
103 # after/before the appropriate item, rather than replacing the list or
104 # assuming absolute positions.
104 # assuming absolute positions.
105 TOPIC_CATEGORY_ORDER = [
105 TOPIC_CATEGORY_ORDER = [
106 TOPIC_CATEGORY_IDS,
106 TOPIC_CATEGORY_IDS,
107 TOPIC_CATEGORY_OUTPUT,
107 TOPIC_CATEGORY_OUTPUT,
108 TOPIC_CATEGORY_CONFIG,
108 TOPIC_CATEGORY_CONFIG,
109 TOPIC_CATEGORY_CONCEPTS,
109 TOPIC_CATEGORY_CONCEPTS,
110 TOPIC_CATEGORY_MISC,
110 TOPIC_CATEGORY_MISC,
111 TOPIC_CATEGORY_NONE,
111 TOPIC_CATEGORY_NONE,
112 ]
112 ]
113
113
114 # Human-readable topic category names. These are translated.
114 # Human-readable topic category names. These are translated.
115 TOPIC_CATEGORY_NAMES = {
115 TOPIC_CATEGORY_NAMES = {
116 TOPIC_CATEGORY_IDS: b'Mercurial identifiers',
116 TOPIC_CATEGORY_IDS: b'Mercurial identifiers',
117 TOPIC_CATEGORY_OUTPUT: b'Mercurial output',
117 TOPIC_CATEGORY_OUTPUT: b'Mercurial output',
118 TOPIC_CATEGORY_CONFIG: b'Mercurial configuration',
118 TOPIC_CATEGORY_CONFIG: b'Mercurial configuration',
119 TOPIC_CATEGORY_CONCEPTS: b'Concepts',
119 TOPIC_CATEGORY_CONCEPTS: b'Concepts',
120 TOPIC_CATEGORY_MISC: b'Miscellaneous',
120 TOPIC_CATEGORY_MISC: b'Miscellaneous',
121 TOPIC_CATEGORY_NONE: b'Uncategorized topics',
121 TOPIC_CATEGORY_NONE: b'Uncategorized topics',
122 }
122 }
123
123
124
124
125 def listexts(header, exts, indent=1, showdeprecated=False):
125 def listexts(header, exts, indent=1, showdeprecated=False):
126 '''return a text listing of the given extensions'''
126 '''return a text listing of the given extensions'''
127 rst = []
127 rst = []
128 if exts:
128 if exts:
129 for name, desc in sorted(pycompat.iteritems(exts)):
129 for name, desc in sorted(pycompat.iteritems(exts)):
130 if not showdeprecated and any(w in desc for w in _exclkeywords):
130 if not showdeprecated and any(w in desc for w in _exclkeywords):
131 continue
131 continue
132 rst.append(b'%s:%s: %s\n' % (b' ' * indent, name, desc))
132 rst.append(b'%s:%s: %s\n' % (b' ' * indent, name, desc))
133 if rst:
133 if rst:
134 rst.insert(0, b'\n%s\n\n' % header)
134 rst.insert(0, b'\n%s\n\n' % header)
135 return rst
135 return rst
136
136
137
137
138 def extshelp(ui):
138 def extshelp(ui):
139 rst = loaddoc(b'extensions')(ui).splitlines(True)
139 rst = loaddoc(b'extensions')(ui).splitlines(True)
140 rst.extend(
140 rst.extend(
141 listexts(
141 listexts(
142 _(b'enabled extensions:'), extensions.enabled(), showdeprecated=True
142 _(b'enabled extensions:'), extensions.enabled(), showdeprecated=True
143 )
143 )
144 )
144 )
145 rst.extend(
145 rst.extend(
146 listexts(
146 listexts(
147 _(b'disabled extensions:'),
147 _(b'disabled extensions:'),
148 extensions.disabled(),
148 extensions.disabled(),
149 showdeprecated=ui.verbose,
149 showdeprecated=ui.verbose,
150 )
150 )
151 )
151 )
152 doc = b''.join(rst)
152 doc = b''.join(rst)
153 return doc
153 return doc
154
154
155 def parsedefaultmarker(text):
156 """given a text 'abc (DEFAULT: def.ghi)',
157 returns (b'abc', (b'def', b'ghi')). Otherwise return None"""
158 if text[-1:] == b')':
159 marker = b' (DEFAULT: '
160 pos = text.find(marker)
161 if pos >= 0:
162 item = text[pos + len(marker):-1]
163 return text[:pos], item.split(b'.', 2)
155
164
156 def optrst(header, options, verbose):
165 def optrst(header, options, verbose, ui):
157 data = []
166 data = []
158 multioccur = False
167 multioccur = False
159 for option in options:
168 for option in options:
160 if len(option) == 5:
169 if len(option) == 5:
161 shortopt, longopt, default, desc, optlabel = option
170 shortopt, longopt, default, desc, optlabel = option
162 else:
171 else:
163 shortopt, longopt, default, desc = option
172 shortopt, longopt, default, desc = option
164 optlabel = _(b"VALUE") # default label
173 optlabel = _(b"VALUE") # default label
165
174
166 if not verbose and any(w in desc for w in _exclkeywords):
175 if not verbose and any(w in desc for w in _exclkeywords):
167 continue
176 continue
168
177 defaultstrsuffix = b''
178 if default is None:
179 parseresult = parsedefaultmarker(desc)
180 if parseresult is not None:
181 (desc, (section, name)) = parseresult
182 if ui.configbool(section, name):
183 default = True
184 defaultstrsuffix = _(b' from config')
169 so = b''
185 so = b''
170 if shortopt:
186 if shortopt:
171 so = b'-' + shortopt
187 so = b'-' + shortopt
172 lo = b'--' + longopt
188 lo = b'--' + longopt
173 if default is True:
189 if default is True:
174 lo = b'--[no-]' + longopt
190 lo = b'--[no-]' + longopt
175
191
176 if isinstance(default, fancyopts.customopt):
192 if isinstance(default, fancyopts.customopt):
177 default = default.getdefaultvalue()
193 default = default.getdefaultvalue()
178 if default and not callable(default):
194 if default and not callable(default):
179 # default is of unknown type, and in Python 2 we abused
195 # default is of unknown type, and in Python 2 we abused
180 # the %s-shows-repr property to handle integers etc. To
196 # the %s-shows-repr property to handle integers etc. To
181 # match that behavior on Python 3, we do str(default) and
197 # match that behavior on Python 3, we do str(default) and
182 # then convert it to bytes.
198 # then convert it to bytes.
183 defaultstr = pycompat.bytestr(default)
199 defaultstr = pycompat.bytestr(default)
184 if default is True:
200 if default is True:
185 defaultstr = _(b"on")
201 defaultstr = _(b"on")
186 desc += _(b" (default: %s)") % defaultstr
202 desc += _(b" (default: %s)") % (defaultstr + defaultstrsuffix)
187
203
188 if isinstance(default, list):
204 if isinstance(default, list):
189 lo += b" %s [+]" % optlabel
205 lo += b" %s [+]" % optlabel
190 multioccur = True
206 multioccur = True
191 elif (default is not None) and not isinstance(default, bool):
207 elif (default is not None) and not isinstance(default, bool):
192 lo += b" %s" % optlabel
208 lo += b" %s" % optlabel
193
209
194 data.append((so, lo, desc))
210 data.append((so, lo, desc))
195
211
196 if multioccur:
212 if multioccur:
197 header += _(b" ([+] can be repeated)")
213 header += _(b" ([+] can be repeated)")
198
214
199 rst = [b'\n%s:\n\n' % header]
215 rst = [b'\n%s:\n\n' % header]
200 rst.extend(minirst.maketable(data, 1))
216 rst.extend(minirst.maketable(data, 1))
201
217
202 return b''.join(rst)
218 return b''.join(rst)
203
219
204
220
205 def indicateomitted(rst, omitted, notomitted=None):
221 def indicateomitted(rst, omitted, notomitted=None):
206 rst.append(b'\n\n.. container:: omitted\n\n %s\n\n' % omitted)
222 rst.append(b'\n\n.. container:: omitted\n\n %s\n\n' % omitted)
207 if notomitted:
223 if notomitted:
208 rst.append(b'\n\n.. container:: notomitted\n\n %s\n\n' % notomitted)
224 rst.append(b'\n\n.. container:: notomitted\n\n %s\n\n' % notomitted)
209
225
210
226
211 def filtercmd(ui, cmd, func, kw, doc):
227 def filtercmd(ui, cmd, func, kw, doc):
212 if not ui.debugflag and cmd.startswith(b"debug") and kw != b"debug":
228 if not ui.debugflag and cmd.startswith(b"debug") and kw != b"debug":
213 # Debug command, and user is not looking for those.
229 # Debug command, and user is not looking for those.
214 return True
230 return True
215 if not ui.verbose:
231 if not ui.verbose:
216 if not kw and not doc:
232 if not kw and not doc:
217 # Command had no documentation, no point in showing it by default.
233 # Command had no documentation, no point in showing it by default.
218 return True
234 return True
219 if getattr(func, 'alias', False) and not getattr(func, 'owndoc', False):
235 if getattr(func, 'alias', False) and not getattr(func, 'owndoc', False):
220 # Alias didn't have its own documentation.
236 # Alias didn't have its own documentation.
221 return True
237 return True
222 if doc and any(w in doc for w in _exclkeywords):
238 if doc and any(w in doc for w in _exclkeywords):
223 # Documentation has excluded keywords.
239 # Documentation has excluded keywords.
224 return True
240 return True
225 if kw == b"shortlist" and not getattr(func, 'helpbasic', False):
241 if kw == b"shortlist" and not getattr(func, 'helpbasic', False):
226 # We're presenting the short list but the command is not basic.
242 # We're presenting the short list but the command is not basic.
227 return True
243 return True
228 if ui.configbool(b'help', b'hidden-command.%s' % cmd):
244 if ui.configbool(b'help', b'hidden-command.%s' % cmd):
229 # Configuration explicitly hides the command.
245 # Configuration explicitly hides the command.
230 return True
246 return True
231 return False
247 return False
232
248
233
249
234 def filtertopic(ui, topic):
250 def filtertopic(ui, topic):
235 return ui.configbool(b'help', b'hidden-topic.%s' % topic, False)
251 return ui.configbool(b'help', b'hidden-topic.%s' % topic, False)
236
252
237
253
238 def topicmatch(ui, commands, kw):
254 def topicmatch(ui, commands, kw):
239 """Return help topics matching kw.
255 """Return help topics matching kw.
240
256
241 Returns {'section': [(name, summary), ...], ...} where section is
257 Returns {'section': [(name, summary), ...], ...} where section is
242 one of topics, commands, extensions, or extensioncommands.
258 one of topics, commands, extensions, or extensioncommands.
243 """
259 """
244 kw = encoding.lower(kw)
260 kw = encoding.lower(kw)
245
261
246 def lowercontains(container):
262 def lowercontains(container):
247 return kw in encoding.lower(container) # translated in helptable
263 return kw in encoding.lower(container) # translated in helptable
248
264
249 results = {
265 results = {
250 b'topics': [],
266 b'topics': [],
251 b'commands': [],
267 b'commands': [],
252 b'extensions': [],
268 b'extensions': [],
253 b'extensioncommands': [],
269 b'extensioncommands': [],
254 }
270 }
255 for topic in helptable:
271 for topic in helptable:
256 names, header, doc = topic[0:3]
272 names, header, doc = topic[0:3]
257 # Old extensions may use a str as doc.
273 # Old extensions may use a str as doc.
258 if (
274 if (
259 sum(map(lowercontains, names))
275 sum(map(lowercontains, names))
260 or lowercontains(header)
276 or lowercontains(header)
261 or (callable(doc) and lowercontains(doc(ui)))
277 or (callable(doc) and lowercontains(doc(ui)))
262 ):
278 ):
263 name = names[0]
279 name = names[0]
264 if not filtertopic(ui, name):
280 if not filtertopic(ui, name):
265 results[b'topics'].append((names[0], header))
281 results[b'topics'].append((names[0], header))
266 for cmd, entry in pycompat.iteritems(commands.table):
282 for cmd, entry in pycompat.iteritems(commands.table):
267 if len(entry) == 3:
283 if len(entry) == 3:
268 summary = entry[2]
284 summary = entry[2]
269 else:
285 else:
270 summary = b''
286 summary = b''
271 # translate docs *before* searching there
287 # translate docs *before* searching there
272 func = entry[0]
288 func = entry[0]
273 docs = _(pycompat.getdoc(func)) or b''
289 docs = _(pycompat.getdoc(func)) or b''
274 if kw in cmd or lowercontains(summary) or lowercontains(docs):
290 if kw in cmd or lowercontains(summary) or lowercontains(docs):
275 doclines = docs.splitlines()
291 doclines = docs.splitlines()
276 if doclines:
292 if doclines:
277 summary = doclines[0]
293 summary = doclines[0]
278 cmdname = cmdutil.parsealiases(cmd)[0]
294 cmdname = cmdutil.parsealiases(cmd)[0]
279 if filtercmd(ui, cmdname, func, kw, docs):
295 if filtercmd(ui, cmdname, func, kw, docs):
280 continue
296 continue
281 results[b'commands'].append((cmdname, summary))
297 results[b'commands'].append((cmdname, summary))
282 for name, docs in itertools.chain(
298 for name, docs in itertools.chain(
283 pycompat.iteritems(extensions.enabled(False)),
299 pycompat.iteritems(extensions.enabled(False)),
284 pycompat.iteritems(extensions.disabled()),
300 pycompat.iteritems(extensions.disabled()),
285 ):
301 ):
286 if not docs:
302 if not docs:
287 continue
303 continue
288 name = name.rpartition(b'.')[-1]
304 name = name.rpartition(b'.')[-1]
289 if lowercontains(name) or lowercontains(docs):
305 if lowercontains(name) or lowercontains(docs):
290 # extension docs are already translated
306 # extension docs are already translated
291 results[b'extensions'].append((name, docs.splitlines()[0]))
307 results[b'extensions'].append((name, docs.splitlines()[0]))
292 try:
308 try:
293 mod = extensions.load(ui, name, b'')
309 mod = extensions.load(ui, name, b'')
294 except ImportError:
310 except ImportError:
295 # debug message would be printed in extensions.load()
311 # debug message would be printed in extensions.load()
296 continue
312 continue
297 for cmd, entry in pycompat.iteritems(getattr(mod, 'cmdtable', {})):
313 for cmd, entry in pycompat.iteritems(getattr(mod, 'cmdtable', {})):
298 if kw in cmd or (len(entry) > 2 and lowercontains(entry[2])):
314 if kw in cmd or (len(entry) > 2 and lowercontains(entry[2])):
299 cmdname = cmdutil.parsealiases(cmd)[0]
315 cmdname = cmdutil.parsealiases(cmd)[0]
300 func = entry[0]
316 func = entry[0]
301 cmddoc = pycompat.getdoc(func)
317 cmddoc = pycompat.getdoc(func)
302 if cmddoc:
318 if cmddoc:
303 cmddoc = gettext(cmddoc).splitlines()[0]
319 cmddoc = gettext(cmddoc).splitlines()[0]
304 else:
320 else:
305 cmddoc = _(b'(no help text available)')
321 cmddoc = _(b'(no help text available)')
306 if filtercmd(ui, cmdname, func, kw, cmddoc):
322 if filtercmd(ui, cmdname, func, kw, cmddoc):
307 continue
323 continue
308 results[b'extensioncommands'].append((cmdname, cmddoc))
324 results[b'extensioncommands'].append((cmdname, cmddoc))
309 return results
325 return results
310
326
311
327
312 def loaddoc(topic, subdir=None):
328 def loaddoc(topic, subdir=None):
313 """Return a delayed loader for help/topic.txt."""
329 """Return a delayed loader for help/topic.txt."""
314
330
315 def loader(ui):
331 def loader(ui):
316 package = b'mercurial.helptext'
332 package = b'mercurial.helptext'
317 if subdir:
333 if subdir:
318 package += b'.' + subdir
334 package += b'.' + subdir
319 with resourceutil.open_resource(package, topic + b'.txt') as fp:
335 with resourceutil.open_resource(package, topic + b'.txt') as fp:
320 doc = gettext(fp.read())
336 doc = gettext(fp.read())
321 for rewriter in helphooks.get(topic, []):
337 for rewriter in helphooks.get(topic, []):
322 doc = rewriter(ui, topic, doc)
338 doc = rewriter(ui, topic, doc)
323 return doc
339 return doc
324
340
325 return loader
341 return loader
326
342
327
343
328 internalstable = sorted(
344 internalstable = sorted(
329 [
345 [
330 ([b'bundle2'], _(b'Bundle2'), loaddoc(b'bundle2', subdir=b'internals')),
346 ([b'bundle2'], _(b'Bundle2'), loaddoc(b'bundle2', subdir=b'internals')),
331 ([b'bundles'], _(b'Bundles'), loaddoc(b'bundles', subdir=b'internals')),
347 ([b'bundles'], _(b'Bundles'), loaddoc(b'bundles', subdir=b'internals')),
332 ([b'cbor'], _(b'CBOR'), loaddoc(b'cbor', subdir=b'internals')),
348 ([b'cbor'], _(b'CBOR'), loaddoc(b'cbor', subdir=b'internals')),
333 ([b'censor'], _(b'Censor'), loaddoc(b'censor', subdir=b'internals')),
349 ([b'censor'], _(b'Censor'), loaddoc(b'censor', subdir=b'internals')),
334 (
350 (
335 [b'changegroups'],
351 [b'changegroups'],
336 _(b'Changegroups'),
352 _(b'Changegroups'),
337 loaddoc(b'changegroups', subdir=b'internals'),
353 loaddoc(b'changegroups', subdir=b'internals'),
338 ),
354 ),
339 (
355 (
340 [b'config'],
356 [b'config'],
341 _(b'Config Registrar'),
357 _(b'Config Registrar'),
342 loaddoc(b'config', subdir=b'internals'),
358 loaddoc(b'config', subdir=b'internals'),
343 ),
359 ),
344 (
360 (
345 [b'extensions', b'extension'],
361 [b'extensions', b'extension'],
346 _(b'Extension API'),
362 _(b'Extension API'),
347 loaddoc(b'extensions', subdir=b'internals'),
363 loaddoc(b'extensions', subdir=b'internals'),
348 ),
364 ),
349 (
365 (
350 [b'mergestate'],
366 [b'mergestate'],
351 _(b'Mergestate'),
367 _(b'Mergestate'),
352 loaddoc(b'mergestate', subdir=b'internals'),
368 loaddoc(b'mergestate', subdir=b'internals'),
353 ),
369 ),
354 (
370 (
355 [b'requirements'],
371 [b'requirements'],
356 _(b'Repository Requirements'),
372 _(b'Repository Requirements'),
357 loaddoc(b'requirements', subdir=b'internals'),
373 loaddoc(b'requirements', subdir=b'internals'),
358 ),
374 ),
359 (
375 (
360 [b'revlogs'],
376 [b'revlogs'],
361 _(b'Revision Logs'),
377 _(b'Revision Logs'),
362 loaddoc(b'revlogs', subdir=b'internals'),
378 loaddoc(b'revlogs', subdir=b'internals'),
363 ),
379 ),
364 (
380 (
365 [b'wireprotocol'],
381 [b'wireprotocol'],
366 _(b'Wire Protocol'),
382 _(b'Wire Protocol'),
367 loaddoc(b'wireprotocol', subdir=b'internals'),
383 loaddoc(b'wireprotocol', subdir=b'internals'),
368 ),
384 ),
369 (
385 (
370 [b'wireprotocolrpc'],
386 [b'wireprotocolrpc'],
371 _(b'Wire Protocol RPC'),
387 _(b'Wire Protocol RPC'),
372 loaddoc(b'wireprotocolrpc', subdir=b'internals'),
388 loaddoc(b'wireprotocolrpc', subdir=b'internals'),
373 ),
389 ),
374 (
390 (
375 [b'wireprotocolv2'],
391 [b'wireprotocolv2'],
376 _(b'Wire Protocol Version 2'),
392 _(b'Wire Protocol Version 2'),
377 loaddoc(b'wireprotocolv2', subdir=b'internals'),
393 loaddoc(b'wireprotocolv2', subdir=b'internals'),
378 ),
394 ),
379 ]
395 ]
380 )
396 )
381
397
382
398
383 def internalshelp(ui):
399 def internalshelp(ui):
384 """Generate the index for the "internals" topic."""
400 """Generate the index for the "internals" topic."""
385 lines = [
401 lines = [
386 b'To access a subtopic, use "hg help internals.{subtopic-name}"\n',
402 b'To access a subtopic, use "hg help internals.{subtopic-name}"\n',
387 b'\n',
403 b'\n',
388 ]
404 ]
389 for names, header, doc in internalstable:
405 for names, header, doc in internalstable:
390 lines.append(b' :%s: %s\n' % (names[0], header))
406 lines.append(b' :%s: %s\n' % (names[0], header))
391
407
392 return b''.join(lines)
408 return b''.join(lines)
393
409
394
410
395 helptable = sorted(
411 helptable = sorted(
396 [
412 [
397 (
413 (
398 [b'bundlespec'],
414 [b'bundlespec'],
399 _(b"Bundle File Formats"),
415 _(b"Bundle File Formats"),
400 loaddoc(b'bundlespec'),
416 loaddoc(b'bundlespec'),
401 TOPIC_CATEGORY_CONCEPTS,
417 TOPIC_CATEGORY_CONCEPTS,
402 ),
418 ),
403 (
419 (
404 [b'color'],
420 [b'color'],
405 _(b"Colorizing Outputs"),
421 _(b"Colorizing Outputs"),
406 loaddoc(b'color'),
422 loaddoc(b'color'),
407 TOPIC_CATEGORY_OUTPUT,
423 TOPIC_CATEGORY_OUTPUT,
408 ),
424 ),
409 (
425 (
410 [b"config", b"hgrc"],
426 [b"config", b"hgrc"],
411 _(b"Configuration Files"),
427 _(b"Configuration Files"),
412 loaddoc(b'config'),
428 loaddoc(b'config'),
413 TOPIC_CATEGORY_CONFIG,
429 TOPIC_CATEGORY_CONFIG,
414 ),
430 ),
415 (
431 (
416 [b'deprecated'],
432 [b'deprecated'],
417 _(b"Deprecated Features"),
433 _(b"Deprecated Features"),
418 loaddoc(b'deprecated'),
434 loaddoc(b'deprecated'),
419 TOPIC_CATEGORY_MISC,
435 TOPIC_CATEGORY_MISC,
420 ),
436 ),
421 (
437 (
422 [b"dates"],
438 [b"dates"],
423 _(b"Date Formats"),
439 _(b"Date Formats"),
424 loaddoc(b'dates'),
440 loaddoc(b'dates'),
425 TOPIC_CATEGORY_OUTPUT,
441 TOPIC_CATEGORY_OUTPUT,
426 ),
442 ),
427 (
443 (
428 [b"flags"],
444 [b"flags"],
429 _(b"Command-line flags"),
445 _(b"Command-line flags"),
430 loaddoc(b'flags'),
446 loaddoc(b'flags'),
431 TOPIC_CATEGORY_CONFIG,
447 TOPIC_CATEGORY_CONFIG,
432 ),
448 ),
433 (
449 (
434 [b"patterns"],
450 [b"patterns"],
435 _(b"File Name Patterns"),
451 _(b"File Name Patterns"),
436 loaddoc(b'patterns'),
452 loaddoc(b'patterns'),
437 TOPIC_CATEGORY_IDS,
453 TOPIC_CATEGORY_IDS,
438 ),
454 ),
439 (
455 (
440 [b'environment', b'env'],
456 [b'environment', b'env'],
441 _(b'Environment Variables'),
457 _(b'Environment Variables'),
442 loaddoc(b'environment'),
458 loaddoc(b'environment'),
443 TOPIC_CATEGORY_CONFIG,
459 TOPIC_CATEGORY_CONFIG,
444 ),
460 ),
445 (
461 (
446 [
462 [
447 b'revisions',
463 b'revisions',
448 b'revs',
464 b'revs',
449 b'revsets',
465 b'revsets',
450 b'revset',
466 b'revset',
451 b'multirevs',
467 b'multirevs',
452 b'mrevs',
468 b'mrevs',
453 ],
469 ],
454 _(b'Specifying Revisions'),
470 _(b'Specifying Revisions'),
455 loaddoc(b'revisions'),
471 loaddoc(b'revisions'),
456 TOPIC_CATEGORY_IDS,
472 TOPIC_CATEGORY_IDS,
457 ),
473 ),
458 (
474 (
459 [b'filesets', b'fileset'],
475 [b'filesets', b'fileset'],
460 _(b"Specifying File Sets"),
476 _(b"Specifying File Sets"),
461 loaddoc(b'filesets'),
477 loaddoc(b'filesets'),
462 TOPIC_CATEGORY_IDS,
478 TOPIC_CATEGORY_IDS,
463 ),
479 ),
464 (
480 (
465 [b'diffs'],
481 [b'diffs'],
466 _(b'Diff Formats'),
482 _(b'Diff Formats'),
467 loaddoc(b'diffs'),
483 loaddoc(b'diffs'),
468 TOPIC_CATEGORY_OUTPUT,
484 TOPIC_CATEGORY_OUTPUT,
469 ),
485 ),
470 (
486 (
471 [b'merge-tools', b'mergetools', b'mergetool'],
487 [b'merge-tools', b'mergetools', b'mergetool'],
472 _(b'Merge Tools'),
488 _(b'Merge Tools'),
473 loaddoc(b'merge-tools'),
489 loaddoc(b'merge-tools'),
474 TOPIC_CATEGORY_CONFIG,
490 TOPIC_CATEGORY_CONFIG,
475 ),
491 ),
476 (
492 (
477 [b'templating', b'templates', b'template', b'style'],
493 [b'templating', b'templates', b'template', b'style'],
478 _(b'Template Usage'),
494 _(b'Template Usage'),
479 loaddoc(b'templates'),
495 loaddoc(b'templates'),
480 TOPIC_CATEGORY_OUTPUT,
496 TOPIC_CATEGORY_OUTPUT,
481 ),
497 ),
482 ([b'urls'], _(b'URL Paths'), loaddoc(b'urls'), TOPIC_CATEGORY_IDS),
498 ([b'urls'], _(b'URL Paths'), loaddoc(b'urls'), TOPIC_CATEGORY_IDS),
483 (
499 (
484 [b"extensions"],
500 [b"extensions"],
485 _(b"Using Additional Features"),
501 _(b"Using Additional Features"),
486 extshelp,
502 extshelp,
487 TOPIC_CATEGORY_CONFIG,
503 TOPIC_CATEGORY_CONFIG,
488 ),
504 ),
489 (
505 (
490 [b"subrepos", b"subrepo"],
506 [b"subrepos", b"subrepo"],
491 _(b"Subrepositories"),
507 _(b"Subrepositories"),
492 loaddoc(b'subrepos'),
508 loaddoc(b'subrepos'),
493 TOPIC_CATEGORY_CONCEPTS,
509 TOPIC_CATEGORY_CONCEPTS,
494 ),
510 ),
495 (
511 (
496 [b"hgweb"],
512 [b"hgweb"],
497 _(b"Configuring hgweb"),
513 _(b"Configuring hgweb"),
498 loaddoc(b'hgweb'),
514 loaddoc(b'hgweb'),
499 TOPIC_CATEGORY_CONFIG,
515 TOPIC_CATEGORY_CONFIG,
500 ),
516 ),
501 (
517 (
502 [b"glossary"],
518 [b"glossary"],
503 _(b"Glossary"),
519 _(b"Glossary"),
504 loaddoc(b'glossary'),
520 loaddoc(b'glossary'),
505 TOPIC_CATEGORY_CONCEPTS,
521 TOPIC_CATEGORY_CONCEPTS,
506 ),
522 ),
507 (
523 (
508 [b"hgignore", b"ignore"],
524 [b"hgignore", b"ignore"],
509 _(b"Syntax for Mercurial Ignore Files"),
525 _(b"Syntax for Mercurial Ignore Files"),
510 loaddoc(b'hgignore'),
526 loaddoc(b'hgignore'),
511 TOPIC_CATEGORY_IDS,
527 TOPIC_CATEGORY_IDS,
512 ),
528 ),
513 (
529 (
514 [b"phases"],
530 [b"phases"],
515 _(b"Working with Phases"),
531 _(b"Working with Phases"),
516 loaddoc(b'phases'),
532 loaddoc(b'phases'),
517 TOPIC_CATEGORY_CONCEPTS,
533 TOPIC_CATEGORY_CONCEPTS,
518 ),
534 ),
519 (
535 (
520 [b'scripting'],
536 [b'scripting'],
521 _(b'Using Mercurial from scripts and automation'),
537 _(b'Using Mercurial from scripts and automation'),
522 loaddoc(b'scripting'),
538 loaddoc(b'scripting'),
523 TOPIC_CATEGORY_MISC,
539 TOPIC_CATEGORY_MISC,
524 ),
540 ),
525 (
541 (
526 [b'internals'],
542 [b'internals'],
527 _(b"Technical implementation topics"),
543 _(b"Technical implementation topics"),
528 internalshelp,
544 internalshelp,
529 TOPIC_CATEGORY_MISC,
545 TOPIC_CATEGORY_MISC,
530 ),
546 ),
531 (
547 (
532 [b'pager'],
548 [b'pager'],
533 _(b"Pager Support"),
549 _(b"Pager Support"),
534 loaddoc(b'pager'),
550 loaddoc(b'pager'),
535 TOPIC_CATEGORY_CONFIG,
551 TOPIC_CATEGORY_CONFIG,
536 ),
552 ),
537 ]
553 ]
538 )
554 )
539
555
540 # Maps topics with sub-topics to a list of their sub-topics.
556 # Maps topics with sub-topics to a list of their sub-topics.
541 subtopics = {
557 subtopics = {
542 b'internals': internalstable,
558 b'internals': internalstable,
543 }
559 }
544
560
545 # Map topics to lists of callable taking the current topic help and
561 # Map topics to lists of callable taking the current topic help and
546 # returning the updated version
562 # returning the updated version
547 helphooks = {}
563 helphooks = {}
548
564
549
565
550 def addtopichook(topic, rewriter):
566 def addtopichook(topic, rewriter):
551 helphooks.setdefault(topic, []).append(rewriter)
567 helphooks.setdefault(topic, []).append(rewriter)
552
568
553
569
554 def makeitemsdoc(ui, topic, doc, marker, items, dedent=False):
570 def makeitemsdoc(ui, topic, doc, marker, items, dedent=False):
555 """Extract docstring from the items key to function mapping, build a
571 """Extract docstring from the items key to function mapping, build a
556 single documentation block and use it to overwrite the marker in doc.
572 single documentation block and use it to overwrite the marker in doc.
557 """
573 """
558 entries = []
574 entries = []
559 for name in sorted(items):
575 for name in sorted(items):
560 text = (pycompat.getdoc(items[name]) or b'').rstrip()
576 text = (pycompat.getdoc(items[name]) or b'').rstrip()
561 if not text or not ui.verbose and any(w in text for w in _exclkeywords):
577 if not text or not ui.verbose and any(w in text for w in _exclkeywords):
562 continue
578 continue
563 text = gettext(text)
579 text = gettext(text)
564 if dedent:
580 if dedent:
565 # Abuse latin1 to use textwrap.dedent() on bytes.
581 # Abuse latin1 to use textwrap.dedent() on bytes.
566 text = textwrap.dedent(text.decode('latin1')).encode('latin1')
582 text = textwrap.dedent(text.decode('latin1')).encode('latin1')
567 lines = text.splitlines()
583 lines = text.splitlines()
568 doclines = [(lines[0])]
584 doclines = [(lines[0])]
569 for l in lines[1:]:
585 for l in lines[1:]:
570 # Stop once we find some Python doctest
586 # Stop once we find some Python doctest
571 if l.strip().startswith(b'>>>'):
587 if l.strip().startswith(b'>>>'):
572 break
588 break
573 if dedent:
589 if dedent:
574 doclines.append(l.rstrip())
590 doclines.append(l.rstrip())
575 else:
591 else:
576 doclines.append(b' ' + l.strip())
592 doclines.append(b' ' + l.strip())
577 entries.append(b'\n'.join(doclines))
593 entries.append(b'\n'.join(doclines))
578 entries = b'\n\n'.join(entries)
594 entries = b'\n\n'.join(entries)
579 return doc.replace(marker, entries)
595 return doc.replace(marker, entries)
580
596
581
597
582 def addtopicsymbols(topic, marker, symbols, dedent=False):
598 def addtopicsymbols(topic, marker, symbols, dedent=False):
583 def add(ui, topic, doc):
599 def add(ui, topic, doc):
584 return makeitemsdoc(ui, topic, doc, marker, symbols, dedent=dedent)
600 return makeitemsdoc(ui, topic, doc, marker, symbols, dedent=dedent)
585
601
586 addtopichook(topic, add)
602 addtopichook(topic, add)
587
603
588
604
589 addtopicsymbols(
605 addtopicsymbols(
590 b'bundlespec',
606 b'bundlespec',
591 b'.. bundlecompressionmarker',
607 b'.. bundlecompressionmarker',
592 compression.bundlecompressiontopics(),
608 compression.bundlecompressiontopics(),
593 )
609 )
594 addtopicsymbols(b'filesets', b'.. predicatesmarker', fileset.symbols)
610 addtopicsymbols(b'filesets', b'.. predicatesmarker', fileset.symbols)
595 addtopicsymbols(
611 addtopicsymbols(
596 b'merge-tools', b'.. internaltoolsmarker', filemerge.internalsdoc
612 b'merge-tools', b'.. internaltoolsmarker', filemerge.internalsdoc
597 )
613 )
598 addtopicsymbols(b'revisions', b'.. predicatesmarker', revset.symbols)
614 addtopicsymbols(b'revisions', b'.. predicatesmarker', revset.symbols)
599 addtopicsymbols(b'templates', b'.. keywordsmarker', templatekw.keywords)
615 addtopicsymbols(b'templates', b'.. keywordsmarker', templatekw.keywords)
600 addtopicsymbols(b'templates', b'.. filtersmarker', templatefilters.filters)
616 addtopicsymbols(b'templates', b'.. filtersmarker', templatefilters.filters)
601 addtopicsymbols(b'templates', b'.. functionsmarker', templatefuncs.funcs)
617 addtopicsymbols(b'templates', b'.. functionsmarker', templatefuncs.funcs)
602 addtopicsymbols(
618 addtopicsymbols(
603 b'hgweb', b'.. webcommandsmarker', webcommands.commands, dedent=True
619 b'hgweb', b'.. webcommandsmarker', webcommands.commands, dedent=True
604 )
620 )
605
621
606
622
607 def inserttweakrc(ui, topic, doc):
623 def inserttweakrc(ui, topic, doc):
608 marker = b'.. tweakdefaultsmarker'
624 marker = b'.. tweakdefaultsmarker'
609 repl = uimod.tweakrc
625 repl = uimod.tweakrc
610
626
611 def sub(m):
627 def sub(m):
612 lines = [m.group(1) + s for s in repl.splitlines()]
628 lines = [m.group(1) + s for s in repl.splitlines()]
613 return b'\n'.join(lines)
629 return b'\n'.join(lines)
614
630
615 return re.sub(br'( *)%s' % re.escape(marker), sub, doc)
631 return re.sub(br'( *)%s' % re.escape(marker), sub, doc)
616
632
617
633
618 addtopichook(b'config', inserttweakrc)
634 addtopichook(b'config', inserttweakrc)
619
635
620
636
621 def help_(
637 def help_(
622 ui,
638 ui,
623 commands,
639 commands,
624 name,
640 name,
625 unknowncmd=False,
641 unknowncmd=False,
626 full=True,
642 full=True,
627 subtopic=None,
643 subtopic=None,
628 fullname=None,
644 fullname=None,
629 **opts
645 **opts
630 ):
646 ):
631 '''
647 '''
632 Generate the help for 'name' as unformatted restructured text. If
648 Generate the help for 'name' as unformatted restructured text. If
633 'name' is None, describe the commands available.
649 'name' is None, describe the commands available.
634 '''
650 '''
635
651
636 opts = pycompat.byteskwargs(opts)
652 opts = pycompat.byteskwargs(opts)
637
653
638 def helpcmd(name, subtopic=None):
654 def helpcmd(name, subtopic=None):
639 try:
655 try:
640 aliases, entry = cmdutil.findcmd(
656 aliases, entry = cmdutil.findcmd(
641 name, commands.table, strict=unknowncmd
657 name, commands.table, strict=unknowncmd
642 )
658 )
643 except error.AmbiguousCommand as inst:
659 except error.AmbiguousCommand as inst:
644 # py3 fix: except vars can't be used outside the scope of the
660 # py3 fix: except vars can't be used outside the scope of the
645 # except block, nor can be used inside a lambda. python issue4617
661 # except block, nor can be used inside a lambda. python issue4617
646 prefix = inst.args[0]
662 prefix = inst.args[0]
647 select = lambda c: cmdutil.parsealiases(c)[0].startswith(prefix)
663 select = lambda c: cmdutil.parsealiases(c)[0].startswith(prefix)
648 rst = helplist(select)
664 rst = helplist(select)
649 return rst
665 return rst
650
666
651 rst = []
667 rst = []
652
668
653 # check if it's an invalid alias and display its error if it is
669 # check if it's an invalid alias and display its error if it is
654 if getattr(entry[0], 'badalias', None):
670 if getattr(entry[0], 'badalias', None):
655 rst.append(entry[0].badalias + b'\n')
671 rst.append(entry[0].badalias + b'\n')
656 if entry[0].unknowncmd:
672 if entry[0].unknowncmd:
657 try:
673 try:
658 rst.extend(helpextcmd(entry[0].cmdname))
674 rst.extend(helpextcmd(entry[0].cmdname))
659 except error.UnknownCommand:
675 except error.UnknownCommand:
660 pass
676 pass
661 return rst
677 return rst
662
678
663 # synopsis
679 # synopsis
664 if len(entry) > 2:
680 if len(entry) > 2:
665 if entry[2].startswith(b'hg'):
681 if entry[2].startswith(b'hg'):
666 rst.append(b"%s\n" % entry[2])
682 rst.append(b"%s\n" % entry[2])
667 else:
683 else:
668 rst.append(b'hg %s %s\n' % (aliases[0], entry[2]))
684 rst.append(b'hg %s %s\n' % (aliases[0], entry[2]))
669 else:
685 else:
670 rst.append(b'hg %s\n' % aliases[0])
686 rst.append(b'hg %s\n' % aliases[0])
671 # aliases
687 # aliases
672 if full and not ui.quiet and len(aliases) > 1:
688 if full and not ui.quiet and len(aliases) > 1:
673 rst.append(_(b"\naliases: %s\n") % b', '.join(aliases[1:]))
689 rst.append(_(b"\naliases: %s\n") % b', '.join(aliases[1:]))
674 rst.append(b'\n')
690 rst.append(b'\n')
675
691
676 # description
692 # description
677 doc = gettext(pycompat.getdoc(entry[0]))
693 doc = gettext(pycompat.getdoc(entry[0]))
678 if not doc:
694 if not doc:
679 doc = _(b"(no help text available)")
695 doc = _(b"(no help text available)")
680 if util.safehasattr(entry[0], b'definition'): # aliased command
696 if util.safehasattr(entry[0], b'definition'): # aliased command
681 source = entry[0].source
697 source = entry[0].source
682 if entry[0].definition.startswith(b'!'): # shell alias
698 if entry[0].definition.startswith(b'!'): # shell alias
683 doc = _(b'shell alias for: %s\n\n%s\n\ndefined by: %s\n') % (
699 doc = _(b'shell alias for: %s\n\n%s\n\ndefined by: %s\n') % (
684 entry[0].definition[1:],
700 entry[0].definition[1:],
685 doc,
701 doc,
686 source,
702 source,
687 )
703 )
688 else:
704 else:
689 doc = _(b'alias for: hg %s\n\n%s\n\ndefined by: %s\n') % (
705 doc = _(b'alias for: hg %s\n\n%s\n\ndefined by: %s\n') % (
690 entry[0].definition,
706 entry[0].definition,
691 doc,
707 doc,
692 source,
708 source,
693 )
709 )
694 doc = doc.splitlines(True)
710 doc = doc.splitlines(True)
695 if ui.quiet or not full:
711 if ui.quiet or not full:
696 rst.append(doc[0])
712 rst.append(doc[0])
697 else:
713 else:
698 rst.extend(doc)
714 rst.extend(doc)
699 rst.append(b'\n')
715 rst.append(b'\n')
700
716
701 # check if this command shadows a non-trivial (multi-line)
717 # check if this command shadows a non-trivial (multi-line)
702 # extension help text
718 # extension help text
703 try:
719 try:
704 mod = extensions.find(name)
720 mod = extensions.find(name)
705 doc = gettext(pycompat.getdoc(mod)) or b''
721 doc = gettext(pycompat.getdoc(mod)) or b''
706 if b'\n' in doc.strip():
722 if b'\n' in doc.strip():
707 msg = _(
723 msg = _(
708 b"(use 'hg help -e %s' to show help for "
724 b"(use 'hg help -e %s' to show help for "
709 b"the %s extension)"
725 b"the %s extension)"
710 ) % (name, name)
726 ) % (name, name)
711 rst.append(b'\n%s\n' % msg)
727 rst.append(b'\n%s\n' % msg)
712 except KeyError:
728 except KeyError:
713 pass
729 pass
714
730
715 # options
731 # options
716 if not ui.quiet and entry[1]:
732 if not ui.quiet and entry[1]:
717 rst.append(optrst(_(b"options"), entry[1], ui.verbose))
733 rst.append(optrst(_(b"options"), entry[1], ui.verbose, ui))
718
734
719 if ui.verbose:
735 if ui.verbose:
720 rst.append(
736 rst.append(
721 optrst(_(b"global options"), commands.globalopts, ui.verbose)
737 optrst(_(b"global options"), commands.globalopts, ui.verbose, ui)
722 )
738 )
723
739
724 if not ui.verbose:
740 if not ui.verbose:
725 if not full:
741 if not full:
726 rst.append(_(b"\n(use 'hg %s -h' to show more help)\n") % name)
742 rst.append(_(b"\n(use 'hg %s -h' to show more help)\n") % name)
727 elif not ui.quiet:
743 elif not ui.quiet:
728 rst.append(
744 rst.append(
729 _(
745 _(
730 b'\n(some details hidden, use --verbose '
746 b'\n(some details hidden, use --verbose '
731 b'to show complete help)'
747 b'to show complete help)'
732 )
748 )
733 )
749 )
734
750
735 return rst
751 return rst
736
752
737 def helplist(select=None, **opts):
753 def helplist(select=None, **opts):
738 # Category -> list of commands
754 # Category -> list of commands
739 cats = {}
755 cats = {}
740 # Command -> short description
756 # Command -> short description
741 h = {}
757 h = {}
742 # Command -> string showing synonyms
758 # Command -> string showing synonyms
743 syns = {}
759 syns = {}
744 for c, e in pycompat.iteritems(commands.table):
760 for c, e in pycompat.iteritems(commands.table):
745 fs = cmdutil.parsealiases(c)
761 fs = cmdutil.parsealiases(c)
746 f = fs[0]
762 f = fs[0]
747 syns[f] = b', '.join(fs)
763 syns[f] = b', '.join(fs)
748 func = e[0]
764 func = e[0]
749 if select and not select(f):
765 if select and not select(f):
750 continue
766 continue
751 doc = pycompat.getdoc(func)
767 doc = pycompat.getdoc(func)
752 if filtercmd(ui, f, func, name, doc):
768 if filtercmd(ui, f, func, name, doc):
753 continue
769 continue
754 doc = gettext(doc)
770 doc = gettext(doc)
755 if not doc:
771 if not doc:
756 doc = _(b"(no help text available)")
772 doc = _(b"(no help text available)")
757 h[f] = doc.splitlines()[0].rstrip()
773 h[f] = doc.splitlines()[0].rstrip()
758
774
759 cat = getattr(func, 'helpcategory', None) or (
775 cat = getattr(func, 'helpcategory', None) or (
760 registrar.command.CATEGORY_NONE
776 registrar.command.CATEGORY_NONE
761 )
777 )
762 cats.setdefault(cat, []).append(f)
778 cats.setdefault(cat, []).append(f)
763
779
764 rst = []
780 rst = []
765 if not h:
781 if not h:
766 if not ui.quiet:
782 if not ui.quiet:
767 rst.append(_(b'no commands defined\n'))
783 rst.append(_(b'no commands defined\n'))
768 return rst
784 return rst
769
785
770 # Output top header.
786 # Output top header.
771 if not ui.quiet:
787 if not ui.quiet:
772 if name == b"shortlist":
788 if name == b"shortlist":
773 rst.append(_(b'basic commands:\n\n'))
789 rst.append(_(b'basic commands:\n\n'))
774 elif name == b"debug":
790 elif name == b"debug":
775 rst.append(_(b'debug commands (internal and unsupported):\n\n'))
791 rst.append(_(b'debug commands (internal and unsupported):\n\n'))
776 else:
792 else:
777 rst.append(_(b'list of commands:\n'))
793 rst.append(_(b'list of commands:\n'))
778
794
779 def appendcmds(cmds):
795 def appendcmds(cmds):
780 cmds = sorted(cmds)
796 cmds = sorted(cmds)
781 for c in cmds:
797 for c in cmds:
782 if ui.verbose:
798 if ui.verbose:
783 rst.append(b" :%s: %s\n" % (syns[c], h[c]))
799 rst.append(b" :%s: %s\n" % (syns[c], h[c]))
784 else:
800 else:
785 rst.append(b' :%s: %s\n' % (c, h[c]))
801 rst.append(b' :%s: %s\n' % (c, h[c]))
786
802
787 if name in (b'shortlist', b'debug'):
803 if name in (b'shortlist', b'debug'):
788 # List without categories.
804 # List without categories.
789 appendcmds(h)
805 appendcmds(h)
790 else:
806 else:
791 # Check that all categories have an order.
807 # Check that all categories have an order.
792 missing_order = set(cats.keys()) - set(CATEGORY_ORDER)
808 missing_order = set(cats.keys()) - set(CATEGORY_ORDER)
793 if missing_order:
809 if missing_order:
794 ui.develwarn(
810 ui.develwarn(
795 b'help categories missing from CATEGORY_ORDER: %s'
811 b'help categories missing from CATEGORY_ORDER: %s'
796 % missing_order
812 % missing_order
797 )
813 )
798
814
799 # List per category.
815 # List per category.
800 for cat in CATEGORY_ORDER:
816 for cat in CATEGORY_ORDER:
801 catfns = cats.get(cat, [])
817 catfns = cats.get(cat, [])
802 if catfns:
818 if catfns:
803 if len(cats) > 1:
819 if len(cats) > 1:
804 catname = gettext(CATEGORY_NAMES[cat])
820 catname = gettext(CATEGORY_NAMES[cat])
805 rst.append(b"\n%s:\n" % catname)
821 rst.append(b"\n%s:\n" % catname)
806 rst.append(b"\n")
822 rst.append(b"\n")
807 appendcmds(catfns)
823 appendcmds(catfns)
808
824
809 ex = opts.get
825 ex = opts.get
810 anyopts = ex('keyword') or not (ex('command') or ex('extension'))
826 anyopts = ex('keyword') or not (ex('command') or ex('extension'))
811 if not name and anyopts:
827 if not name and anyopts:
812 exts = listexts(
828 exts = listexts(
813 _(b'enabled extensions:'),
829 _(b'enabled extensions:'),
814 extensions.enabled(),
830 extensions.enabled(),
815 showdeprecated=ui.verbose,
831 showdeprecated=ui.verbose,
816 )
832 )
817 if exts:
833 if exts:
818 rst.append(b'\n')
834 rst.append(b'\n')
819 rst.extend(exts)
835 rst.extend(exts)
820
836
821 rst.append(_(b"\nadditional help topics:\n"))
837 rst.append(_(b"\nadditional help topics:\n"))
822 # Group commands by category.
838 # Group commands by category.
823 topiccats = {}
839 topiccats = {}
824 for topic in helptable:
840 for topic in helptable:
825 names, header, doc = topic[0:3]
841 names, header, doc = topic[0:3]
826 if len(topic) > 3 and topic[3]:
842 if len(topic) > 3 and topic[3]:
827 category = topic[3]
843 category = topic[3]
828 else:
844 else:
829 category = TOPIC_CATEGORY_NONE
845 category = TOPIC_CATEGORY_NONE
830
846
831 topicname = names[0]
847 topicname = names[0]
832 if not filtertopic(ui, topicname):
848 if not filtertopic(ui, topicname):
833 topiccats.setdefault(category, []).append(
849 topiccats.setdefault(category, []).append(
834 (topicname, header)
850 (topicname, header)
835 )
851 )
836
852
837 # Check that all categories have an order.
853 # Check that all categories have an order.
838 missing_order = set(topiccats.keys()) - set(TOPIC_CATEGORY_ORDER)
854 missing_order = set(topiccats.keys()) - set(TOPIC_CATEGORY_ORDER)
839 if missing_order:
855 if missing_order:
840 ui.develwarn(
856 ui.develwarn(
841 b'help categories missing from TOPIC_CATEGORY_ORDER: %s'
857 b'help categories missing from TOPIC_CATEGORY_ORDER: %s'
842 % missing_order
858 % missing_order
843 )
859 )
844
860
845 # Output topics per category.
861 # Output topics per category.
846 for cat in TOPIC_CATEGORY_ORDER:
862 for cat in TOPIC_CATEGORY_ORDER:
847 topics = topiccats.get(cat, [])
863 topics = topiccats.get(cat, [])
848 if topics:
864 if topics:
849 if len(topiccats) > 1:
865 if len(topiccats) > 1:
850 catname = gettext(TOPIC_CATEGORY_NAMES[cat])
866 catname = gettext(TOPIC_CATEGORY_NAMES[cat])
851 rst.append(b"\n%s:\n" % catname)
867 rst.append(b"\n%s:\n" % catname)
852 rst.append(b"\n")
868 rst.append(b"\n")
853 for t, desc in topics:
869 for t, desc in topics:
854 rst.append(b" :%s: %s\n" % (t, desc))
870 rst.append(b" :%s: %s\n" % (t, desc))
855
871
856 if ui.quiet:
872 if ui.quiet:
857 pass
873 pass
858 elif ui.verbose:
874 elif ui.verbose:
859 rst.append(
875 rst.append(
860 b'\n%s\n'
876 b'\n%s\n'
861 % optrst(_(b"global options"), commands.globalopts, ui.verbose)
877 % optrst(_(b"global options"), commands.globalopts, ui.verbose, ui)
862 )
878 )
863 if name == b'shortlist':
879 if name == b'shortlist':
864 rst.append(
880 rst.append(
865 _(b"\n(use 'hg help' for the full list of commands)\n")
881 _(b"\n(use 'hg help' for the full list of commands)\n")
866 )
882 )
867 else:
883 else:
868 if name == b'shortlist':
884 if name == b'shortlist':
869 rst.append(
885 rst.append(
870 _(
886 _(
871 b"\n(use 'hg help' for the full list of commands "
887 b"\n(use 'hg help' for the full list of commands "
872 b"or 'hg -v' for details)\n"
888 b"or 'hg -v' for details)\n"
873 )
889 )
874 )
890 )
875 elif name and not full:
891 elif name and not full:
876 rst.append(
892 rst.append(
877 _(b"\n(use 'hg help %s' to show the full help text)\n")
893 _(b"\n(use 'hg help %s' to show the full help text)\n")
878 % name
894 % name
879 )
895 )
880 elif name and syns and name in syns.keys():
896 elif name and syns and name in syns.keys():
881 rst.append(
897 rst.append(
882 _(
898 _(
883 b"\n(use 'hg help -v -e %s' to show built-in "
899 b"\n(use 'hg help -v -e %s' to show built-in "
884 b"aliases and global options)\n"
900 b"aliases and global options)\n"
885 )
901 )
886 % name
902 % name
887 )
903 )
888 else:
904 else:
889 rst.append(
905 rst.append(
890 _(
906 _(
891 b"\n(use 'hg help -v%s' to show built-in aliases "
907 b"\n(use 'hg help -v%s' to show built-in aliases "
892 b"and global options)\n"
908 b"and global options)\n"
893 )
909 )
894 % (name and b" " + name or b"")
910 % (name and b" " + name or b"")
895 )
911 )
896 return rst
912 return rst
897
913
898 def helptopic(name, subtopic=None):
914 def helptopic(name, subtopic=None):
899 # Look for sub-topic entry first.
915 # Look for sub-topic entry first.
900 header, doc = None, None
916 header, doc = None, None
901 if subtopic and name in subtopics:
917 if subtopic and name in subtopics:
902 for names, header, doc in subtopics[name]:
918 for names, header, doc in subtopics[name]:
903 if subtopic in names:
919 if subtopic in names:
904 break
920 break
905 if not any(subtopic in s[0] for s in subtopics[name]):
921 if not any(subtopic in s[0] for s in subtopics[name]):
906 raise error.UnknownCommand(name)
922 raise error.UnknownCommand(name)
907
923
908 if not header:
924 if not header:
909 for topic in helptable:
925 for topic in helptable:
910 names, header, doc = topic[0:3]
926 names, header, doc = topic[0:3]
911 if name in names:
927 if name in names:
912 break
928 break
913 else:
929 else:
914 raise error.UnknownCommand(name)
930 raise error.UnknownCommand(name)
915
931
916 rst = [minirst.section(header)]
932 rst = [minirst.section(header)]
917
933
918 # description
934 # description
919 if not doc:
935 if not doc:
920 rst.append(b" %s\n" % _(b"(no help text available)"))
936 rst.append(b" %s\n" % _(b"(no help text available)"))
921 if callable(doc):
937 if callable(doc):
922 rst += [b" %s\n" % l for l in doc(ui).splitlines()]
938 rst += [b" %s\n" % l for l in doc(ui).splitlines()]
923
939
924 if not ui.verbose:
940 if not ui.verbose:
925 omitted = _(
941 omitted = _(
926 b'(some details hidden, use --verbose'
942 b'(some details hidden, use --verbose'
927 b' to show complete help)'
943 b' to show complete help)'
928 )
944 )
929 indicateomitted(rst, omitted)
945 indicateomitted(rst, omitted)
930
946
931 try:
947 try:
932 cmdutil.findcmd(name, commands.table)
948 cmdutil.findcmd(name, commands.table)
933 rst.append(
949 rst.append(
934 _(b"\nuse 'hg help -c %s' to see help for the %s command\n")
950 _(b"\nuse 'hg help -c %s' to see help for the %s command\n")
935 % (name, name)
951 % (name, name)
936 )
952 )
937 except error.UnknownCommand:
953 except error.UnknownCommand:
938 pass
954 pass
939 return rst
955 return rst
940
956
941 def helpext(name, subtopic=None):
957 def helpext(name, subtopic=None):
942 try:
958 try:
943 mod = extensions.find(name)
959 mod = extensions.find(name)
944 doc = gettext(pycompat.getdoc(mod)) or _(b'no help text available')
960 doc = gettext(pycompat.getdoc(mod)) or _(b'no help text available')
945 except KeyError:
961 except KeyError:
946 mod = None
962 mod = None
947 doc = extensions.disabledext(name)
963 doc = extensions.disabledext(name)
948 if not doc:
964 if not doc:
949 raise error.UnknownCommand(name)
965 raise error.UnknownCommand(name)
950
966
951 if b'\n' not in doc:
967 if b'\n' not in doc:
952 head, tail = doc, b""
968 head, tail = doc, b""
953 else:
969 else:
954 head, tail = doc.split(b'\n', 1)
970 head, tail = doc.split(b'\n', 1)
955 rst = [_(b'%s extension - %s\n\n') % (name.rpartition(b'.')[-1], head)]
971 rst = [_(b'%s extension - %s\n\n') % (name.rpartition(b'.')[-1], head)]
956 if tail:
972 if tail:
957 rst.extend(tail.splitlines(True))
973 rst.extend(tail.splitlines(True))
958 rst.append(b'\n')
974 rst.append(b'\n')
959
975
960 if not ui.verbose:
976 if not ui.verbose:
961 omitted = _(
977 omitted = _(
962 b'(some details hidden, use --verbose'
978 b'(some details hidden, use --verbose'
963 b' to show complete help)'
979 b' to show complete help)'
964 )
980 )
965 indicateomitted(rst, omitted)
981 indicateomitted(rst, omitted)
966
982
967 if mod:
983 if mod:
968 try:
984 try:
969 ct = mod.cmdtable
985 ct = mod.cmdtable
970 except AttributeError:
986 except AttributeError:
971 ct = {}
987 ct = {}
972 modcmds = {c.partition(b'|')[0] for c in ct}
988 modcmds = {c.partition(b'|')[0] for c in ct}
973 rst.extend(helplist(modcmds.__contains__))
989 rst.extend(helplist(modcmds.__contains__))
974 else:
990 else:
975 rst.append(
991 rst.append(
976 _(
992 _(
977 b"(use 'hg help extensions' for information on enabling"
993 b"(use 'hg help extensions' for information on enabling"
978 b" extensions)\n"
994 b" extensions)\n"
979 )
995 )
980 )
996 )
981 return rst
997 return rst
982
998
983 def helpextcmd(name, subtopic=None):
999 def helpextcmd(name, subtopic=None):
984 cmd, ext, doc = extensions.disabledcmd(
1000 cmd, ext, doc = extensions.disabledcmd(
985 ui, name, ui.configbool(b'ui', b'strict')
1001 ui, name, ui.configbool(b'ui', b'strict')
986 )
1002 )
987 doc = doc.splitlines()[0]
1003 doc = doc.splitlines()[0]
988
1004
989 rst = listexts(
1005 rst = listexts(
990 _(b"'%s' is provided by the following extension:") % cmd,
1006 _(b"'%s' is provided by the following extension:") % cmd,
991 {ext: doc},
1007 {ext: doc},
992 indent=4,
1008 indent=4,
993 showdeprecated=True,
1009 showdeprecated=True,
994 )
1010 )
995 rst.append(b'\n')
1011 rst.append(b'\n')
996 rst.append(
1012 rst.append(
997 _(
1013 _(
998 b"(use 'hg help extensions' for information on enabling "
1014 b"(use 'hg help extensions' for information on enabling "
999 b"extensions)\n"
1015 b"extensions)\n"
1000 )
1016 )
1001 )
1017 )
1002 return rst
1018 return rst
1003
1019
1004 rst = []
1020 rst = []
1005 kw = opts.get(b'keyword')
1021 kw = opts.get(b'keyword')
1006 if kw or name is None and any(opts[o] for o in opts):
1022 if kw or name is None and any(opts[o] for o in opts):
1007 matches = topicmatch(ui, commands, name or b'')
1023 matches = topicmatch(ui, commands, name or b'')
1008 helpareas = []
1024 helpareas = []
1009 if opts.get(b'extension'):
1025 if opts.get(b'extension'):
1010 helpareas += [(b'extensions', _(b'Extensions'))]
1026 helpareas += [(b'extensions', _(b'Extensions'))]
1011 if opts.get(b'command'):
1027 if opts.get(b'command'):
1012 helpareas += [(b'commands', _(b'Commands'))]
1028 helpareas += [(b'commands', _(b'Commands'))]
1013 if not helpareas:
1029 if not helpareas:
1014 helpareas = [
1030 helpareas = [
1015 (b'topics', _(b'Topics')),
1031 (b'topics', _(b'Topics')),
1016 (b'commands', _(b'Commands')),
1032 (b'commands', _(b'Commands')),
1017 (b'extensions', _(b'Extensions')),
1033 (b'extensions', _(b'Extensions')),
1018 (b'extensioncommands', _(b'Extension Commands')),
1034 (b'extensioncommands', _(b'Extension Commands')),
1019 ]
1035 ]
1020 for t, title in helpareas:
1036 for t, title in helpareas:
1021 if matches[t]:
1037 if matches[t]:
1022 rst.append(b'%s:\n\n' % title)
1038 rst.append(b'%s:\n\n' % title)
1023 rst.extend(minirst.maketable(sorted(matches[t]), 1))
1039 rst.extend(minirst.maketable(sorted(matches[t]), 1))
1024 rst.append(b'\n')
1040 rst.append(b'\n')
1025 if not rst:
1041 if not rst:
1026 msg = _(b'no matches')
1042 msg = _(b'no matches')
1027 hint = _(b"try 'hg help' for a list of topics")
1043 hint = _(b"try 'hg help' for a list of topics")
1028 raise error.Abort(msg, hint=hint)
1044 raise error.Abort(msg, hint=hint)
1029 elif name and name != b'shortlist':
1045 elif name and name != b'shortlist':
1030 queries = []
1046 queries = []
1031 if unknowncmd:
1047 if unknowncmd:
1032 queries += [helpextcmd]
1048 queries += [helpextcmd]
1033 if opts.get(b'extension'):
1049 if opts.get(b'extension'):
1034 queries += [helpext]
1050 queries += [helpext]
1035 if opts.get(b'command'):
1051 if opts.get(b'command'):
1036 queries += [helpcmd]
1052 queries += [helpcmd]
1037 if not queries:
1053 if not queries:
1038 queries = (helptopic, helpcmd, helpext, helpextcmd)
1054 queries = (helptopic, helpcmd, helpext, helpextcmd)
1039 for f in queries:
1055 for f in queries:
1040 try:
1056 try:
1041 rst = f(name, subtopic)
1057 rst = f(name, subtopic)
1042 break
1058 break
1043 except error.UnknownCommand:
1059 except error.UnknownCommand:
1044 pass
1060 pass
1045 else:
1061 else:
1046 if unknowncmd:
1062 if unknowncmd:
1047 raise error.UnknownCommand(name)
1063 raise error.UnknownCommand(name)
1048 else:
1064 else:
1049 if fullname:
1065 if fullname:
1050 formatname = fullname
1066 formatname = fullname
1051 else:
1067 else:
1052 formatname = name
1068 formatname = name
1053 if subtopic:
1069 if subtopic:
1054 hintname = subtopic
1070 hintname = subtopic
1055 else:
1071 else:
1056 hintname = name
1072 hintname = name
1057 msg = _(b'no such help topic: %s') % formatname
1073 msg = _(b'no such help topic: %s') % formatname
1058 hint = _(b"try 'hg help --keyword %s'") % hintname
1074 hint = _(b"try 'hg help --keyword %s'") % hintname
1059 raise error.Abort(msg, hint=hint)
1075 raise error.Abort(msg, hint=hint)
1060 else:
1076 else:
1061 # program name
1077 # program name
1062 if not ui.quiet:
1078 if not ui.quiet:
1063 rst = [_(b"Mercurial Distributed SCM\n"), b'\n']
1079 rst = [_(b"Mercurial Distributed SCM\n"), b'\n']
1064 rst.extend(helplist(None, **pycompat.strkwargs(opts)))
1080 rst.extend(helplist(None, **pycompat.strkwargs(opts)))
1065
1081
1066 return b''.join(rst)
1082 return b''.join(rst)
1067
1083
1068
1084
1069 def formattedhelp(
1085 def formattedhelp(
1070 ui, commands, fullname, keep=None, unknowncmd=False, full=True, **opts
1086 ui, commands, fullname, keep=None, unknowncmd=False, full=True, **opts
1071 ):
1087 ):
1072 """get help for a given topic (as a dotted name) as rendered rst
1088 """get help for a given topic (as a dotted name) as rendered rst
1073
1089
1074 Either returns the rendered help text or raises an exception.
1090 Either returns the rendered help text or raises an exception.
1075 """
1091 """
1076 if keep is None:
1092 if keep is None:
1077 keep = []
1093 keep = []
1078 else:
1094 else:
1079 keep = list(keep) # make a copy so we can mutate this later
1095 keep = list(keep) # make a copy so we can mutate this later
1080
1096
1081 # <fullname> := <name>[.<subtopic][.<section>]
1097 # <fullname> := <name>[.<subtopic][.<section>]
1082 name = subtopic = section = None
1098 name = subtopic = section = None
1083 if fullname is not None:
1099 if fullname is not None:
1084 nameparts = fullname.split(b'.')
1100 nameparts = fullname.split(b'.')
1085 name = nameparts.pop(0)
1101 name = nameparts.pop(0)
1086 if nameparts and name in subtopics:
1102 if nameparts and name in subtopics:
1087 subtopic = nameparts.pop(0)
1103 subtopic = nameparts.pop(0)
1088 if nameparts:
1104 if nameparts:
1089 section = encoding.lower(b'.'.join(nameparts))
1105 section = encoding.lower(b'.'.join(nameparts))
1090
1106
1091 textwidth = ui.configint(b'ui', b'textwidth')
1107 textwidth = ui.configint(b'ui', b'textwidth')
1092 termwidth = ui.termwidth() - 2
1108 termwidth = ui.termwidth() - 2
1093 if textwidth <= 0 or termwidth < textwidth:
1109 if textwidth <= 0 or termwidth < textwidth:
1094 textwidth = termwidth
1110 textwidth = termwidth
1095 text = help_(
1111 text = help_(
1096 ui,
1112 ui,
1097 commands,
1113 commands,
1098 name,
1114 name,
1099 fullname=fullname,
1115 fullname=fullname,
1100 subtopic=subtopic,
1116 subtopic=subtopic,
1101 unknowncmd=unknowncmd,
1117 unknowncmd=unknowncmd,
1102 full=full,
1118 full=full,
1103 **opts
1119 **opts
1104 )
1120 )
1105
1121
1106 blocks, pruned = minirst.parse(text, keep=keep)
1122 blocks, pruned = minirst.parse(text, keep=keep)
1107 if b'verbose' in pruned:
1123 if b'verbose' in pruned:
1108 keep.append(b'omitted')
1124 keep.append(b'omitted')
1109 else:
1125 else:
1110 keep.append(b'notomitted')
1126 keep.append(b'notomitted')
1111 blocks, pruned = minirst.parse(text, keep=keep)
1127 blocks, pruned = minirst.parse(text, keep=keep)
1112 if section:
1128 if section:
1113 blocks = minirst.filtersections(blocks, section)
1129 blocks = minirst.filtersections(blocks, section)
1114
1130
1115 # We could have been given a weird ".foo" section without a name
1131 # We could have been given a weird ".foo" section without a name
1116 # to look for, or we could have simply failed to found "foo.bar"
1132 # to look for, or we could have simply failed to found "foo.bar"
1117 # because bar isn't a section of foo
1133 # because bar isn't a section of foo
1118 if section and not (blocks and name):
1134 if section and not (blocks and name):
1119 raise error.Abort(_(b"help section not found: %s") % fullname)
1135 raise error.Abort(_(b"help section not found: %s") % fullname)
1120
1136
1121 return minirst.formatplain(blocks, textwidth)
1137 return minirst.formatplain(blocks, textwidth)
@@ -1,3896 +1,3902 b''
1 Short help:
1 Short help:
2
2
3 $ hg
3 $ hg
4 Mercurial Distributed SCM
4 Mercurial Distributed SCM
5
5
6 basic commands:
6 basic commands:
7
7
8 add add the specified files on the next commit
8 add add the specified files on the next commit
9 annotate show changeset information by line for each file
9 annotate show changeset information by line for each file
10 clone make a copy of an existing repository
10 clone make a copy of an existing repository
11 commit commit the specified files or all outstanding changes
11 commit commit the specified files or all outstanding changes
12 diff diff repository (or selected files)
12 diff diff repository (or selected files)
13 export dump the header and diffs for one or more changesets
13 export dump the header and diffs for one or more changesets
14 forget forget the specified files on the next commit
14 forget forget the specified files on the next commit
15 init create a new repository in the given directory
15 init create a new repository in the given directory
16 log show revision history of entire repository or files
16 log show revision history of entire repository or files
17 merge merge another revision into working directory
17 merge merge another revision into working directory
18 pull pull changes from the specified source
18 pull pull changes from the specified source
19 push push changes to the specified destination
19 push push changes to the specified destination
20 remove remove the specified files on the next commit
20 remove remove the specified files on the next commit
21 serve start stand-alone webserver
21 serve start stand-alone webserver
22 status show changed files in the working directory
22 status show changed files in the working directory
23 summary summarize working directory state
23 summary summarize working directory state
24 update update working directory (or switch revisions)
24 update update working directory (or switch revisions)
25
25
26 (use 'hg help' for the full list of commands or 'hg -v' for details)
26 (use 'hg help' for the full list of commands or 'hg -v' for details)
27
27
28 $ hg -q
28 $ hg -q
29 add add the specified files on the next commit
29 add add the specified files on the next commit
30 annotate show changeset information by line for each file
30 annotate show changeset information by line for each file
31 clone make a copy of an existing repository
31 clone make a copy of an existing repository
32 commit commit the specified files or all outstanding changes
32 commit commit the specified files or all outstanding changes
33 diff diff repository (or selected files)
33 diff diff repository (or selected files)
34 export dump the header and diffs for one or more changesets
34 export dump the header and diffs for one or more changesets
35 forget forget the specified files on the next commit
35 forget forget the specified files on the next commit
36 init create a new repository in the given directory
36 init create a new repository in the given directory
37 log show revision history of entire repository or files
37 log show revision history of entire repository or files
38 merge merge another revision into working directory
38 merge merge another revision into working directory
39 pull pull changes from the specified source
39 pull pull changes from the specified source
40 push push changes to the specified destination
40 push push changes to the specified destination
41 remove remove the specified files on the next commit
41 remove remove the specified files on the next commit
42 serve start stand-alone webserver
42 serve start stand-alone webserver
43 status show changed files in the working directory
43 status show changed files in the working directory
44 summary summarize working directory state
44 summary summarize working directory state
45 update update working directory (or switch revisions)
45 update update working directory (or switch revisions)
46
46
47 Extra extensions will be printed in help output in a non-reliable order since
47 Extra extensions will be printed in help output in a non-reliable order since
48 the extension is unknown.
48 the extension is unknown.
49 #if no-extraextensions
49 #if no-extraextensions
50
50
51 $ hg help
51 $ hg help
52 Mercurial Distributed SCM
52 Mercurial Distributed SCM
53
53
54 list of commands:
54 list of commands:
55
55
56 Repository creation:
56 Repository creation:
57
57
58 clone make a copy of an existing repository
58 clone make a copy of an existing repository
59 init create a new repository in the given directory
59 init create a new repository in the given directory
60
60
61 Remote repository management:
61 Remote repository management:
62
62
63 incoming show new changesets found in source
63 incoming show new changesets found in source
64 outgoing show changesets not found in the destination
64 outgoing show changesets not found in the destination
65 paths show aliases for remote repositories
65 paths show aliases for remote repositories
66 pull pull changes from the specified source
66 pull pull changes from the specified source
67 push push changes to the specified destination
67 push push changes to the specified destination
68 serve start stand-alone webserver
68 serve start stand-alone webserver
69
69
70 Change creation:
70 Change creation:
71
71
72 commit commit the specified files or all outstanding changes
72 commit commit the specified files or all outstanding changes
73
73
74 Change manipulation:
74 Change manipulation:
75
75
76 backout reverse effect of earlier changeset
76 backout reverse effect of earlier changeset
77 graft copy changes from other branches onto the current branch
77 graft copy changes from other branches onto the current branch
78 merge merge another revision into working directory
78 merge merge another revision into working directory
79
79
80 Change organization:
80 Change organization:
81
81
82 bookmarks create a new bookmark or list existing bookmarks
82 bookmarks create a new bookmark or list existing bookmarks
83 branch set or show the current branch name
83 branch set or show the current branch name
84 branches list repository named branches
84 branches list repository named branches
85 phase set or show the current phase name
85 phase set or show the current phase name
86 tag add one or more tags for the current or given revision
86 tag add one or more tags for the current or given revision
87 tags list repository tags
87 tags list repository tags
88
88
89 File content management:
89 File content management:
90
90
91 annotate show changeset information by line for each file
91 annotate show changeset information by line for each file
92 cat output the current or given revision of files
92 cat output the current or given revision of files
93 copy mark files as copied for the next commit
93 copy mark files as copied for the next commit
94 diff diff repository (or selected files)
94 diff diff repository (or selected files)
95 grep search for a pattern in specified files
95 grep search for a pattern in specified files
96
96
97 Change navigation:
97 Change navigation:
98
98
99 bisect subdivision search of changesets
99 bisect subdivision search of changesets
100 heads show branch heads
100 heads show branch heads
101 identify identify the working directory or specified revision
101 identify identify the working directory or specified revision
102 log show revision history of entire repository or files
102 log show revision history of entire repository or files
103
103
104 Working directory management:
104 Working directory management:
105
105
106 add add the specified files on the next commit
106 add add the specified files on the next commit
107 addremove add all new files, delete all missing files
107 addremove add all new files, delete all missing files
108 files list tracked files
108 files list tracked files
109 forget forget the specified files on the next commit
109 forget forget the specified files on the next commit
110 remove remove the specified files on the next commit
110 remove remove the specified files on the next commit
111 rename rename files; equivalent of copy + remove
111 rename rename files; equivalent of copy + remove
112 resolve redo merges or set/view the merge status of files
112 resolve redo merges or set/view the merge status of files
113 revert restore files to their checkout state
113 revert restore files to their checkout state
114 root print the root (top) of the current working directory
114 root print the root (top) of the current working directory
115 shelve save and set aside changes from the working directory
115 shelve save and set aside changes from the working directory
116 status show changed files in the working directory
116 status show changed files in the working directory
117 summary summarize working directory state
117 summary summarize working directory state
118 unshelve restore a shelved change to the working directory
118 unshelve restore a shelved change to the working directory
119 update update working directory (or switch revisions)
119 update update working directory (or switch revisions)
120
120
121 Change import/export:
121 Change import/export:
122
122
123 archive create an unversioned archive of a repository revision
123 archive create an unversioned archive of a repository revision
124 bundle create a bundle file
124 bundle create a bundle file
125 export dump the header and diffs for one or more changesets
125 export dump the header and diffs for one or more changesets
126 import import an ordered set of patches
126 import import an ordered set of patches
127 unbundle apply one or more bundle files
127 unbundle apply one or more bundle files
128
128
129 Repository maintenance:
129 Repository maintenance:
130
130
131 manifest output the current or given revision of the project manifest
131 manifest output the current or given revision of the project manifest
132 recover roll back an interrupted transaction
132 recover roll back an interrupted transaction
133 verify verify the integrity of the repository
133 verify verify the integrity of the repository
134
134
135 Help:
135 Help:
136
136
137 config show combined config settings from all hgrc files
137 config show combined config settings from all hgrc files
138 help show help for a given topic or a help overview
138 help show help for a given topic or a help overview
139 version output version and copyright information
139 version output version and copyright information
140
140
141 additional help topics:
141 additional help topics:
142
142
143 Mercurial identifiers:
143 Mercurial identifiers:
144
144
145 filesets Specifying File Sets
145 filesets Specifying File Sets
146 hgignore Syntax for Mercurial Ignore Files
146 hgignore Syntax for Mercurial Ignore Files
147 patterns File Name Patterns
147 patterns File Name Patterns
148 revisions Specifying Revisions
148 revisions Specifying Revisions
149 urls URL Paths
149 urls URL Paths
150
150
151 Mercurial output:
151 Mercurial output:
152
152
153 color Colorizing Outputs
153 color Colorizing Outputs
154 dates Date Formats
154 dates Date Formats
155 diffs Diff Formats
155 diffs Diff Formats
156 templating Template Usage
156 templating Template Usage
157
157
158 Mercurial configuration:
158 Mercurial configuration:
159
159
160 config Configuration Files
160 config Configuration Files
161 environment Environment Variables
161 environment Environment Variables
162 extensions Using Additional Features
162 extensions Using Additional Features
163 flags Command-line flags
163 flags Command-line flags
164 hgweb Configuring hgweb
164 hgweb Configuring hgweb
165 merge-tools Merge Tools
165 merge-tools Merge Tools
166 pager Pager Support
166 pager Pager Support
167
167
168 Concepts:
168 Concepts:
169
169
170 bundlespec Bundle File Formats
170 bundlespec Bundle File Formats
171 glossary Glossary
171 glossary Glossary
172 phases Working with Phases
172 phases Working with Phases
173 subrepos Subrepositories
173 subrepos Subrepositories
174
174
175 Miscellaneous:
175 Miscellaneous:
176
176
177 deprecated Deprecated Features
177 deprecated Deprecated Features
178 internals Technical implementation topics
178 internals Technical implementation topics
179 scripting Using Mercurial from scripts and automation
179 scripting Using Mercurial from scripts and automation
180
180
181 (use 'hg help -v' to show built-in aliases and global options)
181 (use 'hg help -v' to show built-in aliases and global options)
182
182
183 $ hg -q help
183 $ hg -q help
184 Repository creation:
184 Repository creation:
185
185
186 clone make a copy of an existing repository
186 clone make a copy of an existing repository
187 init create a new repository in the given directory
187 init create a new repository in the given directory
188
188
189 Remote repository management:
189 Remote repository management:
190
190
191 incoming show new changesets found in source
191 incoming show new changesets found in source
192 outgoing show changesets not found in the destination
192 outgoing show changesets not found in the destination
193 paths show aliases for remote repositories
193 paths show aliases for remote repositories
194 pull pull changes from the specified source
194 pull pull changes from the specified source
195 push push changes to the specified destination
195 push push changes to the specified destination
196 serve start stand-alone webserver
196 serve start stand-alone webserver
197
197
198 Change creation:
198 Change creation:
199
199
200 commit commit the specified files or all outstanding changes
200 commit commit the specified files or all outstanding changes
201
201
202 Change manipulation:
202 Change manipulation:
203
203
204 backout reverse effect of earlier changeset
204 backout reverse effect of earlier changeset
205 graft copy changes from other branches onto the current branch
205 graft copy changes from other branches onto the current branch
206 merge merge another revision into working directory
206 merge merge another revision into working directory
207
207
208 Change organization:
208 Change organization:
209
209
210 bookmarks create a new bookmark or list existing bookmarks
210 bookmarks create a new bookmark or list existing bookmarks
211 branch set or show the current branch name
211 branch set or show the current branch name
212 branches list repository named branches
212 branches list repository named branches
213 phase set or show the current phase name
213 phase set or show the current phase name
214 tag add one or more tags for the current or given revision
214 tag add one or more tags for the current or given revision
215 tags list repository tags
215 tags list repository tags
216
216
217 File content management:
217 File content management:
218
218
219 annotate show changeset information by line for each file
219 annotate show changeset information by line for each file
220 cat output the current or given revision of files
220 cat output the current or given revision of files
221 copy mark files as copied for the next commit
221 copy mark files as copied for the next commit
222 diff diff repository (or selected files)
222 diff diff repository (or selected files)
223 grep search for a pattern in specified files
223 grep search for a pattern in specified files
224
224
225 Change navigation:
225 Change navigation:
226
226
227 bisect subdivision search of changesets
227 bisect subdivision search of changesets
228 heads show branch heads
228 heads show branch heads
229 identify identify the working directory or specified revision
229 identify identify the working directory or specified revision
230 log show revision history of entire repository or files
230 log show revision history of entire repository or files
231
231
232 Working directory management:
232 Working directory management:
233
233
234 add add the specified files on the next commit
234 add add the specified files on the next commit
235 addremove add all new files, delete all missing files
235 addremove add all new files, delete all missing files
236 files list tracked files
236 files list tracked files
237 forget forget the specified files on the next commit
237 forget forget the specified files on the next commit
238 remove remove the specified files on the next commit
238 remove remove the specified files on the next commit
239 rename rename files; equivalent of copy + remove
239 rename rename files; equivalent of copy + remove
240 resolve redo merges or set/view the merge status of files
240 resolve redo merges or set/view the merge status of files
241 revert restore files to their checkout state
241 revert restore files to their checkout state
242 root print the root (top) of the current working directory
242 root print the root (top) of the current working directory
243 shelve save and set aside changes from the working directory
243 shelve save and set aside changes from the working directory
244 status show changed files in the working directory
244 status show changed files in the working directory
245 summary summarize working directory state
245 summary summarize working directory state
246 unshelve restore a shelved change to the working directory
246 unshelve restore a shelved change to the working directory
247 update update working directory (or switch revisions)
247 update update working directory (or switch revisions)
248
248
249 Change import/export:
249 Change import/export:
250
250
251 archive create an unversioned archive of a repository revision
251 archive create an unversioned archive of a repository revision
252 bundle create a bundle file
252 bundle create a bundle file
253 export dump the header and diffs for one or more changesets
253 export dump the header and diffs for one or more changesets
254 import import an ordered set of patches
254 import import an ordered set of patches
255 unbundle apply one or more bundle files
255 unbundle apply one or more bundle files
256
256
257 Repository maintenance:
257 Repository maintenance:
258
258
259 manifest output the current or given revision of the project manifest
259 manifest output the current or given revision of the project manifest
260 recover roll back an interrupted transaction
260 recover roll back an interrupted transaction
261 verify verify the integrity of the repository
261 verify verify the integrity of the repository
262
262
263 Help:
263 Help:
264
264
265 config show combined config settings from all hgrc files
265 config show combined config settings from all hgrc files
266 help show help for a given topic or a help overview
266 help show help for a given topic or a help overview
267 version output version and copyright information
267 version output version and copyright information
268
268
269 additional help topics:
269 additional help topics:
270
270
271 Mercurial identifiers:
271 Mercurial identifiers:
272
272
273 filesets Specifying File Sets
273 filesets Specifying File Sets
274 hgignore Syntax for Mercurial Ignore Files
274 hgignore Syntax for Mercurial Ignore Files
275 patterns File Name Patterns
275 patterns File Name Patterns
276 revisions Specifying Revisions
276 revisions Specifying Revisions
277 urls URL Paths
277 urls URL Paths
278
278
279 Mercurial output:
279 Mercurial output:
280
280
281 color Colorizing Outputs
281 color Colorizing Outputs
282 dates Date Formats
282 dates Date Formats
283 diffs Diff Formats
283 diffs Diff Formats
284 templating Template Usage
284 templating Template Usage
285
285
286 Mercurial configuration:
286 Mercurial configuration:
287
287
288 config Configuration Files
288 config Configuration Files
289 environment Environment Variables
289 environment Environment Variables
290 extensions Using Additional Features
290 extensions Using Additional Features
291 flags Command-line flags
291 flags Command-line flags
292 hgweb Configuring hgweb
292 hgweb Configuring hgweb
293 merge-tools Merge Tools
293 merge-tools Merge Tools
294 pager Pager Support
294 pager Pager Support
295
295
296 Concepts:
296 Concepts:
297
297
298 bundlespec Bundle File Formats
298 bundlespec Bundle File Formats
299 glossary Glossary
299 glossary Glossary
300 phases Working with Phases
300 phases Working with Phases
301 subrepos Subrepositories
301 subrepos Subrepositories
302
302
303 Miscellaneous:
303 Miscellaneous:
304
304
305 deprecated Deprecated Features
305 deprecated Deprecated Features
306 internals Technical implementation topics
306 internals Technical implementation topics
307 scripting Using Mercurial from scripts and automation
307 scripting Using Mercurial from scripts and automation
308
308
309 Test extension help:
309 Test extension help:
310 $ hg help extensions --config extensions.rebase= --config extensions.children=
310 $ hg help extensions --config extensions.rebase= --config extensions.children=
311 Using Additional Features
311 Using Additional Features
312 """""""""""""""""""""""""
312 """""""""""""""""""""""""
313
313
314 Mercurial has the ability to add new features through the use of
314 Mercurial has the ability to add new features through the use of
315 extensions. Extensions may add new commands, add options to existing
315 extensions. Extensions may add new commands, add options to existing
316 commands, change the default behavior of commands, or implement hooks.
316 commands, change the default behavior of commands, or implement hooks.
317
317
318 To enable the "foo" extension, either shipped with Mercurial or in the
318 To enable the "foo" extension, either shipped with Mercurial or in the
319 Python search path, create an entry for it in your configuration file,
319 Python search path, create an entry for it in your configuration file,
320 like this:
320 like this:
321
321
322 [extensions]
322 [extensions]
323 foo =
323 foo =
324
324
325 You may also specify the full path to an extension:
325 You may also specify the full path to an extension:
326
326
327 [extensions]
327 [extensions]
328 myfeature = ~/.hgext/myfeature.py
328 myfeature = ~/.hgext/myfeature.py
329
329
330 See 'hg help config' for more information on configuration files.
330 See 'hg help config' for more information on configuration files.
331
331
332 Extensions are not loaded by default for a variety of reasons: they can
332 Extensions are not loaded by default for a variety of reasons: they can
333 increase startup overhead; they may be meant for advanced usage only; they
333 increase startup overhead; they may be meant for advanced usage only; they
334 may provide potentially dangerous abilities (such as letting you destroy
334 may provide potentially dangerous abilities (such as letting you destroy
335 or modify history); they might not be ready for prime time; or they may
335 or modify history); they might not be ready for prime time; or they may
336 alter some usual behaviors of stock Mercurial. It is thus up to the user
336 alter some usual behaviors of stock Mercurial. It is thus up to the user
337 to activate extensions as needed.
337 to activate extensions as needed.
338
338
339 To explicitly disable an extension enabled in a configuration file of
339 To explicitly disable an extension enabled in a configuration file of
340 broader scope, prepend its path with !:
340 broader scope, prepend its path with !:
341
341
342 [extensions]
342 [extensions]
343 # disabling extension bar residing in /path/to/extension/bar.py
343 # disabling extension bar residing in /path/to/extension/bar.py
344 bar = !/path/to/extension/bar.py
344 bar = !/path/to/extension/bar.py
345 # ditto, but no path was supplied for extension baz
345 # ditto, but no path was supplied for extension baz
346 baz = !
346 baz = !
347
347
348 enabled extensions:
348 enabled extensions:
349
349
350 children command to display child changesets (DEPRECATED)
350 children command to display child changesets (DEPRECATED)
351 rebase command to move sets of revisions to a different ancestor
351 rebase command to move sets of revisions to a different ancestor
352
352
353 disabled extensions:
353 disabled extensions:
354
354
355 acl hooks for controlling repository access
355 acl hooks for controlling repository access
356 blackbox log repository events to a blackbox for debugging
356 blackbox log repository events to a blackbox for debugging
357 bugzilla hooks for integrating with the Bugzilla bug tracker
357 bugzilla hooks for integrating with the Bugzilla bug tracker
358 censor erase file content at a given revision
358 censor erase file content at a given revision
359 churn command to display statistics about repository history
359 churn command to display statistics about repository history
360 clonebundles advertise pre-generated bundles to seed clones
360 clonebundles advertise pre-generated bundles to seed clones
361 closehead close arbitrary heads without checking them out first
361 closehead close arbitrary heads without checking them out first
362 convert import revisions from foreign VCS repositories into
362 convert import revisions from foreign VCS repositories into
363 Mercurial
363 Mercurial
364 eol automatically manage newlines in repository files
364 eol automatically manage newlines in repository files
365 extdiff command to allow external programs to compare revisions
365 extdiff command to allow external programs to compare revisions
366 factotum http authentication with factotum
366 factotum http authentication with factotum
367 fastexport export repositories as git fast-import stream
367 fastexport export repositories as git fast-import stream
368 githelp try mapping git commands to Mercurial commands
368 githelp try mapping git commands to Mercurial commands
369 gpg commands to sign and verify changesets
369 gpg commands to sign and verify changesets
370 hgk browse the repository in a graphical way
370 hgk browse the repository in a graphical way
371 highlight syntax highlighting for hgweb (requires Pygments)
371 highlight syntax highlighting for hgweb (requires Pygments)
372 histedit interactive history editing
372 histedit interactive history editing
373 keyword expand keywords in tracked files
373 keyword expand keywords in tracked files
374 largefiles track large binary files
374 largefiles track large binary files
375 mq manage a stack of patches
375 mq manage a stack of patches
376 notify hooks for sending email push notifications
376 notify hooks for sending email push notifications
377 patchbomb command to send changesets as (a series of) patch emails
377 patchbomb command to send changesets as (a series of) patch emails
378 purge command to delete untracked files from the working
378 purge command to delete untracked files from the working
379 directory
379 directory
380 relink recreates hardlinks between repository clones
380 relink recreates hardlinks between repository clones
381 schemes extend schemes with shortcuts to repository swarms
381 schemes extend schemes with shortcuts to repository swarms
382 share share a common history between several working directories
382 share share a common history between several working directories
383 strip strip changesets and their descendants from history
383 strip strip changesets and their descendants from history
384 transplant command to transplant changesets from another branch
384 transplant command to transplant changesets from another branch
385 win32mbcs allow the use of MBCS paths with problematic encodings
385 win32mbcs allow the use of MBCS paths with problematic encodings
386 zeroconf discover and advertise repositories on the local network
386 zeroconf discover and advertise repositories on the local network
387
387
388 #endif
388 #endif
389
389
390 Verify that deprecated extensions are included if --verbose:
390 Verify that deprecated extensions are included if --verbose:
391
391
392 $ hg -v help extensions | grep children
392 $ hg -v help extensions | grep children
393 children command to display child changesets (DEPRECATED)
393 children command to display child changesets (DEPRECATED)
394
394
395 Verify that extension keywords appear in help templates
395 Verify that extension keywords appear in help templates
396
396
397 $ hg help --config extensions.transplant= templating|grep transplant > /dev/null
397 $ hg help --config extensions.transplant= templating|grep transplant > /dev/null
398
398
399 Test short command list with verbose option
399 Test short command list with verbose option
400
400
401 $ hg -v help shortlist
401 $ hg -v help shortlist
402 Mercurial Distributed SCM
402 Mercurial Distributed SCM
403
403
404 basic commands:
404 basic commands:
405
405
406 abort abort an unfinished operation (EXPERIMENTAL)
406 abort abort an unfinished operation (EXPERIMENTAL)
407 add add the specified files on the next commit
407 add add the specified files on the next commit
408 annotate, blame
408 annotate, blame
409 show changeset information by line for each file
409 show changeset information by line for each file
410 clone make a copy of an existing repository
410 clone make a copy of an existing repository
411 commit, ci commit the specified files or all outstanding changes
411 commit, ci commit the specified files or all outstanding changes
412 continue resumes an interrupted operation (EXPERIMENTAL)
412 continue resumes an interrupted operation (EXPERIMENTAL)
413 diff diff repository (or selected files)
413 diff diff repository (or selected files)
414 export dump the header and diffs for one or more changesets
414 export dump the header and diffs for one or more changesets
415 forget forget the specified files on the next commit
415 forget forget the specified files on the next commit
416 init create a new repository in the given directory
416 init create a new repository in the given directory
417 log, history show revision history of entire repository or files
417 log, history show revision history of entire repository or files
418 merge merge another revision into working directory
418 merge merge another revision into working directory
419 pull pull changes from the specified source
419 pull pull changes from the specified source
420 push push changes to the specified destination
420 push push changes to the specified destination
421 remove, rm remove the specified files on the next commit
421 remove, rm remove the specified files on the next commit
422 serve start stand-alone webserver
422 serve start stand-alone webserver
423 status, st show changed files in the working directory
423 status, st show changed files in the working directory
424 summary, sum summarize working directory state
424 summary, sum summarize working directory state
425 update, up, checkout, co
425 update, up, checkout, co
426 update working directory (or switch revisions)
426 update working directory (or switch revisions)
427
427
428 global options ([+] can be repeated):
428 global options ([+] can be repeated):
429
429
430 -R --repository REPO repository root directory or name of overlay bundle
430 -R --repository REPO repository root directory or name of overlay bundle
431 file
431 file
432 --cwd DIR change working directory
432 --cwd DIR change working directory
433 -y --noninteractive do not prompt, automatically pick the first choice for
433 -y --noninteractive do not prompt, automatically pick the first choice for
434 all prompts
434 all prompts
435 -q --quiet suppress output
435 -q --quiet suppress output
436 -v --verbose enable additional output
436 -v --verbose enable additional output
437 --color TYPE when to colorize (boolean, always, auto, never, or
437 --color TYPE when to colorize (boolean, always, auto, never, or
438 debug)
438 debug)
439 --config CONFIG [+] set/override config option (use 'section.name=value')
439 --config CONFIG [+] set/override config option (use 'section.name=value')
440 --debug enable debugging output
440 --debug enable debugging output
441 --debugger start debugger
441 --debugger start debugger
442 --encoding ENCODE set the charset encoding (default: ascii)
442 --encoding ENCODE set the charset encoding (default: ascii)
443 --encodingmode MODE set the charset encoding mode (default: strict)
443 --encodingmode MODE set the charset encoding mode (default: strict)
444 --traceback always print a traceback on exception
444 --traceback always print a traceback on exception
445 --time time how long the command takes
445 --time time how long the command takes
446 --profile print command execution profile
446 --profile print command execution profile
447 --version output version information and exit
447 --version output version information and exit
448 -h --help display help and exit
448 -h --help display help and exit
449 --hidden consider hidden changesets
449 --hidden consider hidden changesets
450 --pager TYPE when to paginate (boolean, always, auto, or never)
450 --pager TYPE when to paginate (boolean, always, auto, or never)
451 (default: auto)
451 (default: auto)
452
452
453 (use 'hg help' for the full list of commands)
453 (use 'hg help' for the full list of commands)
454
454
455 $ hg add -h
455 $ hg add -h
456 hg add [OPTION]... [FILE]...
456 hg add [OPTION]... [FILE]...
457
457
458 add the specified files on the next commit
458 add the specified files on the next commit
459
459
460 Schedule files to be version controlled and added to the repository.
460 Schedule files to be version controlled and added to the repository.
461
461
462 The files will be added to the repository at the next commit. To undo an
462 The files will be added to the repository at the next commit. To undo an
463 add before that, see 'hg forget'.
463 add before that, see 'hg forget'.
464
464
465 If no names are given, add all files to the repository (except files
465 If no names are given, add all files to the repository (except files
466 matching ".hgignore").
466 matching ".hgignore").
467
467
468 Returns 0 if all files are successfully added.
468 Returns 0 if all files are successfully added.
469
469
470 options ([+] can be repeated):
470 options ([+] can be repeated):
471
471
472 -I --include PATTERN [+] include names matching the given patterns
472 -I --include PATTERN [+] include names matching the given patterns
473 -X --exclude PATTERN [+] exclude names matching the given patterns
473 -X --exclude PATTERN [+] exclude names matching the given patterns
474 -S --subrepos recurse into subrepositories
474 -S --subrepos recurse into subrepositories
475 -n --dry-run do not perform actions, just print output
475 -n --dry-run do not perform actions, just print output
476
476
477 (some details hidden, use --verbose to show complete help)
477 (some details hidden, use --verbose to show complete help)
478
478
479 Verbose help for add
479 Verbose help for add
480
480
481 $ hg add -hv
481 $ hg add -hv
482 hg add [OPTION]... [FILE]...
482 hg add [OPTION]... [FILE]...
483
483
484 add the specified files on the next commit
484 add the specified files on the next commit
485
485
486 Schedule files to be version controlled and added to the repository.
486 Schedule files to be version controlled and added to the repository.
487
487
488 The files will be added to the repository at the next commit. To undo an
488 The files will be added to the repository at the next commit. To undo an
489 add before that, see 'hg forget'.
489 add before that, see 'hg forget'.
490
490
491 If no names are given, add all files to the repository (except files
491 If no names are given, add all files to the repository (except files
492 matching ".hgignore").
492 matching ".hgignore").
493
493
494 Examples:
494 Examples:
495
495
496 - New (unknown) files are added automatically by 'hg add':
496 - New (unknown) files are added automatically by 'hg add':
497
497
498 $ ls
498 $ ls
499 foo.c
499 foo.c
500 $ hg status
500 $ hg status
501 ? foo.c
501 ? foo.c
502 $ hg add
502 $ hg add
503 adding foo.c
503 adding foo.c
504 $ hg status
504 $ hg status
505 A foo.c
505 A foo.c
506
506
507 - Specific files to be added can be specified:
507 - Specific files to be added can be specified:
508
508
509 $ ls
509 $ ls
510 bar.c foo.c
510 bar.c foo.c
511 $ hg status
511 $ hg status
512 ? bar.c
512 ? bar.c
513 ? foo.c
513 ? foo.c
514 $ hg add bar.c
514 $ hg add bar.c
515 $ hg status
515 $ hg status
516 A bar.c
516 A bar.c
517 ? foo.c
517 ? foo.c
518
518
519 Returns 0 if all files are successfully added.
519 Returns 0 if all files are successfully added.
520
520
521 options ([+] can be repeated):
521 options ([+] can be repeated):
522
522
523 -I --include PATTERN [+] include names matching the given patterns
523 -I --include PATTERN [+] include names matching the given patterns
524 -X --exclude PATTERN [+] exclude names matching the given patterns
524 -X --exclude PATTERN [+] exclude names matching the given patterns
525 -S --subrepos recurse into subrepositories
525 -S --subrepos recurse into subrepositories
526 -n --dry-run do not perform actions, just print output
526 -n --dry-run do not perform actions, just print output
527
527
528 global options ([+] can be repeated):
528 global options ([+] can be repeated):
529
529
530 -R --repository REPO repository root directory or name of overlay bundle
530 -R --repository REPO repository root directory or name of overlay bundle
531 file
531 file
532 --cwd DIR change working directory
532 --cwd DIR change working directory
533 -y --noninteractive do not prompt, automatically pick the first choice for
533 -y --noninteractive do not prompt, automatically pick the first choice for
534 all prompts
534 all prompts
535 -q --quiet suppress output
535 -q --quiet suppress output
536 -v --verbose enable additional output
536 -v --verbose enable additional output
537 --color TYPE when to colorize (boolean, always, auto, never, or
537 --color TYPE when to colorize (boolean, always, auto, never, or
538 debug)
538 debug)
539 --config CONFIG [+] set/override config option (use 'section.name=value')
539 --config CONFIG [+] set/override config option (use 'section.name=value')
540 --debug enable debugging output
540 --debug enable debugging output
541 --debugger start debugger
541 --debugger start debugger
542 --encoding ENCODE set the charset encoding (default: ascii)
542 --encoding ENCODE set the charset encoding (default: ascii)
543 --encodingmode MODE set the charset encoding mode (default: strict)
543 --encodingmode MODE set the charset encoding mode (default: strict)
544 --traceback always print a traceback on exception
544 --traceback always print a traceback on exception
545 --time time how long the command takes
545 --time time how long the command takes
546 --profile print command execution profile
546 --profile print command execution profile
547 --version output version information and exit
547 --version output version information and exit
548 -h --help display help and exit
548 -h --help display help and exit
549 --hidden consider hidden changesets
549 --hidden consider hidden changesets
550 --pager TYPE when to paginate (boolean, always, auto, or never)
550 --pager TYPE when to paginate (boolean, always, auto, or never)
551 (default: auto)
551 (default: auto)
552
552
553 Test the textwidth config option
553 Test the textwidth config option
554
554
555 $ hg root -h --config ui.textwidth=50
555 $ hg root -h --config ui.textwidth=50
556 hg root
556 hg root
557
557
558 print the root (top) of the current working
558 print the root (top) of the current working
559 directory
559 directory
560
560
561 Print the root directory of the current
561 Print the root directory of the current
562 repository.
562 repository.
563
563
564 Returns 0 on success.
564 Returns 0 on success.
565
565
566 options:
566 options:
567
567
568 -T --template TEMPLATE display with template
568 -T --template TEMPLATE display with template
569
569
570 (some details hidden, use --verbose to show
570 (some details hidden, use --verbose to show
571 complete help)
571 complete help)
572
572
573 Test help option with version option
573 Test help option with version option
574
574
575 $ hg add -h --version
575 $ hg add -h --version
576 Mercurial Distributed SCM (version *) (glob)
576 Mercurial Distributed SCM (version *) (glob)
577 (see https://mercurial-scm.org for more information)
577 (see https://mercurial-scm.org for more information)
578
578
579 Copyright (C) 2005-* Matt Mackall and others (glob)
579 Copyright (C) 2005-* Matt Mackall and others (glob)
580 This is free software; see the source for copying conditions. There is NO
580 This is free software; see the source for copying conditions. There is NO
581 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
581 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
582
582
583 $ hg add --skjdfks
583 $ hg add --skjdfks
584 hg add: option --skjdfks not recognized
584 hg add: option --skjdfks not recognized
585 hg add [OPTION]... [FILE]...
585 hg add [OPTION]... [FILE]...
586
586
587 add the specified files on the next commit
587 add the specified files on the next commit
588
588
589 options ([+] can be repeated):
589 options ([+] can be repeated):
590
590
591 -I --include PATTERN [+] include names matching the given patterns
591 -I --include PATTERN [+] include names matching the given patterns
592 -X --exclude PATTERN [+] exclude names matching the given patterns
592 -X --exclude PATTERN [+] exclude names matching the given patterns
593 -S --subrepos recurse into subrepositories
593 -S --subrepos recurse into subrepositories
594 -n --dry-run do not perform actions, just print output
594 -n --dry-run do not perform actions, just print output
595
595
596 (use 'hg add -h' to show more help)
596 (use 'hg add -h' to show more help)
597 [255]
597 [255]
598
598
599 Test ambiguous command help
599 Test ambiguous command help
600
600
601 $ hg help ad
601 $ hg help ad
602 list of commands:
602 list of commands:
603
603
604 add add the specified files on the next commit
604 add add the specified files on the next commit
605 addremove add all new files, delete all missing files
605 addremove add all new files, delete all missing files
606
606
607 (use 'hg help -v ad' to show built-in aliases and global options)
607 (use 'hg help -v ad' to show built-in aliases and global options)
608
608
609 Test command without options
609 Test command without options
610
610
611 $ hg help verify
611 $ hg help verify
612 hg verify
612 hg verify
613
613
614 verify the integrity of the repository
614 verify the integrity of the repository
615
615
616 Verify the integrity of the current repository.
616 Verify the integrity of the current repository.
617
617
618 This will perform an extensive check of the repository's integrity,
618 This will perform an extensive check of the repository's integrity,
619 validating the hashes and checksums of each entry in the changelog,
619 validating the hashes and checksums of each entry in the changelog,
620 manifest, and tracked files, as well as the integrity of their crosslinks
620 manifest, and tracked files, as well as the integrity of their crosslinks
621 and indices.
621 and indices.
622
622
623 Please see https://mercurial-scm.org/wiki/RepositoryCorruption for more
623 Please see https://mercurial-scm.org/wiki/RepositoryCorruption for more
624 information about recovery from corruption of the repository.
624 information about recovery from corruption of the repository.
625
625
626 Returns 0 on success, 1 if errors are encountered.
626 Returns 0 on success, 1 if errors are encountered.
627
627
628 options:
628 options:
629
629
630 (some details hidden, use --verbose to show complete help)
630 (some details hidden, use --verbose to show complete help)
631
631
632 $ hg help diff
632 $ hg help diff
633 hg diff [OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...
633 hg diff [OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...
634
634
635 diff repository (or selected files)
635 diff repository (or selected files)
636
636
637 Show differences between revisions for the specified files.
637 Show differences between revisions for the specified files.
638
638
639 Differences between files are shown using the unified diff format.
639 Differences between files are shown using the unified diff format.
640
640
641 Note:
641 Note:
642 'hg diff' may generate unexpected results for merges, as it will
642 'hg diff' may generate unexpected results for merges, as it will
643 default to comparing against the working directory's first parent
643 default to comparing against the working directory's first parent
644 changeset if no revisions are specified.
644 changeset if no revisions are specified.
645
645
646 When two revision arguments are given, then changes are shown between
646 When two revision arguments are given, then changes are shown between
647 those revisions. If only one revision is specified then that revision is
647 those revisions. If only one revision is specified then that revision is
648 compared to the working directory, and, when no revisions are specified,
648 compared to the working directory, and, when no revisions are specified,
649 the working directory files are compared to its first parent.
649 the working directory files are compared to its first parent.
650
650
651 Alternatively you can specify -c/--change with a revision to see the
651 Alternatively you can specify -c/--change with a revision to see the
652 changes in that changeset relative to its first parent.
652 changes in that changeset relative to its first parent.
653
653
654 Without the -a/--text option, diff will avoid generating diffs of files it
654 Without the -a/--text option, diff will avoid generating diffs of files it
655 detects as binary. With -a, diff will generate a diff anyway, probably
655 detects as binary. With -a, diff will generate a diff anyway, probably
656 with undesirable results.
656 with undesirable results.
657
657
658 Use the -g/--git option to generate diffs in the git extended diff format.
658 Use the -g/--git option to generate diffs in the git extended diff format.
659 For more information, read 'hg help diffs'.
659 For more information, read 'hg help diffs'.
660
660
661 Returns 0 on success.
661 Returns 0 on success.
662
662
663 options ([+] can be repeated):
663 options ([+] can be repeated):
664
664
665 -r --rev REV [+] revision
665 -r --rev REV [+] revision
666 -c --change REV change made by revision
666 -c --change REV change made by revision
667 -a --text treat all files as text
667 -a --text treat all files as text
668 -g --git use git extended diff format
668 -g --git use git extended diff format
669 --binary generate binary diffs in git mode (default)
669 --binary generate binary diffs in git mode (default)
670 --nodates omit dates from diff headers
670 --nodates omit dates from diff headers
671 --noprefix omit a/ and b/ prefixes from filenames
671 --noprefix omit a/ and b/ prefixes from filenames
672 -p --show-function show which function each change is in
672 -p --show-function show which function each change is in
673 --reverse produce a diff that undoes the changes
673 --reverse produce a diff that undoes the changes
674 -w --ignore-all-space ignore white space when comparing lines
674 -w --ignore-all-space ignore white space when comparing lines
675 -b --ignore-space-change ignore changes in the amount of white space
675 -b --ignore-space-change ignore changes in the amount of white space
676 -B --ignore-blank-lines ignore changes whose lines are all blank
676 -B --ignore-blank-lines ignore changes whose lines are all blank
677 -Z --ignore-space-at-eol ignore changes in whitespace at EOL
677 -Z --ignore-space-at-eol ignore changes in whitespace at EOL
678 -U --unified NUM number of lines of context to show
678 -U --unified NUM number of lines of context to show
679 --stat output diffstat-style summary of changes
679 --stat output diffstat-style summary of changes
680 --root DIR produce diffs relative to subdirectory
680 --root DIR produce diffs relative to subdirectory
681 -I --include PATTERN [+] include names matching the given patterns
681 -I --include PATTERN [+] include names matching the given patterns
682 -X --exclude PATTERN [+] exclude names matching the given patterns
682 -X --exclude PATTERN [+] exclude names matching the given patterns
683 -S --subrepos recurse into subrepositories
683 -S --subrepos recurse into subrepositories
684
684
685 (some details hidden, use --verbose to show complete help)
685 (some details hidden, use --verbose to show complete help)
686
686
687 $ hg help status
687 $ hg help status
688 hg status [OPTION]... [FILE]...
688 hg status [OPTION]... [FILE]...
689
689
690 aliases: st
690 aliases: st
691
691
692 show changed files in the working directory
692 show changed files in the working directory
693
693
694 Show status of files in the repository. If names are given, only files
694 Show status of files in the repository. If names are given, only files
695 that match are shown. Files that are clean or ignored or the source of a
695 that match are shown. Files that are clean or ignored or the source of a
696 copy/move operation, are not listed unless -c/--clean, -i/--ignored,
696 copy/move operation, are not listed unless -c/--clean, -i/--ignored,
697 -C/--copies or -A/--all are given. Unless options described with "show
697 -C/--copies or -A/--all are given. Unless options described with "show
698 only ..." are given, the options -mardu are used.
698 only ..." are given, the options -mardu are used.
699
699
700 Option -q/--quiet hides untracked (unknown and ignored) files unless
700 Option -q/--quiet hides untracked (unknown and ignored) files unless
701 explicitly requested with -u/--unknown or -i/--ignored.
701 explicitly requested with -u/--unknown or -i/--ignored.
702
702
703 Note:
703 Note:
704 'hg status' may appear to disagree with diff if permissions have
704 'hg status' may appear to disagree with diff if permissions have
705 changed or a merge has occurred. The standard diff format does not
705 changed or a merge has occurred. The standard diff format does not
706 report permission changes and diff only reports changes relative to one
706 report permission changes and diff only reports changes relative to one
707 merge parent.
707 merge parent.
708
708
709 If one revision is given, it is used as the base revision. If two
709 If one revision is given, it is used as the base revision. If two
710 revisions are given, the differences between them are shown. The --change
710 revisions are given, the differences between them are shown. The --change
711 option can also be used as a shortcut to list the changed files of a
711 option can also be used as a shortcut to list the changed files of a
712 revision from its first parent.
712 revision from its first parent.
713
713
714 The codes used to show the status of files are:
714 The codes used to show the status of files are:
715
715
716 M = modified
716 M = modified
717 A = added
717 A = added
718 R = removed
718 R = removed
719 C = clean
719 C = clean
720 ! = missing (deleted by non-hg command, but still tracked)
720 ! = missing (deleted by non-hg command, but still tracked)
721 ? = not tracked
721 ? = not tracked
722 I = ignored
722 I = ignored
723 = origin of the previous file (with --copies)
723 = origin of the previous file (with --copies)
724
724
725 Returns 0 on success.
725 Returns 0 on success.
726
726
727 options ([+] can be repeated):
727 options ([+] can be repeated):
728
728
729 -A --all show status of all files
729 -A --all show status of all files
730 -m --modified show only modified files
730 -m --modified show only modified files
731 -a --added show only added files
731 -a --added show only added files
732 -r --removed show only removed files
732 -r --removed show only removed files
733 -d --deleted show only deleted (but tracked) files
733 -d --deleted show only deleted (but tracked) files
734 -c --clean show only files without changes
734 -c --clean show only files without changes
735 -u --unknown show only unknown (not tracked) files
735 -u --unknown show only unknown (not tracked) files
736 -i --ignored show only ignored files
736 -i --ignored show only ignored files
737 -n --no-status hide status prefix
737 -n --no-status hide status prefix
738 -C --copies show source of copied files
738 -C --copies show source of copied files
739 -0 --print0 end filenames with NUL, for use with xargs
739 -0 --print0 end filenames with NUL, for use with xargs
740 --rev REV [+] show difference from revision
740 --rev REV [+] show difference from revision
741 --change REV list the changed files of a revision
741 --change REV list the changed files of a revision
742 -I --include PATTERN [+] include names matching the given patterns
742 -I --include PATTERN [+] include names matching the given patterns
743 -X --exclude PATTERN [+] exclude names matching the given patterns
743 -X --exclude PATTERN [+] exclude names matching the given patterns
744 -S --subrepos recurse into subrepositories
744 -S --subrepos recurse into subrepositories
745 -T --template TEMPLATE display with template
745 -T --template TEMPLATE display with template
746
746
747 (some details hidden, use --verbose to show complete help)
747 (some details hidden, use --verbose to show complete help)
748
748
749 $ hg -q help status
749 $ hg -q help status
750 hg status [OPTION]... [FILE]...
750 hg status [OPTION]... [FILE]...
751
751
752 show changed files in the working directory
752 show changed files in the working directory
753
753
754 $ hg help foo
754 $ hg help foo
755 abort: no such help topic: foo
755 abort: no such help topic: foo
756 (try 'hg help --keyword foo')
756 (try 'hg help --keyword foo')
757 [255]
757 [255]
758
758
759 $ hg skjdfks
759 $ hg skjdfks
760 hg: unknown command 'skjdfks'
760 hg: unknown command 'skjdfks'
761 (use 'hg help' for a list of commands)
761 (use 'hg help' for a list of commands)
762 [255]
762 [255]
763
763
764 Typoed command gives suggestion
764 Typoed command gives suggestion
765 $ hg puls
765 $ hg puls
766 hg: unknown command 'puls'
766 hg: unknown command 'puls'
767 (did you mean one of pull, push?)
767 (did you mean one of pull, push?)
768 [255]
768 [255]
769
769
770 Not enabled extension gets suggested
770 Not enabled extension gets suggested
771
771
772 $ hg rebase
772 $ hg rebase
773 hg: unknown command 'rebase'
773 hg: unknown command 'rebase'
774 'rebase' is provided by the following extension:
774 'rebase' is provided by the following extension:
775
775
776 rebase command to move sets of revisions to a different ancestor
776 rebase command to move sets of revisions to a different ancestor
777
777
778 (use 'hg help extensions' for information on enabling extensions)
778 (use 'hg help extensions' for information on enabling extensions)
779 [255]
779 [255]
780
780
781 Disabled extension gets suggested
781 Disabled extension gets suggested
782 $ hg --config extensions.rebase=! rebase
782 $ hg --config extensions.rebase=! rebase
783 hg: unknown command 'rebase'
783 hg: unknown command 'rebase'
784 'rebase' is provided by the following extension:
784 'rebase' is provided by the following extension:
785
785
786 rebase command to move sets of revisions to a different ancestor
786 rebase command to move sets of revisions to a different ancestor
787
787
788 (use 'hg help extensions' for information on enabling extensions)
788 (use 'hg help extensions' for information on enabling extensions)
789 [255]
789 [255]
790
790
791 Checking that help adapts based on the config:
792
793 $ hg help diff --config ui.tweakdefaults=true | egrep -e '^ *(-g|config)'
794 -g --[no-]git use git extended diff format (default: on from
795 config)
796
791 Make sure that we don't run afoul of the help system thinking that
797 Make sure that we don't run afoul of the help system thinking that
792 this is a section and erroring out weirdly.
798 this is a section and erroring out weirdly.
793
799
794 $ hg .log
800 $ hg .log
795 hg: unknown command '.log'
801 hg: unknown command '.log'
796 (did you mean log?)
802 (did you mean log?)
797 [255]
803 [255]
798
804
799 $ hg log.
805 $ hg log.
800 hg: unknown command 'log.'
806 hg: unknown command 'log.'
801 (did you mean log?)
807 (did you mean log?)
802 [255]
808 [255]
803 $ hg pu.lh
809 $ hg pu.lh
804 hg: unknown command 'pu.lh'
810 hg: unknown command 'pu.lh'
805 (did you mean one of pull, push?)
811 (did you mean one of pull, push?)
806 [255]
812 [255]
807
813
808 $ cat > helpext.py <<EOF
814 $ cat > helpext.py <<EOF
809 > import os
815 > import os
810 > from mercurial import commands, fancyopts, registrar
816 > from mercurial import commands, fancyopts, registrar
811 >
817 >
812 > def func(arg):
818 > def func(arg):
813 > return '%sfoo' % arg
819 > return '%sfoo' % arg
814 > class customopt(fancyopts.customopt):
820 > class customopt(fancyopts.customopt):
815 > def newstate(self, oldstate, newparam, abort):
821 > def newstate(self, oldstate, newparam, abort):
816 > return '%sbar' % oldstate
822 > return '%sbar' % oldstate
817 > cmdtable = {}
823 > cmdtable = {}
818 > command = registrar.command(cmdtable)
824 > command = registrar.command(cmdtable)
819 >
825 >
820 > @command(b'nohelp',
826 > @command(b'nohelp',
821 > [(b'', b'longdesc', 3, b'x'*67),
827 > [(b'', b'longdesc', 3, b'x'*67),
822 > (b'n', b'', None, b'normal desc'),
828 > (b'n', b'', None, b'normal desc'),
823 > (b'', b'newline', b'', b'line1\nline2'),
829 > (b'', b'newline', b'', b'line1\nline2'),
824 > (b'', b'default-off', False, b'enable X'),
830 > (b'', b'default-off', False, b'enable X'),
825 > (b'', b'default-on', True, b'enable Y'),
831 > (b'', b'default-on', True, b'enable Y'),
826 > (b'', b'callableopt', func, b'adds foo'),
832 > (b'', b'callableopt', func, b'adds foo'),
827 > (b'', b'customopt', customopt(''), b'adds bar'),
833 > (b'', b'customopt', customopt(''), b'adds bar'),
828 > (b'', b'customopt-withdefault', customopt('foo'), b'adds bar')],
834 > (b'', b'customopt-withdefault', customopt('foo'), b'adds bar')],
829 > b'hg nohelp',
835 > b'hg nohelp',
830 > norepo=True)
836 > norepo=True)
831 > @command(b'debugoptADV', [(b'', b'aopt', None, b'option is (ADVANCED)')])
837 > @command(b'debugoptADV', [(b'', b'aopt', None, b'option is (ADVANCED)')])
832 > @command(b'debugoptDEP', [(b'', b'dopt', None, b'option is (DEPRECATED)')])
838 > @command(b'debugoptDEP', [(b'', b'dopt', None, b'option is (DEPRECATED)')])
833 > @command(b'debugoptEXP', [(b'', b'eopt', None, b'option is (EXPERIMENTAL)')])
839 > @command(b'debugoptEXP', [(b'', b'eopt', None, b'option is (EXPERIMENTAL)')])
834 > def nohelp(ui, *args, **kwargs):
840 > def nohelp(ui, *args, **kwargs):
835 > pass
841 > pass
836 >
842 >
837 > @command(b'hashelp', [], b'hg hashelp', norepo=True)
843 > @command(b'hashelp', [], b'hg hashelp', norepo=True)
838 > def hashelp(ui, *args, **kwargs):
844 > def hashelp(ui, *args, **kwargs):
839 > """Extension command's help"""
845 > """Extension command's help"""
840 >
846 >
841 > def uisetup(ui):
847 > def uisetup(ui):
842 > ui.setconfig(b'alias', b'shellalias', b'!echo hi', b'helpext')
848 > ui.setconfig(b'alias', b'shellalias', b'!echo hi', b'helpext')
843 > ui.setconfig(b'alias', b'hgalias', b'summary', b'helpext')
849 > ui.setconfig(b'alias', b'hgalias', b'summary', b'helpext')
844 > ui.setconfig(b'alias', b'hgalias:doc', b'My doc', b'helpext')
850 > ui.setconfig(b'alias', b'hgalias:doc', b'My doc', b'helpext')
845 > ui.setconfig(b'alias', b'hgalias:category', b'navigation', b'helpext')
851 > ui.setconfig(b'alias', b'hgalias:category', b'navigation', b'helpext')
846 > ui.setconfig(b'alias', b'hgaliasnodoc', b'summary', b'helpext')
852 > ui.setconfig(b'alias', b'hgaliasnodoc', b'summary', b'helpext')
847 >
853 >
848 > EOF
854 > EOF
849 $ echo '[extensions]' >> $HGRCPATH
855 $ echo '[extensions]' >> $HGRCPATH
850 $ echo "helpext = `pwd`/helpext.py" >> $HGRCPATH
856 $ echo "helpext = `pwd`/helpext.py" >> $HGRCPATH
851
857
852 Test for aliases
858 Test for aliases
853
859
854 $ hg help | grep hgalias
860 $ hg help | grep hgalias
855 hgalias My doc
861 hgalias My doc
856
862
857 $ hg help hgalias
863 $ hg help hgalias
858 hg hgalias [--remote]
864 hg hgalias [--remote]
859
865
860 alias for: hg summary
866 alias for: hg summary
861
867
862 My doc
868 My doc
863
869
864 defined by: helpext
870 defined by: helpext
865
871
866 options:
872 options:
867
873
868 --remote check for push and pull
874 --remote check for push and pull
869
875
870 (some details hidden, use --verbose to show complete help)
876 (some details hidden, use --verbose to show complete help)
871 $ hg help hgaliasnodoc
877 $ hg help hgaliasnodoc
872 hg hgaliasnodoc [--remote]
878 hg hgaliasnodoc [--remote]
873
879
874 alias for: hg summary
880 alias for: hg summary
875
881
876 summarize working directory state
882 summarize working directory state
877
883
878 This generates a brief summary of the working directory state, including
884 This generates a brief summary of the working directory state, including
879 parents, branch, commit status, phase and available updates.
885 parents, branch, commit status, phase and available updates.
880
886
881 With the --remote option, this will check the default paths for incoming
887 With the --remote option, this will check the default paths for incoming
882 and outgoing changes. This can be time-consuming.
888 and outgoing changes. This can be time-consuming.
883
889
884 Returns 0 on success.
890 Returns 0 on success.
885
891
886 defined by: helpext
892 defined by: helpext
887
893
888 options:
894 options:
889
895
890 --remote check for push and pull
896 --remote check for push and pull
891
897
892 (some details hidden, use --verbose to show complete help)
898 (some details hidden, use --verbose to show complete help)
893
899
894 $ hg help shellalias
900 $ hg help shellalias
895 hg shellalias
901 hg shellalias
896
902
897 shell alias for: echo hi
903 shell alias for: echo hi
898
904
899 (no help text available)
905 (no help text available)
900
906
901 defined by: helpext
907 defined by: helpext
902
908
903 (some details hidden, use --verbose to show complete help)
909 (some details hidden, use --verbose to show complete help)
904
910
905 Test command with no help text
911 Test command with no help text
906
912
907 $ hg help nohelp
913 $ hg help nohelp
908 hg nohelp
914 hg nohelp
909
915
910 (no help text available)
916 (no help text available)
911
917
912 options:
918 options:
913
919
914 --longdesc VALUE
920 --longdesc VALUE
915 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
921 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
916 xxxxxxxxxxxxxxxxxxxxxxx (default: 3)
922 xxxxxxxxxxxxxxxxxxxxxxx (default: 3)
917 -n -- normal desc
923 -n -- normal desc
918 --newline VALUE line1 line2
924 --newline VALUE line1 line2
919 --default-off enable X
925 --default-off enable X
920 --[no-]default-on enable Y (default: on)
926 --[no-]default-on enable Y (default: on)
921 --callableopt VALUE adds foo
927 --callableopt VALUE adds foo
922 --customopt VALUE adds bar
928 --customopt VALUE adds bar
923 --customopt-withdefault VALUE adds bar (default: foo)
929 --customopt-withdefault VALUE adds bar (default: foo)
924
930
925 (some details hidden, use --verbose to show complete help)
931 (some details hidden, use --verbose to show complete help)
926
932
927 Test that default list of commands includes extension commands that have help,
933 Test that default list of commands includes extension commands that have help,
928 but not those that don't, except in verbose mode, when a keyword is passed, or
934 but not those that don't, except in verbose mode, when a keyword is passed, or
929 when help about the extension is requested.
935 when help about the extension is requested.
930
936
931 #if no-extraextensions
937 #if no-extraextensions
932
938
933 $ hg help | grep hashelp
939 $ hg help | grep hashelp
934 hashelp Extension command's help
940 hashelp Extension command's help
935 $ hg help | grep nohelp
941 $ hg help | grep nohelp
936 [1]
942 [1]
937 $ hg help -v | grep nohelp
943 $ hg help -v | grep nohelp
938 nohelp (no help text available)
944 nohelp (no help text available)
939
945
940 $ hg help -k nohelp
946 $ hg help -k nohelp
941 Commands:
947 Commands:
942
948
943 nohelp hg nohelp
949 nohelp hg nohelp
944
950
945 Extension Commands:
951 Extension Commands:
946
952
947 nohelp (no help text available)
953 nohelp (no help text available)
948
954
949 $ hg help helpext
955 $ hg help helpext
950 helpext extension - no help text available
956 helpext extension - no help text available
951
957
952 list of commands:
958 list of commands:
953
959
954 hashelp Extension command's help
960 hashelp Extension command's help
955 nohelp (no help text available)
961 nohelp (no help text available)
956
962
957 (use 'hg help -v helpext' to show built-in aliases and global options)
963 (use 'hg help -v helpext' to show built-in aliases and global options)
958
964
959 #endif
965 #endif
960
966
961 Test list of internal help commands
967 Test list of internal help commands
962
968
963 $ hg help debug
969 $ hg help debug
964 debug commands (internal and unsupported):
970 debug commands (internal and unsupported):
965
971
966 debugancestor
972 debugancestor
967 find the ancestor revision of two revisions in a given index
973 find the ancestor revision of two revisions in a given index
968 debugapplystreamclonebundle
974 debugapplystreamclonebundle
969 apply a stream clone bundle file
975 apply a stream clone bundle file
970 debugbuilddag
976 debugbuilddag
971 builds a repo with a given DAG from scratch in the current
977 builds a repo with a given DAG from scratch in the current
972 empty repo
978 empty repo
973 debugbundle lists the contents of a bundle
979 debugbundle lists the contents of a bundle
974 debugcapabilities
980 debugcapabilities
975 lists the capabilities of a remote peer
981 lists the capabilities of a remote peer
976 debugcheckstate
982 debugcheckstate
977 validate the correctness of the current dirstate
983 validate the correctness of the current dirstate
978 debugcolor show available color, effects or style
984 debugcolor show available color, effects or style
979 debugcommands
985 debugcommands
980 list all available commands and options
986 list all available commands and options
981 debugcomplete
987 debugcomplete
982 returns the completion list associated with the given command
988 returns the completion list associated with the given command
983 debugcreatestreamclonebundle
989 debugcreatestreamclonebundle
984 create a stream clone bundle file
990 create a stream clone bundle file
985 debugdag format the changelog or an index DAG as a concise textual
991 debugdag format the changelog or an index DAG as a concise textual
986 description
992 description
987 debugdata dump the contents of a data file revision
993 debugdata dump the contents of a data file revision
988 debugdate parse and display a date
994 debugdate parse and display a date
989 debugdeltachain
995 debugdeltachain
990 dump information about delta chains in a revlog
996 dump information about delta chains in a revlog
991 debugdirstate
997 debugdirstate
992 show the contents of the current dirstate
998 show the contents of the current dirstate
993 debugdiscovery
999 debugdiscovery
994 runs the changeset discovery protocol in isolation
1000 runs the changeset discovery protocol in isolation
995 debugdownload
1001 debugdownload
996 download a resource using Mercurial logic and config
1002 download a resource using Mercurial logic and config
997 debugextensions
1003 debugextensions
998 show information about active extensions
1004 show information about active extensions
999 debugfileset parse and apply a fileset specification
1005 debugfileset parse and apply a fileset specification
1000 debugformat display format information about the current repository
1006 debugformat display format information about the current repository
1001 debugfsinfo show information detected about current filesystem
1007 debugfsinfo show information detected about current filesystem
1002 debuggetbundle
1008 debuggetbundle
1003 retrieves a bundle from a repo
1009 retrieves a bundle from a repo
1004 debugignore display the combined ignore pattern and information about
1010 debugignore display the combined ignore pattern and information about
1005 ignored files
1011 ignored files
1006 debugindex dump index data for a storage primitive
1012 debugindex dump index data for a storage primitive
1007 debugindexdot
1013 debugindexdot
1008 dump an index DAG as a graphviz dot file
1014 dump an index DAG as a graphviz dot file
1009 debugindexstats
1015 debugindexstats
1010 show stats related to the changelog index
1016 show stats related to the changelog index
1011 debuginstall test Mercurial installation
1017 debuginstall test Mercurial installation
1012 debugknown test whether node ids are known to a repo
1018 debugknown test whether node ids are known to a repo
1013 debuglocks show or modify state of locks
1019 debuglocks show or modify state of locks
1014 debugmanifestfulltextcache
1020 debugmanifestfulltextcache
1015 show, clear or amend the contents of the manifest fulltext
1021 show, clear or amend the contents of the manifest fulltext
1016 cache
1022 cache
1017 debugmergestate
1023 debugmergestate
1018 print merge state
1024 print merge state
1019 debugnamecomplete
1025 debugnamecomplete
1020 complete "names" - tags, open branch names, bookmark names
1026 complete "names" - tags, open branch names, bookmark names
1021 debugobsolete
1027 debugobsolete
1022 create arbitrary obsolete marker
1028 create arbitrary obsolete marker
1023 debugoptADV (no help text available)
1029 debugoptADV (no help text available)
1024 debugoptDEP (no help text available)
1030 debugoptDEP (no help text available)
1025 debugoptEXP (no help text available)
1031 debugoptEXP (no help text available)
1026 debugp1copies
1032 debugp1copies
1027 dump copy information compared to p1
1033 dump copy information compared to p1
1028 debugp2copies
1034 debugp2copies
1029 dump copy information compared to p2
1035 dump copy information compared to p2
1030 debugpathcomplete
1036 debugpathcomplete
1031 complete part or all of a tracked path
1037 complete part or all of a tracked path
1032 debugpathcopies
1038 debugpathcopies
1033 show copies between two revisions
1039 show copies between two revisions
1034 debugpeer establish a connection to a peer repository
1040 debugpeer establish a connection to a peer repository
1035 debugpickmergetool
1041 debugpickmergetool
1036 examine which merge tool is chosen for specified file
1042 examine which merge tool is chosen for specified file
1037 debugpushkey access the pushkey key/value protocol
1043 debugpushkey access the pushkey key/value protocol
1038 debugpvec (no help text available)
1044 debugpvec (no help text available)
1039 debugrebuilddirstate
1045 debugrebuilddirstate
1040 rebuild the dirstate as it would look like for the given
1046 rebuild the dirstate as it would look like for the given
1041 revision
1047 revision
1042 debugrebuildfncache
1048 debugrebuildfncache
1043 rebuild the fncache file
1049 rebuild the fncache file
1044 debugrename dump rename information
1050 debugrename dump rename information
1045 debugrevlog show data and statistics about a revlog
1051 debugrevlog show data and statistics about a revlog
1046 debugrevlogindex
1052 debugrevlogindex
1047 dump the contents of a revlog index
1053 dump the contents of a revlog index
1048 debugrevspec parse and apply a revision specification
1054 debugrevspec parse and apply a revision specification
1049 debugserve run a server with advanced settings
1055 debugserve run a server with advanced settings
1050 debugsetparents
1056 debugsetparents
1051 manually set the parents of the current working directory
1057 manually set the parents of the current working directory
1052 debugsidedata
1058 debugsidedata
1053 dump the side data for a cl/manifest/file revision
1059 dump the side data for a cl/manifest/file revision
1054 debugssl test a secure connection to a server
1060 debugssl test a secure connection to a server
1055 debugsub (no help text available)
1061 debugsub (no help text available)
1056 debugsuccessorssets
1062 debugsuccessorssets
1057 show set of successors for revision
1063 show set of successors for revision
1058 debugtagscache
1064 debugtagscache
1059 display the contents of .hg/cache/hgtagsfnodes1
1065 display the contents of .hg/cache/hgtagsfnodes1
1060 debugtemplate
1066 debugtemplate
1061 parse and apply a template
1067 parse and apply a template
1062 debuguigetpass
1068 debuguigetpass
1063 show prompt to type password
1069 show prompt to type password
1064 debuguiprompt
1070 debuguiprompt
1065 show plain prompt
1071 show plain prompt
1066 debugupdatecaches
1072 debugupdatecaches
1067 warm all known caches in the repository
1073 warm all known caches in the repository
1068 debugupgraderepo
1074 debugupgraderepo
1069 upgrade a repository to use different features
1075 upgrade a repository to use different features
1070 debugwalk show how files match on given patterns
1076 debugwalk show how files match on given patterns
1071 debugwhyunstable
1077 debugwhyunstable
1072 explain instabilities of a changeset
1078 explain instabilities of a changeset
1073 debugwireargs
1079 debugwireargs
1074 (no help text available)
1080 (no help text available)
1075 debugwireproto
1081 debugwireproto
1076 send wire protocol commands to a server
1082 send wire protocol commands to a server
1077
1083
1078 (use 'hg help -v debug' to show built-in aliases and global options)
1084 (use 'hg help -v debug' to show built-in aliases and global options)
1079
1085
1080 internals topic renders index of available sub-topics
1086 internals topic renders index of available sub-topics
1081
1087
1082 $ hg help internals
1088 $ hg help internals
1083 Technical implementation topics
1089 Technical implementation topics
1084 """""""""""""""""""""""""""""""
1090 """""""""""""""""""""""""""""""
1085
1091
1086 To access a subtopic, use "hg help internals.{subtopic-name}"
1092 To access a subtopic, use "hg help internals.{subtopic-name}"
1087
1093
1088 bundle2 Bundle2
1094 bundle2 Bundle2
1089 bundles Bundles
1095 bundles Bundles
1090 cbor CBOR
1096 cbor CBOR
1091 censor Censor
1097 censor Censor
1092 changegroups Changegroups
1098 changegroups Changegroups
1093 config Config Registrar
1099 config Config Registrar
1094 extensions Extension API
1100 extensions Extension API
1095 mergestate Mergestate
1101 mergestate Mergestate
1096 requirements Repository Requirements
1102 requirements Repository Requirements
1097 revlogs Revision Logs
1103 revlogs Revision Logs
1098 wireprotocol Wire Protocol
1104 wireprotocol Wire Protocol
1099 wireprotocolrpc
1105 wireprotocolrpc
1100 Wire Protocol RPC
1106 Wire Protocol RPC
1101 wireprotocolv2
1107 wireprotocolv2
1102 Wire Protocol Version 2
1108 Wire Protocol Version 2
1103
1109
1104 sub-topics can be accessed
1110 sub-topics can be accessed
1105
1111
1106 $ hg help internals.changegroups
1112 $ hg help internals.changegroups
1107 Changegroups
1113 Changegroups
1108 """"""""""""
1114 """"""""""""
1109
1115
1110 Changegroups are representations of repository revlog data, specifically
1116 Changegroups are representations of repository revlog data, specifically
1111 the changelog data, root/flat manifest data, treemanifest data, and
1117 the changelog data, root/flat manifest data, treemanifest data, and
1112 filelogs.
1118 filelogs.
1113
1119
1114 There are 3 versions of changegroups: "1", "2", and "3". From a high-
1120 There are 3 versions of changegroups: "1", "2", and "3". From a high-
1115 level, versions "1" and "2" are almost exactly the same, with the only
1121 level, versions "1" and "2" are almost exactly the same, with the only
1116 difference being an additional item in the *delta header*. Version "3"
1122 difference being an additional item in the *delta header*. Version "3"
1117 adds support for storage flags in the *delta header* and optionally
1123 adds support for storage flags in the *delta header* and optionally
1118 exchanging treemanifests (enabled by setting an option on the
1124 exchanging treemanifests (enabled by setting an option on the
1119 "changegroup" part in the bundle2).
1125 "changegroup" part in the bundle2).
1120
1126
1121 Changegroups when not exchanging treemanifests consist of 3 logical
1127 Changegroups when not exchanging treemanifests consist of 3 logical
1122 segments:
1128 segments:
1123
1129
1124 +---------------------------------+
1130 +---------------------------------+
1125 | | | |
1131 | | | |
1126 | changeset | manifest | filelogs |
1132 | changeset | manifest | filelogs |
1127 | | | |
1133 | | | |
1128 | | | |
1134 | | | |
1129 +---------------------------------+
1135 +---------------------------------+
1130
1136
1131 When exchanging treemanifests, there are 4 logical segments:
1137 When exchanging treemanifests, there are 4 logical segments:
1132
1138
1133 +-------------------------------------------------+
1139 +-------------------------------------------------+
1134 | | | | |
1140 | | | | |
1135 | changeset | root | treemanifests | filelogs |
1141 | changeset | root | treemanifests | filelogs |
1136 | | manifest | | |
1142 | | manifest | | |
1137 | | | | |
1143 | | | | |
1138 +-------------------------------------------------+
1144 +-------------------------------------------------+
1139
1145
1140 The principle building block of each segment is a *chunk*. A *chunk* is a
1146 The principle building block of each segment is a *chunk*. A *chunk* is a
1141 framed piece of data:
1147 framed piece of data:
1142
1148
1143 +---------------------------------------+
1149 +---------------------------------------+
1144 | | |
1150 | | |
1145 | length | data |
1151 | length | data |
1146 | (4 bytes) | (<length - 4> bytes) |
1152 | (4 bytes) | (<length - 4> bytes) |
1147 | | |
1153 | | |
1148 +---------------------------------------+
1154 +---------------------------------------+
1149
1155
1150 All integers are big-endian signed integers. Each chunk starts with a
1156 All integers are big-endian signed integers. Each chunk starts with a
1151 32-bit integer indicating the length of the entire chunk (including the
1157 32-bit integer indicating the length of the entire chunk (including the
1152 length field itself).
1158 length field itself).
1153
1159
1154 There is a special case chunk that has a value of 0 for the length
1160 There is a special case chunk that has a value of 0 for the length
1155 ("0x00000000"). We call this an *empty chunk*.
1161 ("0x00000000"). We call this an *empty chunk*.
1156
1162
1157 Delta Groups
1163 Delta Groups
1158 ============
1164 ============
1159
1165
1160 A *delta group* expresses the content of a revlog as a series of deltas,
1166 A *delta group* expresses the content of a revlog as a series of deltas,
1161 or patches against previous revisions.
1167 or patches against previous revisions.
1162
1168
1163 Delta groups consist of 0 or more *chunks* followed by the *empty chunk*
1169 Delta groups consist of 0 or more *chunks* followed by the *empty chunk*
1164 to signal the end of the delta group:
1170 to signal the end of the delta group:
1165
1171
1166 +------------------------------------------------------------------------+
1172 +------------------------------------------------------------------------+
1167 | | | | | |
1173 | | | | | |
1168 | chunk0 length | chunk0 data | chunk1 length | chunk1 data | 0x0 |
1174 | chunk0 length | chunk0 data | chunk1 length | chunk1 data | 0x0 |
1169 | (4 bytes) | (various) | (4 bytes) | (various) | (4 bytes) |
1175 | (4 bytes) | (various) | (4 bytes) | (various) | (4 bytes) |
1170 | | | | | |
1176 | | | | | |
1171 +------------------------------------------------------------------------+
1177 +------------------------------------------------------------------------+
1172
1178
1173 Each *chunk*'s data consists of the following:
1179 Each *chunk*'s data consists of the following:
1174
1180
1175 +---------------------------------------+
1181 +---------------------------------------+
1176 | | |
1182 | | |
1177 | delta header | delta data |
1183 | delta header | delta data |
1178 | (various by version) | (various) |
1184 | (various by version) | (various) |
1179 | | |
1185 | | |
1180 +---------------------------------------+
1186 +---------------------------------------+
1181
1187
1182 The *delta data* is a series of *delta*s that describe a diff from an
1188 The *delta data* is a series of *delta*s that describe a diff from an
1183 existing entry (either that the recipient already has, or previously
1189 existing entry (either that the recipient already has, or previously
1184 specified in the bundle/changegroup).
1190 specified in the bundle/changegroup).
1185
1191
1186 The *delta header* is different between versions "1", "2", and "3" of the
1192 The *delta header* is different between versions "1", "2", and "3" of the
1187 changegroup format.
1193 changegroup format.
1188
1194
1189 Version 1 (headerlen=80):
1195 Version 1 (headerlen=80):
1190
1196
1191 +------------------------------------------------------+
1197 +------------------------------------------------------+
1192 | | | | |
1198 | | | | |
1193 | node | p1 node | p2 node | link node |
1199 | node | p1 node | p2 node | link node |
1194 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
1200 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
1195 | | | | |
1201 | | | | |
1196 +------------------------------------------------------+
1202 +------------------------------------------------------+
1197
1203
1198 Version 2 (headerlen=100):
1204 Version 2 (headerlen=100):
1199
1205
1200 +------------------------------------------------------------------+
1206 +------------------------------------------------------------------+
1201 | | | | | |
1207 | | | | | |
1202 | node | p1 node | p2 node | base node | link node |
1208 | node | p1 node | p2 node | base node | link node |
1203 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
1209 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
1204 | | | | | |
1210 | | | | | |
1205 +------------------------------------------------------------------+
1211 +------------------------------------------------------------------+
1206
1212
1207 Version 3 (headerlen=102):
1213 Version 3 (headerlen=102):
1208
1214
1209 +------------------------------------------------------------------------------+
1215 +------------------------------------------------------------------------------+
1210 | | | | | | |
1216 | | | | | | |
1211 | node | p1 node | p2 node | base node | link node | flags |
1217 | node | p1 node | p2 node | base node | link node | flags |
1212 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (2 bytes) |
1218 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (2 bytes) |
1213 | | | | | | |
1219 | | | | | | |
1214 +------------------------------------------------------------------------------+
1220 +------------------------------------------------------------------------------+
1215
1221
1216 The *delta data* consists of "chunklen - 4 - headerlen" bytes, which
1222 The *delta data* consists of "chunklen - 4 - headerlen" bytes, which
1217 contain a series of *delta*s, densely packed (no separators). These deltas
1223 contain a series of *delta*s, densely packed (no separators). These deltas
1218 describe a diff from an existing entry (either that the recipient already
1224 describe a diff from an existing entry (either that the recipient already
1219 has, or previously specified in the bundle/changegroup). The format is
1225 has, or previously specified in the bundle/changegroup). The format is
1220 described more fully in "hg help internals.bdiff", but briefly:
1226 described more fully in "hg help internals.bdiff", but briefly:
1221
1227
1222 +---------------------------------------------------------------+
1228 +---------------------------------------------------------------+
1223 | | | | |
1229 | | | | |
1224 | start offset | end offset | new length | content |
1230 | start offset | end offset | new length | content |
1225 | (4 bytes) | (4 bytes) | (4 bytes) | (<new length> bytes) |
1231 | (4 bytes) | (4 bytes) | (4 bytes) | (<new length> bytes) |
1226 | | | | |
1232 | | | | |
1227 +---------------------------------------------------------------+
1233 +---------------------------------------------------------------+
1228
1234
1229 Please note that the length field in the delta data does *not* include
1235 Please note that the length field in the delta data does *not* include
1230 itself.
1236 itself.
1231
1237
1232 In version 1, the delta is always applied against the previous node from
1238 In version 1, the delta is always applied against the previous node from
1233 the changegroup or the first parent if this is the first entry in the
1239 the changegroup or the first parent if this is the first entry in the
1234 changegroup.
1240 changegroup.
1235
1241
1236 In version 2 and up, the delta base node is encoded in the entry in the
1242 In version 2 and up, the delta base node is encoded in the entry in the
1237 changegroup. This allows the delta to be expressed against any parent,
1243 changegroup. This allows the delta to be expressed against any parent,
1238 which can result in smaller deltas and more efficient encoding of data.
1244 which can result in smaller deltas and more efficient encoding of data.
1239
1245
1240 The *flags* field holds bitwise flags affecting the processing of revision
1246 The *flags* field holds bitwise flags affecting the processing of revision
1241 data. The following flags are defined:
1247 data. The following flags are defined:
1242
1248
1243 32768
1249 32768
1244 Censored revision. The revision's fulltext has been replaced by censor
1250 Censored revision. The revision's fulltext has been replaced by censor
1245 metadata. May only occur on file revisions.
1251 metadata. May only occur on file revisions.
1246
1252
1247 16384
1253 16384
1248 Ellipsis revision. Revision hash does not match data (likely due to
1254 Ellipsis revision. Revision hash does not match data (likely due to
1249 rewritten parents).
1255 rewritten parents).
1250
1256
1251 8192
1257 8192
1252 Externally stored. The revision fulltext contains "key:value" "\n"
1258 Externally stored. The revision fulltext contains "key:value" "\n"
1253 delimited metadata defining an object stored elsewhere. Used by the LFS
1259 delimited metadata defining an object stored elsewhere. Used by the LFS
1254 extension.
1260 extension.
1255
1261
1256 For historical reasons, the integer values are identical to revlog version
1262 For historical reasons, the integer values are identical to revlog version
1257 1 per-revision storage flags and correspond to bits being set in this
1263 1 per-revision storage flags and correspond to bits being set in this
1258 2-byte field. Bits were allocated starting from the most-significant bit,
1264 2-byte field. Bits were allocated starting from the most-significant bit,
1259 hence the reverse ordering and allocation of these flags.
1265 hence the reverse ordering and allocation of these flags.
1260
1266
1261 Changeset Segment
1267 Changeset Segment
1262 =================
1268 =================
1263
1269
1264 The *changeset segment* consists of a single *delta group* holding
1270 The *changeset segment* consists of a single *delta group* holding
1265 changelog data. The *empty chunk* at the end of the *delta group* denotes
1271 changelog data. The *empty chunk* at the end of the *delta group* denotes
1266 the boundary to the *manifest segment*.
1272 the boundary to the *manifest segment*.
1267
1273
1268 Manifest Segment
1274 Manifest Segment
1269 ================
1275 ================
1270
1276
1271 The *manifest segment* consists of a single *delta group* holding manifest
1277 The *manifest segment* consists of a single *delta group* holding manifest
1272 data. If treemanifests are in use, it contains only the manifest for the
1278 data. If treemanifests are in use, it contains only the manifest for the
1273 root directory of the repository. Otherwise, it contains the entire
1279 root directory of the repository. Otherwise, it contains the entire
1274 manifest data. The *empty chunk* at the end of the *delta group* denotes
1280 manifest data. The *empty chunk* at the end of the *delta group* denotes
1275 the boundary to the next segment (either the *treemanifests segment* or
1281 the boundary to the next segment (either the *treemanifests segment* or
1276 the *filelogs segment*, depending on version and the request options).
1282 the *filelogs segment*, depending on version and the request options).
1277
1283
1278 Treemanifests Segment
1284 Treemanifests Segment
1279 ---------------------
1285 ---------------------
1280
1286
1281 The *treemanifests segment* only exists in changegroup version "3", and
1287 The *treemanifests segment* only exists in changegroup version "3", and
1282 only if the 'treemanifest' param is part of the bundle2 changegroup part
1288 only if the 'treemanifest' param is part of the bundle2 changegroup part
1283 (it is not possible to use changegroup version 3 outside of bundle2).
1289 (it is not possible to use changegroup version 3 outside of bundle2).
1284 Aside from the filenames in the *treemanifests segment* containing a
1290 Aside from the filenames in the *treemanifests segment* containing a
1285 trailing "/" character, it behaves identically to the *filelogs segment*
1291 trailing "/" character, it behaves identically to the *filelogs segment*
1286 (see below). The final sub-segment is followed by an *empty chunk*
1292 (see below). The final sub-segment is followed by an *empty chunk*
1287 (logically, a sub-segment with filename size 0). This denotes the boundary
1293 (logically, a sub-segment with filename size 0). This denotes the boundary
1288 to the *filelogs segment*.
1294 to the *filelogs segment*.
1289
1295
1290 Filelogs Segment
1296 Filelogs Segment
1291 ================
1297 ================
1292
1298
1293 The *filelogs segment* consists of multiple sub-segments, each
1299 The *filelogs segment* consists of multiple sub-segments, each
1294 corresponding to an individual file whose data is being described:
1300 corresponding to an individual file whose data is being described:
1295
1301
1296 +--------------------------------------------------+
1302 +--------------------------------------------------+
1297 | | | | | |
1303 | | | | | |
1298 | filelog0 | filelog1 | filelog2 | ... | 0x0 |
1304 | filelog0 | filelog1 | filelog2 | ... | 0x0 |
1299 | | | | | (4 bytes) |
1305 | | | | | (4 bytes) |
1300 | | | | | |
1306 | | | | | |
1301 +--------------------------------------------------+
1307 +--------------------------------------------------+
1302
1308
1303 The final filelog sub-segment is followed by an *empty chunk* (logically,
1309 The final filelog sub-segment is followed by an *empty chunk* (logically,
1304 a sub-segment with filename size 0). This denotes the end of the segment
1310 a sub-segment with filename size 0). This denotes the end of the segment
1305 and of the overall changegroup.
1311 and of the overall changegroup.
1306
1312
1307 Each filelog sub-segment consists of the following:
1313 Each filelog sub-segment consists of the following:
1308
1314
1309 +------------------------------------------------------+
1315 +------------------------------------------------------+
1310 | | | |
1316 | | | |
1311 | filename length | filename | delta group |
1317 | filename length | filename | delta group |
1312 | (4 bytes) | (<length - 4> bytes) | (various) |
1318 | (4 bytes) | (<length - 4> bytes) | (various) |
1313 | | | |
1319 | | | |
1314 +------------------------------------------------------+
1320 +------------------------------------------------------+
1315
1321
1316 That is, a *chunk* consisting of the filename (not terminated or padded)
1322 That is, a *chunk* consisting of the filename (not terminated or padded)
1317 followed by N chunks constituting the *delta group* for this file. The
1323 followed by N chunks constituting the *delta group* for this file. The
1318 *empty chunk* at the end of each *delta group* denotes the boundary to the
1324 *empty chunk* at the end of each *delta group* denotes the boundary to the
1319 next filelog sub-segment.
1325 next filelog sub-segment.
1320
1326
1321 non-existent subtopics print an error
1327 non-existent subtopics print an error
1322
1328
1323 $ hg help internals.foo
1329 $ hg help internals.foo
1324 abort: no such help topic: internals.foo
1330 abort: no such help topic: internals.foo
1325 (try 'hg help --keyword foo')
1331 (try 'hg help --keyword foo')
1326 [255]
1332 [255]
1327
1333
1328 test advanced, deprecated and experimental options are hidden in command help
1334 test advanced, deprecated and experimental options are hidden in command help
1329 $ hg help debugoptADV
1335 $ hg help debugoptADV
1330 hg debugoptADV
1336 hg debugoptADV
1331
1337
1332 (no help text available)
1338 (no help text available)
1333
1339
1334 options:
1340 options:
1335
1341
1336 (some details hidden, use --verbose to show complete help)
1342 (some details hidden, use --verbose to show complete help)
1337 $ hg help debugoptDEP
1343 $ hg help debugoptDEP
1338 hg debugoptDEP
1344 hg debugoptDEP
1339
1345
1340 (no help text available)
1346 (no help text available)
1341
1347
1342 options:
1348 options:
1343
1349
1344 (some details hidden, use --verbose to show complete help)
1350 (some details hidden, use --verbose to show complete help)
1345
1351
1346 $ hg help debugoptEXP
1352 $ hg help debugoptEXP
1347 hg debugoptEXP
1353 hg debugoptEXP
1348
1354
1349 (no help text available)
1355 (no help text available)
1350
1356
1351 options:
1357 options:
1352
1358
1353 (some details hidden, use --verbose to show complete help)
1359 (some details hidden, use --verbose to show complete help)
1354
1360
1355 test advanced, deprecated and experimental options are shown with -v
1361 test advanced, deprecated and experimental options are shown with -v
1356 $ hg help -v debugoptADV | grep aopt
1362 $ hg help -v debugoptADV | grep aopt
1357 --aopt option is (ADVANCED)
1363 --aopt option is (ADVANCED)
1358 $ hg help -v debugoptDEP | grep dopt
1364 $ hg help -v debugoptDEP | grep dopt
1359 --dopt option is (DEPRECATED)
1365 --dopt option is (DEPRECATED)
1360 $ hg help -v debugoptEXP | grep eopt
1366 $ hg help -v debugoptEXP | grep eopt
1361 --eopt option is (EXPERIMENTAL)
1367 --eopt option is (EXPERIMENTAL)
1362
1368
1363 #if gettext
1369 #if gettext
1364 test deprecated option is hidden with translation with untranslated description
1370 test deprecated option is hidden with translation with untranslated description
1365 (use many globy for not failing on changed transaction)
1371 (use many globy for not failing on changed transaction)
1366 $ LANGUAGE=sv hg help debugoptDEP
1372 $ LANGUAGE=sv hg help debugoptDEP
1367 hg debugoptDEP
1373 hg debugoptDEP
1368
1374
1369 (*) (glob)
1375 (*) (glob)
1370
1376
1371 options:
1377 options:
1372
1378
1373 (some details hidden, use --verbose to show complete help)
1379 (some details hidden, use --verbose to show complete help)
1374 #endif
1380 #endif
1375
1381
1376 Test commands that collide with topics (issue4240)
1382 Test commands that collide with topics (issue4240)
1377
1383
1378 $ hg config -hq
1384 $ hg config -hq
1379 hg config [-u] [NAME]...
1385 hg config [-u] [NAME]...
1380
1386
1381 show combined config settings from all hgrc files
1387 show combined config settings from all hgrc files
1382 $ hg showconfig -hq
1388 $ hg showconfig -hq
1383 hg config [-u] [NAME]...
1389 hg config [-u] [NAME]...
1384
1390
1385 show combined config settings from all hgrc files
1391 show combined config settings from all hgrc files
1386
1392
1387 Test a help topic
1393 Test a help topic
1388
1394
1389 $ hg help dates
1395 $ hg help dates
1390 Date Formats
1396 Date Formats
1391 """"""""""""
1397 """"""""""""
1392
1398
1393 Some commands allow the user to specify a date, e.g.:
1399 Some commands allow the user to specify a date, e.g.:
1394
1400
1395 - backout, commit, import, tag: Specify the commit date.
1401 - backout, commit, import, tag: Specify the commit date.
1396 - log, revert, update: Select revision(s) by date.
1402 - log, revert, update: Select revision(s) by date.
1397
1403
1398 Many date formats are valid. Here are some examples:
1404 Many date formats are valid. Here are some examples:
1399
1405
1400 - "Wed Dec 6 13:18:29 2006" (local timezone assumed)
1406 - "Wed Dec 6 13:18:29 2006" (local timezone assumed)
1401 - "Dec 6 13:18 -0600" (year assumed, time offset provided)
1407 - "Dec 6 13:18 -0600" (year assumed, time offset provided)
1402 - "Dec 6 13:18 UTC" (UTC and GMT are aliases for +0000)
1408 - "Dec 6 13:18 UTC" (UTC and GMT are aliases for +0000)
1403 - "Dec 6" (midnight)
1409 - "Dec 6" (midnight)
1404 - "13:18" (today assumed)
1410 - "13:18" (today assumed)
1405 - "3:39" (3:39AM assumed)
1411 - "3:39" (3:39AM assumed)
1406 - "3:39pm" (15:39)
1412 - "3:39pm" (15:39)
1407 - "2006-12-06 13:18:29" (ISO 8601 format)
1413 - "2006-12-06 13:18:29" (ISO 8601 format)
1408 - "2006-12-6 13:18"
1414 - "2006-12-6 13:18"
1409 - "2006-12-6"
1415 - "2006-12-6"
1410 - "12-6"
1416 - "12-6"
1411 - "12/6"
1417 - "12/6"
1412 - "12/6/6" (Dec 6 2006)
1418 - "12/6/6" (Dec 6 2006)
1413 - "today" (midnight)
1419 - "today" (midnight)
1414 - "yesterday" (midnight)
1420 - "yesterday" (midnight)
1415 - "now" - right now
1421 - "now" - right now
1416
1422
1417 Lastly, there is Mercurial's internal format:
1423 Lastly, there is Mercurial's internal format:
1418
1424
1419 - "1165411109 0" (Wed Dec 6 13:18:29 2006 UTC)
1425 - "1165411109 0" (Wed Dec 6 13:18:29 2006 UTC)
1420
1426
1421 This is the internal representation format for dates. The first number is
1427 This is the internal representation format for dates. The first number is
1422 the number of seconds since the epoch (1970-01-01 00:00 UTC). The second
1428 the number of seconds since the epoch (1970-01-01 00:00 UTC). The second
1423 is the offset of the local timezone, in seconds west of UTC (negative if
1429 is the offset of the local timezone, in seconds west of UTC (negative if
1424 the timezone is east of UTC).
1430 the timezone is east of UTC).
1425
1431
1426 The log command also accepts date ranges:
1432 The log command also accepts date ranges:
1427
1433
1428 - "<DATE" - at or before a given date/time
1434 - "<DATE" - at or before a given date/time
1429 - ">DATE" - on or after a given date/time
1435 - ">DATE" - on or after a given date/time
1430 - "DATE to DATE" - a date range, inclusive
1436 - "DATE to DATE" - a date range, inclusive
1431 - "-DAYS" - within a given number of days of today
1437 - "-DAYS" - within a given number of days of today
1432
1438
1433 Test repeated config section name
1439 Test repeated config section name
1434
1440
1435 $ hg help config.host
1441 $ hg help config.host
1436 "http_proxy.host"
1442 "http_proxy.host"
1437 Host name and (optional) port of the proxy server, for example
1443 Host name and (optional) port of the proxy server, for example
1438 "myproxy:8000".
1444 "myproxy:8000".
1439
1445
1440 "smtp.host"
1446 "smtp.host"
1441 Host name of mail server, e.g. "mail.example.com".
1447 Host name of mail server, e.g. "mail.example.com".
1442
1448
1443
1449
1444 Test section name with dot
1450 Test section name with dot
1445
1451
1446 $ hg help config.ui.username
1452 $ hg help config.ui.username
1447 "ui.username"
1453 "ui.username"
1448 The committer of a changeset created when running "commit". Typically
1454 The committer of a changeset created when running "commit". Typically
1449 a person's name and email address, e.g. "Fred Widget
1455 a person's name and email address, e.g. "Fred Widget
1450 <fred@example.com>". Environment variables in the username are
1456 <fred@example.com>". Environment variables in the username are
1451 expanded.
1457 expanded.
1452
1458
1453 (default: "$EMAIL" or "username@hostname". If the username in hgrc is
1459 (default: "$EMAIL" or "username@hostname". If the username in hgrc is
1454 empty, e.g. if the system admin set "username =" in the system hgrc,
1460 empty, e.g. if the system admin set "username =" in the system hgrc,
1455 it has to be specified manually or in a different hgrc file)
1461 it has to be specified manually or in a different hgrc file)
1456
1462
1457
1463
1458 $ hg help config.annotate.git
1464 $ hg help config.annotate.git
1459 abort: help section not found: config.annotate.git
1465 abort: help section not found: config.annotate.git
1460 [255]
1466 [255]
1461
1467
1462 $ hg help config.update.check
1468 $ hg help config.update.check
1463 "commands.update.check"
1469 "commands.update.check"
1464 Determines what level of checking 'hg update' will perform before
1470 Determines what level of checking 'hg update' will perform before
1465 moving to a destination revision. Valid values are "abort", "none",
1471 moving to a destination revision. Valid values are "abort", "none",
1466 "linear", and "noconflict". "abort" always fails if the working
1472 "linear", and "noconflict". "abort" always fails if the working
1467 directory has uncommitted changes. "none" performs no checking, and
1473 directory has uncommitted changes. "none" performs no checking, and
1468 may result in a merge with uncommitted changes. "linear" allows any
1474 may result in a merge with uncommitted changes. "linear" allows any
1469 update as long as it follows a straight line in the revision history,
1475 update as long as it follows a straight line in the revision history,
1470 and may trigger a merge with uncommitted changes. "noconflict" will
1476 and may trigger a merge with uncommitted changes. "noconflict" will
1471 allow any update which would not trigger a merge with uncommitted
1477 allow any update which would not trigger a merge with uncommitted
1472 changes, if any are present. (default: "linear")
1478 changes, if any are present. (default: "linear")
1473
1479
1474
1480
1475 $ hg help config.commands.update.check
1481 $ hg help config.commands.update.check
1476 "commands.update.check"
1482 "commands.update.check"
1477 Determines what level of checking 'hg update' will perform before
1483 Determines what level of checking 'hg update' will perform before
1478 moving to a destination revision. Valid values are "abort", "none",
1484 moving to a destination revision. Valid values are "abort", "none",
1479 "linear", and "noconflict". "abort" always fails if the working
1485 "linear", and "noconflict". "abort" always fails if the working
1480 directory has uncommitted changes. "none" performs no checking, and
1486 directory has uncommitted changes. "none" performs no checking, and
1481 may result in a merge with uncommitted changes. "linear" allows any
1487 may result in a merge with uncommitted changes. "linear" allows any
1482 update as long as it follows a straight line in the revision history,
1488 update as long as it follows a straight line in the revision history,
1483 and may trigger a merge with uncommitted changes. "noconflict" will
1489 and may trigger a merge with uncommitted changes. "noconflict" will
1484 allow any update which would not trigger a merge with uncommitted
1490 allow any update which would not trigger a merge with uncommitted
1485 changes, if any are present. (default: "linear")
1491 changes, if any are present. (default: "linear")
1486
1492
1487
1493
1488 $ hg help config.ommands.update.check
1494 $ hg help config.ommands.update.check
1489 abort: help section not found: config.ommands.update.check
1495 abort: help section not found: config.ommands.update.check
1490 [255]
1496 [255]
1491
1497
1492 Unrelated trailing paragraphs shouldn't be included
1498 Unrelated trailing paragraphs shouldn't be included
1493
1499
1494 $ hg help config.extramsg | grep '^$'
1500 $ hg help config.extramsg | grep '^$'
1495
1501
1496
1502
1497 Test capitalized section name
1503 Test capitalized section name
1498
1504
1499 $ hg help scripting.HGPLAIN > /dev/null
1505 $ hg help scripting.HGPLAIN > /dev/null
1500
1506
1501 Help subsection:
1507 Help subsection:
1502
1508
1503 $ hg help config.charsets |grep "Email example:" > /dev/null
1509 $ hg help config.charsets |grep "Email example:" > /dev/null
1504 [1]
1510 [1]
1505
1511
1506 Show nested definitions
1512 Show nested definitions
1507 ("profiling.type"[break]"ls"[break]"stat"[break])
1513 ("profiling.type"[break]"ls"[break]"stat"[break])
1508
1514
1509 $ hg help config.type | egrep '^$'|wc -l
1515 $ hg help config.type | egrep '^$'|wc -l
1510 \s*3 (re)
1516 \s*3 (re)
1511
1517
1512 $ hg help config.profiling.type.ls
1518 $ hg help config.profiling.type.ls
1513 "profiling.type.ls"
1519 "profiling.type.ls"
1514 Use Python's built-in instrumenting profiler. This profiler works on
1520 Use Python's built-in instrumenting profiler. This profiler works on
1515 all platforms, but each line number it reports is the first line of
1521 all platforms, but each line number it reports is the first line of
1516 a function. This restriction makes it difficult to identify the
1522 a function. This restriction makes it difficult to identify the
1517 expensive parts of a non-trivial function.
1523 expensive parts of a non-trivial function.
1518
1524
1519
1525
1520 Separate sections from subsections
1526 Separate sections from subsections
1521
1527
1522 $ hg help config.format | egrep '^ ("|-)|^\s*$' | uniq
1528 $ hg help config.format | egrep '^ ("|-)|^\s*$' | uniq
1523 "format"
1529 "format"
1524 --------
1530 --------
1525
1531
1526 "usegeneraldelta"
1532 "usegeneraldelta"
1527
1533
1528 "dotencode"
1534 "dotencode"
1529
1535
1530 "usefncache"
1536 "usefncache"
1531
1537
1532 "usestore"
1538 "usestore"
1533
1539
1534 "sparse-revlog"
1540 "sparse-revlog"
1535
1541
1536 "revlog-compression"
1542 "revlog-compression"
1537
1543
1538 "bookmarks-in-store"
1544 "bookmarks-in-store"
1539
1545
1540 "profiling"
1546 "profiling"
1541 -----------
1547 -----------
1542
1548
1543 "format"
1549 "format"
1544
1550
1545 "progress"
1551 "progress"
1546 ----------
1552 ----------
1547
1553
1548 "format"
1554 "format"
1549
1555
1550
1556
1551 Last item in help config.*:
1557 Last item in help config.*:
1552
1558
1553 $ hg help config.`hg help config|grep '^ "'| \
1559 $ hg help config.`hg help config|grep '^ "'| \
1554 > tail -1|sed 's![ "]*!!g'`| \
1560 > tail -1|sed 's![ "]*!!g'`| \
1555 > grep 'hg help -c config' > /dev/null
1561 > grep 'hg help -c config' > /dev/null
1556 [1]
1562 [1]
1557
1563
1558 note to use help -c for general hg help config:
1564 note to use help -c for general hg help config:
1559
1565
1560 $ hg help config |grep 'hg help -c config' > /dev/null
1566 $ hg help config |grep 'hg help -c config' > /dev/null
1561
1567
1562 Test templating help
1568 Test templating help
1563
1569
1564 $ hg help templating | egrep '(desc|diffstat|firstline|nonempty) '
1570 $ hg help templating | egrep '(desc|diffstat|firstline|nonempty) '
1565 desc String. The text of the changeset description.
1571 desc String. The text of the changeset description.
1566 diffstat String. Statistics of changes with the following format:
1572 diffstat String. Statistics of changes with the following format:
1567 firstline Any text. Returns the first line of text.
1573 firstline Any text. Returns the first line of text.
1568 nonempty Any text. Returns '(none)' if the string is empty.
1574 nonempty Any text. Returns '(none)' if the string is empty.
1569
1575
1570 Test deprecated items
1576 Test deprecated items
1571
1577
1572 $ hg help -v templating | grep currentbookmark
1578 $ hg help -v templating | grep currentbookmark
1573 currentbookmark
1579 currentbookmark
1574 $ hg help templating | (grep currentbookmark || true)
1580 $ hg help templating | (grep currentbookmark || true)
1575
1581
1576 Test help hooks
1582 Test help hooks
1577
1583
1578 $ cat > helphook1.py <<EOF
1584 $ cat > helphook1.py <<EOF
1579 > from mercurial import help
1585 > from mercurial import help
1580 >
1586 >
1581 > def rewrite(ui, topic, doc):
1587 > def rewrite(ui, topic, doc):
1582 > return doc + b'\nhelphook1\n'
1588 > return doc + b'\nhelphook1\n'
1583 >
1589 >
1584 > def extsetup(ui):
1590 > def extsetup(ui):
1585 > help.addtopichook(b'revisions', rewrite)
1591 > help.addtopichook(b'revisions', rewrite)
1586 > EOF
1592 > EOF
1587 $ cat > helphook2.py <<EOF
1593 $ cat > helphook2.py <<EOF
1588 > from mercurial import help
1594 > from mercurial import help
1589 >
1595 >
1590 > def rewrite(ui, topic, doc):
1596 > def rewrite(ui, topic, doc):
1591 > return doc + b'\nhelphook2\n'
1597 > return doc + b'\nhelphook2\n'
1592 >
1598 >
1593 > def extsetup(ui):
1599 > def extsetup(ui):
1594 > help.addtopichook(b'revisions', rewrite)
1600 > help.addtopichook(b'revisions', rewrite)
1595 > EOF
1601 > EOF
1596 $ echo '[extensions]' >> $HGRCPATH
1602 $ echo '[extensions]' >> $HGRCPATH
1597 $ echo "helphook1 = `pwd`/helphook1.py" >> $HGRCPATH
1603 $ echo "helphook1 = `pwd`/helphook1.py" >> $HGRCPATH
1598 $ echo "helphook2 = `pwd`/helphook2.py" >> $HGRCPATH
1604 $ echo "helphook2 = `pwd`/helphook2.py" >> $HGRCPATH
1599 $ hg help revsets | grep helphook
1605 $ hg help revsets | grep helphook
1600 helphook1
1606 helphook1
1601 helphook2
1607 helphook2
1602
1608
1603 help -c should only show debug --debug
1609 help -c should only show debug --debug
1604
1610
1605 $ hg help -c --debug|egrep debug|wc -l|egrep '^\s*0\s*$'
1611 $ hg help -c --debug|egrep debug|wc -l|egrep '^\s*0\s*$'
1606 [1]
1612 [1]
1607
1613
1608 help -c should only show deprecated for -v
1614 help -c should only show deprecated for -v
1609
1615
1610 $ hg help -c -v|egrep DEPRECATED|wc -l|egrep '^\s*0\s*$'
1616 $ hg help -c -v|egrep DEPRECATED|wc -l|egrep '^\s*0\s*$'
1611 [1]
1617 [1]
1612
1618
1613 Test -s / --system
1619 Test -s / --system
1614
1620
1615 $ hg help config.files -s windows |grep 'etc/mercurial' | \
1621 $ hg help config.files -s windows |grep 'etc/mercurial' | \
1616 > wc -l | sed -e 's/ //g'
1622 > wc -l | sed -e 's/ //g'
1617 0
1623 0
1618 $ hg help config.files --system unix | grep 'USER' | \
1624 $ hg help config.files --system unix | grep 'USER' | \
1619 > wc -l | sed -e 's/ //g'
1625 > wc -l | sed -e 's/ //g'
1620 0
1626 0
1621
1627
1622 Test -e / -c / -k combinations
1628 Test -e / -c / -k combinations
1623
1629
1624 $ hg help -c|egrep '^[A-Z].*:|^ debug'
1630 $ hg help -c|egrep '^[A-Z].*:|^ debug'
1625 Commands:
1631 Commands:
1626 $ hg help -e|egrep '^[A-Z].*:|^ debug'
1632 $ hg help -e|egrep '^[A-Z].*:|^ debug'
1627 Extensions:
1633 Extensions:
1628 $ hg help -k|egrep '^[A-Z].*:|^ debug'
1634 $ hg help -k|egrep '^[A-Z].*:|^ debug'
1629 Topics:
1635 Topics:
1630 Commands:
1636 Commands:
1631 Extensions:
1637 Extensions:
1632 Extension Commands:
1638 Extension Commands:
1633 $ hg help -c schemes
1639 $ hg help -c schemes
1634 abort: no such help topic: schemes
1640 abort: no such help topic: schemes
1635 (try 'hg help --keyword schemes')
1641 (try 'hg help --keyword schemes')
1636 [255]
1642 [255]
1637 $ hg help -e schemes |head -1
1643 $ hg help -e schemes |head -1
1638 schemes extension - extend schemes with shortcuts to repository swarms
1644 schemes extension - extend schemes with shortcuts to repository swarms
1639 $ hg help -c -k dates |egrep '^(Topics|Extensions|Commands):'
1645 $ hg help -c -k dates |egrep '^(Topics|Extensions|Commands):'
1640 Commands:
1646 Commands:
1641 $ hg help -e -k a |egrep '^(Topics|Extensions|Commands):'
1647 $ hg help -e -k a |egrep '^(Topics|Extensions|Commands):'
1642 Extensions:
1648 Extensions:
1643 $ hg help -e -c -k date |egrep '^(Topics|Extensions|Commands):'
1649 $ hg help -e -c -k date |egrep '^(Topics|Extensions|Commands):'
1644 Extensions:
1650 Extensions:
1645 Commands:
1651 Commands:
1646 $ hg help -c commit > /dev/null
1652 $ hg help -c commit > /dev/null
1647 $ hg help -e -c commit > /dev/null
1653 $ hg help -e -c commit > /dev/null
1648 $ hg help -e commit
1654 $ hg help -e commit
1649 abort: no such help topic: commit
1655 abort: no such help topic: commit
1650 (try 'hg help --keyword commit')
1656 (try 'hg help --keyword commit')
1651 [255]
1657 [255]
1652
1658
1653 Test keyword search help
1659 Test keyword search help
1654
1660
1655 $ cat > prefixedname.py <<EOF
1661 $ cat > prefixedname.py <<EOF
1656 > '''matched against word "clone"
1662 > '''matched against word "clone"
1657 > '''
1663 > '''
1658 > EOF
1664 > EOF
1659 $ echo '[extensions]' >> $HGRCPATH
1665 $ echo '[extensions]' >> $HGRCPATH
1660 $ echo "dot.dot.prefixedname = `pwd`/prefixedname.py" >> $HGRCPATH
1666 $ echo "dot.dot.prefixedname = `pwd`/prefixedname.py" >> $HGRCPATH
1661 $ hg help -k clone
1667 $ hg help -k clone
1662 Topics:
1668 Topics:
1663
1669
1664 config Configuration Files
1670 config Configuration Files
1665 extensions Using Additional Features
1671 extensions Using Additional Features
1666 glossary Glossary
1672 glossary Glossary
1667 phases Working with Phases
1673 phases Working with Phases
1668 subrepos Subrepositories
1674 subrepos Subrepositories
1669 urls URL Paths
1675 urls URL Paths
1670
1676
1671 Commands:
1677 Commands:
1672
1678
1673 bookmarks create a new bookmark or list existing bookmarks
1679 bookmarks create a new bookmark or list existing bookmarks
1674 clone make a copy of an existing repository
1680 clone make a copy of an existing repository
1675 paths show aliases for remote repositories
1681 paths show aliases for remote repositories
1676 pull pull changes from the specified source
1682 pull pull changes from the specified source
1677 update update working directory (or switch revisions)
1683 update update working directory (or switch revisions)
1678
1684
1679 Extensions:
1685 Extensions:
1680
1686
1681 clonebundles advertise pre-generated bundles to seed clones
1687 clonebundles advertise pre-generated bundles to seed clones
1682 narrow create clones which fetch history data for subset of files
1688 narrow create clones which fetch history data for subset of files
1683 (EXPERIMENTAL)
1689 (EXPERIMENTAL)
1684 prefixedname matched against word "clone"
1690 prefixedname matched against word "clone"
1685 relink recreates hardlinks between repository clones
1691 relink recreates hardlinks between repository clones
1686
1692
1687 Extension Commands:
1693 Extension Commands:
1688
1694
1689 qclone clone main and patch repository at same time
1695 qclone clone main and patch repository at same time
1690
1696
1691 Test unfound topic
1697 Test unfound topic
1692
1698
1693 $ hg help nonexistingtopicthatwillneverexisteverever
1699 $ hg help nonexistingtopicthatwillneverexisteverever
1694 abort: no such help topic: nonexistingtopicthatwillneverexisteverever
1700 abort: no such help topic: nonexistingtopicthatwillneverexisteverever
1695 (try 'hg help --keyword nonexistingtopicthatwillneverexisteverever')
1701 (try 'hg help --keyword nonexistingtopicthatwillneverexisteverever')
1696 [255]
1702 [255]
1697
1703
1698 Test unfound keyword
1704 Test unfound keyword
1699
1705
1700 $ hg help --keyword nonexistingwordthatwillneverexisteverever
1706 $ hg help --keyword nonexistingwordthatwillneverexisteverever
1701 abort: no matches
1707 abort: no matches
1702 (try 'hg help' for a list of topics)
1708 (try 'hg help' for a list of topics)
1703 [255]
1709 [255]
1704
1710
1705 Test omit indicating for help
1711 Test omit indicating for help
1706
1712
1707 $ cat > addverboseitems.py <<EOF
1713 $ cat > addverboseitems.py <<EOF
1708 > r'''extension to test omit indicating.
1714 > r'''extension to test omit indicating.
1709 >
1715 >
1710 > This paragraph is never omitted (for extension)
1716 > This paragraph is never omitted (for extension)
1711 >
1717 >
1712 > .. container:: verbose
1718 > .. container:: verbose
1713 >
1719 >
1714 > This paragraph is omitted,
1720 > This paragraph is omitted,
1715 > if :hg:\`help\` is invoked without \`\`-v\`\` (for extension)
1721 > if :hg:\`help\` is invoked without \`\`-v\`\` (for extension)
1716 >
1722 >
1717 > This paragraph is never omitted, too (for extension)
1723 > This paragraph is never omitted, too (for extension)
1718 > '''
1724 > '''
1719 > from __future__ import absolute_import
1725 > from __future__ import absolute_import
1720 > from mercurial import commands, help
1726 > from mercurial import commands, help
1721 > testtopic = br"""This paragraph is never omitted (for topic).
1727 > testtopic = br"""This paragraph is never omitted (for topic).
1722 >
1728 >
1723 > .. container:: verbose
1729 > .. container:: verbose
1724 >
1730 >
1725 > This paragraph is omitted,
1731 > This paragraph is omitted,
1726 > if :hg:\`help\` is invoked without \`\`-v\`\` (for topic)
1732 > if :hg:\`help\` is invoked without \`\`-v\`\` (for topic)
1727 >
1733 >
1728 > This paragraph is never omitted, too (for topic)
1734 > This paragraph is never omitted, too (for topic)
1729 > """
1735 > """
1730 > def extsetup(ui):
1736 > def extsetup(ui):
1731 > help.helptable.append(([b"topic-containing-verbose"],
1737 > help.helptable.append(([b"topic-containing-verbose"],
1732 > b"This is the topic to test omit indicating.",
1738 > b"This is the topic to test omit indicating.",
1733 > lambda ui: testtopic))
1739 > lambda ui: testtopic))
1734 > EOF
1740 > EOF
1735 $ echo '[extensions]' >> $HGRCPATH
1741 $ echo '[extensions]' >> $HGRCPATH
1736 $ echo "addverboseitems = `pwd`/addverboseitems.py" >> $HGRCPATH
1742 $ echo "addverboseitems = `pwd`/addverboseitems.py" >> $HGRCPATH
1737 $ hg help addverboseitems
1743 $ hg help addverboseitems
1738 addverboseitems extension - extension to test omit indicating.
1744 addverboseitems extension - extension to test omit indicating.
1739
1745
1740 This paragraph is never omitted (for extension)
1746 This paragraph is never omitted (for extension)
1741
1747
1742 This paragraph is never omitted, too (for extension)
1748 This paragraph is never omitted, too (for extension)
1743
1749
1744 (some details hidden, use --verbose to show complete help)
1750 (some details hidden, use --verbose to show complete help)
1745
1751
1746 no commands defined
1752 no commands defined
1747 $ hg help -v addverboseitems
1753 $ hg help -v addverboseitems
1748 addverboseitems extension - extension to test omit indicating.
1754 addverboseitems extension - extension to test omit indicating.
1749
1755
1750 This paragraph is never omitted (for extension)
1756 This paragraph is never omitted (for extension)
1751
1757
1752 This paragraph is omitted, if 'hg help' is invoked without "-v" (for
1758 This paragraph is omitted, if 'hg help' is invoked without "-v" (for
1753 extension)
1759 extension)
1754
1760
1755 This paragraph is never omitted, too (for extension)
1761 This paragraph is never omitted, too (for extension)
1756
1762
1757 no commands defined
1763 no commands defined
1758 $ hg help topic-containing-verbose
1764 $ hg help topic-containing-verbose
1759 This is the topic to test omit indicating.
1765 This is the topic to test omit indicating.
1760 """"""""""""""""""""""""""""""""""""""""""
1766 """"""""""""""""""""""""""""""""""""""""""
1761
1767
1762 This paragraph is never omitted (for topic).
1768 This paragraph is never omitted (for topic).
1763
1769
1764 This paragraph is never omitted, too (for topic)
1770 This paragraph is never omitted, too (for topic)
1765
1771
1766 (some details hidden, use --verbose to show complete help)
1772 (some details hidden, use --verbose to show complete help)
1767 $ hg help -v topic-containing-verbose
1773 $ hg help -v topic-containing-verbose
1768 This is the topic to test omit indicating.
1774 This is the topic to test omit indicating.
1769 """"""""""""""""""""""""""""""""""""""""""
1775 """"""""""""""""""""""""""""""""""""""""""
1770
1776
1771 This paragraph is never omitted (for topic).
1777 This paragraph is never omitted (for topic).
1772
1778
1773 This paragraph is omitted, if 'hg help' is invoked without "-v" (for
1779 This paragraph is omitted, if 'hg help' is invoked without "-v" (for
1774 topic)
1780 topic)
1775
1781
1776 This paragraph is never omitted, too (for topic)
1782 This paragraph is never omitted, too (for topic)
1777
1783
1778 Test section lookup
1784 Test section lookup
1779
1785
1780 $ hg help revset.merge
1786 $ hg help revset.merge
1781 "merge()"
1787 "merge()"
1782 Changeset is a merge changeset.
1788 Changeset is a merge changeset.
1783
1789
1784 $ hg help glossary.dag
1790 $ hg help glossary.dag
1785 DAG
1791 DAG
1786 The repository of changesets of a distributed version control system
1792 The repository of changesets of a distributed version control system
1787 (DVCS) can be described as a directed acyclic graph (DAG), consisting
1793 (DVCS) can be described as a directed acyclic graph (DAG), consisting
1788 of nodes and edges, where nodes correspond to changesets and edges
1794 of nodes and edges, where nodes correspond to changesets and edges
1789 imply a parent -> child relation. This graph can be visualized by
1795 imply a parent -> child relation. This graph can be visualized by
1790 graphical tools such as 'hg log --graph'. In Mercurial, the DAG is
1796 graphical tools such as 'hg log --graph'. In Mercurial, the DAG is
1791 limited by the requirement for children to have at most two parents.
1797 limited by the requirement for children to have at most two parents.
1792
1798
1793
1799
1794 $ hg help hgrc.paths
1800 $ hg help hgrc.paths
1795 "paths"
1801 "paths"
1796 -------
1802 -------
1797
1803
1798 Assigns symbolic names and behavior to repositories.
1804 Assigns symbolic names and behavior to repositories.
1799
1805
1800 Options are symbolic names defining the URL or directory that is the
1806 Options are symbolic names defining the URL or directory that is the
1801 location of the repository. Example:
1807 location of the repository. Example:
1802
1808
1803 [paths]
1809 [paths]
1804 my_server = https://example.com/my_repo
1810 my_server = https://example.com/my_repo
1805 local_path = /home/me/repo
1811 local_path = /home/me/repo
1806
1812
1807 These symbolic names can be used from the command line. To pull from
1813 These symbolic names can be used from the command line. To pull from
1808 "my_server": 'hg pull my_server'. To push to "local_path": 'hg push
1814 "my_server": 'hg pull my_server'. To push to "local_path": 'hg push
1809 local_path'.
1815 local_path'.
1810
1816
1811 Options containing colons (":") denote sub-options that can influence
1817 Options containing colons (":") denote sub-options that can influence
1812 behavior for that specific path. Example:
1818 behavior for that specific path. Example:
1813
1819
1814 [paths]
1820 [paths]
1815 my_server = https://example.com/my_path
1821 my_server = https://example.com/my_path
1816 my_server:pushurl = ssh://example.com/my_path
1822 my_server:pushurl = ssh://example.com/my_path
1817
1823
1818 The following sub-options can be defined:
1824 The following sub-options can be defined:
1819
1825
1820 "pushurl"
1826 "pushurl"
1821 The URL to use for push operations. If not defined, the location
1827 The URL to use for push operations. If not defined, the location
1822 defined by the path's main entry is used.
1828 defined by the path's main entry is used.
1823
1829
1824 "pushrev"
1830 "pushrev"
1825 A revset defining which revisions to push by default.
1831 A revset defining which revisions to push by default.
1826
1832
1827 When 'hg push' is executed without a "-r" argument, the revset defined
1833 When 'hg push' is executed without a "-r" argument, the revset defined
1828 by this sub-option is evaluated to determine what to push.
1834 by this sub-option is evaluated to determine what to push.
1829
1835
1830 For example, a value of "." will push the working directory's revision
1836 For example, a value of "." will push the working directory's revision
1831 by default.
1837 by default.
1832
1838
1833 Revsets specifying bookmarks will not result in the bookmark being
1839 Revsets specifying bookmarks will not result in the bookmark being
1834 pushed.
1840 pushed.
1835
1841
1836 The following special named paths exist:
1842 The following special named paths exist:
1837
1843
1838 "default"
1844 "default"
1839 The URL or directory to use when no source or remote is specified.
1845 The URL or directory to use when no source or remote is specified.
1840
1846
1841 'hg clone' will automatically define this path to the location the
1847 'hg clone' will automatically define this path to the location the
1842 repository was cloned from.
1848 repository was cloned from.
1843
1849
1844 "default-push"
1850 "default-push"
1845 (deprecated) The URL or directory for the default 'hg push' location.
1851 (deprecated) The URL or directory for the default 'hg push' location.
1846 "default:pushurl" should be used instead.
1852 "default:pushurl" should be used instead.
1847
1853
1848 $ hg help glossary.mcguffin
1854 $ hg help glossary.mcguffin
1849 abort: help section not found: glossary.mcguffin
1855 abort: help section not found: glossary.mcguffin
1850 [255]
1856 [255]
1851
1857
1852 $ hg help glossary.mc.guffin
1858 $ hg help glossary.mc.guffin
1853 abort: help section not found: glossary.mc.guffin
1859 abort: help section not found: glossary.mc.guffin
1854 [255]
1860 [255]
1855
1861
1856 $ hg help template.files
1862 $ hg help template.files
1857 files List of strings. All files modified, added, or removed by
1863 files List of strings. All files modified, added, or removed by
1858 this changeset.
1864 this changeset.
1859 files(pattern)
1865 files(pattern)
1860 All files of the current changeset matching the pattern. See
1866 All files of the current changeset matching the pattern. See
1861 'hg help patterns'.
1867 'hg help patterns'.
1862
1868
1863 Test section lookup by translated message
1869 Test section lookup by translated message
1864
1870
1865 str.lower() instead of encoding.lower(str) on translated message might
1871 str.lower() instead of encoding.lower(str) on translated message might
1866 make message meaningless, because some encoding uses 0x41(A) - 0x5a(Z)
1872 make message meaningless, because some encoding uses 0x41(A) - 0x5a(Z)
1867 as the second or later byte of multi-byte character.
1873 as the second or later byte of multi-byte character.
1868
1874
1869 For example, "\x8bL\x98^" (translation of "record" in ja_JP.cp932)
1875 For example, "\x8bL\x98^" (translation of "record" in ja_JP.cp932)
1870 contains 0x4c (L). str.lower() replaces 0x4c(L) by 0x6c(l) and this
1876 contains 0x4c (L). str.lower() replaces 0x4c(L) by 0x6c(l) and this
1871 replacement makes message meaningless.
1877 replacement makes message meaningless.
1872
1878
1873 This tests that section lookup by translated string isn't broken by
1879 This tests that section lookup by translated string isn't broken by
1874 such str.lower().
1880 such str.lower().
1875
1881
1876 $ "$PYTHON" <<EOF
1882 $ "$PYTHON" <<EOF
1877 > def escape(s):
1883 > def escape(s):
1878 > return b''.join(b'\\u%x' % ord(uc) for uc in s.decode('cp932'))
1884 > return b''.join(b'\\u%x' % ord(uc) for uc in s.decode('cp932'))
1879 > # translation of "record" in ja_JP.cp932
1885 > # translation of "record" in ja_JP.cp932
1880 > upper = b"\x8bL\x98^"
1886 > upper = b"\x8bL\x98^"
1881 > # str.lower()-ed section name should be treated as different one
1887 > # str.lower()-ed section name should be treated as different one
1882 > lower = b"\x8bl\x98^"
1888 > lower = b"\x8bl\x98^"
1883 > with open('ambiguous.py', 'wb') as fp:
1889 > with open('ambiguous.py', 'wb') as fp:
1884 > fp.write(b"""# ambiguous section names in ja_JP.cp932
1890 > fp.write(b"""# ambiguous section names in ja_JP.cp932
1885 > u'''summary of extension
1891 > u'''summary of extension
1886 >
1892 >
1887 > %s
1893 > %s
1888 > ----
1894 > ----
1889 >
1895 >
1890 > Upper name should show only this message
1896 > Upper name should show only this message
1891 >
1897 >
1892 > %s
1898 > %s
1893 > ----
1899 > ----
1894 >
1900 >
1895 > Lower name should show only this message
1901 > Lower name should show only this message
1896 >
1902 >
1897 > subsequent section
1903 > subsequent section
1898 > ------------------
1904 > ------------------
1899 >
1905 >
1900 > This should be hidden at 'hg help ambiguous' with section name.
1906 > This should be hidden at 'hg help ambiguous' with section name.
1901 > '''
1907 > '''
1902 > """ % (escape(upper), escape(lower)))
1908 > """ % (escape(upper), escape(lower)))
1903 > EOF
1909 > EOF
1904
1910
1905 $ cat >> $HGRCPATH <<EOF
1911 $ cat >> $HGRCPATH <<EOF
1906 > [extensions]
1912 > [extensions]
1907 > ambiguous = ./ambiguous.py
1913 > ambiguous = ./ambiguous.py
1908 > EOF
1914 > EOF
1909
1915
1910 $ "$PYTHON" <<EOF | sh
1916 $ "$PYTHON" <<EOF | sh
1911 > from mercurial import pycompat
1917 > from mercurial import pycompat
1912 > upper = b"\x8bL\x98^"
1918 > upper = b"\x8bL\x98^"
1913 > pycompat.stdout.write(b"hg --encoding cp932 help -e ambiguous.%s\n" % upper)
1919 > pycompat.stdout.write(b"hg --encoding cp932 help -e ambiguous.%s\n" % upper)
1914 > EOF
1920 > EOF
1915 \x8bL\x98^ (esc)
1921 \x8bL\x98^ (esc)
1916 ----
1922 ----
1917
1923
1918 Upper name should show only this message
1924 Upper name should show only this message
1919
1925
1920
1926
1921 $ "$PYTHON" <<EOF | sh
1927 $ "$PYTHON" <<EOF | sh
1922 > from mercurial import pycompat
1928 > from mercurial import pycompat
1923 > lower = b"\x8bl\x98^"
1929 > lower = b"\x8bl\x98^"
1924 > pycompat.stdout.write(b"hg --encoding cp932 help -e ambiguous.%s\n" % lower)
1930 > pycompat.stdout.write(b"hg --encoding cp932 help -e ambiguous.%s\n" % lower)
1925 > EOF
1931 > EOF
1926 \x8bl\x98^ (esc)
1932 \x8bl\x98^ (esc)
1927 ----
1933 ----
1928
1934
1929 Lower name should show only this message
1935 Lower name should show only this message
1930
1936
1931
1937
1932 $ cat >> $HGRCPATH <<EOF
1938 $ cat >> $HGRCPATH <<EOF
1933 > [extensions]
1939 > [extensions]
1934 > ambiguous = !
1940 > ambiguous = !
1935 > EOF
1941 > EOF
1936
1942
1937 Show help content of disabled extensions
1943 Show help content of disabled extensions
1938
1944
1939 $ cat >> $HGRCPATH <<EOF
1945 $ cat >> $HGRCPATH <<EOF
1940 > [extensions]
1946 > [extensions]
1941 > ambiguous = !./ambiguous.py
1947 > ambiguous = !./ambiguous.py
1942 > EOF
1948 > EOF
1943 $ hg help -e ambiguous
1949 $ hg help -e ambiguous
1944 ambiguous extension - (no help text available)
1950 ambiguous extension - (no help text available)
1945
1951
1946 (use 'hg help extensions' for information on enabling extensions)
1952 (use 'hg help extensions' for information on enabling extensions)
1947
1953
1948 Test dynamic list of merge tools only shows up once
1954 Test dynamic list of merge tools only shows up once
1949 $ hg help merge-tools
1955 $ hg help merge-tools
1950 Merge Tools
1956 Merge Tools
1951 """""""""""
1957 """""""""""
1952
1958
1953 To merge files Mercurial uses merge tools.
1959 To merge files Mercurial uses merge tools.
1954
1960
1955 A merge tool combines two different versions of a file into a merged file.
1961 A merge tool combines two different versions of a file into a merged file.
1956 Merge tools are given the two files and the greatest common ancestor of
1962 Merge tools are given the two files and the greatest common ancestor of
1957 the two file versions, so they can determine the changes made on both
1963 the two file versions, so they can determine the changes made on both
1958 branches.
1964 branches.
1959
1965
1960 Merge tools are used both for 'hg resolve', 'hg merge', 'hg update', 'hg
1966 Merge tools are used both for 'hg resolve', 'hg merge', 'hg update', 'hg
1961 backout' and in several extensions.
1967 backout' and in several extensions.
1962
1968
1963 Usually, the merge tool tries to automatically reconcile the files by
1969 Usually, the merge tool tries to automatically reconcile the files by
1964 combining all non-overlapping changes that occurred separately in the two
1970 combining all non-overlapping changes that occurred separately in the two
1965 different evolutions of the same initial base file. Furthermore, some
1971 different evolutions of the same initial base file. Furthermore, some
1966 interactive merge programs make it easier to manually resolve conflicting
1972 interactive merge programs make it easier to manually resolve conflicting
1967 merges, either in a graphical way, or by inserting some conflict markers.
1973 merges, either in a graphical way, or by inserting some conflict markers.
1968 Mercurial does not include any interactive merge programs but relies on
1974 Mercurial does not include any interactive merge programs but relies on
1969 external tools for that.
1975 external tools for that.
1970
1976
1971 Available merge tools
1977 Available merge tools
1972 =====================
1978 =====================
1973
1979
1974 External merge tools and their properties are configured in the merge-
1980 External merge tools and their properties are configured in the merge-
1975 tools configuration section - see hgrc(5) - but they can often just be
1981 tools configuration section - see hgrc(5) - but they can often just be
1976 named by their executable.
1982 named by their executable.
1977
1983
1978 A merge tool is generally usable if its executable can be found on the
1984 A merge tool is generally usable if its executable can be found on the
1979 system and if it can handle the merge. The executable is found if it is an
1985 system and if it can handle the merge. The executable is found if it is an
1980 absolute or relative executable path or the name of an application in the
1986 absolute or relative executable path or the name of an application in the
1981 executable search path. The tool is assumed to be able to handle the merge
1987 executable search path. The tool is assumed to be able to handle the merge
1982 if it can handle symlinks if the file is a symlink, if it can handle
1988 if it can handle symlinks if the file is a symlink, if it can handle
1983 binary files if the file is binary, and if a GUI is available if the tool
1989 binary files if the file is binary, and if a GUI is available if the tool
1984 requires a GUI.
1990 requires a GUI.
1985
1991
1986 There are some internal merge tools which can be used. The internal merge
1992 There are some internal merge tools which can be used. The internal merge
1987 tools are:
1993 tools are:
1988
1994
1989 ":dump"
1995 ":dump"
1990 Creates three versions of the files to merge, containing the contents of
1996 Creates three versions of the files to merge, containing the contents of
1991 local, other and base. These files can then be used to perform a merge
1997 local, other and base. These files can then be used to perform a merge
1992 manually. If the file to be merged is named "a.txt", these files will
1998 manually. If the file to be merged is named "a.txt", these files will
1993 accordingly be named "a.txt.local", "a.txt.other" and "a.txt.base" and
1999 accordingly be named "a.txt.local", "a.txt.other" and "a.txt.base" and
1994 they will be placed in the same directory as "a.txt".
2000 they will be placed in the same directory as "a.txt".
1995
2001
1996 This implies premerge. Therefore, files aren't dumped, if premerge runs
2002 This implies premerge. Therefore, files aren't dumped, if premerge runs
1997 successfully. Use :forcedump to forcibly write files out.
2003 successfully. Use :forcedump to forcibly write files out.
1998
2004
1999 (actual capabilities: binary, symlink)
2005 (actual capabilities: binary, symlink)
2000
2006
2001 ":fail"
2007 ":fail"
2002 Rather than attempting to merge files that were modified on both
2008 Rather than attempting to merge files that were modified on both
2003 branches, it marks them as unresolved. The resolve command must be used
2009 branches, it marks them as unresolved. The resolve command must be used
2004 to resolve these conflicts.
2010 to resolve these conflicts.
2005
2011
2006 (actual capabilities: binary, symlink)
2012 (actual capabilities: binary, symlink)
2007
2013
2008 ":forcedump"
2014 ":forcedump"
2009 Creates three versions of the files as same as :dump, but omits
2015 Creates three versions of the files as same as :dump, but omits
2010 premerge.
2016 premerge.
2011
2017
2012 (actual capabilities: binary, symlink)
2018 (actual capabilities: binary, symlink)
2013
2019
2014 ":local"
2020 ":local"
2015 Uses the local 'p1()' version of files as the merged version.
2021 Uses the local 'p1()' version of files as the merged version.
2016
2022
2017 (actual capabilities: binary, symlink)
2023 (actual capabilities: binary, symlink)
2018
2024
2019 ":merge"
2025 ":merge"
2020 Uses the internal non-interactive simple merge algorithm for merging
2026 Uses the internal non-interactive simple merge algorithm for merging
2021 files. It will fail if there are any conflicts and leave markers in the
2027 files. It will fail if there are any conflicts and leave markers in the
2022 partially merged file. Markers will have two sections, one for each side
2028 partially merged file. Markers will have two sections, one for each side
2023 of merge.
2029 of merge.
2024
2030
2025 ":merge-local"
2031 ":merge-local"
2026 Like :merge, but resolve all conflicts non-interactively in favor of the
2032 Like :merge, but resolve all conflicts non-interactively in favor of the
2027 local 'p1()' changes.
2033 local 'p1()' changes.
2028
2034
2029 ":merge-other"
2035 ":merge-other"
2030 Like :merge, but resolve all conflicts non-interactively in favor of the
2036 Like :merge, but resolve all conflicts non-interactively in favor of the
2031 other 'p2()' changes.
2037 other 'p2()' changes.
2032
2038
2033 ":merge3"
2039 ":merge3"
2034 Uses the internal non-interactive simple merge algorithm for merging
2040 Uses the internal non-interactive simple merge algorithm for merging
2035 files. It will fail if there are any conflicts and leave markers in the
2041 files. It will fail if there are any conflicts and leave markers in the
2036 partially merged file. Marker will have three sections, one from each
2042 partially merged file. Marker will have three sections, one from each
2037 side of the merge and one for the base content.
2043 side of the merge and one for the base content.
2038
2044
2039 ":other"
2045 ":other"
2040 Uses the other 'p2()' version of files as the merged version.
2046 Uses the other 'p2()' version of files as the merged version.
2041
2047
2042 (actual capabilities: binary, symlink)
2048 (actual capabilities: binary, symlink)
2043
2049
2044 ":prompt"
2050 ":prompt"
2045 Asks the user which of the local 'p1()' or the other 'p2()' version to
2051 Asks the user which of the local 'p1()' or the other 'p2()' version to
2046 keep as the merged version.
2052 keep as the merged version.
2047
2053
2048 (actual capabilities: binary, symlink)
2054 (actual capabilities: binary, symlink)
2049
2055
2050 ":tagmerge"
2056 ":tagmerge"
2051 Uses the internal tag merge algorithm (experimental).
2057 Uses the internal tag merge algorithm (experimental).
2052
2058
2053 ":union"
2059 ":union"
2054 Uses the internal non-interactive simple merge algorithm for merging
2060 Uses the internal non-interactive simple merge algorithm for merging
2055 files. It will use both left and right sides for conflict regions. No
2061 files. It will use both left and right sides for conflict regions. No
2056 markers are inserted.
2062 markers are inserted.
2057
2063
2058 Internal tools are always available and do not require a GUI but will by
2064 Internal tools are always available and do not require a GUI but will by
2059 default not handle symlinks or binary files. See next section for detail
2065 default not handle symlinks or binary files. See next section for detail
2060 about "actual capabilities" described above.
2066 about "actual capabilities" described above.
2061
2067
2062 Choosing a merge tool
2068 Choosing a merge tool
2063 =====================
2069 =====================
2064
2070
2065 Mercurial uses these rules when deciding which merge tool to use:
2071 Mercurial uses these rules when deciding which merge tool to use:
2066
2072
2067 1. If a tool has been specified with the --tool option to merge or
2073 1. If a tool has been specified with the --tool option to merge or
2068 resolve, it is used. If it is the name of a tool in the merge-tools
2074 resolve, it is used. If it is the name of a tool in the merge-tools
2069 configuration, its configuration is used. Otherwise the specified tool
2075 configuration, its configuration is used. Otherwise the specified tool
2070 must be executable by the shell.
2076 must be executable by the shell.
2071 2. If the "HGMERGE" environment variable is present, its value is used and
2077 2. If the "HGMERGE" environment variable is present, its value is used and
2072 must be executable by the shell.
2078 must be executable by the shell.
2073 3. If the filename of the file to be merged matches any of the patterns in
2079 3. If the filename of the file to be merged matches any of the patterns in
2074 the merge-patterns configuration section, the first usable merge tool
2080 the merge-patterns configuration section, the first usable merge tool
2075 corresponding to a matching pattern is used.
2081 corresponding to a matching pattern is used.
2076 4. If ui.merge is set it will be considered next. If the value is not the
2082 4. If ui.merge is set it will be considered next. If the value is not the
2077 name of a configured tool, the specified value is used and must be
2083 name of a configured tool, the specified value is used and must be
2078 executable by the shell. Otherwise the named tool is used if it is
2084 executable by the shell. Otherwise the named tool is used if it is
2079 usable.
2085 usable.
2080 5. If any usable merge tools are present in the merge-tools configuration
2086 5. If any usable merge tools are present in the merge-tools configuration
2081 section, the one with the highest priority is used.
2087 section, the one with the highest priority is used.
2082 6. If a program named "hgmerge" can be found on the system, it is used -
2088 6. If a program named "hgmerge" can be found on the system, it is used -
2083 but it will by default not be used for symlinks and binary files.
2089 but it will by default not be used for symlinks and binary files.
2084 7. If the file to be merged is not binary and is not a symlink, then
2090 7. If the file to be merged is not binary and is not a symlink, then
2085 internal ":merge" is used.
2091 internal ":merge" is used.
2086 8. Otherwise, ":prompt" is used.
2092 8. Otherwise, ":prompt" is used.
2087
2093
2088 For historical reason, Mercurial treats merge tools as below while
2094 For historical reason, Mercurial treats merge tools as below while
2089 examining rules above.
2095 examining rules above.
2090
2096
2091 step specified via binary symlink
2097 step specified via binary symlink
2092 ----------------------------------
2098 ----------------------------------
2093 1. --tool o/o o/o
2099 1. --tool o/o o/o
2094 2. HGMERGE o/o o/o
2100 2. HGMERGE o/o o/o
2095 3. merge-patterns o/o(*) x/?(*)
2101 3. merge-patterns o/o(*) x/?(*)
2096 4. ui.merge x/?(*) x/?(*)
2102 4. ui.merge x/?(*) x/?(*)
2097
2103
2098 Each capability column indicates Mercurial behavior for internal/external
2104 Each capability column indicates Mercurial behavior for internal/external
2099 merge tools at examining each rule.
2105 merge tools at examining each rule.
2100
2106
2101 - "o": "assume that a tool has capability"
2107 - "o": "assume that a tool has capability"
2102 - "x": "assume that a tool does not have capability"
2108 - "x": "assume that a tool does not have capability"
2103 - "?": "check actual capability of a tool"
2109 - "?": "check actual capability of a tool"
2104
2110
2105 If "merge.strict-capability-check" configuration is true, Mercurial checks
2111 If "merge.strict-capability-check" configuration is true, Mercurial checks
2106 capabilities of merge tools strictly in (*) cases above (= each capability
2112 capabilities of merge tools strictly in (*) cases above (= each capability
2107 column becomes "?/?"). It is false by default for backward compatibility.
2113 column becomes "?/?"). It is false by default for backward compatibility.
2108
2114
2109 Note:
2115 Note:
2110 After selecting a merge program, Mercurial will by default attempt to
2116 After selecting a merge program, Mercurial will by default attempt to
2111 merge the files using a simple merge algorithm first. Only if it
2117 merge the files using a simple merge algorithm first. Only if it
2112 doesn't succeed because of conflicting changes will Mercurial actually
2118 doesn't succeed because of conflicting changes will Mercurial actually
2113 execute the merge program. Whether to use the simple merge algorithm
2119 execute the merge program. Whether to use the simple merge algorithm
2114 first can be controlled by the premerge setting of the merge tool.
2120 first can be controlled by the premerge setting of the merge tool.
2115 Premerge is enabled by default unless the file is binary or a symlink.
2121 Premerge is enabled by default unless the file is binary or a symlink.
2116
2122
2117 See the merge-tools and ui sections of hgrc(5) for details on the
2123 See the merge-tools and ui sections of hgrc(5) for details on the
2118 configuration of merge tools.
2124 configuration of merge tools.
2119
2125
2120 Compression engines listed in `hg help bundlespec`
2126 Compression engines listed in `hg help bundlespec`
2121
2127
2122 $ hg help bundlespec | grep gzip
2128 $ hg help bundlespec | grep gzip
2123 "v1" bundles can only use the "gzip", "bzip2", and "none" compression
2129 "v1" bundles can only use the "gzip", "bzip2", and "none" compression
2124 An algorithm that produces smaller bundles than "gzip".
2130 An algorithm that produces smaller bundles than "gzip".
2125 This engine will likely produce smaller bundles than "gzip" but will be
2131 This engine will likely produce smaller bundles than "gzip" but will be
2126 "gzip"
2132 "gzip"
2127 better compression than "gzip". It also frequently yields better (?)
2133 better compression than "gzip". It also frequently yields better (?)
2128
2134
2129 Test usage of section marks in help documents
2135 Test usage of section marks in help documents
2130
2136
2131 $ cd "$TESTDIR"/../doc
2137 $ cd "$TESTDIR"/../doc
2132 $ "$PYTHON" check-seclevel.py
2138 $ "$PYTHON" check-seclevel.py
2133 $ cd $TESTTMP
2139 $ cd $TESTTMP
2134
2140
2135 #if serve
2141 #if serve
2136
2142
2137 Test the help pages in hgweb.
2143 Test the help pages in hgweb.
2138
2144
2139 Dish up an empty repo; serve it cold.
2145 Dish up an empty repo; serve it cold.
2140
2146
2141 $ hg init "$TESTTMP/test"
2147 $ hg init "$TESTTMP/test"
2142 $ hg serve -R "$TESTTMP/test" -n test -p $HGPORT -d --pid-file=hg.pid
2148 $ hg serve -R "$TESTTMP/test" -n test -p $HGPORT -d --pid-file=hg.pid
2143 $ cat hg.pid >> $DAEMON_PIDS
2149 $ cat hg.pid >> $DAEMON_PIDS
2144
2150
2145 $ get-with-headers.py $LOCALIP:$HGPORT "help"
2151 $ get-with-headers.py $LOCALIP:$HGPORT "help"
2146 200 Script output follows
2152 200 Script output follows
2147
2153
2148 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
2154 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
2149 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
2155 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
2150 <head>
2156 <head>
2151 <link rel="icon" href="/static/hgicon.png" type="image/png" />
2157 <link rel="icon" href="/static/hgicon.png" type="image/png" />
2152 <meta name="robots" content="index, nofollow" />
2158 <meta name="robots" content="index, nofollow" />
2153 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
2159 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
2154 <script type="text/javascript" src="/static/mercurial.js"></script>
2160 <script type="text/javascript" src="/static/mercurial.js"></script>
2155
2161
2156 <title>Help: Index</title>
2162 <title>Help: Index</title>
2157 </head>
2163 </head>
2158 <body>
2164 <body>
2159
2165
2160 <div class="container">
2166 <div class="container">
2161 <div class="menu">
2167 <div class="menu">
2162 <div class="logo">
2168 <div class="logo">
2163 <a href="https://mercurial-scm.org/">
2169 <a href="https://mercurial-scm.org/">
2164 <img src="/static/hglogo.png" alt="mercurial" /></a>
2170 <img src="/static/hglogo.png" alt="mercurial" /></a>
2165 </div>
2171 </div>
2166 <ul>
2172 <ul>
2167 <li><a href="/shortlog">log</a></li>
2173 <li><a href="/shortlog">log</a></li>
2168 <li><a href="/graph">graph</a></li>
2174 <li><a href="/graph">graph</a></li>
2169 <li><a href="/tags">tags</a></li>
2175 <li><a href="/tags">tags</a></li>
2170 <li><a href="/bookmarks">bookmarks</a></li>
2176 <li><a href="/bookmarks">bookmarks</a></li>
2171 <li><a href="/branches">branches</a></li>
2177 <li><a href="/branches">branches</a></li>
2172 </ul>
2178 </ul>
2173 <ul>
2179 <ul>
2174 <li class="active">help</li>
2180 <li class="active">help</li>
2175 </ul>
2181 </ul>
2176 </div>
2182 </div>
2177
2183
2178 <div class="main">
2184 <div class="main">
2179 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
2185 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
2180
2186
2181 <form class="search" action="/log">
2187 <form class="search" action="/log">
2182
2188
2183 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
2189 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
2184 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
2190 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
2185 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
2191 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
2186 </form>
2192 </form>
2187 <table class="bigtable">
2193 <table class="bigtable">
2188 <tr><td colspan="2"><h2><a name="topics" href="#topics">Topics</a></h2></td></tr>
2194 <tr><td colspan="2"><h2><a name="topics" href="#topics">Topics</a></h2></td></tr>
2189
2195
2190 <tr><td>
2196 <tr><td>
2191 <a href="/help/bundlespec">
2197 <a href="/help/bundlespec">
2192 bundlespec
2198 bundlespec
2193 </a>
2199 </a>
2194 </td><td>
2200 </td><td>
2195 Bundle File Formats
2201 Bundle File Formats
2196 </td></tr>
2202 </td></tr>
2197 <tr><td>
2203 <tr><td>
2198 <a href="/help/color">
2204 <a href="/help/color">
2199 color
2205 color
2200 </a>
2206 </a>
2201 </td><td>
2207 </td><td>
2202 Colorizing Outputs
2208 Colorizing Outputs
2203 </td></tr>
2209 </td></tr>
2204 <tr><td>
2210 <tr><td>
2205 <a href="/help/config">
2211 <a href="/help/config">
2206 config
2212 config
2207 </a>
2213 </a>
2208 </td><td>
2214 </td><td>
2209 Configuration Files
2215 Configuration Files
2210 </td></tr>
2216 </td></tr>
2211 <tr><td>
2217 <tr><td>
2212 <a href="/help/dates">
2218 <a href="/help/dates">
2213 dates
2219 dates
2214 </a>
2220 </a>
2215 </td><td>
2221 </td><td>
2216 Date Formats
2222 Date Formats
2217 </td></tr>
2223 </td></tr>
2218 <tr><td>
2224 <tr><td>
2219 <a href="/help/deprecated">
2225 <a href="/help/deprecated">
2220 deprecated
2226 deprecated
2221 </a>
2227 </a>
2222 </td><td>
2228 </td><td>
2223 Deprecated Features
2229 Deprecated Features
2224 </td></tr>
2230 </td></tr>
2225 <tr><td>
2231 <tr><td>
2226 <a href="/help/diffs">
2232 <a href="/help/diffs">
2227 diffs
2233 diffs
2228 </a>
2234 </a>
2229 </td><td>
2235 </td><td>
2230 Diff Formats
2236 Diff Formats
2231 </td></tr>
2237 </td></tr>
2232 <tr><td>
2238 <tr><td>
2233 <a href="/help/environment">
2239 <a href="/help/environment">
2234 environment
2240 environment
2235 </a>
2241 </a>
2236 </td><td>
2242 </td><td>
2237 Environment Variables
2243 Environment Variables
2238 </td></tr>
2244 </td></tr>
2239 <tr><td>
2245 <tr><td>
2240 <a href="/help/extensions">
2246 <a href="/help/extensions">
2241 extensions
2247 extensions
2242 </a>
2248 </a>
2243 </td><td>
2249 </td><td>
2244 Using Additional Features
2250 Using Additional Features
2245 </td></tr>
2251 </td></tr>
2246 <tr><td>
2252 <tr><td>
2247 <a href="/help/filesets">
2253 <a href="/help/filesets">
2248 filesets
2254 filesets
2249 </a>
2255 </a>
2250 </td><td>
2256 </td><td>
2251 Specifying File Sets
2257 Specifying File Sets
2252 </td></tr>
2258 </td></tr>
2253 <tr><td>
2259 <tr><td>
2254 <a href="/help/flags">
2260 <a href="/help/flags">
2255 flags
2261 flags
2256 </a>
2262 </a>
2257 </td><td>
2263 </td><td>
2258 Command-line flags
2264 Command-line flags
2259 </td></tr>
2265 </td></tr>
2260 <tr><td>
2266 <tr><td>
2261 <a href="/help/glossary">
2267 <a href="/help/glossary">
2262 glossary
2268 glossary
2263 </a>
2269 </a>
2264 </td><td>
2270 </td><td>
2265 Glossary
2271 Glossary
2266 </td></tr>
2272 </td></tr>
2267 <tr><td>
2273 <tr><td>
2268 <a href="/help/hgignore">
2274 <a href="/help/hgignore">
2269 hgignore
2275 hgignore
2270 </a>
2276 </a>
2271 </td><td>
2277 </td><td>
2272 Syntax for Mercurial Ignore Files
2278 Syntax for Mercurial Ignore Files
2273 </td></tr>
2279 </td></tr>
2274 <tr><td>
2280 <tr><td>
2275 <a href="/help/hgweb">
2281 <a href="/help/hgweb">
2276 hgweb
2282 hgweb
2277 </a>
2283 </a>
2278 </td><td>
2284 </td><td>
2279 Configuring hgweb
2285 Configuring hgweb
2280 </td></tr>
2286 </td></tr>
2281 <tr><td>
2287 <tr><td>
2282 <a href="/help/internals">
2288 <a href="/help/internals">
2283 internals
2289 internals
2284 </a>
2290 </a>
2285 </td><td>
2291 </td><td>
2286 Technical implementation topics
2292 Technical implementation topics
2287 </td></tr>
2293 </td></tr>
2288 <tr><td>
2294 <tr><td>
2289 <a href="/help/merge-tools">
2295 <a href="/help/merge-tools">
2290 merge-tools
2296 merge-tools
2291 </a>
2297 </a>
2292 </td><td>
2298 </td><td>
2293 Merge Tools
2299 Merge Tools
2294 </td></tr>
2300 </td></tr>
2295 <tr><td>
2301 <tr><td>
2296 <a href="/help/pager">
2302 <a href="/help/pager">
2297 pager
2303 pager
2298 </a>
2304 </a>
2299 </td><td>
2305 </td><td>
2300 Pager Support
2306 Pager Support
2301 </td></tr>
2307 </td></tr>
2302 <tr><td>
2308 <tr><td>
2303 <a href="/help/patterns">
2309 <a href="/help/patterns">
2304 patterns
2310 patterns
2305 </a>
2311 </a>
2306 </td><td>
2312 </td><td>
2307 File Name Patterns
2313 File Name Patterns
2308 </td></tr>
2314 </td></tr>
2309 <tr><td>
2315 <tr><td>
2310 <a href="/help/phases">
2316 <a href="/help/phases">
2311 phases
2317 phases
2312 </a>
2318 </a>
2313 </td><td>
2319 </td><td>
2314 Working with Phases
2320 Working with Phases
2315 </td></tr>
2321 </td></tr>
2316 <tr><td>
2322 <tr><td>
2317 <a href="/help/revisions">
2323 <a href="/help/revisions">
2318 revisions
2324 revisions
2319 </a>
2325 </a>
2320 </td><td>
2326 </td><td>
2321 Specifying Revisions
2327 Specifying Revisions
2322 </td></tr>
2328 </td></tr>
2323 <tr><td>
2329 <tr><td>
2324 <a href="/help/scripting">
2330 <a href="/help/scripting">
2325 scripting
2331 scripting
2326 </a>
2332 </a>
2327 </td><td>
2333 </td><td>
2328 Using Mercurial from scripts and automation
2334 Using Mercurial from scripts and automation
2329 </td></tr>
2335 </td></tr>
2330 <tr><td>
2336 <tr><td>
2331 <a href="/help/subrepos">
2337 <a href="/help/subrepos">
2332 subrepos
2338 subrepos
2333 </a>
2339 </a>
2334 </td><td>
2340 </td><td>
2335 Subrepositories
2341 Subrepositories
2336 </td></tr>
2342 </td></tr>
2337 <tr><td>
2343 <tr><td>
2338 <a href="/help/templating">
2344 <a href="/help/templating">
2339 templating
2345 templating
2340 </a>
2346 </a>
2341 </td><td>
2347 </td><td>
2342 Template Usage
2348 Template Usage
2343 </td></tr>
2349 </td></tr>
2344 <tr><td>
2350 <tr><td>
2345 <a href="/help/urls">
2351 <a href="/help/urls">
2346 urls
2352 urls
2347 </a>
2353 </a>
2348 </td><td>
2354 </td><td>
2349 URL Paths
2355 URL Paths
2350 </td></tr>
2356 </td></tr>
2351 <tr><td>
2357 <tr><td>
2352 <a href="/help/topic-containing-verbose">
2358 <a href="/help/topic-containing-verbose">
2353 topic-containing-verbose
2359 topic-containing-verbose
2354 </a>
2360 </a>
2355 </td><td>
2361 </td><td>
2356 This is the topic to test omit indicating.
2362 This is the topic to test omit indicating.
2357 </td></tr>
2363 </td></tr>
2358
2364
2359
2365
2360 <tr><td colspan="2"><h2><a name="main" href="#main">Main Commands</a></h2></td></tr>
2366 <tr><td colspan="2"><h2><a name="main" href="#main">Main Commands</a></h2></td></tr>
2361
2367
2362 <tr><td>
2368 <tr><td>
2363 <a href="/help/abort">
2369 <a href="/help/abort">
2364 abort
2370 abort
2365 </a>
2371 </a>
2366 </td><td>
2372 </td><td>
2367 abort an unfinished operation (EXPERIMENTAL)
2373 abort an unfinished operation (EXPERIMENTAL)
2368 </td></tr>
2374 </td></tr>
2369 <tr><td>
2375 <tr><td>
2370 <a href="/help/add">
2376 <a href="/help/add">
2371 add
2377 add
2372 </a>
2378 </a>
2373 </td><td>
2379 </td><td>
2374 add the specified files on the next commit
2380 add the specified files on the next commit
2375 </td></tr>
2381 </td></tr>
2376 <tr><td>
2382 <tr><td>
2377 <a href="/help/annotate">
2383 <a href="/help/annotate">
2378 annotate
2384 annotate
2379 </a>
2385 </a>
2380 </td><td>
2386 </td><td>
2381 show changeset information by line for each file
2387 show changeset information by line for each file
2382 </td></tr>
2388 </td></tr>
2383 <tr><td>
2389 <tr><td>
2384 <a href="/help/clone">
2390 <a href="/help/clone">
2385 clone
2391 clone
2386 </a>
2392 </a>
2387 </td><td>
2393 </td><td>
2388 make a copy of an existing repository
2394 make a copy of an existing repository
2389 </td></tr>
2395 </td></tr>
2390 <tr><td>
2396 <tr><td>
2391 <a href="/help/commit">
2397 <a href="/help/commit">
2392 commit
2398 commit
2393 </a>
2399 </a>
2394 </td><td>
2400 </td><td>
2395 commit the specified files or all outstanding changes
2401 commit the specified files or all outstanding changes
2396 </td></tr>
2402 </td></tr>
2397 <tr><td>
2403 <tr><td>
2398 <a href="/help/continue">
2404 <a href="/help/continue">
2399 continue
2405 continue
2400 </a>
2406 </a>
2401 </td><td>
2407 </td><td>
2402 resumes an interrupted operation (EXPERIMENTAL)
2408 resumes an interrupted operation (EXPERIMENTAL)
2403 </td></tr>
2409 </td></tr>
2404 <tr><td>
2410 <tr><td>
2405 <a href="/help/diff">
2411 <a href="/help/diff">
2406 diff
2412 diff
2407 </a>
2413 </a>
2408 </td><td>
2414 </td><td>
2409 diff repository (or selected files)
2415 diff repository (or selected files)
2410 </td></tr>
2416 </td></tr>
2411 <tr><td>
2417 <tr><td>
2412 <a href="/help/export">
2418 <a href="/help/export">
2413 export
2419 export
2414 </a>
2420 </a>
2415 </td><td>
2421 </td><td>
2416 dump the header and diffs for one or more changesets
2422 dump the header and diffs for one or more changesets
2417 </td></tr>
2423 </td></tr>
2418 <tr><td>
2424 <tr><td>
2419 <a href="/help/forget">
2425 <a href="/help/forget">
2420 forget
2426 forget
2421 </a>
2427 </a>
2422 </td><td>
2428 </td><td>
2423 forget the specified files on the next commit
2429 forget the specified files on the next commit
2424 </td></tr>
2430 </td></tr>
2425 <tr><td>
2431 <tr><td>
2426 <a href="/help/init">
2432 <a href="/help/init">
2427 init
2433 init
2428 </a>
2434 </a>
2429 </td><td>
2435 </td><td>
2430 create a new repository in the given directory
2436 create a new repository in the given directory
2431 </td></tr>
2437 </td></tr>
2432 <tr><td>
2438 <tr><td>
2433 <a href="/help/log">
2439 <a href="/help/log">
2434 log
2440 log
2435 </a>
2441 </a>
2436 </td><td>
2442 </td><td>
2437 show revision history of entire repository or files
2443 show revision history of entire repository or files
2438 </td></tr>
2444 </td></tr>
2439 <tr><td>
2445 <tr><td>
2440 <a href="/help/merge">
2446 <a href="/help/merge">
2441 merge
2447 merge
2442 </a>
2448 </a>
2443 </td><td>
2449 </td><td>
2444 merge another revision into working directory
2450 merge another revision into working directory
2445 </td></tr>
2451 </td></tr>
2446 <tr><td>
2452 <tr><td>
2447 <a href="/help/pull">
2453 <a href="/help/pull">
2448 pull
2454 pull
2449 </a>
2455 </a>
2450 </td><td>
2456 </td><td>
2451 pull changes from the specified source
2457 pull changes from the specified source
2452 </td></tr>
2458 </td></tr>
2453 <tr><td>
2459 <tr><td>
2454 <a href="/help/push">
2460 <a href="/help/push">
2455 push
2461 push
2456 </a>
2462 </a>
2457 </td><td>
2463 </td><td>
2458 push changes to the specified destination
2464 push changes to the specified destination
2459 </td></tr>
2465 </td></tr>
2460 <tr><td>
2466 <tr><td>
2461 <a href="/help/remove">
2467 <a href="/help/remove">
2462 remove
2468 remove
2463 </a>
2469 </a>
2464 </td><td>
2470 </td><td>
2465 remove the specified files on the next commit
2471 remove the specified files on the next commit
2466 </td></tr>
2472 </td></tr>
2467 <tr><td>
2473 <tr><td>
2468 <a href="/help/serve">
2474 <a href="/help/serve">
2469 serve
2475 serve
2470 </a>
2476 </a>
2471 </td><td>
2477 </td><td>
2472 start stand-alone webserver
2478 start stand-alone webserver
2473 </td></tr>
2479 </td></tr>
2474 <tr><td>
2480 <tr><td>
2475 <a href="/help/status">
2481 <a href="/help/status">
2476 status
2482 status
2477 </a>
2483 </a>
2478 </td><td>
2484 </td><td>
2479 show changed files in the working directory
2485 show changed files in the working directory
2480 </td></tr>
2486 </td></tr>
2481 <tr><td>
2487 <tr><td>
2482 <a href="/help/summary">
2488 <a href="/help/summary">
2483 summary
2489 summary
2484 </a>
2490 </a>
2485 </td><td>
2491 </td><td>
2486 summarize working directory state
2492 summarize working directory state
2487 </td></tr>
2493 </td></tr>
2488 <tr><td>
2494 <tr><td>
2489 <a href="/help/update">
2495 <a href="/help/update">
2490 update
2496 update
2491 </a>
2497 </a>
2492 </td><td>
2498 </td><td>
2493 update working directory (or switch revisions)
2499 update working directory (or switch revisions)
2494 </td></tr>
2500 </td></tr>
2495
2501
2496
2502
2497
2503
2498 <tr><td colspan="2"><h2><a name="other" href="#other">Other Commands</a></h2></td></tr>
2504 <tr><td colspan="2"><h2><a name="other" href="#other">Other Commands</a></h2></td></tr>
2499
2505
2500 <tr><td>
2506 <tr><td>
2501 <a href="/help/addremove">
2507 <a href="/help/addremove">
2502 addremove
2508 addremove
2503 </a>
2509 </a>
2504 </td><td>
2510 </td><td>
2505 add all new files, delete all missing files
2511 add all new files, delete all missing files
2506 </td></tr>
2512 </td></tr>
2507 <tr><td>
2513 <tr><td>
2508 <a href="/help/archive">
2514 <a href="/help/archive">
2509 archive
2515 archive
2510 </a>
2516 </a>
2511 </td><td>
2517 </td><td>
2512 create an unversioned archive of a repository revision
2518 create an unversioned archive of a repository revision
2513 </td></tr>
2519 </td></tr>
2514 <tr><td>
2520 <tr><td>
2515 <a href="/help/backout">
2521 <a href="/help/backout">
2516 backout
2522 backout
2517 </a>
2523 </a>
2518 </td><td>
2524 </td><td>
2519 reverse effect of earlier changeset
2525 reverse effect of earlier changeset
2520 </td></tr>
2526 </td></tr>
2521 <tr><td>
2527 <tr><td>
2522 <a href="/help/bisect">
2528 <a href="/help/bisect">
2523 bisect
2529 bisect
2524 </a>
2530 </a>
2525 </td><td>
2531 </td><td>
2526 subdivision search of changesets
2532 subdivision search of changesets
2527 </td></tr>
2533 </td></tr>
2528 <tr><td>
2534 <tr><td>
2529 <a href="/help/bookmarks">
2535 <a href="/help/bookmarks">
2530 bookmarks
2536 bookmarks
2531 </a>
2537 </a>
2532 </td><td>
2538 </td><td>
2533 create a new bookmark or list existing bookmarks
2539 create a new bookmark or list existing bookmarks
2534 </td></tr>
2540 </td></tr>
2535 <tr><td>
2541 <tr><td>
2536 <a href="/help/branch">
2542 <a href="/help/branch">
2537 branch
2543 branch
2538 </a>
2544 </a>
2539 </td><td>
2545 </td><td>
2540 set or show the current branch name
2546 set or show the current branch name
2541 </td></tr>
2547 </td></tr>
2542 <tr><td>
2548 <tr><td>
2543 <a href="/help/branches">
2549 <a href="/help/branches">
2544 branches
2550 branches
2545 </a>
2551 </a>
2546 </td><td>
2552 </td><td>
2547 list repository named branches
2553 list repository named branches
2548 </td></tr>
2554 </td></tr>
2549 <tr><td>
2555 <tr><td>
2550 <a href="/help/bundle">
2556 <a href="/help/bundle">
2551 bundle
2557 bundle
2552 </a>
2558 </a>
2553 </td><td>
2559 </td><td>
2554 create a bundle file
2560 create a bundle file
2555 </td></tr>
2561 </td></tr>
2556 <tr><td>
2562 <tr><td>
2557 <a href="/help/cat">
2563 <a href="/help/cat">
2558 cat
2564 cat
2559 </a>
2565 </a>
2560 </td><td>
2566 </td><td>
2561 output the current or given revision of files
2567 output the current or given revision of files
2562 </td></tr>
2568 </td></tr>
2563 <tr><td>
2569 <tr><td>
2564 <a href="/help/config">
2570 <a href="/help/config">
2565 config
2571 config
2566 </a>
2572 </a>
2567 </td><td>
2573 </td><td>
2568 show combined config settings from all hgrc files
2574 show combined config settings from all hgrc files
2569 </td></tr>
2575 </td></tr>
2570 <tr><td>
2576 <tr><td>
2571 <a href="/help/copy">
2577 <a href="/help/copy">
2572 copy
2578 copy
2573 </a>
2579 </a>
2574 </td><td>
2580 </td><td>
2575 mark files as copied for the next commit
2581 mark files as copied for the next commit
2576 </td></tr>
2582 </td></tr>
2577 <tr><td>
2583 <tr><td>
2578 <a href="/help/files">
2584 <a href="/help/files">
2579 files
2585 files
2580 </a>
2586 </a>
2581 </td><td>
2587 </td><td>
2582 list tracked files
2588 list tracked files
2583 </td></tr>
2589 </td></tr>
2584 <tr><td>
2590 <tr><td>
2585 <a href="/help/graft">
2591 <a href="/help/graft">
2586 graft
2592 graft
2587 </a>
2593 </a>
2588 </td><td>
2594 </td><td>
2589 copy changes from other branches onto the current branch
2595 copy changes from other branches onto the current branch
2590 </td></tr>
2596 </td></tr>
2591 <tr><td>
2597 <tr><td>
2592 <a href="/help/grep">
2598 <a href="/help/grep">
2593 grep
2599 grep
2594 </a>
2600 </a>
2595 </td><td>
2601 </td><td>
2596 search for a pattern in specified files
2602 search for a pattern in specified files
2597 </td></tr>
2603 </td></tr>
2598 <tr><td>
2604 <tr><td>
2599 <a href="/help/hashelp">
2605 <a href="/help/hashelp">
2600 hashelp
2606 hashelp
2601 </a>
2607 </a>
2602 </td><td>
2608 </td><td>
2603 Extension command's help
2609 Extension command's help
2604 </td></tr>
2610 </td></tr>
2605 <tr><td>
2611 <tr><td>
2606 <a href="/help/heads">
2612 <a href="/help/heads">
2607 heads
2613 heads
2608 </a>
2614 </a>
2609 </td><td>
2615 </td><td>
2610 show branch heads
2616 show branch heads
2611 </td></tr>
2617 </td></tr>
2612 <tr><td>
2618 <tr><td>
2613 <a href="/help/help">
2619 <a href="/help/help">
2614 help
2620 help
2615 </a>
2621 </a>
2616 </td><td>
2622 </td><td>
2617 show help for a given topic or a help overview
2623 show help for a given topic or a help overview
2618 </td></tr>
2624 </td></tr>
2619 <tr><td>
2625 <tr><td>
2620 <a href="/help/hgalias">
2626 <a href="/help/hgalias">
2621 hgalias
2627 hgalias
2622 </a>
2628 </a>
2623 </td><td>
2629 </td><td>
2624 My doc
2630 My doc
2625 </td></tr>
2631 </td></tr>
2626 <tr><td>
2632 <tr><td>
2627 <a href="/help/hgaliasnodoc">
2633 <a href="/help/hgaliasnodoc">
2628 hgaliasnodoc
2634 hgaliasnodoc
2629 </a>
2635 </a>
2630 </td><td>
2636 </td><td>
2631 summarize working directory state
2637 summarize working directory state
2632 </td></tr>
2638 </td></tr>
2633 <tr><td>
2639 <tr><td>
2634 <a href="/help/identify">
2640 <a href="/help/identify">
2635 identify
2641 identify
2636 </a>
2642 </a>
2637 </td><td>
2643 </td><td>
2638 identify the working directory or specified revision
2644 identify the working directory or specified revision
2639 </td></tr>
2645 </td></tr>
2640 <tr><td>
2646 <tr><td>
2641 <a href="/help/import">
2647 <a href="/help/import">
2642 import
2648 import
2643 </a>
2649 </a>
2644 </td><td>
2650 </td><td>
2645 import an ordered set of patches
2651 import an ordered set of patches
2646 </td></tr>
2652 </td></tr>
2647 <tr><td>
2653 <tr><td>
2648 <a href="/help/incoming">
2654 <a href="/help/incoming">
2649 incoming
2655 incoming
2650 </a>
2656 </a>
2651 </td><td>
2657 </td><td>
2652 show new changesets found in source
2658 show new changesets found in source
2653 </td></tr>
2659 </td></tr>
2654 <tr><td>
2660 <tr><td>
2655 <a href="/help/manifest">
2661 <a href="/help/manifest">
2656 manifest
2662 manifest
2657 </a>
2663 </a>
2658 </td><td>
2664 </td><td>
2659 output the current or given revision of the project manifest
2665 output the current or given revision of the project manifest
2660 </td></tr>
2666 </td></tr>
2661 <tr><td>
2667 <tr><td>
2662 <a href="/help/nohelp">
2668 <a href="/help/nohelp">
2663 nohelp
2669 nohelp
2664 </a>
2670 </a>
2665 </td><td>
2671 </td><td>
2666 (no help text available)
2672 (no help text available)
2667 </td></tr>
2673 </td></tr>
2668 <tr><td>
2674 <tr><td>
2669 <a href="/help/outgoing">
2675 <a href="/help/outgoing">
2670 outgoing
2676 outgoing
2671 </a>
2677 </a>
2672 </td><td>
2678 </td><td>
2673 show changesets not found in the destination
2679 show changesets not found in the destination
2674 </td></tr>
2680 </td></tr>
2675 <tr><td>
2681 <tr><td>
2676 <a href="/help/paths">
2682 <a href="/help/paths">
2677 paths
2683 paths
2678 </a>
2684 </a>
2679 </td><td>
2685 </td><td>
2680 show aliases for remote repositories
2686 show aliases for remote repositories
2681 </td></tr>
2687 </td></tr>
2682 <tr><td>
2688 <tr><td>
2683 <a href="/help/phase">
2689 <a href="/help/phase">
2684 phase
2690 phase
2685 </a>
2691 </a>
2686 </td><td>
2692 </td><td>
2687 set or show the current phase name
2693 set or show the current phase name
2688 </td></tr>
2694 </td></tr>
2689 <tr><td>
2695 <tr><td>
2690 <a href="/help/recover">
2696 <a href="/help/recover">
2691 recover
2697 recover
2692 </a>
2698 </a>
2693 </td><td>
2699 </td><td>
2694 roll back an interrupted transaction
2700 roll back an interrupted transaction
2695 </td></tr>
2701 </td></tr>
2696 <tr><td>
2702 <tr><td>
2697 <a href="/help/rename">
2703 <a href="/help/rename">
2698 rename
2704 rename
2699 </a>
2705 </a>
2700 </td><td>
2706 </td><td>
2701 rename files; equivalent of copy + remove
2707 rename files; equivalent of copy + remove
2702 </td></tr>
2708 </td></tr>
2703 <tr><td>
2709 <tr><td>
2704 <a href="/help/resolve">
2710 <a href="/help/resolve">
2705 resolve
2711 resolve
2706 </a>
2712 </a>
2707 </td><td>
2713 </td><td>
2708 redo merges or set/view the merge status of files
2714 redo merges or set/view the merge status of files
2709 </td></tr>
2715 </td></tr>
2710 <tr><td>
2716 <tr><td>
2711 <a href="/help/revert">
2717 <a href="/help/revert">
2712 revert
2718 revert
2713 </a>
2719 </a>
2714 </td><td>
2720 </td><td>
2715 restore files to their checkout state
2721 restore files to their checkout state
2716 </td></tr>
2722 </td></tr>
2717 <tr><td>
2723 <tr><td>
2718 <a href="/help/root">
2724 <a href="/help/root">
2719 root
2725 root
2720 </a>
2726 </a>
2721 </td><td>
2727 </td><td>
2722 print the root (top) of the current working directory
2728 print the root (top) of the current working directory
2723 </td></tr>
2729 </td></tr>
2724 <tr><td>
2730 <tr><td>
2725 <a href="/help/shellalias">
2731 <a href="/help/shellalias">
2726 shellalias
2732 shellalias
2727 </a>
2733 </a>
2728 </td><td>
2734 </td><td>
2729 (no help text available)
2735 (no help text available)
2730 </td></tr>
2736 </td></tr>
2731 <tr><td>
2737 <tr><td>
2732 <a href="/help/shelve">
2738 <a href="/help/shelve">
2733 shelve
2739 shelve
2734 </a>
2740 </a>
2735 </td><td>
2741 </td><td>
2736 save and set aside changes from the working directory
2742 save and set aside changes from the working directory
2737 </td></tr>
2743 </td></tr>
2738 <tr><td>
2744 <tr><td>
2739 <a href="/help/tag">
2745 <a href="/help/tag">
2740 tag
2746 tag
2741 </a>
2747 </a>
2742 </td><td>
2748 </td><td>
2743 add one or more tags for the current or given revision
2749 add one or more tags for the current or given revision
2744 </td></tr>
2750 </td></tr>
2745 <tr><td>
2751 <tr><td>
2746 <a href="/help/tags">
2752 <a href="/help/tags">
2747 tags
2753 tags
2748 </a>
2754 </a>
2749 </td><td>
2755 </td><td>
2750 list repository tags
2756 list repository tags
2751 </td></tr>
2757 </td></tr>
2752 <tr><td>
2758 <tr><td>
2753 <a href="/help/unbundle">
2759 <a href="/help/unbundle">
2754 unbundle
2760 unbundle
2755 </a>
2761 </a>
2756 </td><td>
2762 </td><td>
2757 apply one or more bundle files
2763 apply one or more bundle files
2758 </td></tr>
2764 </td></tr>
2759 <tr><td>
2765 <tr><td>
2760 <a href="/help/unshelve">
2766 <a href="/help/unshelve">
2761 unshelve
2767 unshelve
2762 </a>
2768 </a>
2763 </td><td>
2769 </td><td>
2764 restore a shelved change to the working directory
2770 restore a shelved change to the working directory
2765 </td></tr>
2771 </td></tr>
2766 <tr><td>
2772 <tr><td>
2767 <a href="/help/verify">
2773 <a href="/help/verify">
2768 verify
2774 verify
2769 </a>
2775 </a>
2770 </td><td>
2776 </td><td>
2771 verify the integrity of the repository
2777 verify the integrity of the repository
2772 </td></tr>
2778 </td></tr>
2773 <tr><td>
2779 <tr><td>
2774 <a href="/help/version">
2780 <a href="/help/version">
2775 version
2781 version
2776 </a>
2782 </a>
2777 </td><td>
2783 </td><td>
2778 output version and copyright information
2784 output version and copyright information
2779 </td></tr>
2785 </td></tr>
2780
2786
2781
2787
2782 </table>
2788 </table>
2783 </div>
2789 </div>
2784 </div>
2790 </div>
2785
2791
2786
2792
2787
2793
2788 </body>
2794 </body>
2789 </html>
2795 </html>
2790
2796
2791
2797
2792 $ get-with-headers.py $LOCALIP:$HGPORT "help/add"
2798 $ get-with-headers.py $LOCALIP:$HGPORT "help/add"
2793 200 Script output follows
2799 200 Script output follows
2794
2800
2795 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
2801 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
2796 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
2802 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
2797 <head>
2803 <head>
2798 <link rel="icon" href="/static/hgicon.png" type="image/png" />
2804 <link rel="icon" href="/static/hgicon.png" type="image/png" />
2799 <meta name="robots" content="index, nofollow" />
2805 <meta name="robots" content="index, nofollow" />
2800 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
2806 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
2801 <script type="text/javascript" src="/static/mercurial.js"></script>
2807 <script type="text/javascript" src="/static/mercurial.js"></script>
2802
2808
2803 <title>Help: add</title>
2809 <title>Help: add</title>
2804 </head>
2810 </head>
2805 <body>
2811 <body>
2806
2812
2807 <div class="container">
2813 <div class="container">
2808 <div class="menu">
2814 <div class="menu">
2809 <div class="logo">
2815 <div class="logo">
2810 <a href="https://mercurial-scm.org/">
2816 <a href="https://mercurial-scm.org/">
2811 <img src="/static/hglogo.png" alt="mercurial" /></a>
2817 <img src="/static/hglogo.png" alt="mercurial" /></a>
2812 </div>
2818 </div>
2813 <ul>
2819 <ul>
2814 <li><a href="/shortlog">log</a></li>
2820 <li><a href="/shortlog">log</a></li>
2815 <li><a href="/graph">graph</a></li>
2821 <li><a href="/graph">graph</a></li>
2816 <li><a href="/tags">tags</a></li>
2822 <li><a href="/tags">tags</a></li>
2817 <li><a href="/bookmarks">bookmarks</a></li>
2823 <li><a href="/bookmarks">bookmarks</a></li>
2818 <li><a href="/branches">branches</a></li>
2824 <li><a href="/branches">branches</a></li>
2819 </ul>
2825 </ul>
2820 <ul>
2826 <ul>
2821 <li class="active"><a href="/help">help</a></li>
2827 <li class="active"><a href="/help">help</a></li>
2822 </ul>
2828 </ul>
2823 </div>
2829 </div>
2824
2830
2825 <div class="main">
2831 <div class="main">
2826 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
2832 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
2827 <h3>Help: add</h3>
2833 <h3>Help: add</h3>
2828
2834
2829 <form class="search" action="/log">
2835 <form class="search" action="/log">
2830
2836
2831 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
2837 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
2832 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
2838 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
2833 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
2839 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
2834 </form>
2840 </form>
2835 <div id="doc">
2841 <div id="doc">
2836 <p>
2842 <p>
2837 hg add [OPTION]... [FILE]...
2843 hg add [OPTION]... [FILE]...
2838 </p>
2844 </p>
2839 <p>
2845 <p>
2840 add the specified files on the next commit
2846 add the specified files on the next commit
2841 </p>
2847 </p>
2842 <p>
2848 <p>
2843 Schedule files to be version controlled and added to the
2849 Schedule files to be version controlled and added to the
2844 repository.
2850 repository.
2845 </p>
2851 </p>
2846 <p>
2852 <p>
2847 The files will be added to the repository at the next commit. To
2853 The files will be added to the repository at the next commit. To
2848 undo an add before that, see 'hg forget'.
2854 undo an add before that, see 'hg forget'.
2849 </p>
2855 </p>
2850 <p>
2856 <p>
2851 If no names are given, add all files to the repository (except
2857 If no names are given, add all files to the repository (except
2852 files matching &quot;.hgignore&quot;).
2858 files matching &quot;.hgignore&quot;).
2853 </p>
2859 </p>
2854 <p>
2860 <p>
2855 Examples:
2861 Examples:
2856 </p>
2862 </p>
2857 <ul>
2863 <ul>
2858 <li> New (unknown) files are added automatically by 'hg add':
2864 <li> New (unknown) files are added automatically by 'hg add':
2859 <pre>
2865 <pre>
2860 \$ ls (re)
2866 \$ ls (re)
2861 foo.c
2867 foo.c
2862 \$ hg status (re)
2868 \$ hg status (re)
2863 ? foo.c
2869 ? foo.c
2864 \$ hg add (re)
2870 \$ hg add (re)
2865 adding foo.c
2871 adding foo.c
2866 \$ hg status (re)
2872 \$ hg status (re)
2867 A foo.c
2873 A foo.c
2868 </pre>
2874 </pre>
2869 <li> Specific files to be added can be specified:
2875 <li> Specific files to be added can be specified:
2870 <pre>
2876 <pre>
2871 \$ ls (re)
2877 \$ ls (re)
2872 bar.c foo.c
2878 bar.c foo.c
2873 \$ hg status (re)
2879 \$ hg status (re)
2874 ? bar.c
2880 ? bar.c
2875 ? foo.c
2881 ? foo.c
2876 \$ hg add bar.c (re)
2882 \$ hg add bar.c (re)
2877 \$ hg status (re)
2883 \$ hg status (re)
2878 A bar.c
2884 A bar.c
2879 ? foo.c
2885 ? foo.c
2880 </pre>
2886 </pre>
2881 </ul>
2887 </ul>
2882 <p>
2888 <p>
2883 Returns 0 if all files are successfully added.
2889 Returns 0 if all files are successfully added.
2884 </p>
2890 </p>
2885 <p>
2891 <p>
2886 options ([+] can be repeated):
2892 options ([+] can be repeated):
2887 </p>
2893 </p>
2888 <table>
2894 <table>
2889 <tr><td>-I</td>
2895 <tr><td>-I</td>
2890 <td>--include PATTERN [+]</td>
2896 <td>--include PATTERN [+]</td>
2891 <td>include names matching the given patterns</td></tr>
2897 <td>include names matching the given patterns</td></tr>
2892 <tr><td>-X</td>
2898 <tr><td>-X</td>
2893 <td>--exclude PATTERN [+]</td>
2899 <td>--exclude PATTERN [+]</td>
2894 <td>exclude names matching the given patterns</td></tr>
2900 <td>exclude names matching the given patterns</td></tr>
2895 <tr><td>-S</td>
2901 <tr><td>-S</td>
2896 <td>--subrepos</td>
2902 <td>--subrepos</td>
2897 <td>recurse into subrepositories</td></tr>
2903 <td>recurse into subrepositories</td></tr>
2898 <tr><td>-n</td>
2904 <tr><td>-n</td>
2899 <td>--dry-run</td>
2905 <td>--dry-run</td>
2900 <td>do not perform actions, just print output</td></tr>
2906 <td>do not perform actions, just print output</td></tr>
2901 </table>
2907 </table>
2902 <p>
2908 <p>
2903 global options ([+] can be repeated):
2909 global options ([+] can be repeated):
2904 </p>
2910 </p>
2905 <table>
2911 <table>
2906 <tr><td>-R</td>
2912 <tr><td>-R</td>
2907 <td>--repository REPO</td>
2913 <td>--repository REPO</td>
2908 <td>repository root directory or name of overlay bundle file</td></tr>
2914 <td>repository root directory or name of overlay bundle file</td></tr>
2909 <tr><td></td>
2915 <tr><td></td>
2910 <td>--cwd DIR</td>
2916 <td>--cwd DIR</td>
2911 <td>change working directory</td></tr>
2917 <td>change working directory</td></tr>
2912 <tr><td>-y</td>
2918 <tr><td>-y</td>
2913 <td>--noninteractive</td>
2919 <td>--noninteractive</td>
2914 <td>do not prompt, automatically pick the first choice for all prompts</td></tr>
2920 <td>do not prompt, automatically pick the first choice for all prompts</td></tr>
2915 <tr><td>-q</td>
2921 <tr><td>-q</td>
2916 <td>--quiet</td>
2922 <td>--quiet</td>
2917 <td>suppress output</td></tr>
2923 <td>suppress output</td></tr>
2918 <tr><td>-v</td>
2924 <tr><td>-v</td>
2919 <td>--verbose</td>
2925 <td>--verbose</td>
2920 <td>enable additional output</td></tr>
2926 <td>enable additional output</td></tr>
2921 <tr><td></td>
2927 <tr><td></td>
2922 <td>--color TYPE</td>
2928 <td>--color TYPE</td>
2923 <td>when to colorize (boolean, always, auto, never, or debug)</td></tr>
2929 <td>when to colorize (boolean, always, auto, never, or debug)</td></tr>
2924 <tr><td></td>
2930 <tr><td></td>
2925 <td>--config CONFIG [+]</td>
2931 <td>--config CONFIG [+]</td>
2926 <td>set/override config option (use 'section.name=value')</td></tr>
2932 <td>set/override config option (use 'section.name=value')</td></tr>
2927 <tr><td></td>
2933 <tr><td></td>
2928 <td>--debug</td>
2934 <td>--debug</td>
2929 <td>enable debugging output</td></tr>
2935 <td>enable debugging output</td></tr>
2930 <tr><td></td>
2936 <tr><td></td>
2931 <td>--debugger</td>
2937 <td>--debugger</td>
2932 <td>start debugger</td></tr>
2938 <td>start debugger</td></tr>
2933 <tr><td></td>
2939 <tr><td></td>
2934 <td>--encoding ENCODE</td>
2940 <td>--encoding ENCODE</td>
2935 <td>set the charset encoding (default: ascii)</td></tr>
2941 <td>set the charset encoding (default: ascii)</td></tr>
2936 <tr><td></td>
2942 <tr><td></td>
2937 <td>--encodingmode MODE</td>
2943 <td>--encodingmode MODE</td>
2938 <td>set the charset encoding mode (default: strict)</td></tr>
2944 <td>set the charset encoding mode (default: strict)</td></tr>
2939 <tr><td></td>
2945 <tr><td></td>
2940 <td>--traceback</td>
2946 <td>--traceback</td>
2941 <td>always print a traceback on exception</td></tr>
2947 <td>always print a traceback on exception</td></tr>
2942 <tr><td></td>
2948 <tr><td></td>
2943 <td>--time</td>
2949 <td>--time</td>
2944 <td>time how long the command takes</td></tr>
2950 <td>time how long the command takes</td></tr>
2945 <tr><td></td>
2951 <tr><td></td>
2946 <td>--profile</td>
2952 <td>--profile</td>
2947 <td>print command execution profile</td></tr>
2953 <td>print command execution profile</td></tr>
2948 <tr><td></td>
2954 <tr><td></td>
2949 <td>--version</td>
2955 <td>--version</td>
2950 <td>output version information and exit</td></tr>
2956 <td>output version information and exit</td></tr>
2951 <tr><td>-h</td>
2957 <tr><td>-h</td>
2952 <td>--help</td>
2958 <td>--help</td>
2953 <td>display help and exit</td></tr>
2959 <td>display help and exit</td></tr>
2954 <tr><td></td>
2960 <tr><td></td>
2955 <td>--hidden</td>
2961 <td>--hidden</td>
2956 <td>consider hidden changesets</td></tr>
2962 <td>consider hidden changesets</td></tr>
2957 <tr><td></td>
2963 <tr><td></td>
2958 <td>--pager TYPE</td>
2964 <td>--pager TYPE</td>
2959 <td>when to paginate (boolean, always, auto, or never) (default: auto)</td></tr>
2965 <td>when to paginate (boolean, always, auto, or never) (default: auto)</td></tr>
2960 </table>
2966 </table>
2961
2967
2962 </div>
2968 </div>
2963 </div>
2969 </div>
2964 </div>
2970 </div>
2965
2971
2966
2972
2967
2973
2968 </body>
2974 </body>
2969 </html>
2975 </html>
2970
2976
2971
2977
2972 $ get-with-headers.py $LOCALIP:$HGPORT "help/remove"
2978 $ get-with-headers.py $LOCALIP:$HGPORT "help/remove"
2973 200 Script output follows
2979 200 Script output follows
2974
2980
2975 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
2981 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
2976 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
2982 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
2977 <head>
2983 <head>
2978 <link rel="icon" href="/static/hgicon.png" type="image/png" />
2984 <link rel="icon" href="/static/hgicon.png" type="image/png" />
2979 <meta name="robots" content="index, nofollow" />
2985 <meta name="robots" content="index, nofollow" />
2980 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
2986 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
2981 <script type="text/javascript" src="/static/mercurial.js"></script>
2987 <script type="text/javascript" src="/static/mercurial.js"></script>
2982
2988
2983 <title>Help: remove</title>
2989 <title>Help: remove</title>
2984 </head>
2990 </head>
2985 <body>
2991 <body>
2986
2992
2987 <div class="container">
2993 <div class="container">
2988 <div class="menu">
2994 <div class="menu">
2989 <div class="logo">
2995 <div class="logo">
2990 <a href="https://mercurial-scm.org/">
2996 <a href="https://mercurial-scm.org/">
2991 <img src="/static/hglogo.png" alt="mercurial" /></a>
2997 <img src="/static/hglogo.png" alt="mercurial" /></a>
2992 </div>
2998 </div>
2993 <ul>
2999 <ul>
2994 <li><a href="/shortlog">log</a></li>
3000 <li><a href="/shortlog">log</a></li>
2995 <li><a href="/graph">graph</a></li>
3001 <li><a href="/graph">graph</a></li>
2996 <li><a href="/tags">tags</a></li>
3002 <li><a href="/tags">tags</a></li>
2997 <li><a href="/bookmarks">bookmarks</a></li>
3003 <li><a href="/bookmarks">bookmarks</a></li>
2998 <li><a href="/branches">branches</a></li>
3004 <li><a href="/branches">branches</a></li>
2999 </ul>
3005 </ul>
3000 <ul>
3006 <ul>
3001 <li class="active"><a href="/help">help</a></li>
3007 <li class="active"><a href="/help">help</a></li>
3002 </ul>
3008 </ul>
3003 </div>
3009 </div>
3004
3010
3005 <div class="main">
3011 <div class="main">
3006 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3012 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3007 <h3>Help: remove</h3>
3013 <h3>Help: remove</h3>
3008
3014
3009 <form class="search" action="/log">
3015 <form class="search" action="/log">
3010
3016
3011 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3017 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3012 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3018 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3013 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3019 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3014 </form>
3020 </form>
3015 <div id="doc">
3021 <div id="doc">
3016 <p>
3022 <p>
3017 hg remove [OPTION]... FILE...
3023 hg remove [OPTION]... FILE...
3018 </p>
3024 </p>
3019 <p>
3025 <p>
3020 aliases: rm
3026 aliases: rm
3021 </p>
3027 </p>
3022 <p>
3028 <p>
3023 remove the specified files on the next commit
3029 remove the specified files on the next commit
3024 </p>
3030 </p>
3025 <p>
3031 <p>
3026 Schedule the indicated files for removal from the current branch.
3032 Schedule the indicated files for removal from the current branch.
3027 </p>
3033 </p>
3028 <p>
3034 <p>
3029 This command schedules the files to be removed at the next commit.
3035 This command schedules the files to be removed at the next commit.
3030 To undo a remove before that, see 'hg revert'. To undo added
3036 To undo a remove before that, see 'hg revert'. To undo added
3031 files, see 'hg forget'.
3037 files, see 'hg forget'.
3032 </p>
3038 </p>
3033 <p>
3039 <p>
3034 -A/--after can be used to remove only files that have already
3040 -A/--after can be used to remove only files that have already
3035 been deleted, -f/--force can be used to force deletion, and -Af
3041 been deleted, -f/--force can be used to force deletion, and -Af
3036 can be used to remove files from the next revision without
3042 can be used to remove files from the next revision without
3037 deleting them from the working directory.
3043 deleting them from the working directory.
3038 </p>
3044 </p>
3039 <p>
3045 <p>
3040 The following table details the behavior of remove for different
3046 The following table details the behavior of remove for different
3041 file states (columns) and option combinations (rows). The file
3047 file states (columns) and option combinations (rows). The file
3042 states are Added [A], Clean [C], Modified [M] and Missing [!]
3048 states are Added [A], Clean [C], Modified [M] and Missing [!]
3043 (as reported by 'hg status'). The actions are Warn, Remove
3049 (as reported by 'hg status'). The actions are Warn, Remove
3044 (from branch) and Delete (from disk):
3050 (from branch) and Delete (from disk):
3045 </p>
3051 </p>
3046 <table>
3052 <table>
3047 <tr><td>opt/state</td>
3053 <tr><td>opt/state</td>
3048 <td>A</td>
3054 <td>A</td>
3049 <td>C</td>
3055 <td>C</td>
3050 <td>M</td>
3056 <td>M</td>
3051 <td>!</td></tr>
3057 <td>!</td></tr>
3052 <tr><td>none</td>
3058 <tr><td>none</td>
3053 <td>W</td>
3059 <td>W</td>
3054 <td>RD</td>
3060 <td>RD</td>
3055 <td>W</td>
3061 <td>W</td>
3056 <td>R</td></tr>
3062 <td>R</td></tr>
3057 <tr><td>-f</td>
3063 <tr><td>-f</td>
3058 <td>R</td>
3064 <td>R</td>
3059 <td>RD</td>
3065 <td>RD</td>
3060 <td>RD</td>
3066 <td>RD</td>
3061 <td>R</td></tr>
3067 <td>R</td></tr>
3062 <tr><td>-A</td>
3068 <tr><td>-A</td>
3063 <td>W</td>
3069 <td>W</td>
3064 <td>W</td>
3070 <td>W</td>
3065 <td>W</td>
3071 <td>W</td>
3066 <td>R</td></tr>
3072 <td>R</td></tr>
3067 <tr><td>-Af</td>
3073 <tr><td>-Af</td>
3068 <td>R</td>
3074 <td>R</td>
3069 <td>R</td>
3075 <td>R</td>
3070 <td>R</td>
3076 <td>R</td>
3071 <td>R</td></tr>
3077 <td>R</td></tr>
3072 </table>
3078 </table>
3073 <p>
3079 <p>
3074 <b>Note:</b>
3080 <b>Note:</b>
3075 </p>
3081 </p>
3076 <p>
3082 <p>
3077 'hg remove' never deletes files in Added [A] state from the
3083 'hg remove' never deletes files in Added [A] state from the
3078 working directory, not even if &quot;--force&quot; is specified.
3084 working directory, not even if &quot;--force&quot; is specified.
3079 </p>
3085 </p>
3080 <p>
3086 <p>
3081 Returns 0 on success, 1 if any warnings encountered.
3087 Returns 0 on success, 1 if any warnings encountered.
3082 </p>
3088 </p>
3083 <p>
3089 <p>
3084 options ([+] can be repeated):
3090 options ([+] can be repeated):
3085 </p>
3091 </p>
3086 <table>
3092 <table>
3087 <tr><td>-A</td>
3093 <tr><td>-A</td>
3088 <td>--after</td>
3094 <td>--after</td>
3089 <td>record delete for missing files</td></tr>
3095 <td>record delete for missing files</td></tr>
3090 <tr><td>-f</td>
3096 <tr><td>-f</td>
3091 <td>--force</td>
3097 <td>--force</td>
3092 <td>forget added files, delete modified files</td></tr>
3098 <td>forget added files, delete modified files</td></tr>
3093 <tr><td>-S</td>
3099 <tr><td>-S</td>
3094 <td>--subrepos</td>
3100 <td>--subrepos</td>
3095 <td>recurse into subrepositories</td></tr>
3101 <td>recurse into subrepositories</td></tr>
3096 <tr><td>-I</td>
3102 <tr><td>-I</td>
3097 <td>--include PATTERN [+]</td>
3103 <td>--include PATTERN [+]</td>
3098 <td>include names matching the given patterns</td></tr>
3104 <td>include names matching the given patterns</td></tr>
3099 <tr><td>-X</td>
3105 <tr><td>-X</td>
3100 <td>--exclude PATTERN [+]</td>
3106 <td>--exclude PATTERN [+]</td>
3101 <td>exclude names matching the given patterns</td></tr>
3107 <td>exclude names matching the given patterns</td></tr>
3102 <tr><td>-n</td>
3108 <tr><td>-n</td>
3103 <td>--dry-run</td>
3109 <td>--dry-run</td>
3104 <td>do not perform actions, just print output</td></tr>
3110 <td>do not perform actions, just print output</td></tr>
3105 </table>
3111 </table>
3106 <p>
3112 <p>
3107 global options ([+] can be repeated):
3113 global options ([+] can be repeated):
3108 </p>
3114 </p>
3109 <table>
3115 <table>
3110 <tr><td>-R</td>
3116 <tr><td>-R</td>
3111 <td>--repository REPO</td>
3117 <td>--repository REPO</td>
3112 <td>repository root directory or name of overlay bundle file</td></tr>
3118 <td>repository root directory or name of overlay bundle file</td></tr>
3113 <tr><td></td>
3119 <tr><td></td>
3114 <td>--cwd DIR</td>
3120 <td>--cwd DIR</td>
3115 <td>change working directory</td></tr>
3121 <td>change working directory</td></tr>
3116 <tr><td>-y</td>
3122 <tr><td>-y</td>
3117 <td>--noninteractive</td>
3123 <td>--noninteractive</td>
3118 <td>do not prompt, automatically pick the first choice for all prompts</td></tr>
3124 <td>do not prompt, automatically pick the first choice for all prompts</td></tr>
3119 <tr><td>-q</td>
3125 <tr><td>-q</td>
3120 <td>--quiet</td>
3126 <td>--quiet</td>
3121 <td>suppress output</td></tr>
3127 <td>suppress output</td></tr>
3122 <tr><td>-v</td>
3128 <tr><td>-v</td>
3123 <td>--verbose</td>
3129 <td>--verbose</td>
3124 <td>enable additional output</td></tr>
3130 <td>enable additional output</td></tr>
3125 <tr><td></td>
3131 <tr><td></td>
3126 <td>--color TYPE</td>
3132 <td>--color TYPE</td>
3127 <td>when to colorize (boolean, always, auto, never, or debug)</td></tr>
3133 <td>when to colorize (boolean, always, auto, never, or debug)</td></tr>
3128 <tr><td></td>
3134 <tr><td></td>
3129 <td>--config CONFIG [+]</td>
3135 <td>--config CONFIG [+]</td>
3130 <td>set/override config option (use 'section.name=value')</td></tr>
3136 <td>set/override config option (use 'section.name=value')</td></tr>
3131 <tr><td></td>
3137 <tr><td></td>
3132 <td>--debug</td>
3138 <td>--debug</td>
3133 <td>enable debugging output</td></tr>
3139 <td>enable debugging output</td></tr>
3134 <tr><td></td>
3140 <tr><td></td>
3135 <td>--debugger</td>
3141 <td>--debugger</td>
3136 <td>start debugger</td></tr>
3142 <td>start debugger</td></tr>
3137 <tr><td></td>
3143 <tr><td></td>
3138 <td>--encoding ENCODE</td>
3144 <td>--encoding ENCODE</td>
3139 <td>set the charset encoding (default: ascii)</td></tr>
3145 <td>set the charset encoding (default: ascii)</td></tr>
3140 <tr><td></td>
3146 <tr><td></td>
3141 <td>--encodingmode MODE</td>
3147 <td>--encodingmode MODE</td>
3142 <td>set the charset encoding mode (default: strict)</td></tr>
3148 <td>set the charset encoding mode (default: strict)</td></tr>
3143 <tr><td></td>
3149 <tr><td></td>
3144 <td>--traceback</td>
3150 <td>--traceback</td>
3145 <td>always print a traceback on exception</td></tr>
3151 <td>always print a traceback on exception</td></tr>
3146 <tr><td></td>
3152 <tr><td></td>
3147 <td>--time</td>
3153 <td>--time</td>
3148 <td>time how long the command takes</td></tr>
3154 <td>time how long the command takes</td></tr>
3149 <tr><td></td>
3155 <tr><td></td>
3150 <td>--profile</td>
3156 <td>--profile</td>
3151 <td>print command execution profile</td></tr>
3157 <td>print command execution profile</td></tr>
3152 <tr><td></td>
3158 <tr><td></td>
3153 <td>--version</td>
3159 <td>--version</td>
3154 <td>output version information and exit</td></tr>
3160 <td>output version information and exit</td></tr>
3155 <tr><td>-h</td>
3161 <tr><td>-h</td>
3156 <td>--help</td>
3162 <td>--help</td>
3157 <td>display help and exit</td></tr>
3163 <td>display help and exit</td></tr>
3158 <tr><td></td>
3164 <tr><td></td>
3159 <td>--hidden</td>
3165 <td>--hidden</td>
3160 <td>consider hidden changesets</td></tr>
3166 <td>consider hidden changesets</td></tr>
3161 <tr><td></td>
3167 <tr><td></td>
3162 <td>--pager TYPE</td>
3168 <td>--pager TYPE</td>
3163 <td>when to paginate (boolean, always, auto, or never) (default: auto)</td></tr>
3169 <td>when to paginate (boolean, always, auto, or never) (default: auto)</td></tr>
3164 </table>
3170 </table>
3165
3171
3166 </div>
3172 </div>
3167 </div>
3173 </div>
3168 </div>
3174 </div>
3169
3175
3170
3176
3171
3177
3172 </body>
3178 </body>
3173 </html>
3179 </html>
3174
3180
3175
3181
3176 $ get-with-headers.py $LOCALIP:$HGPORT "help/dates"
3182 $ get-with-headers.py $LOCALIP:$HGPORT "help/dates"
3177 200 Script output follows
3183 200 Script output follows
3178
3184
3179 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3185 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3180 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3186 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3181 <head>
3187 <head>
3182 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3188 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3183 <meta name="robots" content="index, nofollow" />
3189 <meta name="robots" content="index, nofollow" />
3184 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3190 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3185 <script type="text/javascript" src="/static/mercurial.js"></script>
3191 <script type="text/javascript" src="/static/mercurial.js"></script>
3186
3192
3187 <title>Help: dates</title>
3193 <title>Help: dates</title>
3188 </head>
3194 </head>
3189 <body>
3195 <body>
3190
3196
3191 <div class="container">
3197 <div class="container">
3192 <div class="menu">
3198 <div class="menu">
3193 <div class="logo">
3199 <div class="logo">
3194 <a href="https://mercurial-scm.org/">
3200 <a href="https://mercurial-scm.org/">
3195 <img src="/static/hglogo.png" alt="mercurial" /></a>
3201 <img src="/static/hglogo.png" alt="mercurial" /></a>
3196 </div>
3202 </div>
3197 <ul>
3203 <ul>
3198 <li><a href="/shortlog">log</a></li>
3204 <li><a href="/shortlog">log</a></li>
3199 <li><a href="/graph">graph</a></li>
3205 <li><a href="/graph">graph</a></li>
3200 <li><a href="/tags">tags</a></li>
3206 <li><a href="/tags">tags</a></li>
3201 <li><a href="/bookmarks">bookmarks</a></li>
3207 <li><a href="/bookmarks">bookmarks</a></li>
3202 <li><a href="/branches">branches</a></li>
3208 <li><a href="/branches">branches</a></li>
3203 </ul>
3209 </ul>
3204 <ul>
3210 <ul>
3205 <li class="active"><a href="/help">help</a></li>
3211 <li class="active"><a href="/help">help</a></li>
3206 </ul>
3212 </ul>
3207 </div>
3213 </div>
3208
3214
3209 <div class="main">
3215 <div class="main">
3210 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3216 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3211 <h3>Help: dates</h3>
3217 <h3>Help: dates</h3>
3212
3218
3213 <form class="search" action="/log">
3219 <form class="search" action="/log">
3214
3220
3215 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3221 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3216 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3222 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3217 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3223 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3218 </form>
3224 </form>
3219 <div id="doc">
3225 <div id="doc">
3220 <h1>Date Formats</h1>
3226 <h1>Date Formats</h1>
3221 <p>
3227 <p>
3222 Some commands allow the user to specify a date, e.g.:
3228 Some commands allow the user to specify a date, e.g.:
3223 </p>
3229 </p>
3224 <ul>
3230 <ul>
3225 <li> backout, commit, import, tag: Specify the commit date.
3231 <li> backout, commit, import, tag: Specify the commit date.
3226 <li> log, revert, update: Select revision(s) by date.
3232 <li> log, revert, update: Select revision(s) by date.
3227 </ul>
3233 </ul>
3228 <p>
3234 <p>
3229 Many date formats are valid. Here are some examples:
3235 Many date formats are valid. Here are some examples:
3230 </p>
3236 </p>
3231 <ul>
3237 <ul>
3232 <li> &quot;Wed Dec 6 13:18:29 2006&quot; (local timezone assumed)
3238 <li> &quot;Wed Dec 6 13:18:29 2006&quot; (local timezone assumed)
3233 <li> &quot;Dec 6 13:18 -0600&quot; (year assumed, time offset provided)
3239 <li> &quot;Dec 6 13:18 -0600&quot; (year assumed, time offset provided)
3234 <li> &quot;Dec 6 13:18 UTC&quot; (UTC and GMT are aliases for +0000)
3240 <li> &quot;Dec 6 13:18 UTC&quot; (UTC and GMT are aliases for +0000)
3235 <li> &quot;Dec 6&quot; (midnight)
3241 <li> &quot;Dec 6&quot; (midnight)
3236 <li> &quot;13:18&quot; (today assumed)
3242 <li> &quot;13:18&quot; (today assumed)
3237 <li> &quot;3:39&quot; (3:39AM assumed)
3243 <li> &quot;3:39&quot; (3:39AM assumed)
3238 <li> &quot;3:39pm&quot; (15:39)
3244 <li> &quot;3:39pm&quot; (15:39)
3239 <li> &quot;2006-12-06 13:18:29&quot; (ISO 8601 format)
3245 <li> &quot;2006-12-06 13:18:29&quot; (ISO 8601 format)
3240 <li> &quot;2006-12-6 13:18&quot;
3246 <li> &quot;2006-12-6 13:18&quot;
3241 <li> &quot;2006-12-6&quot;
3247 <li> &quot;2006-12-6&quot;
3242 <li> &quot;12-6&quot;
3248 <li> &quot;12-6&quot;
3243 <li> &quot;12/6&quot;
3249 <li> &quot;12/6&quot;
3244 <li> &quot;12/6/6&quot; (Dec 6 2006)
3250 <li> &quot;12/6/6&quot; (Dec 6 2006)
3245 <li> &quot;today&quot; (midnight)
3251 <li> &quot;today&quot; (midnight)
3246 <li> &quot;yesterday&quot; (midnight)
3252 <li> &quot;yesterday&quot; (midnight)
3247 <li> &quot;now&quot; - right now
3253 <li> &quot;now&quot; - right now
3248 </ul>
3254 </ul>
3249 <p>
3255 <p>
3250 Lastly, there is Mercurial's internal format:
3256 Lastly, there is Mercurial's internal format:
3251 </p>
3257 </p>
3252 <ul>
3258 <ul>
3253 <li> &quot;1165411109 0&quot; (Wed Dec 6 13:18:29 2006 UTC)
3259 <li> &quot;1165411109 0&quot; (Wed Dec 6 13:18:29 2006 UTC)
3254 </ul>
3260 </ul>
3255 <p>
3261 <p>
3256 This is the internal representation format for dates. The first number
3262 This is the internal representation format for dates. The first number
3257 is the number of seconds since the epoch (1970-01-01 00:00 UTC). The
3263 is the number of seconds since the epoch (1970-01-01 00:00 UTC). The
3258 second is the offset of the local timezone, in seconds west of UTC
3264 second is the offset of the local timezone, in seconds west of UTC
3259 (negative if the timezone is east of UTC).
3265 (negative if the timezone is east of UTC).
3260 </p>
3266 </p>
3261 <p>
3267 <p>
3262 The log command also accepts date ranges:
3268 The log command also accepts date ranges:
3263 </p>
3269 </p>
3264 <ul>
3270 <ul>
3265 <li> &quot;&lt;DATE&quot; - at or before a given date/time
3271 <li> &quot;&lt;DATE&quot; - at or before a given date/time
3266 <li> &quot;&gt;DATE&quot; - on or after a given date/time
3272 <li> &quot;&gt;DATE&quot; - on or after a given date/time
3267 <li> &quot;DATE to DATE&quot; - a date range, inclusive
3273 <li> &quot;DATE to DATE&quot; - a date range, inclusive
3268 <li> &quot;-DAYS&quot; - within a given number of days of today
3274 <li> &quot;-DAYS&quot; - within a given number of days of today
3269 </ul>
3275 </ul>
3270
3276
3271 </div>
3277 </div>
3272 </div>
3278 </div>
3273 </div>
3279 </div>
3274
3280
3275
3281
3276
3282
3277 </body>
3283 </body>
3278 </html>
3284 </html>
3279
3285
3280
3286
3281 $ get-with-headers.py $LOCALIP:$HGPORT "help/pager"
3287 $ get-with-headers.py $LOCALIP:$HGPORT "help/pager"
3282 200 Script output follows
3288 200 Script output follows
3283
3289
3284 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3290 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3285 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3291 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3286 <head>
3292 <head>
3287 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3293 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3288 <meta name="robots" content="index, nofollow" />
3294 <meta name="robots" content="index, nofollow" />
3289 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3295 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3290 <script type="text/javascript" src="/static/mercurial.js"></script>
3296 <script type="text/javascript" src="/static/mercurial.js"></script>
3291
3297
3292 <title>Help: pager</title>
3298 <title>Help: pager</title>
3293 </head>
3299 </head>
3294 <body>
3300 <body>
3295
3301
3296 <div class="container">
3302 <div class="container">
3297 <div class="menu">
3303 <div class="menu">
3298 <div class="logo">
3304 <div class="logo">
3299 <a href="https://mercurial-scm.org/">
3305 <a href="https://mercurial-scm.org/">
3300 <img src="/static/hglogo.png" alt="mercurial" /></a>
3306 <img src="/static/hglogo.png" alt="mercurial" /></a>
3301 </div>
3307 </div>
3302 <ul>
3308 <ul>
3303 <li><a href="/shortlog">log</a></li>
3309 <li><a href="/shortlog">log</a></li>
3304 <li><a href="/graph">graph</a></li>
3310 <li><a href="/graph">graph</a></li>
3305 <li><a href="/tags">tags</a></li>
3311 <li><a href="/tags">tags</a></li>
3306 <li><a href="/bookmarks">bookmarks</a></li>
3312 <li><a href="/bookmarks">bookmarks</a></li>
3307 <li><a href="/branches">branches</a></li>
3313 <li><a href="/branches">branches</a></li>
3308 </ul>
3314 </ul>
3309 <ul>
3315 <ul>
3310 <li class="active"><a href="/help">help</a></li>
3316 <li class="active"><a href="/help">help</a></li>
3311 </ul>
3317 </ul>
3312 </div>
3318 </div>
3313
3319
3314 <div class="main">
3320 <div class="main">
3315 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3321 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3316 <h3>Help: pager</h3>
3322 <h3>Help: pager</h3>
3317
3323
3318 <form class="search" action="/log">
3324 <form class="search" action="/log">
3319
3325
3320 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3326 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3321 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3327 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3322 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3328 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3323 </form>
3329 </form>
3324 <div id="doc">
3330 <div id="doc">
3325 <h1>Pager Support</h1>
3331 <h1>Pager Support</h1>
3326 <p>
3332 <p>
3327 Some Mercurial commands can produce a lot of output, and Mercurial will
3333 Some Mercurial commands can produce a lot of output, and Mercurial will
3328 attempt to use a pager to make those commands more pleasant.
3334 attempt to use a pager to make those commands more pleasant.
3329 </p>
3335 </p>
3330 <p>
3336 <p>
3331 To set the pager that should be used, set the application variable:
3337 To set the pager that should be used, set the application variable:
3332 </p>
3338 </p>
3333 <pre>
3339 <pre>
3334 [pager]
3340 [pager]
3335 pager = less -FRX
3341 pager = less -FRX
3336 </pre>
3342 </pre>
3337 <p>
3343 <p>
3338 If no pager is set in the user or repository configuration, Mercurial uses the
3344 If no pager is set in the user or repository configuration, Mercurial uses the
3339 environment variable $PAGER. If $PAGER is not set, pager.pager from the default
3345 environment variable $PAGER. If $PAGER is not set, pager.pager from the default
3340 or system configuration is used. If none of these are set, a default pager will
3346 or system configuration is used. If none of these are set, a default pager will
3341 be used, typically 'less' on Unix and 'more' on Windows.
3347 be used, typically 'less' on Unix and 'more' on Windows.
3342 </p>
3348 </p>
3343 <p>
3349 <p>
3344 You can disable the pager for certain commands by adding them to the
3350 You can disable the pager for certain commands by adding them to the
3345 pager.ignore list:
3351 pager.ignore list:
3346 </p>
3352 </p>
3347 <pre>
3353 <pre>
3348 [pager]
3354 [pager]
3349 ignore = version, help, update
3355 ignore = version, help, update
3350 </pre>
3356 </pre>
3351 <p>
3357 <p>
3352 To ignore global commands like 'hg version' or 'hg help', you have
3358 To ignore global commands like 'hg version' or 'hg help', you have
3353 to specify them in your user configuration file.
3359 to specify them in your user configuration file.
3354 </p>
3360 </p>
3355 <p>
3361 <p>
3356 To control whether the pager is used at all for an individual command,
3362 To control whether the pager is used at all for an individual command,
3357 you can use --pager=&lt;value&gt;:
3363 you can use --pager=&lt;value&gt;:
3358 </p>
3364 </p>
3359 <ul>
3365 <ul>
3360 <li> use as needed: 'auto'.
3366 <li> use as needed: 'auto'.
3361 <li> require the pager: 'yes' or 'on'.
3367 <li> require the pager: 'yes' or 'on'.
3362 <li> suppress the pager: 'no' or 'off' (any unrecognized value will also work).
3368 <li> suppress the pager: 'no' or 'off' (any unrecognized value will also work).
3363 </ul>
3369 </ul>
3364 <p>
3370 <p>
3365 To globally turn off all attempts to use a pager, set:
3371 To globally turn off all attempts to use a pager, set:
3366 </p>
3372 </p>
3367 <pre>
3373 <pre>
3368 [ui]
3374 [ui]
3369 paginate = never
3375 paginate = never
3370 </pre>
3376 </pre>
3371 <p>
3377 <p>
3372 which will prevent the pager from running.
3378 which will prevent the pager from running.
3373 </p>
3379 </p>
3374
3380
3375 </div>
3381 </div>
3376 </div>
3382 </div>
3377 </div>
3383 </div>
3378
3384
3379
3385
3380
3386
3381 </body>
3387 </body>
3382 </html>
3388 </html>
3383
3389
3384
3390
3385 Sub-topic indexes rendered properly
3391 Sub-topic indexes rendered properly
3386
3392
3387 $ get-with-headers.py $LOCALIP:$HGPORT "help/internals"
3393 $ get-with-headers.py $LOCALIP:$HGPORT "help/internals"
3388 200 Script output follows
3394 200 Script output follows
3389
3395
3390 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3396 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3391 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3397 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3392 <head>
3398 <head>
3393 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3399 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3394 <meta name="robots" content="index, nofollow" />
3400 <meta name="robots" content="index, nofollow" />
3395 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3401 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3396 <script type="text/javascript" src="/static/mercurial.js"></script>
3402 <script type="text/javascript" src="/static/mercurial.js"></script>
3397
3403
3398 <title>Help: internals</title>
3404 <title>Help: internals</title>
3399 </head>
3405 </head>
3400 <body>
3406 <body>
3401
3407
3402 <div class="container">
3408 <div class="container">
3403 <div class="menu">
3409 <div class="menu">
3404 <div class="logo">
3410 <div class="logo">
3405 <a href="https://mercurial-scm.org/">
3411 <a href="https://mercurial-scm.org/">
3406 <img src="/static/hglogo.png" alt="mercurial" /></a>
3412 <img src="/static/hglogo.png" alt="mercurial" /></a>
3407 </div>
3413 </div>
3408 <ul>
3414 <ul>
3409 <li><a href="/shortlog">log</a></li>
3415 <li><a href="/shortlog">log</a></li>
3410 <li><a href="/graph">graph</a></li>
3416 <li><a href="/graph">graph</a></li>
3411 <li><a href="/tags">tags</a></li>
3417 <li><a href="/tags">tags</a></li>
3412 <li><a href="/bookmarks">bookmarks</a></li>
3418 <li><a href="/bookmarks">bookmarks</a></li>
3413 <li><a href="/branches">branches</a></li>
3419 <li><a href="/branches">branches</a></li>
3414 </ul>
3420 </ul>
3415 <ul>
3421 <ul>
3416 <li><a href="/help">help</a></li>
3422 <li><a href="/help">help</a></li>
3417 </ul>
3423 </ul>
3418 </div>
3424 </div>
3419
3425
3420 <div class="main">
3426 <div class="main">
3421 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3427 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3422
3428
3423 <form class="search" action="/log">
3429 <form class="search" action="/log">
3424
3430
3425 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3431 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3426 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3432 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3427 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3433 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3428 </form>
3434 </form>
3429 <table class="bigtable">
3435 <table class="bigtable">
3430 <tr><td colspan="2"><h2><a name="topics" href="#topics">Topics</a></h2></td></tr>
3436 <tr><td colspan="2"><h2><a name="topics" href="#topics">Topics</a></h2></td></tr>
3431
3437
3432 <tr><td>
3438 <tr><td>
3433 <a href="/help/internals.bundle2">
3439 <a href="/help/internals.bundle2">
3434 bundle2
3440 bundle2
3435 </a>
3441 </a>
3436 </td><td>
3442 </td><td>
3437 Bundle2
3443 Bundle2
3438 </td></tr>
3444 </td></tr>
3439 <tr><td>
3445 <tr><td>
3440 <a href="/help/internals.bundles">
3446 <a href="/help/internals.bundles">
3441 bundles
3447 bundles
3442 </a>
3448 </a>
3443 </td><td>
3449 </td><td>
3444 Bundles
3450 Bundles
3445 </td></tr>
3451 </td></tr>
3446 <tr><td>
3452 <tr><td>
3447 <a href="/help/internals.cbor">
3453 <a href="/help/internals.cbor">
3448 cbor
3454 cbor
3449 </a>
3455 </a>
3450 </td><td>
3456 </td><td>
3451 CBOR
3457 CBOR
3452 </td></tr>
3458 </td></tr>
3453 <tr><td>
3459 <tr><td>
3454 <a href="/help/internals.censor">
3460 <a href="/help/internals.censor">
3455 censor
3461 censor
3456 </a>
3462 </a>
3457 </td><td>
3463 </td><td>
3458 Censor
3464 Censor
3459 </td></tr>
3465 </td></tr>
3460 <tr><td>
3466 <tr><td>
3461 <a href="/help/internals.changegroups">
3467 <a href="/help/internals.changegroups">
3462 changegroups
3468 changegroups
3463 </a>
3469 </a>
3464 </td><td>
3470 </td><td>
3465 Changegroups
3471 Changegroups
3466 </td></tr>
3472 </td></tr>
3467 <tr><td>
3473 <tr><td>
3468 <a href="/help/internals.config">
3474 <a href="/help/internals.config">
3469 config
3475 config
3470 </a>
3476 </a>
3471 </td><td>
3477 </td><td>
3472 Config Registrar
3478 Config Registrar
3473 </td></tr>
3479 </td></tr>
3474 <tr><td>
3480 <tr><td>
3475 <a href="/help/internals.extensions">
3481 <a href="/help/internals.extensions">
3476 extensions
3482 extensions
3477 </a>
3483 </a>
3478 </td><td>
3484 </td><td>
3479 Extension API
3485 Extension API
3480 </td></tr>
3486 </td></tr>
3481 <tr><td>
3487 <tr><td>
3482 <a href="/help/internals.mergestate">
3488 <a href="/help/internals.mergestate">
3483 mergestate
3489 mergestate
3484 </a>
3490 </a>
3485 </td><td>
3491 </td><td>
3486 Mergestate
3492 Mergestate
3487 </td></tr>
3493 </td></tr>
3488 <tr><td>
3494 <tr><td>
3489 <a href="/help/internals.requirements">
3495 <a href="/help/internals.requirements">
3490 requirements
3496 requirements
3491 </a>
3497 </a>
3492 </td><td>
3498 </td><td>
3493 Repository Requirements
3499 Repository Requirements
3494 </td></tr>
3500 </td></tr>
3495 <tr><td>
3501 <tr><td>
3496 <a href="/help/internals.revlogs">
3502 <a href="/help/internals.revlogs">
3497 revlogs
3503 revlogs
3498 </a>
3504 </a>
3499 </td><td>
3505 </td><td>
3500 Revision Logs
3506 Revision Logs
3501 </td></tr>
3507 </td></tr>
3502 <tr><td>
3508 <tr><td>
3503 <a href="/help/internals.wireprotocol">
3509 <a href="/help/internals.wireprotocol">
3504 wireprotocol
3510 wireprotocol
3505 </a>
3511 </a>
3506 </td><td>
3512 </td><td>
3507 Wire Protocol
3513 Wire Protocol
3508 </td></tr>
3514 </td></tr>
3509 <tr><td>
3515 <tr><td>
3510 <a href="/help/internals.wireprotocolrpc">
3516 <a href="/help/internals.wireprotocolrpc">
3511 wireprotocolrpc
3517 wireprotocolrpc
3512 </a>
3518 </a>
3513 </td><td>
3519 </td><td>
3514 Wire Protocol RPC
3520 Wire Protocol RPC
3515 </td></tr>
3521 </td></tr>
3516 <tr><td>
3522 <tr><td>
3517 <a href="/help/internals.wireprotocolv2">
3523 <a href="/help/internals.wireprotocolv2">
3518 wireprotocolv2
3524 wireprotocolv2
3519 </a>
3525 </a>
3520 </td><td>
3526 </td><td>
3521 Wire Protocol Version 2
3527 Wire Protocol Version 2
3522 </td></tr>
3528 </td></tr>
3523
3529
3524
3530
3525
3531
3526
3532
3527
3533
3528 </table>
3534 </table>
3529 </div>
3535 </div>
3530 </div>
3536 </div>
3531
3537
3532
3538
3533
3539
3534 </body>
3540 </body>
3535 </html>
3541 </html>
3536
3542
3537
3543
3538 Sub-topic topics rendered properly
3544 Sub-topic topics rendered properly
3539
3545
3540 $ get-with-headers.py $LOCALIP:$HGPORT "help/internals.changegroups"
3546 $ get-with-headers.py $LOCALIP:$HGPORT "help/internals.changegroups"
3541 200 Script output follows
3547 200 Script output follows
3542
3548
3543 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3549 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3544 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3550 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3545 <head>
3551 <head>
3546 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3552 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3547 <meta name="robots" content="index, nofollow" />
3553 <meta name="robots" content="index, nofollow" />
3548 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3554 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3549 <script type="text/javascript" src="/static/mercurial.js"></script>
3555 <script type="text/javascript" src="/static/mercurial.js"></script>
3550
3556
3551 <title>Help: internals.changegroups</title>
3557 <title>Help: internals.changegroups</title>
3552 </head>
3558 </head>
3553 <body>
3559 <body>
3554
3560
3555 <div class="container">
3561 <div class="container">
3556 <div class="menu">
3562 <div class="menu">
3557 <div class="logo">
3563 <div class="logo">
3558 <a href="https://mercurial-scm.org/">
3564 <a href="https://mercurial-scm.org/">
3559 <img src="/static/hglogo.png" alt="mercurial" /></a>
3565 <img src="/static/hglogo.png" alt="mercurial" /></a>
3560 </div>
3566 </div>
3561 <ul>
3567 <ul>
3562 <li><a href="/shortlog">log</a></li>
3568 <li><a href="/shortlog">log</a></li>
3563 <li><a href="/graph">graph</a></li>
3569 <li><a href="/graph">graph</a></li>
3564 <li><a href="/tags">tags</a></li>
3570 <li><a href="/tags">tags</a></li>
3565 <li><a href="/bookmarks">bookmarks</a></li>
3571 <li><a href="/bookmarks">bookmarks</a></li>
3566 <li><a href="/branches">branches</a></li>
3572 <li><a href="/branches">branches</a></li>
3567 </ul>
3573 </ul>
3568 <ul>
3574 <ul>
3569 <li class="active"><a href="/help">help</a></li>
3575 <li class="active"><a href="/help">help</a></li>
3570 </ul>
3576 </ul>
3571 </div>
3577 </div>
3572
3578
3573 <div class="main">
3579 <div class="main">
3574 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3580 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3575 <h3>Help: internals.changegroups</h3>
3581 <h3>Help: internals.changegroups</h3>
3576
3582
3577 <form class="search" action="/log">
3583 <form class="search" action="/log">
3578
3584
3579 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3585 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3580 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3586 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3581 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3587 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3582 </form>
3588 </form>
3583 <div id="doc">
3589 <div id="doc">
3584 <h1>Changegroups</h1>
3590 <h1>Changegroups</h1>
3585 <p>
3591 <p>
3586 Changegroups are representations of repository revlog data, specifically
3592 Changegroups are representations of repository revlog data, specifically
3587 the changelog data, root/flat manifest data, treemanifest data, and
3593 the changelog data, root/flat manifest data, treemanifest data, and
3588 filelogs.
3594 filelogs.
3589 </p>
3595 </p>
3590 <p>
3596 <p>
3591 There are 3 versions of changegroups: &quot;1&quot;, &quot;2&quot;, and &quot;3&quot;. From a
3597 There are 3 versions of changegroups: &quot;1&quot;, &quot;2&quot;, and &quot;3&quot;. From a
3592 high-level, versions &quot;1&quot; and &quot;2&quot; are almost exactly the same, with the
3598 high-level, versions &quot;1&quot; and &quot;2&quot; are almost exactly the same, with the
3593 only difference being an additional item in the *delta header*. Version
3599 only difference being an additional item in the *delta header*. Version
3594 &quot;3&quot; adds support for storage flags in the *delta header* and optionally
3600 &quot;3&quot; adds support for storage flags in the *delta header* and optionally
3595 exchanging treemanifests (enabled by setting an option on the
3601 exchanging treemanifests (enabled by setting an option on the
3596 &quot;changegroup&quot; part in the bundle2).
3602 &quot;changegroup&quot; part in the bundle2).
3597 </p>
3603 </p>
3598 <p>
3604 <p>
3599 Changegroups when not exchanging treemanifests consist of 3 logical
3605 Changegroups when not exchanging treemanifests consist of 3 logical
3600 segments:
3606 segments:
3601 </p>
3607 </p>
3602 <pre>
3608 <pre>
3603 +---------------------------------+
3609 +---------------------------------+
3604 | | | |
3610 | | | |
3605 | changeset | manifest | filelogs |
3611 | changeset | manifest | filelogs |
3606 | | | |
3612 | | | |
3607 | | | |
3613 | | | |
3608 +---------------------------------+
3614 +---------------------------------+
3609 </pre>
3615 </pre>
3610 <p>
3616 <p>
3611 When exchanging treemanifests, there are 4 logical segments:
3617 When exchanging treemanifests, there are 4 logical segments:
3612 </p>
3618 </p>
3613 <pre>
3619 <pre>
3614 +-------------------------------------------------+
3620 +-------------------------------------------------+
3615 | | | | |
3621 | | | | |
3616 | changeset | root | treemanifests | filelogs |
3622 | changeset | root | treemanifests | filelogs |
3617 | | manifest | | |
3623 | | manifest | | |
3618 | | | | |
3624 | | | | |
3619 +-------------------------------------------------+
3625 +-------------------------------------------------+
3620 </pre>
3626 </pre>
3621 <p>
3627 <p>
3622 The principle building block of each segment is a *chunk*. A *chunk*
3628 The principle building block of each segment is a *chunk*. A *chunk*
3623 is a framed piece of data:
3629 is a framed piece of data:
3624 </p>
3630 </p>
3625 <pre>
3631 <pre>
3626 +---------------------------------------+
3632 +---------------------------------------+
3627 | | |
3633 | | |
3628 | length | data |
3634 | length | data |
3629 | (4 bytes) | (&lt;length - 4&gt; bytes) |
3635 | (4 bytes) | (&lt;length - 4&gt; bytes) |
3630 | | |
3636 | | |
3631 +---------------------------------------+
3637 +---------------------------------------+
3632 </pre>
3638 </pre>
3633 <p>
3639 <p>
3634 All integers are big-endian signed integers. Each chunk starts with a 32-bit
3640 All integers are big-endian signed integers. Each chunk starts with a 32-bit
3635 integer indicating the length of the entire chunk (including the length field
3641 integer indicating the length of the entire chunk (including the length field
3636 itself).
3642 itself).
3637 </p>
3643 </p>
3638 <p>
3644 <p>
3639 There is a special case chunk that has a value of 0 for the length
3645 There is a special case chunk that has a value of 0 for the length
3640 (&quot;0x00000000&quot;). We call this an *empty chunk*.
3646 (&quot;0x00000000&quot;). We call this an *empty chunk*.
3641 </p>
3647 </p>
3642 <h2>Delta Groups</h2>
3648 <h2>Delta Groups</h2>
3643 <p>
3649 <p>
3644 A *delta group* expresses the content of a revlog as a series of deltas,
3650 A *delta group* expresses the content of a revlog as a series of deltas,
3645 or patches against previous revisions.
3651 or patches against previous revisions.
3646 </p>
3652 </p>
3647 <p>
3653 <p>
3648 Delta groups consist of 0 or more *chunks* followed by the *empty chunk*
3654 Delta groups consist of 0 or more *chunks* followed by the *empty chunk*
3649 to signal the end of the delta group:
3655 to signal the end of the delta group:
3650 </p>
3656 </p>
3651 <pre>
3657 <pre>
3652 +------------------------------------------------------------------------+
3658 +------------------------------------------------------------------------+
3653 | | | | | |
3659 | | | | | |
3654 | chunk0 length | chunk0 data | chunk1 length | chunk1 data | 0x0 |
3660 | chunk0 length | chunk0 data | chunk1 length | chunk1 data | 0x0 |
3655 | (4 bytes) | (various) | (4 bytes) | (various) | (4 bytes) |
3661 | (4 bytes) | (various) | (4 bytes) | (various) | (4 bytes) |
3656 | | | | | |
3662 | | | | | |
3657 +------------------------------------------------------------------------+
3663 +------------------------------------------------------------------------+
3658 </pre>
3664 </pre>
3659 <p>
3665 <p>
3660 Each *chunk*'s data consists of the following:
3666 Each *chunk*'s data consists of the following:
3661 </p>
3667 </p>
3662 <pre>
3668 <pre>
3663 +---------------------------------------+
3669 +---------------------------------------+
3664 | | |
3670 | | |
3665 | delta header | delta data |
3671 | delta header | delta data |
3666 | (various by version) | (various) |
3672 | (various by version) | (various) |
3667 | | |
3673 | | |
3668 +---------------------------------------+
3674 +---------------------------------------+
3669 </pre>
3675 </pre>
3670 <p>
3676 <p>
3671 The *delta data* is a series of *delta*s that describe a diff from an existing
3677 The *delta data* is a series of *delta*s that describe a diff from an existing
3672 entry (either that the recipient already has, or previously specified in the
3678 entry (either that the recipient already has, or previously specified in the
3673 bundle/changegroup).
3679 bundle/changegroup).
3674 </p>
3680 </p>
3675 <p>
3681 <p>
3676 The *delta header* is different between versions &quot;1&quot;, &quot;2&quot;, and
3682 The *delta header* is different between versions &quot;1&quot;, &quot;2&quot;, and
3677 &quot;3&quot; of the changegroup format.
3683 &quot;3&quot; of the changegroup format.
3678 </p>
3684 </p>
3679 <p>
3685 <p>
3680 Version 1 (headerlen=80):
3686 Version 1 (headerlen=80):
3681 </p>
3687 </p>
3682 <pre>
3688 <pre>
3683 +------------------------------------------------------+
3689 +------------------------------------------------------+
3684 | | | | |
3690 | | | | |
3685 | node | p1 node | p2 node | link node |
3691 | node | p1 node | p2 node | link node |
3686 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
3692 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
3687 | | | | |
3693 | | | | |
3688 +------------------------------------------------------+
3694 +------------------------------------------------------+
3689 </pre>
3695 </pre>
3690 <p>
3696 <p>
3691 Version 2 (headerlen=100):
3697 Version 2 (headerlen=100):
3692 </p>
3698 </p>
3693 <pre>
3699 <pre>
3694 +------------------------------------------------------------------+
3700 +------------------------------------------------------------------+
3695 | | | | | |
3701 | | | | | |
3696 | node | p1 node | p2 node | base node | link node |
3702 | node | p1 node | p2 node | base node | link node |
3697 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
3703 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
3698 | | | | | |
3704 | | | | | |
3699 +------------------------------------------------------------------+
3705 +------------------------------------------------------------------+
3700 </pre>
3706 </pre>
3701 <p>
3707 <p>
3702 Version 3 (headerlen=102):
3708 Version 3 (headerlen=102):
3703 </p>
3709 </p>
3704 <pre>
3710 <pre>
3705 +------------------------------------------------------------------------------+
3711 +------------------------------------------------------------------------------+
3706 | | | | | | |
3712 | | | | | | |
3707 | node | p1 node | p2 node | base node | link node | flags |
3713 | node | p1 node | p2 node | base node | link node | flags |
3708 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (2 bytes) |
3714 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (2 bytes) |
3709 | | | | | | |
3715 | | | | | | |
3710 +------------------------------------------------------------------------------+
3716 +------------------------------------------------------------------------------+
3711 </pre>
3717 </pre>
3712 <p>
3718 <p>
3713 The *delta data* consists of &quot;chunklen - 4 - headerlen&quot; bytes, which contain a
3719 The *delta data* consists of &quot;chunklen - 4 - headerlen&quot; bytes, which contain a
3714 series of *delta*s, densely packed (no separators). These deltas describe a diff
3720 series of *delta*s, densely packed (no separators). These deltas describe a diff
3715 from an existing entry (either that the recipient already has, or previously
3721 from an existing entry (either that the recipient already has, or previously
3716 specified in the bundle/changegroup). The format is described more fully in
3722 specified in the bundle/changegroup). The format is described more fully in
3717 &quot;hg help internals.bdiff&quot;, but briefly:
3723 &quot;hg help internals.bdiff&quot;, but briefly:
3718 </p>
3724 </p>
3719 <pre>
3725 <pre>
3720 +---------------------------------------------------------------+
3726 +---------------------------------------------------------------+
3721 | | | | |
3727 | | | | |
3722 | start offset | end offset | new length | content |
3728 | start offset | end offset | new length | content |
3723 | (4 bytes) | (4 bytes) | (4 bytes) | (&lt;new length&gt; bytes) |
3729 | (4 bytes) | (4 bytes) | (4 bytes) | (&lt;new length&gt; bytes) |
3724 | | | | |
3730 | | | | |
3725 +---------------------------------------------------------------+
3731 +---------------------------------------------------------------+
3726 </pre>
3732 </pre>
3727 <p>
3733 <p>
3728 Please note that the length field in the delta data does *not* include itself.
3734 Please note that the length field in the delta data does *not* include itself.
3729 </p>
3735 </p>
3730 <p>
3736 <p>
3731 In version 1, the delta is always applied against the previous node from
3737 In version 1, the delta is always applied against the previous node from
3732 the changegroup or the first parent if this is the first entry in the
3738 the changegroup or the first parent if this is the first entry in the
3733 changegroup.
3739 changegroup.
3734 </p>
3740 </p>
3735 <p>
3741 <p>
3736 In version 2 and up, the delta base node is encoded in the entry in the
3742 In version 2 and up, the delta base node is encoded in the entry in the
3737 changegroup. This allows the delta to be expressed against any parent,
3743 changegroup. This allows the delta to be expressed against any parent,
3738 which can result in smaller deltas and more efficient encoding of data.
3744 which can result in smaller deltas and more efficient encoding of data.
3739 </p>
3745 </p>
3740 <p>
3746 <p>
3741 The *flags* field holds bitwise flags affecting the processing of revision
3747 The *flags* field holds bitwise flags affecting the processing of revision
3742 data. The following flags are defined:
3748 data. The following flags are defined:
3743 </p>
3749 </p>
3744 <dl>
3750 <dl>
3745 <dt>32768
3751 <dt>32768
3746 <dd>Censored revision. The revision's fulltext has been replaced by censor metadata. May only occur on file revisions.
3752 <dd>Censored revision. The revision's fulltext has been replaced by censor metadata. May only occur on file revisions.
3747 <dt>16384
3753 <dt>16384
3748 <dd>Ellipsis revision. Revision hash does not match data (likely due to rewritten parents).
3754 <dd>Ellipsis revision. Revision hash does not match data (likely due to rewritten parents).
3749 <dt>8192
3755 <dt>8192
3750 <dd>Externally stored. The revision fulltext contains &quot;key:value&quot; &quot;\n&quot; delimited metadata defining an object stored elsewhere. Used by the LFS extension.
3756 <dd>Externally stored. The revision fulltext contains &quot;key:value&quot; &quot;\n&quot; delimited metadata defining an object stored elsewhere. Used by the LFS extension.
3751 </dl>
3757 </dl>
3752 <p>
3758 <p>
3753 For historical reasons, the integer values are identical to revlog version 1
3759 For historical reasons, the integer values are identical to revlog version 1
3754 per-revision storage flags and correspond to bits being set in this 2-byte
3760 per-revision storage flags and correspond to bits being set in this 2-byte
3755 field. Bits were allocated starting from the most-significant bit, hence the
3761 field. Bits were allocated starting from the most-significant bit, hence the
3756 reverse ordering and allocation of these flags.
3762 reverse ordering and allocation of these flags.
3757 </p>
3763 </p>
3758 <h2>Changeset Segment</h2>
3764 <h2>Changeset Segment</h2>
3759 <p>
3765 <p>
3760 The *changeset segment* consists of a single *delta group* holding
3766 The *changeset segment* consists of a single *delta group* holding
3761 changelog data. The *empty chunk* at the end of the *delta group* denotes
3767 changelog data. The *empty chunk* at the end of the *delta group* denotes
3762 the boundary to the *manifest segment*.
3768 the boundary to the *manifest segment*.
3763 </p>
3769 </p>
3764 <h2>Manifest Segment</h2>
3770 <h2>Manifest Segment</h2>
3765 <p>
3771 <p>
3766 The *manifest segment* consists of a single *delta group* holding manifest
3772 The *manifest segment* consists of a single *delta group* holding manifest
3767 data. If treemanifests are in use, it contains only the manifest for the
3773 data. If treemanifests are in use, it contains only the manifest for the
3768 root directory of the repository. Otherwise, it contains the entire
3774 root directory of the repository. Otherwise, it contains the entire
3769 manifest data. The *empty chunk* at the end of the *delta group* denotes
3775 manifest data. The *empty chunk* at the end of the *delta group* denotes
3770 the boundary to the next segment (either the *treemanifests segment* or the
3776 the boundary to the next segment (either the *treemanifests segment* or the
3771 *filelogs segment*, depending on version and the request options).
3777 *filelogs segment*, depending on version and the request options).
3772 </p>
3778 </p>
3773 <h3>Treemanifests Segment</h3>
3779 <h3>Treemanifests Segment</h3>
3774 <p>
3780 <p>
3775 The *treemanifests segment* only exists in changegroup version &quot;3&quot;, and
3781 The *treemanifests segment* only exists in changegroup version &quot;3&quot;, and
3776 only if the 'treemanifest' param is part of the bundle2 changegroup part
3782 only if the 'treemanifest' param is part of the bundle2 changegroup part
3777 (it is not possible to use changegroup version 3 outside of bundle2).
3783 (it is not possible to use changegroup version 3 outside of bundle2).
3778 Aside from the filenames in the *treemanifests segment* containing a
3784 Aside from the filenames in the *treemanifests segment* containing a
3779 trailing &quot;/&quot; character, it behaves identically to the *filelogs segment*
3785 trailing &quot;/&quot; character, it behaves identically to the *filelogs segment*
3780 (see below). The final sub-segment is followed by an *empty chunk* (logically,
3786 (see below). The final sub-segment is followed by an *empty chunk* (logically,
3781 a sub-segment with filename size 0). This denotes the boundary to the
3787 a sub-segment with filename size 0). This denotes the boundary to the
3782 *filelogs segment*.
3788 *filelogs segment*.
3783 </p>
3789 </p>
3784 <h2>Filelogs Segment</h2>
3790 <h2>Filelogs Segment</h2>
3785 <p>
3791 <p>
3786 The *filelogs segment* consists of multiple sub-segments, each
3792 The *filelogs segment* consists of multiple sub-segments, each
3787 corresponding to an individual file whose data is being described:
3793 corresponding to an individual file whose data is being described:
3788 </p>
3794 </p>
3789 <pre>
3795 <pre>
3790 +--------------------------------------------------+
3796 +--------------------------------------------------+
3791 | | | | | |
3797 | | | | | |
3792 | filelog0 | filelog1 | filelog2 | ... | 0x0 |
3798 | filelog0 | filelog1 | filelog2 | ... | 0x0 |
3793 | | | | | (4 bytes) |
3799 | | | | | (4 bytes) |
3794 | | | | | |
3800 | | | | | |
3795 +--------------------------------------------------+
3801 +--------------------------------------------------+
3796 </pre>
3802 </pre>
3797 <p>
3803 <p>
3798 The final filelog sub-segment is followed by an *empty chunk* (logically,
3804 The final filelog sub-segment is followed by an *empty chunk* (logically,
3799 a sub-segment with filename size 0). This denotes the end of the segment
3805 a sub-segment with filename size 0). This denotes the end of the segment
3800 and of the overall changegroup.
3806 and of the overall changegroup.
3801 </p>
3807 </p>
3802 <p>
3808 <p>
3803 Each filelog sub-segment consists of the following:
3809 Each filelog sub-segment consists of the following:
3804 </p>
3810 </p>
3805 <pre>
3811 <pre>
3806 +------------------------------------------------------+
3812 +------------------------------------------------------+
3807 | | | |
3813 | | | |
3808 | filename length | filename | delta group |
3814 | filename length | filename | delta group |
3809 | (4 bytes) | (&lt;length - 4&gt; bytes) | (various) |
3815 | (4 bytes) | (&lt;length - 4&gt; bytes) | (various) |
3810 | | | |
3816 | | | |
3811 +------------------------------------------------------+
3817 +------------------------------------------------------+
3812 </pre>
3818 </pre>
3813 <p>
3819 <p>
3814 That is, a *chunk* consisting of the filename (not terminated or padded)
3820 That is, a *chunk* consisting of the filename (not terminated or padded)
3815 followed by N chunks constituting the *delta group* for this file. The
3821 followed by N chunks constituting the *delta group* for this file. The
3816 *empty chunk* at the end of each *delta group* denotes the boundary to the
3822 *empty chunk* at the end of each *delta group* denotes the boundary to the
3817 next filelog sub-segment.
3823 next filelog sub-segment.
3818 </p>
3824 </p>
3819
3825
3820 </div>
3826 </div>
3821 </div>
3827 </div>
3822 </div>
3828 </div>
3823
3829
3824
3830
3825
3831
3826 </body>
3832 </body>
3827 </html>
3833 </html>
3828
3834
3829
3835
3830 $ get-with-headers.py 127.0.0.1:$HGPORT "help/unknowntopic"
3836 $ get-with-headers.py 127.0.0.1:$HGPORT "help/unknowntopic"
3831 404 Not Found
3837 404 Not Found
3832
3838
3833 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3839 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3834 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3840 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3835 <head>
3841 <head>
3836 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3842 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3837 <meta name="robots" content="index, nofollow" />
3843 <meta name="robots" content="index, nofollow" />
3838 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3844 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3839 <script type="text/javascript" src="/static/mercurial.js"></script>
3845 <script type="text/javascript" src="/static/mercurial.js"></script>
3840
3846
3841 <title>test: error</title>
3847 <title>test: error</title>
3842 </head>
3848 </head>
3843 <body>
3849 <body>
3844
3850
3845 <div class="container">
3851 <div class="container">
3846 <div class="menu">
3852 <div class="menu">
3847 <div class="logo">
3853 <div class="logo">
3848 <a href="https://mercurial-scm.org/">
3854 <a href="https://mercurial-scm.org/">
3849 <img src="/static/hglogo.png" width=75 height=90 border=0 alt="mercurial" /></a>
3855 <img src="/static/hglogo.png" width=75 height=90 border=0 alt="mercurial" /></a>
3850 </div>
3856 </div>
3851 <ul>
3857 <ul>
3852 <li><a href="/shortlog">log</a></li>
3858 <li><a href="/shortlog">log</a></li>
3853 <li><a href="/graph">graph</a></li>
3859 <li><a href="/graph">graph</a></li>
3854 <li><a href="/tags">tags</a></li>
3860 <li><a href="/tags">tags</a></li>
3855 <li><a href="/bookmarks">bookmarks</a></li>
3861 <li><a href="/bookmarks">bookmarks</a></li>
3856 <li><a href="/branches">branches</a></li>
3862 <li><a href="/branches">branches</a></li>
3857 </ul>
3863 </ul>
3858 <ul>
3864 <ul>
3859 <li><a href="/help">help</a></li>
3865 <li><a href="/help">help</a></li>
3860 </ul>
3866 </ul>
3861 </div>
3867 </div>
3862
3868
3863 <div class="main">
3869 <div class="main">
3864
3870
3865 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3871 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3866 <h3>error</h3>
3872 <h3>error</h3>
3867
3873
3868
3874
3869 <form class="search" action="/log">
3875 <form class="search" action="/log">
3870
3876
3871 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3877 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3872 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3878 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3873 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3879 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3874 </form>
3880 </form>
3875
3881
3876 <div class="description">
3882 <div class="description">
3877 <p>
3883 <p>
3878 An error occurred while processing your request:
3884 An error occurred while processing your request:
3879 </p>
3885 </p>
3880 <p>
3886 <p>
3881 Not Found
3887 Not Found
3882 </p>
3888 </p>
3883 </div>
3889 </div>
3884 </div>
3890 </div>
3885 </div>
3891 </div>
3886
3892
3887
3893
3888
3894
3889 </body>
3895 </body>
3890 </html>
3896 </html>
3891
3897
3892 [1]
3898 [1]
3893
3899
3894 $ killdaemons.py
3900 $ killdaemons.py
3895
3901
3896 #endif
3902 #endif
General Comments 0
You need to be logged in to leave comments. Login now