##// END OF EJS Templates
bundle: add an experimental knob to include obsmarkers in bundle...
marmoute -
r32516:37d70ba1 default
parent child Browse files
Show More
@@ -1,1748 +1,1755 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 from __future__ import absolute_import
148 from __future__ import absolute_import
149
149
150 import errno
150 import errno
151 import re
151 import re
152 import string
152 import string
153 import struct
153 import struct
154 import sys
154 import sys
155
155
156 from .i18n import _
156 from .i18n import _
157 from . import (
157 from . import (
158 changegroup,
158 changegroup,
159 error,
159 error,
160 obsolete,
160 obsolete,
161 pushkey,
161 pushkey,
162 pycompat,
162 pycompat,
163 tags,
163 tags,
164 url,
164 url,
165 util,
165 util,
166 )
166 )
167
167
168 urlerr = util.urlerr
168 urlerr = util.urlerr
169 urlreq = util.urlreq
169 urlreq = util.urlreq
170
170
171 _pack = struct.pack
171 _pack = struct.pack
172 _unpack = struct.unpack
172 _unpack = struct.unpack
173
173
174 _fstreamparamsize = '>i'
174 _fstreamparamsize = '>i'
175 _fpartheadersize = '>i'
175 _fpartheadersize = '>i'
176 _fparttypesize = '>B'
176 _fparttypesize = '>B'
177 _fpartid = '>I'
177 _fpartid = '>I'
178 _fpayloadsize = '>i'
178 _fpayloadsize = '>i'
179 _fpartparamcount = '>BB'
179 _fpartparamcount = '>BB'
180
180
181 preferedchunksize = 4096
181 preferedchunksize = 4096
182
182
183 _parttypeforbidden = re.compile('[^a-zA-Z0-9_:-]')
183 _parttypeforbidden = re.compile('[^a-zA-Z0-9_:-]')
184
184
185 def outdebug(ui, message):
185 def outdebug(ui, message):
186 """debug regarding output stream (bundling)"""
186 """debug regarding output stream (bundling)"""
187 if ui.configbool('devel', 'bundle2.debug', False):
187 if ui.configbool('devel', 'bundle2.debug', False):
188 ui.debug('bundle2-output: %s\n' % message)
188 ui.debug('bundle2-output: %s\n' % message)
189
189
190 def indebug(ui, message):
190 def indebug(ui, message):
191 """debug on input stream (unbundling)"""
191 """debug on input stream (unbundling)"""
192 if ui.configbool('devel', 'bundle2.debug', False):
192 if ui.configbool('devel', 'bundle2.debug', False):
193 ui.debug('bundle2-input: %s\n' % message)
193 ui.debug('bundle2-input: %s\n' % message)
194
194
195 def validateparttype(parttype):
195 def validateparttype(parttype):
196 """raise ValueError if a parttype contains invalid character"""
196 """raise ValueError if a parttype contains invalid character"""
197 if _parttypeforbidden.search(parttype):
197 if _parttypeforbidden.search(parttype):
198 raise ValueError(parttype)
198 raise ValueError(parttype)
199
199
200 def _makefpartparamsizes(nbparams):
200 def _makefpartparamsizes(nbparams):
201 """return a struct format to read part parameter sizes
201 """return a struct format to read part parameter sizes
202
202
203 The number parameters is variable so we need to build that format
203 The number parameters is variable so we need to build that format
204 dynamically.
204 dynamically.
205 """
205 """
206 return '>'+('BB'*nbparams)
206 return '>'+('BB'*nbparams)
207
207
208 parthandlermapping = {}
208 parthandlermapping = {}
209
209
210 def parthandler(parttype, params=()):
210 def parthandler(parttype, params=()):
211 """decorator that register a function as a bundle2 part handler
211 """decorator that register a function as a bundle2 part handler
212
212
213 eg::
213 eg::
214
214
215 @parthandler('myparttype', ('mandatory', 'param', 'handled'))
215 @parthandler('myparttype', ('mandatory', 'param', 'handled'))
216 def myparttypehandler(...):
216 def myparttypehandler(...):
217 '''process a part of type "my part".'''
217 '''process a part of type "my part".'''
218 ...
218 ...
219 """
219 """
220 validateparttype(parttype)
220 validateparttype(parttype)
221 def _decorator(func):
221 def _decorator(func):
222 lparttype = parttype.lower() # enforce lower case matching.
222 lparttype = parttype.lower() # enforce lower case matching.
223 assert lparttype not in parthandlermapping
223 assert lparttype not in parthandlermapping
224 parthandlermapping[lparttype] = func
224 parthandlermapping[lparttype] = func
225 func.params = frozenset(params)
225 func.params = frozenset(params)
226 return func
226 return func
227 return _decorator
227 return _decorator
228
228
229 class unbundlerecords(object):
229 class unbundlerecords(object):
230 """keep record of what happens during and unbundle
230 """keep record of what happens during and unbundle
231
231
232 New records are added using `records.add('cat', obj)`. Where 'cat' is a
232 New records are added using `records.add('cat', obj)`. Where 'cat' is a
233 category of record and obj is an arbitrary object.
233 category of record and obj is an arbitrary object.
234
234
235 `records['cat']` will return all entries of this category 'cat'.
235 `records['cat']` will return all entries of this category 'cat'.
236
236
237 Iterating on the object itself will yield `('category', obj)` tuples
237 Iterating on the object itself will yield `('category', obj)` tuples
238 for all entries.
238 for all entries.
239
239
240 All iterations happens in chronological order.
240 All iterations happens in chronological order.
241 """
241 """
242
242
243 def __init__(self):
243 def __init__(self):
244 self._categories = {}
244 self._categories = {}
245 self._sequences = []
245 self._sequences = []
246 self._replies = {}
246 self._replies = {}
247
247
248 def add(self, category, entry, inreplyto=None):
248 def add(self, category, entry, inreplyto=None):
249 """add a new record of a given category.
249 """add a new record of a given category.
250
250
251 The entry can then be retrieved in the list returned by
251 The entry can then be retrieved in the list returned by
252 self['category']."""
252 self['category']."""
253 self._categories.setdefault(category, []).append(entry)
253 self._categories.setdefault(category, []).append(entry)
254 self._sequences.append((category, entry))
254 self._sequences.append((category, entry))
255 if inreplyto is not None:
255 if inreplyto is not None:
256 self.getreplies(inreplyto).add(category, entry)
256 self.getreplies(inreplyto).add(category, entry)
257
257
258 def getreplies(self, partid):
258 def getreplies(self, partid):
259 """get the records that are replies to a specific part"""
259 """get the records that are replies to a specific part"""
260 return self._replies.setdefault(partid, unbundlerecords())
260 return self._replies.setdefault(partid, unbundlerecords())
261
261
262 def __getitem__(self, cat):
262 def __getitem__(self, cat):
263 return tuple(self._categories.get(cat, ()))
263 return tuple(self._categories.get(cat, ()))
264
264
265 def __iter__(self):
265 def __iter__(self):
266 return iter(self._sequences)
266 return iter(self._sequences)
267
267
268 def __len__(self):
268 def __len__(self):
269 return len(self._sequences)
269 return len(self._sequences)
270
270
271 def __nonzero__(self):
271 def __nonzero__(self):
272 return bool(self._sequences)
272 return bool(self._sequences)
273
273
274 __bool__ = __nonzero__
274 __bool__ = __nonzero__
275
275
276 class bundleoperation(object):
276 class bundleoperation(object):
277 """an object that represents a single bundling process
277 """an object that represents a single bundling process
278
278
279 Its purpose is to carry unbundle-related objects and states.
279 Its purpose is to carry unbundle-related objects and states.
280
280
281 A new object should be created at the beginning of each bundle processing.
281 A new object should be created at the beginning of each bundle processing.
282 The object is to be returned by the processing function.
282 The object is to be returned by the processing function.
283
283
284 The object has very little content now it will ultimately contain:
284 The object has very little content now it will ultimately contain:
285 * an access to the repo the bundle is applied to,
285 * an access to the repo the bundle is applied to,
286 * a ui object,
286 * a ui object,
287 * a way to retrieve a transaction to add changes to the repo,
287 * a way to retrieve a transaction to add changes to the repo,
288 * a way to record the result of processing each part,
288 * a way to record the result of processing each part,
289 * a way to construct a bundle response when applicable.
289 * a way to construct a bundle response when applicable.
290 """
290 """
291
291
292 def __init__(self, repo, transactiongetter, captureoutput=True):
292 def __init__(self, repo, transactiongetter, captureoutput=True):
293 self.repo = repo
293 self.repo = repo
294 self.ui = repo.ui
294 self.ui = repo.ui
295 self.records = unbundlerecords()
295 self.records = unbundlerecords()
296 self.gettransaction = transactiongetter
296 self.gettransaction = transactiongetter
297 self.reply = None
297 self.reply = None
298 self.captureoutput = captureoutput
298 self.captureoutput = captureoutput
299
299
300 class TransactionUnavailable(RuntimeError):
300 class TransactionUnavailable(RuntimeError):
301 pass
301 pass
302
302
303 def _notransaction():
303 def _notransaction():
304 """default method to get a transaction while processing a bundle
304 """default method to get a transaction while processing a bundle
305
305
306 Raise an exception to highlight the fact that no transaction was expected
306 Raise an exception to highlight the fact that no transaction was expected
307 to be created"""
307 to be created"""
308 raise TransactionUnavailable()
308 raise TransactionUnavailable()
309
309
310 def applybundle(repo, unbundler, tr, source=None, url=None, op=None):
310 def applybundle(repo, unbundler, tr, source=None, url=None, op=None):
311 # transform me into unbundler.apply() as soon as the freeze is lifted
311 # transform me into unbundler.apply() as soon as the freeze is lifted
312 tr.hookargs['bundle2'] = '1'
312 tr.hookargs['bundle2'] = '1'
313 if source is not None and 'source' not in tr.hookargs:
313 if source is not None and 'source' not in tr.hookargs:
314 tr.hookargs['source'] = source
314 tr.hookargs['source'] = source
315 if url is not None and 'url' not in tr.hookargs:
315 if url is not None and 'url' not in tr.hookargs:
316 tr.hookargs['url'] = url
316 tr.hookargs['url'] = url
317 return processbundle(repo, unbundler, lambda: tr, op=op)
317 return processbundle(repo, unbundler, lambda: tr, op=op)
318
318
319 def processbundle(repo, unbundler, transactiongetter=None, op=None):
319 def processbundle(repo, unbundler, transactiongetter=None, op=None):
320 """This function process a bundle, apply effect to/from a repo
320 """This function process a bundle, apply effect to/from a repo
321
321
322 It iterates over each part then searches for and uses the proper handling
322 It iterates over each part then searches for and uses the proper handling
323 code to process the part. Parts are processed in order.
323 code to process the part. Parts are processed in order.
324
324
325 Unknown Mandatory part will abort the process.
325 Unknown Mandatory part will abort the process.
326
326
327 It is temporarily possible to provide a prebuilt bundleoperation to the
327 It is temporarily possible to provide a prebuilt bundleoperation to the
328 function. This is used to ensure output is properly propagated in case of
328 function. This is used to ensure output is properly propagated in case of
329 an error during the unbundling. This output capturing part will likely be
329 an error during the unbundling. This output capturing part will likely be
330 reworked and this ability will probably go away in the process.
330 reworked and this ability will probably go away in the process.
331 """
331 """
332 if op is None:
332 if op is None:
333 if transactiongetter is None:
333 if transactiongetter is None:
334 transactiongetter = _notransaction
334 transactiongetter = _notransaction
335 op = bundleoperation(repo, transactiongetter)
335 op = bundleoperation(repo, transactiongetter)
336 # todo:
336 # todo:
337 # - replace this is a init function soon.
337 # - replace this is a init function soon.
338 # - exception catching
338 # - exception catching
339 unbundler.params
339 unbundler.params
340 if repo.ui.debugflag:
340 if repo.ui.debugflag:
341 msg = ['bundle2-input-bundle:']
341 msg = ['bundle2-input-bundle:']
342 if unbundler.params:
342 if unbundler.params:
343 msg.append(' %i params')
343 msg.append(' %i params')
344 if op.gettransaction is None:
344 if op.gettransaction is None:
345 msg.append(' no-transaction')
345 msg.append(' no-transaction')
346 else:
346 else:
347 msg.append(' with-transaction')
347 msg.append(' with-transaction')
348 msg.append('\n')
348 msg.append('\n')
349 repo.ui.debug(''.join(msg))
349 repo.ui.debug(''.join(msg))
350 iterparts = enumerate(unbundler.iterparts())
350 iterparts = enumerate(unbundler.iterparts())
351 part = None
351 part = None
352 nbpart = 0
352 nbpart = 0
353 try:
353 try:
354 for nbpart, part in iterparts:
354 for nbpart, part in iterparts:
355 _processpart(op, part)
355 _processpart(op, part)
356 except Exception as exc:
356 except Exception as exc:
357 # Any exceptions seeking to the end of the bundle at this point are
357 # Any exceptions seeking to the end of the bundle at this point are
358 # almost certainly related to the underlying stream being bad.
358 # almost certainly related to the underlying stream being bad.
359 # And, chances are that the exception we're handling is related to
359 # And, chances are that the exception we're handling is related to
360 # getting in that bad state. So, we swallow the seeking error and
360 # getting in that bad state. So, we swallow the seeking error and
361 # re-raise the original error.
361 # re-raise the original error.
362 seekerror = False
362 seekerror = False
363 try:
363 try:
364 for nbpart, part in iterparts:
364 for nbpart, part in iterparts:
365 # consume the bundle content
365 # consume the bundle content
366 part.seek(0, 2)
366 part.seek(0, 2)
367 except Exception:
367 except Exception:
368 seekerror = True
368 seekerror = True
369
369
370 # Small hack to let caller code distinguish exceptions from bundle2
370 # Small hack to let caller code distinguish exceptions from bundle2
371 # processing from processing the old format. This is mostly
371 # processing from processing the old format. This is mostly
372 # needed to handle different return codes to unbundle according to the
372 # needed to handle different return codes to unbundle according to the
373 # type of bundle. We should probably clean up or drop this return code
373 # type of bundle. We should probably clean up or drop this return code
374 # craziness in a future version.
374 # craziness in a future version.
375 exc.duringunbundle2 = True
375 exc.duringunbundle2 = True
376 salvaged = []
376 salvaged = []
377 replycaps = None
377 replycaps = None
378 if op.reply is not None:
378 if op.reply is not None:
379 salvaged = op.reply.salvageoutput()
379 salvaged = op.reply.salvageoutput()
380 replycaps = op.reply.capabilities
380 replycaps = op.reply.capabilities
381 exc._replycaps = replycaps
381 exc._replycaps = replycaps
382 exc._bundle2salvagedoutput = salvaged
382 exc._bundle2salvagedoutput = salvaged
383
383
384 # Re-raising from a variable loses the original stack. So only use
384 # Re-raising from a variable loses the original stack. So only use
385 # that form if we need to.
385 # that form if we need to.
386 if seekerror:
386 if seekerror:
387 raise exc
387 raise exc
388 else:
388 else:
389 raise
389 raise
390 finally:
390 finally:
391 repo.ui.debug('bundle2-input-bundle: %i parts total\n' % nbpart)
391 repo.ui.debug('bundle2-input-bundle: %i parts total\n' % nbpart)
392
392
393 return op
393 return op
394
394
395 def _processpart(op, part):
395 def _processpart(op, part):
396 """process a single part from a bundle
396 """process a single part from a bundle
397
397
398 The part is guaranteed to have been fully consumed when the function exits
398 The part is guaranteed to have been fully consumed when the function exits
399 (even if an exception is raised)."""
399 (even if an exception is raised)."""
400 status = 'unknown' # used by debug output
400 status = 'unknown' # used by debug output
401 hardabort = False
401 hardabort = False
402 try:
402 try:
403 try:
403 try:
404 handler = parthandlermapping.get(part.type)
404 handler = parthandlermapping.get(part.type)
405 if handler is None:
405 if handler is None:
406 status = 'unsupported-type'
406 status = 'unsupported-type'
407 raise error.BundleUnknownFeatureError(parttype=part.type)
407 raise error.BundleUnknownFeatureError(parttype=part.type)
408 indebug(op.ui, 'found a handler for part %r' % part.type)
408 indebug(op.ui, 'found a handler for part %r' % part.type)
409 unknownparams = part.mandatorykeys - handler.params
409 unknownparams = part.mandatorykeys - handler.params
410 if unknownparams:
410 if unknownparams:
411 unknownparams = list(unknownparams)
411 unknownparams = list(unknownparams)
412 unknownparams.sort()
412 unknownparams.sort()
413 status = 'unsupported-params (%s)' % unknownparams
413 status = 'unsupported-params (%s)' % unknownparams
414 raise error.BundleUnknownFeatureError(parttype=part.type,
414 raise error.BundleUnknownFeatureError(parttype=part.type,
415 params=unknownparams)
415 params=unknownparams)
416 status = 'supported'
416 status = 'supported'
417 except error.BundleUnknownFeatureError as exc:
417 except error.BundleUnknownFeatureError as exc:
418 if part.mandatory: # mandatory parts
418 if part.mandatory: # mandatory parts
419 raise
419 raise
420 indebug(op.ui, 'ignoring unsupported advisory part %s' % exc)
420 indebug(op.ui, 'ignoring unsupported advisory part %s' % exc)
421 return # skip to part processing
421 return # skip to part processing
422 finally:
422 finally:
423 if op.ui.debugflag:
423 if op.ui.debugflag:
424 msg = ['bundle2-input-part: "%s"' % part.type]
424 msg = ['bundle2-input-part: "%s"' % part.type]
425 if not part.mandatory:
425 if not part.mandatory:
426 msg.append(' (advisory)')
426 msg.append(' (advisory)')
427 nbmp = len(part.mandatorykeys)
427 nbmp = len(part.mandatorykeys)
428 nbap = len(part.params) - nbmp
428 nbap = len(part.params) - nbmp
429 if nbmp or nbap:
429 if nbmp or nbap:
430 msg.append(' (params:')
430 msg.append(' (params:')
431 if nbmp:
431 if nbmp:
432 msg.append(' %i mandatory' % nbmp)
432 msg.append(' %i mandatory' % nbmp)
433 if nbap:
433 if nbap:
434 msg.append(' %i advisory' % nbmp)
434 msg.append(' %i advisory' % nbmp)
435 msg.append(')')
435 msg.append(')')
436 msg.append(' %s\n' % status)
436 msg.append(' %s\n' % status)
437 op.ui.debug(''.join(msg))
437 op.ui.debug(''.join(msg))
438
438
439 # handler is called outside the above try block so that we don't
439 # handler is called outside the above try block so that we don't
440 # risk catching KeyErrors from anything other than the
440 # risk catching KeyErrors from anything other than the
441 # parthandlermapping lookup (any KeyError raised by handler()
441 # parthandlermapping lookup (any KeyError raised by handler()
442 # itself represents a defect of a different variety).
442 # itself represents a defect of a different variety).
443 output = None
443 output = None
444 if op.captureoutput and op.reply is not None:
444 if op.captureoutput and op.reply is not None:
445 op.ui.pushbuffer(error=True, subproc=True)
445 op.ui.pushbuffer(error=True, subproc=True)
446 output = ''
446 output = ''
447 try:
447 try:
448 handler(op, part)
448 handler(op, part)
449 finally:
449 finally:
450 if output is not None:
450 if output is not None:
451 output = op.ui.popbuffer()
451 output = op.ui.popbuffer()
452 if output:
452 if output:
453 outpart = op.reply.newpart('output', data=output,
453 outpart = op.reply.newpart('output', data=output,
454 mandatory=False)
454 mandatory=False)
455 outpart.addparam('in-reply-to', str(part.id), mandatory=False)
455 outpart.addparam('in-reply-to', str(part.id), mandatory=False)
456 # If exiting or interrupted, do not attempt to seek the stream in the
456 # If exiting or interrupted, do not attempt to seek the stream in the
457 # finally block below. This makes abort faster.
457 # finally block below. This makes abort faster.
458 except (SystemExit, KeyboardInterrupt):
458 except (SystemExit, KeyboardInterrupt):
459 hardabort = True
459 hardabort = True
460 raise
460 raise
461 finally:
461 finally:
462 # consume the part content to not corrupt the stream.
462 # consume the part content to not corrupt the stream.
463 if not hardabort:
463 if not hardabort:
464 part.seek(0, 2)
464 part.seek(0, 2)
465
465
466
466
467 def decodecaps(blob):
467 def decodecaps(blob):
468 """decode a bundle2 caps bytes blob into a dictionary
468 """decode a bundle2 caps bytes blob into a dictionary
469
469
470 The blob is a list of capabilities (one per line)
470 The blob is a list of capabilities (one per line)
471 Capabilities may have values using a line of the form::
471 Capabilities may have values using a line of the form::
472
472
473 capability=value1,value2,value3
473 capability=value1,value2,value3
474
474
475 The values are always a list."""
475 The values are always a list."""
476 caps = {}
476 caps = {}
477 for line in blob.splitlines():
477 for line in blob.splitlines():
478 if not line:
478 if not line:
479 continue
479 continue
480 if '=' not in line:
480 if '=' not in line:
481 key, vals = line, ()
481 key, vals = line, ()
482 else:
482 else:
483 key, vals = line.split('=', 1)
483 key, vals = line.split('=', 1)
484 vals = vals.split(',')
484 vals = vals.split(',')
485 key = urlreq.unquote(key)
485 key = urlreq.unquote(key)
486 vals = [urlreq.unquote(v) for v in vals]
486 vals = [urlreq.unquote(v) for v in vals]
487 caps[key] = vals
487 caps[key] = vals
488 return caps
488 return caps
489
489
490 def encodecaps(caps):
490 def encodecaps(caps):
491 """encode a bundle2 caps dictionary into a bytes blob"""
491 """encode a bundle2 caps dictionary into a bytes blob"""
492 chunks = []
492 chunks = []
493 for ca in sorted(caps):
493 for ca in sorted(caps):
494 vals = caps[ca]
494 vals = caps[ca]
495 ca = urlreq.quote(ca)
495 ca = urlreq.quote(ca)
496 vals = [urlreq.quote(v) for v in vals]
496 vals = [urlreq.quote(v) for v in vals]
497 if vals:
497 if vals:
498 ca = "%s=%s" % (ca, ','.join(vals))
498 ca = "%s=%s" % (ca, ','.join(vals))
499 chunks.append(ca)
499 chunks.append(ca)
500 return '\n'.join(chunks)
500 return '\n'.join(chunks)
501
501
502 bundletypes = {
502 bundletypes = {
503 "": ("", 'UN'), # only when using unbundle on ssh and old http servers
503 "": ("", 'UN'), # only when using unbundle on ssh and old http servers
504 # since the unification ssh accepts a header but there
504 # since the unification ssh accepts a header but there
505 # is no capability signaling it.
505 # is no capability signaling it.
506 "HG20": (), # special-cased below
506 "HG20": (), # special-cased below
507 "HG10UN": ("HG10UN", 'UN'),
507 "HG10UN": ("HG10UN", 'UN'),
508 "HG10BZ": ("HG10", 'BZ'),
508 "HG10BZ": ("HG10", 'BZ'),
509 "HG10GZ": ("HG10GZ", 'GZ'),
509 "HG10GZ": ("HG10GZ", 'GZ'),
510 }
510 }
511
511
512 # hgweb uses this list to communicate its preferred type
512 # hgweb uses this list to communicate its preferred type
513 bundlepriority = ['HG10GZ', 'HG10BZ', 'HG10UN']
513 bundlepriority = ['HG10GZ', 'HG10BZ', 'HG10UN']
514
514
515 class bundle20(object):
515 class bundle20(object):
516 """represent an outgoing bundle2 container
516 """represent an outgoing bundle2 container
517
517
518 Use the `addparam` method to add stream level parameter. and `newpart` to
518 Use the `addparam` method to add stream level parameter. and `newpart` to
519 populate it. Then call `getchunks` to retrieve all the binary chunks of
519 populate it. Then call `getchunks` to retrieve all the binary chunks of
520 data that compose the bundle2 container."""
520 data that compose the bundle2 container."""
521
521
522 _magicstring = 'HG20'
522 _magicstring = 'HG20'
523
523
524 def __init__(self, ui, capabilities=()):
524 def __init__(self, ui, capabilities=()):
525 self.ui = ui
525 self.ui = ui
526 self._params = []
526 self._params = []
527 self._parts = []
527 self._parts = []
528 self.capabilities = dict(capabilities)
528 self.capabilities = dict(capabilities)
529 self._compengine = util.compengines.forbundletype('UN')
529 self._compengine = util.compengines.forbundletype('UN')
530 self._compopts = None
530 self._compopts = None
531
531
532 def setcompression(self, alg, compopts=None):
532 def setcompression(self, alg, compopts=None):
533 """setup core part compression to <alg>"""
533 """setup core part compression to <alg>"""
534 if alg in (None, 'UN'):
534 if alg in (None, 'UN'):
535 return
535 return
536 assert not any(n.lower() == 'compression' for n, v in self._params)
536 assert not any(n.lower() == 'compression' for n, v in self._params)
537 self.addparam('Compression', alg)
537 self.addparam('Compression', alg)
538 self._compengine = util.compengines.forbundletype(alg)
538 self._compengine = util.compengines.forbundletype(alg)
539 self._compopts = compopts
539 self._compopts = compopts
540
540
541 @property
541 @property
542 def nbparts(self):
542 def nbparts(self):
543 """total number of parts added to the bundler"""
543 """total number of parts added to the bundler"""
544 return len(self._parts)
544 return len(self._parts)
545
545
546 # methods used to defines the bundle2 content
546 # methods used to defines the bundle2 content
547 def addparam(self, name, value=None):
547 def addparam(self, name, value=None):
548 """add a stream level parameter"""
548 """add a stream level parameter"""
549 if not name:
549 if not name:
550 raise ValueError('empty parameter name')
550 raise ValueError('empty parameter name')
551 if name[0] not in string.letters:
551 if name[0] not in string.letters:
552 raise ValueError('non letter first character: %r' % name)
552 raise ValueError('non letter first character: %r' % name)
553 self._params.append((name, value))
553 self._params.append((name, value))
554
554
555 def addpart(self, part):
555 def addpart(self, part):
556 """add a new part to the bundle2 container
556 """add a new part to the bundle2 container
557
557
558 Parts contains the actual applicative payload."""
558 Parts contains the actual applicative payload."""
559 assert part.id is None
559 assert part.id is None
560 part.id = len(self._parts) # very cheap counter
560 part.id = len(self._parts) # very cheap counter
561 self._parts.append(part)
561 self._parts.append(part)
562
562
563 def newpart(self, typeid, *args, **kwargs):
563 def newpart(self, typeid, *args, **kwargs):
564 """create a new part and add it to the containers
564 """create a new part and add it to the containers
565
565
566 As the part is directly added to the containers. For now, this means
566 As the part is directly added to the containers. For now, this means
567 that any failure to properly initialize the part after calling
567 that any failure to properly initialize the part after calling
568 ``newpart`` should result in a failure of the whole bundling process.
568 ``newpart`` should result in a failure of the whole bundling process.
569
569
570 You can still fall back to manually create and add if you need better
570 You can still fall back to manually create and add if you need better
571 control."""
571 control."""
572 part = bundlepart(typeid, *args, **kwargs)
572 part = bundlepart(typeid, *args, **kwargs)
573 self.addpart(part)
573 self.addpart(part)
574 return part
574 return part
575
575
576 # methods used to generate the bundle2 stream
576 # methods used to generate the bundle2 stream
577 def getchunks(self):
577 def getchunks(self):
578 if self.ui.debugflag:
578 if self.ui.debugflag:
579 msg = ['bundle2-output-bundle: "%s",' % self._magicstring]
579 msg = ['bundle2-output-bundle: "%s",' % self._magicstring]
580 if self._params:
580 if self._params:
581 msg.append(' (%i params)' % len(self._params))
581 msg.append(' (%i params)' % len(self._params))
582 msg.append(' %i parts total\n' % len(self._parts))
582 msg.append(' %i parts total\n' % len(self._parts))
583 self.ui.debug(''.join(msg))
583 self.ui.debug(''.join(msg))
584 outdebug(self.ui, 'start emission of %s stream' % self._magicstring)
584 outdebug(self.ui, 'start emission of %s stream' % self._magicstring)
585 yield self._magicstring
585 yield self._magicstring
586 param = self._paramchunk()
586 param = self._paramchunk()
587 outdebug(self.ui, 'bundle parameter: %s' % param)
587 outdebug(self.ui, 'bundle parameter: %s' % param)
588 yield _pack(_fstreamparamsize, len(param))
588 yield _pack(_fstreamparamsize, len(param))
589 if param:
589 if param:
590 yield param
590 yield param
591 for chunk in self._compengine.compressstream(self._getcorechunk(),
591 for chunk in self._compengine.compressstream(self._getcorechunk(),
592 self._compopts):
592 self._compopts):
593 yield chunk
593 yield chunk
594
594
595 def _paramchunk(self):
595 def _paramchunk(self):
596 """return a encoded version of all stream parameters"""
596 """return a encoded version of all stream parameters"""
597 blocks = []
597 blocks = []
598 for par, value in self._params:
598 for par, value in self._params:
599 par = urlreq.quote(par)
599 par = urlreq.quote(par)
600 if value is not None:
600 if value is not None:
601 value = urlreq.quote(value)
601 value = urlreq.quote(value)
602 par = '%s=%s' % (par, value)
602 par = '%s=%s' % (par, value)
603 blocks.append(par)
603 blocks.append(par)
604 return ' '.join(blocks)
604 return ' '.join(blocks)
605
605
606 def _getcorechunk(self):
606 def _getcorechunk(self):
607 """yield chunk for the core part of the bundle
607 """yield chunk for the core part of the bundle
608
608
609 (all but headers and parameters)"""
609 (all but headers and parameters)"""
610 outdebug(self.ui, 'start of parts')
610 outdebug(self.ui, 'start of parts')
611 for part in self._parts:
611 for part in self._parts:
612 outdebug(self.ui, 'bundle part: "%s"' % part.type)
612 outdebug(self.ui, 'bundle part: "%s"' % part.type)
613 for chunk in part.getchunks(ui=self.ui):
613 for chunk in part.getchunks(ui=self.ui):
614 yield chunk
614 yield chunk
615 outdebug(self.ui, 'end of bundle')
615 outdebug(self.ui, 'end of bundle')
616 yield _pack(_fpartheadersize, 0)
616 yield _pack(_fpartheadersize, 0)
617
617
618
618
619 def salvageoutput(self):
619 def salvageoutput(self):
620 """return a list with a copy of all output parts in the bundle
620 """return a list with a copy of all output parts in the bundle
621
621
622 This is meant to be used during error handling to make sure we preserve
622 This is meant to be used during error handling to make sure we preserve
623 server output"""
623 server output"""
624 salvaged = []
624 salvaged = []
625 for part in self._parts:
625 for part in self._parts:
626 if part.type.startswith('output'):
626 if part.type.startswith('output'):
627 salvaged.append(part.copy())
627 salvaged.append(part.copy())
628 return salvaged
628 return salvaged
629
629
630
630
631 class unpackermixin(object):
631 class unpackermixin(object):
632 """A mixin to extract bytes and struct data from a stream"""
632 """A mixin to extract bytes and struct data from a stream"""
633
633
634 def __init__(self, fp):
634 def __init__(self, fp):
635 self._fp = fp
635 self._fp = fp
636
636
637 def _unpack(self, format):
637 def _unpack(self, format):
638 """unpack this struct format from the stream
638 """unpack this struct format from the stream
639
639
640 This method is meant for internal usage by the bundle2 protocol only.
640 This method is meant for internal usage by the bundle2 protocol only.
641 They directly manipulate the low level stream including bundle2 level
641 They directly manipulate the low level stream including bundle2 level
642 instruction.
642 instruction.
643
643
644 Do not use it to implement higher-level logic or methods."""
644 Do not use it to implement higher-level logic or methods."""
645 data = self._readexact(struct.calcsize(format))
645 data = self._readexact(struct.calcsize(format))
646 return _unpack(format, data)
646 return _unpack(format, data)
647
647
648 def _readexact(self, size):
648 def _readexact(self, size):
649 """read exactly <size> bytes from the stream
649 """read exactly <size> bytes from the stream
650
650
651 This method is meant for internal usage by the bundle2 protocol only.
651 This method is meant for internal usage by the bundle2 protocol only.
652 They directly manipulate the low level stream including bundle2 level
652 They directly manipulate the low level stream including bundle2 level
653 instruction.
653 instruction.
654
654
655 Do not use it to implement higher-level logic or methods."""
655 Do not use it to implement higher-level logic or methods."""
656 return changegroup.readexactly(self._fp, size)
656 return changegroup.readexactly(self._fp, size)
657
657
658 def getunbundler(ui, fp, magicstring=None):
658 def getunbundler(ui, fp, magicstring=None):
659 """return a valid unbundler object for a given magicstring"""
659 """return a valid unbundler object for a given magicstring"""
660 if magicstring is None:
660 if magicstring is None:
661 magicstring = changegroup.readexactly(fp, 4)
661 magicstring = changegroup.readexactly(fp, 4)
662 magic, version = magicstring[0:2], magicstring[2:4]
662 magic, version = magicstring[0:2], magicstring[2:4]
663 if magic != 'HG':
663 if magic != 'HG':
664 raise error.Abort(_('not a Mercurial bundle'))
664 raise error.Abort(_('not a Mercurial bundle'))
665 unbundlerclass = formatmap.get(version)
665 unbundlerclass = formatmap.get(version)
666 if unbundlerclass is None:
666 if unbundlerclass is None:
667 raise error.Abort(_('unknown bundle version %s') % version)
667 raise error.Abort(_('unknown bundle version %s') % version)
668 unbundler = unbundlerclass(ui, fp)
668 unbundler = unbundlerclass(ui, fp)
669 indebug(ui, 'start processing of %s stream' % magicstring)
669 indebug(ui, 'start processing of %s stream' % magicstring)
670 return unbundler
670 return unbundler
671
671
672 class unbundle20(unpackermixin):
672 class unbundle20(unpackermixin):
673 """interpret a bundle2 stream
673 """interpret a bundle2 stream
674
674
675 This class is fed with a binary stream and yields parts through its
675 This class is fed with a binary stream and yields parts through its
676 `iterparts` methods."""
676 `iterparts` methods."""
677
677
678 _magicstring = 'HG20'
678 _magicstring = 'HG20'
679
679
680 def __init__(self, ui, fp):
680 def __init__(self, ui, fp):
681 """If header is specified, we do not read it out of the stream."""
681 """If header is specified, we do not read it out of the stream."""
682 self.ui = ui
682 self.ui = ui
683 self._compengine = util.compengines.forbundletype('UN')
683 self._compengine = util.compengines.forbundletype('UN')
684 self._compressed = None
684 self._compressed = None
685 super(unbundle20, self).__init__(fp)
685 super(unbundle20, self).__init__(fp)
686
686
687 @util.propertycache
687 @util.propertycache
688 def params(self):
688 def params(self):
689 """dictionary of stream level parameters"""
689 """dictionary of stream level parameters"""
690 indebug(self.ui, 'reading bundle2 stream parameters')
690 indebug(self.ui, 'reading bundle2 stream parameters')
691 params = {}
691 params = {}
692 paramssize = self._unpack(_fstreamparamsize)[0]
692 paramssize = self._unpack(_fstreamparamsize)[0]
693 if paramssize < 0:
693 if paramssize < 0:
694 raise error.BundleValueError('negative bundle param size: %i'
694 raise error.BundleValueError('negative bundle param size: %i'
695 % paramssize)
695 % paramssize)
696 if paramssize:
696 if paramssize:
697 params = self._readexact(paramssize)
697 params = self._readexact(paramssize)
698 params = self._processallparams(params)
698 params = self._processallparams(params)
699 return params
699 return params
700
700
701 def _processallparams(self, paramsblock):
701 def _processallparams(self, paramsblock):
702 """"""
702 """"""
703 params = util.sortdict()
703 params = util.sortdict()
704 for p in paramsblock.split(' '):
704 for p in paramsblock.split(' '):
705 p = p.split('=', 1)
705 p = p.split('=', 1)
706 p = [urlreq.unquote(i) for i in p]
706 p = [urlreq.unquote(i) for i in p]
707 if len(p) < 2:
707 if len(p) < 2:
708 p.append(None)
708 p.append(None)
709 self._processparam(*p)
709 self._processparam(*p)
710 params[p[0]] = p[1]
710 params[p[0]] = p[1]
711 return params
711 return params
712
712
713
713
714 def _processparam(self, name, value):
714 def _processparam(self, name, value):
715 """process a parameter, applying its effect if needed
715 """process a parameter, applying its effect if needed
716
716
717 Parameter starting with a lower case letter are advisory and will be
717 Parameter starting with a lower case letter are advisory and will be
718 ignored when unknown. Those starting with an upper case letter are
718 ignored when unknown. Those starting with an upper case letter are
719 mandatory and will this function will raise a KeyError when unknown.
719 mandatory and will this function will raise a KeyError when unknown.
720
720
721 Note: no option are currently supported. Any input will be either
721 Note: no option are currently supported. Any input will be either
722 ignored or failing.
722 ignored or failing.
723 """
723 """
724 if not name:
724 if not name:
725 raise ValueError('empty parameter name')
725 raise ValueError('empty parameter name')
726 if name[0] not in string.letters:
726 if name[0] not in string.letters:
727 raise ValueError('non letter first character: %r' % name)
727 raise ValueError('non letter first character: %r' % name)
728 try:
728 try:
729 handler = b2streamparamsmap[name.lower()]
729 handler = b2streamparamsmap[name.lower()]
730 except KeyError:
730 except KeyError:
731 if name[0].islower():
731 if name[0].islower():
732 indebug(self.ui, "ignoring unknown parameter %r" % name)
732 indebug(self.ui, "ignoring unknown parameter %r" % name)
733 else:
733 else:
734 raise error.BundleUnknownFeatureError(params=(name,))
734 raise error.BundleUnknownFeatureError(params=(name,))
735 else:
735 else:
736 handler(self, name, value)
736 handler(self, name, value)
737
737
738 def _forwardchunks(self):
738 def _forwardchunks(self):
739 """utility to transfer a bundle2 as binary
739 """utility to transfer a bundle2 as binary
740
740
741 This is made necessary by the fact the 'getbundle' command over 'ssh'
741 This is made necessary by the fact the 'getbundle' command over 'ssh'
742 have no way to know then the reply end, relying on the bundle to be
742 have no way to know then the reply end, relying on the bundle to be
743 interpreted to know its end. This is terrible and we are sorry, but we
743 interpreted to know its end. This is terrible and we are sorry, but we
744 needed to move forward to get general delta enabled.
744 needed to move forward to get general delta enabled.
745 """
745 """
746 yield self._magicstring
746 yield self._magicstring
747 assert 'params' not in vars(self)
747 assert 'params' not in vars(self)
748 paramssize = self._unpack(_fstreamparamsize)[0]
748 paramssize = self._unpack(_fstreamparamsize)[0]
749 if paramssize < 0:
749 if paramssize < 0:
750 raise error.BundleValueError('negative bundle param size: %i'
750 raise error.BundleValueError('negative bundle param size: %i'
751 % paramssize)
751 % paramssize)
752 yield _pack(_fstreamparamsize, paramssize)
752 yield _pack(_fstreamparamsize, paramssize)
753 if paramssize:
753 if paramssize:
754 params = self._readexact(paramssize)
754 params = self._readexact(paramssize)
755 self._processallparams(params)
755 self._processallparams(params)
756 yield params
756 yield params
757 assert self._compengine.bundletype == 'UN'
757 assert self._compengine.bundletype == 'UN'
758 # From there, payload might need to be decompressed
758 # From there, payload might need to be decompressed
759 self._fp = self._compengine.decompressorreader(self._fp)
759 self._fp = self._compengine.decompressorreader(self._fp)
760 emptycount = 0
760 emptycount = 0
761 while emptycount < 2:
761 while emptycount < 2:
762 # so we can brainlessly loop
762 # so we can brainlessly loop
763 assert _fpartheadersize == _fpayloadsize
763 assert _fpartheadersize == _fpayloadsize
764 size = self._unpack(_fpartheadersize)[0]
764 size = self._unpack(_fpartheadersize)[0]
765 yield _pack(_fpartheadersize, size)
765 yield _pack(_fpartheadersize, size)
766 if size:
766 if size:
767 emptycount = 0
767 emptycount = 0
768 else:
768 else:
769 emptycount += 1
769 emptycount += 1
770 continue
770 continue
771 if size == flaginterrupt:
771 if size == flaginterrupt:
772 continue
772 continue
773 elif size < 0:
773 elif size < 0:
774 raise error.BundleValueError('negative chunk size: %i')
774 raise error.BundleValueError('negative chunk size: %i')
775 yield self._readexact(size)
775 yield self._readexact(size)
776
776
777
777
778 def iterparts(self):
778 def iterparts(self):
779 """yield all parts contained in the stream"""
779 """yield all parts contained in the stream"""
780 # make sure param have been loaded
780 # make sure param have been loaded
781 self.params
781 self.params
782 # From there, payload need to be decompressed
782 # From there, payload need to be decompressed
783 self._fp = self._compengine.decompressorreader(self._fp)
783 self._fp = self._compengine.decompressorreader(self._fp)
784 indebug(self.ui, 'start extraction of bundle2 parts')
784 indebug(self.ui, 'start extraction of bundle2 parts')
785 headerblock = self._readpartheader()
785 headerblock = self._readpartheader()
786 while headerblock is not None:
786 while headerblock is not None:
787 part = unbundlepart(self.ui, headerblock, self._fp)
787 part = unbundlepart(self.ui, headerblock, self._fp)
788 yield part
788 yield part
789 part.seek(0, 2)
789 part.seek(0, 2)
790 headerblock = self._readpartheader()
790 headerblock = self._readpartheader()
791 indebug(self.ui, 'end of bundle2 stream')
791 indebug(self.ui, 'end of bundle2 stream')
792
792
793 def _readpartheader(self):
793 def _readpartheader(self):
794 """reads a part header size and return the bytes blob
794 """reads a part header size and return the bytes blob
795
795
796 returns None if empty"""
796 returns None if empty"""
797 headersize = self._unpack(_fpartheadersize)[0]
797 headersize = self._unpack(_fpartheadersize)[0]
798 if headersize < 0:
798 if headersize < 0:
799 raise error.BundleValueError('negative part header size: %i'
799 raise error.BundleValueError('negative part header size: %i'
800 % headersize)
800 % headersize)
801 indebug(self.ui, 'part header size: %i' % headersize)
801 indebug(self.ui, 'part header size: %i' % headersize)
802 if headersize:
802 if headersize:
803 return self._readexact(headersize)
803 return self._readexact(headersize)
804 return None
804 return None
805
805
806 def compressed(self):
806 def compressed(self):
807 self.params # load params
807 self.params # load params
808 return self._compressed
808 return self._compressed
809
809
810 def close(self):
810 def close(self):
811 """close underlying file"""
811 """close underlying file"""
812 if util.safehasattr(self._fp, 'close'):
812 if util.safehasattr(self._fp, 'close'):
813 return self._fp.close()
813 return self._fp.close()
814
814
815 formatmap = {'20': unbundle20}
815 formatmap = {'20': unbundle20}
816
816
817 b2streamparamsmap = {}
817 b2streamparamsmap = {}
818
818
819 def b2streamparamhandler(name):
819 def b2streamparamhandler(name):
820 """register a handler for a stream level parameter"""
820 """register a handler for a stream level parameter"""
821 def decorator(func):
821 def decorator(func):
822 assert name not in formatmap
822 assert name not in formatmap
823 b2streamparamsmap[name] = func
823 b2streamparamsmap[name] = func
824 return func
824 return func
825 return decorator
825 return decorator
826
826
827 @b2streamparamhandler('compression')
827 @b2streamparamhandler('compression')
828 def processcompression(unbundler, param, value):
828 def processcompression(unbundler, param, value):
829 """read compression parameter and install payload decompression"""
829 """read compression parameter and install payload decompression"""
830 if value not in util.compengines.supportedbundletypes:
830 if value not in util.compengines.supportedbundletypes:
831 raise error.BundleUnknownFeatureError(params=(param,),
831 raise error.BundleUnknownFeatureError(params=(param,),
832 values=(value,))
832 values=(value,))
833 unbundler._compengine = util.compengines.forbundletype(value)
833 unbundler._compengine = util.compengines.forbundletype(value)
834 if value is not None:
834 if value is not None:
835 unbundler._compressed = True
835 unbundler._compressed = True
836
836
837 class bundlepart(object):
837 class bundlepart(object):
838 """A bundle2 part contains application level payload
838 """A bundle2 part contains application level payload
839
839
840 The part `type` is used to route the part to the application level
840 The part `type` is used to route the part to the application level
841 handler.
841 handler.
842
842
843 The part payload is contained in ``part.data``. It could be raw bytes or a
843 The part payload is contained in ``part.data``. It could be raw bytes or a
844 generator of byte chunks.
844 generator of byte chunks.
845
845
846 You can add parameters to the part using the ``addparam`` method.
846 You can add parameters to the part using the ``addparam`` method.
847 Parameters can be either mandatory (default) or advisory. Remote side
847 Parameters can be either mandatory (default) or advisory. Remote side
848 should be able to safely ignore the advisory ones.
848 should be able to safely ignore the advisory ones.
849
849
850 Both data and parameters cannot be modified after the generation has begun.
850 Both data and parameters cannot be modified after the generation has begun.
851 """
851 """
852
852
853 def __init__(self, parttype, mandatoryparams=(), advisoryparams=(),
853 def __init__(self, parttype, mandatoryparams=(), advisoryparams=(),
854 data='', mandatory=True):
854 data='', mandatory=True):
855 validateparttype(parttype)
855 validateparttype(parttype)
856 self.id = None
856 self.id = None
857 self.type = parttype
857 self.type = parttype
858 self._data = data
858 self._data = data
859 self._mandatoryparams = list(mandatoryparams)
859 self._mandatoryparams = list(mandatoryparams)
860 self._advisoryparams = list(advisoryparams)
860 self._advisoryparams = list(advisoryparams)
861 # checking for duplicated entries
861 # checking for duplicated entries
862 self._seenparams = set()
862 self._seenparams = set()
863 for pname, __ in self._mandatoryparams + self._advisoryparams:
863 for pname, __ in self._mandatoryparams + self._advisoryparams:
864 if pname in self._seenparams:
864 if pname in self._seenparams:
865 raise error.ProgrammingError('duplicated params: %s' % pname)
865 raise error.ProgrammingError('duplicated params: %s' % pname)
866 self._seenparams.add(pname)
866 self._seenparams.add(pname)
867 # status of the part's generation:
867 # status of the part's generation:
868 # - None: not started,
868 # - None: not started,
869 # - False: currently generated,
869 # - False: currently generated,
870 # - True: generation done.
870 # - True: generation done.
871 self._generated = None
871 self._generated = None
872 self.mandatory = mandatory
872 self.mandatory = mandatory
873
873
874 def __repr__(self):
874 def __repr__(self):
875 cls = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
875 cls = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
876 return ('<%s object at %x; id: %s; type: %s; mandatory: %s>'
876 return ('<%s object at %x; id: %s; type: %s; mandatory: %s>'
877 % (cls, id(self), self.id, self.type, self.mandatory))
877 % (cls, id(self), self.id, self.type, self.mandatory))
878
878
879 def copy(self):
879 def copy(self):
880 """return a copy of the part
880 """return a copy of the part
881
881
882 The new part have the very same content but no partid assigned yet.
882 The new part have the very same content but no partid assigned yet.
883 Parts with generated data cannot be copied."""
883 Parts with generated data cannot be copied."""
884 assert not util.safehasattr(self.data, 'next')
884 assert not util.safehasattr(self.data, 'next')
885 return self.__class__(self.type, self._mandatoryparams,
885 return self.__class__(self.type, self._mandatoryparams,
886 self._advisoryparams, self._data, self.mandatory)
886 self._advisoryparams, self._data, self.mandatory)
887
887
888 # methods used to defines the part content
888 # methods used to defines the part content
889 @property
889 @property
890 def data(self):
890 def data(self):
891 return self._data
891 return self._data
892
892
893 @data.setter
893 @data.setter
894 def data(self, data):
894 def data(self, data):
895 if self._generated is not None:
895 if self._generated is not None:
896 raise error.ReadOnlyPartError('part is being generated')
896 raise error.ReadOnlyPartError('part is being generated')
897 self._data = data
897 self._data = data
898
898
899 @property
899 @property
900 def mandatoryparams(self):
900 def mandatoryparams(self):
901 # make it an immutable tuple to force people through ``addparam``
901 # make it an immutable tuple to force people through ``addparam``
902 return tuple(self._mandatoryparams)
902 return tuple(self._mandatoryparams)
903
903
904 @property
904 @property
905 def advisoryparams(self):
905 def advisoryparams(self):
906 # make it an immutable tuple to force people through ``addparam``
906 # make it an immutable tuple to force people through ``addparam``
907 return tuple(self._advisoryparams)
907 return tuple(self._advisoryparams)
908
908
909 def addparam(self, name, value='', mandatory=True):
909 def addparam(self, name, value='', mandatory=True):
910 """add a parameter to the part
910 """add a parameter to the part
911
911
912 If 'mandatory' is set to True, the remote handler must claim support
912 If 'mandatory' is set to True, the remote handler must claim support
913 for this parameter or the unbundling will be aborted.
913 for this parameter or the unbundling will be aborted.
914
914
915 The 'name' and 'value' cannot exceed 255 bytes each.
915 The 'name' and 'value' cannot exceed 255 bytes each.
916 """
916 """
917 if self._generated is not None:
917 if self._generated is not None:
918 raise error.ReadOnlyPartError('part is being generated')
918 raise error.ReadOnlyPartError('part is being generated')
919 if name in self._seenparams:
919 if name in self._seenparams:
920 raise ValueError('duplicated params: %s' % name)
920 raise ValueError('duplicated params: %s' % name)
921 self._seenparams.add(name)
921 self._seenparams.add(name)
922 params = self._advisoryparams
922 params = self._advisoryparams
923 if mandatory:
923 if mandatory:
924 params = self._mandatoryparams
924 params = self._mandatoryparams
925 params.append((name, value))
925 params.append((name, value))
926
926
927 # methods used to generates the bundle2 stream
927 # methods used to generates the bundle2 stream
928 def getchunks(self, ui):
928 def getchunks(self, ui):
929 if self._generated is not None:
929 if self._generated is not None:
930 raise error.ProgrammingError('part can only be consumed once')
930 raise error.ProgrammingError('part can only be consumed once')
931 self._generated = False
931 self._generated = False
932
932
933 if ui.debugflag:
933 if ui.debugflag:
934 msg = ['bundle2-output-part: "%s"' % self.type]
934 msg = ['bundle2-output-part: "%s"' % self.type]
935 if not self.mandatory:
935 if not self.mandatory:
936 msg.append(' (advisory)')
936 msg.append(' (advisory)')
937 nbmp = len(self.mandatoryparams)
937 nbmp = len(self.mandatoryparams)
938 nbap = len(self.advisoryparams)
938 nbap = len(self.advisoryparams)
939 if nbmp or nbap:
939 if nbmp or nbap:
940 msg.append(' (params:')
940 msg.append(' (params:')
941 if nbmp:
941 if nbmp:
942 msg.append(' %i mandatory' % nbmp)
942 msg.append(' %i mandatory' % nbmp)
943 if nbap:
943 if nbap:
944 msg.append(' %i advisory' % nbmp)
944 msg.append(' %i advisory' % nbmp)
945 msg.append(')')
945 msg.append(')')
946 if not self.data:
946 if not self.data:
947 msg.append(' empty payload')
947 msg.append(' empty payload')
948 elif util.safehasattr(self.data, 'next'):
948 elif util.safehasattr(self.data, 'next'):
949 msg.append(' streamed payload')
949 msg.append(' streamed payload')
950 else:
950 else:
951 msg.append(' %i bytes payload' % len(self.data))
951 msg.append(' %i bytes payload' % len(self.data))
952 msg.append('\n')
952 msg.append('\n')
953 ui.debug(''.join(msg))
953 ui.debug(''.join(msg))
954
954
955 #### header
955 #### header
956 if self.mandatory:
956 if self.mandatory:
957 parttype = self.type.upper()
957 parttype = self.type.upper()
958 else:
958 else:
959 parttype = self.type.lower()
959 parttype = self.type.lower()
960 outdebug(ui, 'part %s: "%s"' % (self.id, parttype))
960 outdebug(ui, 'part %s: "%s"' % (self.id, parttype))
961 ## parttype
961 ## parttype
962 header = [_pack(_fparttypesize, len(parttype)),
962 header = [_pack(_fparttypesize, len(parttype)),
963 parttype, _pack(_fpartid, self.id),
963 parttype, _pack(_fpartid, self.id),
964 ]
964 ]
965 ## parameters
965 ## parameters
966 # count
966 # count
967 manpar = self.mandatoryparams
967 manpar = self.mandatoryparams
968 advpar = self.advisoryparams
968 advpar = self.advisoryparams
969 header.append(_pack(_fpartparamcount, len(manpar), len(advpar)))
969 header.append(_pack(_fpartparamcount, len(manpar), len(advpar)))
970 # size
970 # size
971 parsizes = []
971 parsizes = []
972 for key, value in manpar:
972 for key, value in manpar:
973 parsizes.append(len(key))
973 parsizes.append(len(key))
974 parsizes.append(len(value))
974 parsizes.append(len(value))
975 for key, value in advpar:
975 for key, value in advpar:
976 parsizes.append(len(key))
976 parsizes.append(len(key))
977 parsizes.append(len(value))
977 parsizes.append(len(value))
978 paramsizes = _pack(_makefpartparamsizes(len(parsizes) / 2), *parsizes)
978 paramsizes = _pack(_makefpartparamsizes(len(parsizes) / 2), *parsizes)
979 header.append(paramsizes)
979 header.append(paramsizes)
980 # key, value
980 # key, value
981 for key, value in manpar:
981 for key, value in manpar:
982 header.append(key)
982 header.append(key)
983 header.append(value)
983 header.append(value)
984 for key, value in advpar:
984 for key, value in advpar:
985 header.append(key)
985 header.append(key)
986 header.append(value)
986 header.append(value)
987 ## finalize header
987 ## finalize header
988 headerchunk = ''.join(header)
988 headerchunk = ''.join(header)
989 outdebug(ui, 'header chunk size: %i' % len(headerchunk))
989 outdebug(ui, 'header chunk size: %i' % len(headerchunk))
990 yield _pack(_fpartheadersize, len(headerchunk))
990 yield _pack(_fpartheadersize, len(headerchunk))
991 yield headerchunk
991 yield headerchunk
992 ## payload
992 ## payload
993 try:
993 try:
994 for chunk in self._payloadchunks():
994 for chunk in self._payloadchunks():
995 outdebug(ui, 'payload chunk size: %i' % len(chunk))
995 outdebug(ui, 'payload chunk size: %i' % len(chunk))
996 yield _pack(_fpayloadsize, len(chunk))
996 yield _pack(_fpayloadsize, len(chunk))
997 yield chunk
997 yield chunk
998 except GeneratorExit:
998 except GeneratorExit:
999 # GeneratorExit means that nobody is listening for our
999 # GeneratorExit means that nobody is listening for our
1000 # results anyway, so just bail quickly rather than trying
1000 # results anyway, so just bail quickly rather than trying
1001 # to produce an error part.
1001 # to produce an error part.
1002 ui.debug('bundle2-generatorexit\n')
1002 ui.debug('bundle2-generatorexit\n')
1003 raise
1003 raise
1004 except BaseException as exc:
1004 except BaseException as exc:
1005 # backup exception data for later
1005 # backup exception data for later
1006 ui.debug('bundle2-input-stream-interrupt: encoding exception %s'
1006 ui.debug('bundle2-input-stream-interrupt: encoding exception %s'
1007 % exc)
1007 % exc)
1008 tb = sys.exc_info()[2]
1008 tb = sys.exc_info()[2]
1009 msg = 'unexpected error: %s' % exc
1009 msg = 'unexpected error: %s' % exc
1010 interpart = bundlepart('error:abort', [('message', msg)],
1010 interpart = bundlepart('error:abort', [('message', msg)],
1011 mandatory=False)
1011 mandatory=False)
1012 interpart.id = 0
1012 interpart.id = 0
1013 yield _pack(_fpayloadsize, -1)
1013 yield _pack(_fpayloadsize, -1)
1014 for chunk in interpart.getchunks(ui=ui):
1014 for chunk in interpart.getchunks(ui=ui):
1015 yield chunk
1015 yield chunk
1016 outdebug(ui, 'closing payload chunk')
1016 outdebug(ui, 'closing payload chunk')
1017 # abort current part payload
1017 # abort current part payload
1018 yield _pack(_fpayloadsize, 0)
1018 yield _pack(_fpayloadsize, 0)
1019 pycompat.raisewithtb(exc, tb)
1019 pycompat.raisewithtb(exc, tb)
1020 # end of payload
1020 # end of payload
1021 outdebug(ui, 'closing payload chunk')
1021 outdebug(ui, 'closing payload chunk')
1022 yield _pack(_fpayloadsize, 0)
1022 yield _pack(_fpayloadsize, 0)
1023 self._generated = True
1023 self._generated = True
1024
1024
1025 def _payloadchunks(self):
1025 def _payloadchunks(self):
1026 """yield chunks of a the part payload
1026 """yield chunks of a the part payload
1027
1027
1028 Exists to handle the different methods to provide data to a part."""
1028 Exists to handle the different methods to provide data to a part."""
1029 # we only support fixed size data now.
1029 # we only support fixed size data now.
1030 # This will be improved in the future.
1030 # This will be improved in the future.
1031 if util.safehasattr(self.data, 'next'):
1031 if util.safehasattr(self.data, 'next'):
1032 buff = util.chunkbuffer(self.data)
1032 buff = util.chunkbuffer(self.data)
1033 chunk = buff.read(preferedchunksize)
1033 chunk = buff.read(preferedchunksize)
1034 while chunk:
1034 while chunk:
1035 yield chunk
1035 yield chunk
1036 chunk = buff.read(preferedchunksize)
1036 chunk = buff.read(preferedchunksize)
1037 elif len(self.data):
1037 elif len(self.data):
1038 yield self.data
1038 yield self.data
1039
1039
1040
1040
1041 flaginterrupt = -1
1041 flaginterrupt = -1
1042
1042
1043 class interrupthandler(unpackermixin):
1043 class interrupthandler(unpackermixin):
1044 """read one part and process it with restricted capability
1044 """read one part and process it with restricted capability
1045
1045
1046 This allows to transmit exception raised on the producer size during part
1046 This allows to transmit exception raised on the producer size during part
1047 iteration while the consumer is reading a part.
1047 iteration while the consumer is reading a part.
1048
1048
1049 Part processed in this manner only have access to a ui object,"""
1049 Part processed in this manner only have access to a ui object,"""
1050
1050
1051 def __init__(self, ui, fp):
1051 def __init__(self, ui, fp):
1052 super(interrupthandler, self).__init__(fp)
1052 super(interrupthandler, self).__init__(fp)
1053 self.ui = ui
1053 self.ui = ui
1054
1054
1055 def _readpartheader(self):
1055 def _readpartheader(self):
1056 """reads a part header size and return the bytes blob
1056 """reads a part header size and return the bytes blob
1057
1057
1058 returns None if empty"""
1058 returns None if empty"""
1059 headersize = self._unpack(_fpartheadersize)[0]
1059 headersize = self._unpack(_fpartheadersize)[0]
1060 if headersize < 0:
1060 if headersize < 0:
1061 raise error.BundleValueError('negative part header size: %i'
1061 raise error.BundleValueError('negative part header size: %i'
1062 % headersize)
1062 % headersize)
1063 indebug(self.ui, 'part header size: %i\n' % headersize)
1063 indebug(self.ui, 'part header size: %i\n' % headersize)
1064 if headersize:
1064 if headersize:
1065 return self._readexact(headersize)
1065 return self._readexact(headersize)
1066 return None
1066 return None
1067
1067
1068 def __call__(self):
1068 def __call__(self):
1069
1069
1070 self.ui.debug('bundle2-input-stream-interrupt:'
1070 self.ui.debug('bundle2-input-stream-interrupt:'
1071 ' opening out of band context\n')
1071 ' opening out of band context\n')
1072 indebug(self.ui, 'bundle2 stream interruption, looking for a part.')
1072 indebug(self.ui, 'bundle2 stream interruption, looking for a part.')
1073 headerblock = self._readpartheader()
1073 headerblock = self._readpartheader()
1074 if headerblock is None:
1074 if headerblock is None:
1075 indebug(self.ui, 'no part found during interruption.')
1075 indebug(self.ui, 'no part found during interruption.')
1076 return
1076 return
1077 part = unbundlepart(self.ui, headerblock, self._fp)
1077 part = unbundlepart(self.ui, headerblock, self._fp)
1078 op = interruptoperation(self.ui)
1078 op = interruptoperation(self.ui)
1079 _processpart(op, part)
1079 _processpart(op, part)
1080 self.ui.debug('bundle2-input-stream-interrupt:'
1080 self.ui.debug('bundle2-input-stream-interrupt:'
1081 ' closing out of band context\n')
1081 ' closing out of band context\n')
1082
1082
1083 class interruptoperation(object):
1083 class interruptoperation(object):
1084 """A limited operation to be use by part handler during interruption
1084 """A limited operation to be use by part handler during interruption
1085
1085
1086 It only have access to an ui object.
1086 It only have access to an ui object.
1087 """
1087 """
1088
1088
1089 def __init__(self, ui):
1089 def __init__(self, ui):
1090 self.ui = ui
1090 self.ui = ui
1091 self.reply = None
1091 self.reply = None
1092 self.captureoutput = False
1092 self.captureoutput = False
1093
1093
1094 @property
1094 @property
1095 def repo(self):
1095 def repo(self):
1096 raise error.ProgrammingError('no repo access from stream interruption')
1096 raise error.ProgrammingError('no repo access from stream interruption')
1097
1097
1098 def gettransaction(self):
1098 def gettransaction(self):
1099 raise TransactionUnavailable('no repo access from stream interruption')
1099 raise TransactionUnavailable('no repo access from stream interruption')
1100
1100
1101 class unbundlepart(unpackermixin):
1101 class unbundlepart(unpackermixin):
1102 """a bundle part read from a bundle"""
1102 """a bundle part read from a bundle"""
1103
1103
1104 def __init__(self, ui, header, fp):
1104 def __init__(self, ui, header, fp):
1105 super(unbundlepart, self).__init__(fp)
1105 super(unbundlepart, self).__init__(fp)
1106 self._seekable = (util.safehasattr(fp, 'seek') and
1106 self._seekable = (util.safehasattr(fp, 'seek') and
1107 util.safehasattr(fp, 'tell'))
1107 util.safehasattr(fp, 'tell'))
1108 self.ui = ui
1108 self.ui = ui
1109 # unbundle state attr
1109 # unbundle state attr
1110 self._headerdata = header
1110 self._headerdata = header
1111 self._headeroffset = 0
1111 self._headeroffset = 0
1112 self._initialized = False
1112 self._initialized = False
1113 self.consumed = False
1113 self.consumed = False
1114 # part data
1114 # part data
1115 self.id = None
1115 self.id = None
1116 self.type = None
1116 self.type = None
1117 self.mandatoryparams = None
1117 self.mandatoryparams = None
1118 self.advisoryparams = None
1118 self.advisoryparams = None
1119 self.params = None
1119 self.params = None
1120 self.mandatorykeys = ()
1120 self.mandatorykeys = ()
1121 self._payloadstream = None
1121 self._payloadstream = None
1122 self._readheader()
1122 self._readheader()
1123 self._mandatory = None
1123 self._mandatory = None
1124 self._chunkindex = [] #(payload, file) position tuples for chunk starts
1124 self._chunkindex = [] #(payload, file) position tuples for chunk starts
1125 self._pos = 0
1125 self._pos = 0
1126
1126
1127 def _fromheader(self, size):
1127 def _fromheader(self, size):
1128 """return the next <size> byte from the header"""
1128 """return the next <size> byte from the header"""
1129 offset = self._headeroffset
1129 offset = self._headeroffset
1130 data = self._headerdata[offset:(offset + size)]
1130 data = self._headerdata[offset:(offset + size)]
1131 self._headeroffset = offset + size
1131 self._headeroffset = offset + size
1132 return data
1132 return data
1133
1133
1134 def _unpackheader(self, format):
1134 def _unpackheader(self, format):
1135 """read given format from header
1135 """read given format from header
1136
1136
1137 This automatically compute the size of the format to read."""
1137 This automatically compute the size of the format to read."""
1138 data = self._fromheader(struct.calcsize(format))
1138 data = self._fromheader(struct.calcsize(format))
1139 return _unpack(format, data)
1139 return _unpack(format, data)
1140
1140
1141 def _initparams(self, mandatoryparams, advisoryparams):
1141 def _initparams(self, mandatoryparams, advisoryparams):
1142 """internal function to setup all logic related parameters"""
1142 """internal function to setup all logic related parameters"""
1143 # make it read only to prevent people touching it by mistake.
1143 # make it read only to prevent people touching it by mistake.
1144 self.mandatoryparams = tuple(mandatoryparams)
1144 self.mandatoryparams = tuple(mandatoryparams)
1145 self.advisoryparams = tuple(advisoryparams)
1145 self.advisoryparams = tuple(advisoryparams)
1146 # user friendly UI
1146 # user friendly UI
1147 self.params = util.sortdict(self.mandatoryparams)
1147 self.params = util.sortdict(self.mandatoryparams)
1148 self.params.update(self.advisoryparams)
1148 self.params.update(self.advisoryparams)
1149 self.mandatorykeys = frozenset(p[0] for p in mandatoryparams)
1149 self.mandatorykeys = frozenset(p[0] for p in mandatoryparams)
1150
1150
1151 def _payloadchunks(self, chunknum=0):
1151 def _payloadchunks(self, chunknum=0):
1152 '''seek to specified chunk and start yielding data'''
1152 '''seek to specified chunk and start yielding data'''
1153 if len(self._chunkindex) == 0:
1153 if len(self._chunkindex) == 0:
1154 assert chunknum == 0, 'Must start with chunk 0'
1154 assert chunknum == 0, 'Must start with chunk 0'
1155 self._chunkindex.append((0, self._tellfp()))
1155 self._chunkindex.append((0, self._tellfp()))
1156 else:
1156 else:
1157 assert chunknum < len(self._chunkindex), \
1157 assert chunknum < len(self._chunkindex), \
1158 'Unknown chunk %d' % chunknum
1158 'Unknown chunk %d' % chunknum
1159 self._seekfp(self._chunkindex[chunknum][1])
1159 self._seekfp(self._chunkindex[chunknum][1])
1160
1160
1161 pos = self._chunkindex[chunknum][0]
1161 pos = self._chunkindex[chunknum][0]
1162 payloadsize = self._unpack(_fpayloadsize)[0]
1162 payloadsize = self._unpack(_fpayloadsize)[0]
1163 indebug(self.ui, 'payload chunk size: %i' % payloadsize)
1163 indebug(self.ui, 'payload chunk size: %i' % payloadsize)
1164 while payloadsize:
1164 while payloadsize:
1165 if payloadsize == flaginterrupt:
1165 if payloadsize == flaginterrupt:
1166 # interruption detection, the handler will now read a
1166 # interruption detection, the handler will now read a
1167 # single part and process it.
1167 # single part and process it.
1168 interrupthandler(self.ui, self._fp)()
1168 interrupthandler(self.ui, self._fp)()
1169 elif payloadsize < 0:
1169 elif payloadsize < 0:
1170 msg = 'negative payload chunk size: %i' % payloadsize
1170 msg = 'negative payload chunk size: %i' % payloadsize
1171 raise error.BundleValueError(msg)
1171 raise error.BundleValueError(msg)
1172 else:
1172 else:
1173 result = self._readexact(payloadsize)
1173 result = self._readexact(payloadsize)
1174 chunknum += 1
1174 chunknum += 1
1175 pos += payloadsize
1175 pos += payloadsize
1176 if chunknum == len(self._chunkindex):
1176 if chunknum == len(self._chunkindex):
1177 self._chunkindex.append((pos, self._tellfp()))
1177 self._chunkindex.append((pos, self._tellfp()))
1178 yield result
1178 yield result
1179 payloadsize = self._unpack(_fpayloadsize)[0]
1179 payloadsize = self._unpack(_fpayloadsize)[0]
1180 indebug(self.ui, 'payload chunk size: %i' % payloadsize)
1180 indebug(self.ui, 'payload chunk size: %i' % payloadsize)
1181
1181
1182 def _findchunk(self, pos):
1182 def _findchunk(self, pos):
1183 '''for a given payload position, return a chunk number and offset'''
1183 '''for a given payload position, return a chunk number and offset'''
1184 for chunk, (ppos, fpos) in enumerate(self._chunkindex):
1184 for chunk, (ppos, fpos) in enumerate(self._chunkindex):
1185 if ppos == pos:
1185 if ppos == pos:
1186 return chunk, 0
1186 return chunk, 0
1187 elif ppos > pos:
1187 elif ppos > pos:
1188 return chunk - 1, pos - self._chunkindex[chunk - 1][0]
1188 return chunk - 1, pos - self._chunkindex[chunk - 1][0]
1189 raise ValueError('Unknown chunk')
1189 raise ValueError('Unknown chunk')
1190
1190
1191 def _readheader(self):
1191 def _readheader(self):
1192 """read the header and setup the object"""
1192 """read the header and setup the object"""
1193 typesize = self._unpackheader(_fparttypesize)[0]
1193 typesize = self._unpackheader(_fparttypesize)[0]
1194 self.type = self._fromheader(typesize)
1194 self.type = self._fromheader(typesize)
1195 indebug(self.ui, 'part type: "%s"' % self.type)
1195 indebug(self.ui, 'part type: "%s"' % self.type)
1196 self.id = self._unpackheader(_fpartid)[0]
1196 self.id = self._unpackheader(_fpartid)[0]
1197 indebug(self.ui, 'part id: "%s"' % self.id)
1197 indebug(self.ui, 'part id: "%s"' % self.id)
1198 # extract mandatory bit from type
1198 # extract mandatory bit from type
1199 self.mandatory = (self.type != self.type.lower())
1199 self.mandatory = (self.type != self.type.lower())
1200 self.type = self.type.lower()
1200 self.type = self.type.lower()
1201 ## reading parameters
1201 ## reading parameters
1202 # param count
1202 # param count
1203 mancount, advcount = self._unpackheader(_fpartparamcount)
1203 mancount, advcount = self._unpackheader(_fpartparamcount)
1204 indebug(self.ui, 'part parameters: %i' % (mancount + advcount))
1204 indebug(self.ui, 'part parameters: %i' % (mancount + advcount))
1205 # param size
1205 # param size
1206 fparamsizes = _makefpartparamsizes(mancount + advcount)
1206 fparamsizes = _makefpartparamsizes(mancount + advcount)
1207 paramsizes = self._unpackheader(fparamsizes)
1207 paramsizes = self._unpackheader(fparamsizes)
1208 # make it a list of couple again
1208 # make it a list of couple again
1209 paramsizes = zip(paramsizes[::2], paramsizes[1::2])
1209 paramsizes = zip(paramsizes[::2], paramsizes[1::2])
1210 # split mandatory from advisory
1210 # split mandatory from advisory
1211 mansizes = paramsizes[:mancount]
1211 mansizes = paramsizes[:mancount]
1212 advsizes = paramsizes[mancount:]
1212 advsizes = paramsizes[mancount:]
1213 # retrieve param value
1213 # retrieve param value
1214 manparams = []
1214 manparams = []
1215 for key, value in mansizes:
1215 for key, value in mansizes:
1216 manparams.append((self._fromheader(key), self._fromheader(value)))
1216 manparams.append((self._fromheader(key), self._fromheader(value)))
1217 advparams = []
1217 advparams = []
1218 for key, value in advsizes:
1218 for key, value in advsizes:
1219 advparams.append((self._fromheader(key), self._fromheader(value)))
1219 advparams.append((self._fromheader(key), self._fromheader(value)))
1220 self._initparams(manparams, advparams)
1220 self._initparams(manparams, advparams)
1221 ## part payload
1221 ## part payload
1222 self._payloadstream = util.chunkbuffer(self._payloadchunks())
1222 self._payloadstream = util.chunkbuffer(self._payloadchunks())
1223 # we read the data, tell it
1223 # we read the data, tell it
1224 self._initialized = True
1224 self._initialized = True
1225
1225
1226 def read(self, size=None):
1226 def read(self, size=None):
1227 """read payload data"""
1227 """read payload data"""
1228 if not self._initialized:
1228 if not self._initialized:
1229 self._readheader()
1229 self._readheader()
1230 if size is None:
1230 if size is None:
1231 data = self._payloadstream.read()
1231 data = self._payloadstream.read()
1232 else:
1232 else:
1233 data = self._payloadstream.read(size)
1233 data = self._payloadstream.read(size)
1234 self._pos += len(data)
1234 self._pos += len(data)
1235 if size is None or len(data) < size:
1235 if size is None or len(data) < size:
1236 if not self.consumed and self._pos:
1236 if not self.consumed and self._pos:
1237 self.ui.debug('bundle2-input-part: total payload size %i\n'
1237 self.ui.debug('bundle2-input-part: total payload size %i\n'
1238 % self._pos)
1238 % self._pos)
1239 self.consumed = True
1239 self.consumed = True
1240 return data
1240 return data
1241
1241
1242 def tell(self):
1242 def tell(self):
1243 return self._pos
1243 return self._pos
1244
1244
1245 def seek(self, offset, whence=0):
1245 def seek(self, offset, whence=0):
1246 if whence == 0:
1246 if whence == 0:
1247 newpos = offset
1247 newpos = offset
1248 elif whence == 1:
1248 elif whence == 1:
1249 newpos = self._pos + offset
1249 newpos = self._pos + offset
1250 elif whence == 2:
1250 elif whence == 2:
1251 if not self.consumed:
1251 if not self.consumed:
1252 self.read()
1252 self.read()
1253 newpos = self._chunkindex[-1][0] - offset
1253 newpos = self._chunkindex[-1][0] - offset
1254 else:
1254 else:
1255 raise ValueError('Unknown whence value: %r' % (whence,))
1255 raise ValueError('Unknown whence value: %r' % (whence,))
1256
1256
1257 if newpos > self._chunkindex[-1][0] and not self.consumed:
1257 if newpos > self._chunkindex[-1][0] and not self.consumed:
1258 self.read()
1258 self.read()
1259 if not 0 <= newpos <= self._chunkindex[-1][0]:
1259 if not 0 <= newpos <= self._chunkindex[-1][0]:
1260 raise ValueError('Offset out of range')
1260 raise ValueError('Offset out of range')
1261
1261
1262 if self._pos != newpos:
1262 if self._pos != newpos:
1263 chunk, internaloffset = self._findchunk(newpos)
1263 chunk, internaloffset = self._findchunk(newpos)
1264 self._payloadstream = util.chunkbuffer(self._payloadchunks(chunk))
1264 self._payloadstream = util.chunkbuffer(self._payloadchunks(chunk))
1265 adjust = self.read(internaloffset)
1265 adjust = self.read(internaloffset)
1266 if len(adjust) != internaloffset:
1266 if len(adjust) != internaloffset:
1267 raise error.Abort(_('Seek failed\n'))
1267 raise error.Abort(_('Seek failed\n'))
1268 self._pos = newpos
1268 self._pos = newpos
1269
1269
1270 def _seekfp(self, offset, whence=0):
1270 def _seekfp(self, offset, whence=0):
1271 """move the underlying file pointer
1271 """move the underlying file pointer
1272
1272
1273 This method is meant for internal usage by the bundle2 protocol only.
1273 This method is meant for internal usage by the bundle2 protocol only.
1274 They directly manipulate the low level stream including bundle2 level
1274 They directly manipulate the low level stream including bundle2 level
1275 instruction.
1275 instruction.
1276
1276
1277 Do not use it to implement higher-level logic or methods."""
1277 Do not use it to implement higher-level logic or methods."""
1278 if self._seekable:
1278 if self._seekable:
1279 return self._fp.seek(offset, whence)
1279 return self._fp.seek(offset, whence)
1280 else:
1280 else:
1281 raise NotImplementedError(_('File pointer is not seekable'))
1281 raise NotImplementedError(_('File pointer is not seekable'))
1282
1282
1283 def _tellfp(self):
1283 def _tellfp(self):
1284 """return the file offset, or None if file is not seekable
1284 """return the file offset, or None if file is not seekable
1285
1285
1286 This method is meant for internal usage by the bundle2 protocol only.
1286 This method is meant for internal usage by the bundle2 protocol only.
1287 They directly manipulate the low level stream including bundle2 level
1287 They directly manipulate the low level stream including bundle2 level
1288 instruction.
1288 instruction.
1289
1289
1290 Do not use it to implement higher-level logic or methods."""
1290 Do not use it to implement higher-level logic or methods."""
1291 if self._seekable:
1291 if self._seekable:
1292 try:
1292 try:
1293 return self._fp.tell()
1293 return self._fp.tell()
1294 except IOError as e:
1294 except IOError as e:
1295 if e.errno == errno.ESPIPE:
1295 if e.errno == errno.ESPIPE:
1296 self._seekable = False
1296 self._seekable = False
1297 else:
1297 else:
1298 raise
1298 raise
1299 return None
1299 return None
1300
1300
1301 # These are only the static capabilities.
1301 # These are only the static capabilities.
1302 # Check the 'getrepocaps' function for the rest.
1302 # Check the 'getrepocaps' function for the rest.
1303 capabilities = {'HG20': (),
1303 capabilities = {'HG20': (),
1304 'error': ('abort', 'unsupportedcontent', 'pushraced',
1304 'error': ('abort', 'unsupportedcontent', 'pushraced',
1305 'pushkey'),
1305 'pushkey'),
1306 'listkeys': (),
1306 'listkeys': (),
1307 'pushkey': (),
1307 'pushkey': (),
1308 'digests': tuple(sorted(util.DIGESTS.keys())),
1308 'digests': tuple(sorted(util.DIGESTS.keys())),
1309 'remote-changegroup': ('http', 'https'),
1309 'remote-changegroup': ('http', 'https'),
1310 'hgtagsfnodes': (),
1310 'hgtagsfnodes': (),
1311 }
1311 }
1312
1312
1313 def getrepocaps(repo, allowpushback=False):
1313 def getrepocaps(repo, allowpushback=False):
1314 """return the bundle2 capabilities for a given repo
1314 """return the bundle2 capabilities for a given repo
1315
1315
1316 Exists to allow extensions (like evolution) to mutate the capabilities.
1316 Exists to allow extensions (like evolution) to mutate the capabilities.
1317 """
1317 """
1318 caps = capabilities.copy()
1318 caps = capabilities.copy()
1319 caps['changegroup'] = tuple(sorted(
1319 caps['changegroup'] = tuple(sorted(
1320 changegroup.supportedincomingversions(repo)))
1320 changegroup.supportedincomingversions(repo)))
1321 if obsolete.isenabled(repo, obsolete.exchangeopt):
1321 if obsolete.isenabled(repo, obsolete.exchangeopt):
1322 supportedformat = tuple('V%i' % v for v in obsolete.formats)
1322 supportedformat = tuple('V%i' % v for v in obsolete.formats)
1323 caps['obsmarkers'] = supportedformat
1323 caps['obsmarkers'] = supportedformat
1324 if allowpushback:
1324 if allowpushback:
1325 caps['pushback'] = ()
1325 caps['pushback'] = ()
1326 return caps
1326 return caps
1327
1327
1328 def bundle2caps(remote):
1328 def bundle2caps(remote):
1329 """return the bundle capabilities of a peer as dict"""
1329 """return the bundle capabilities of a peer as dict"""
1330 raw = remote.capable('bundle2')
1330 raw = remote.capable('bundle2')
1331 if not raw and raw != '':
1331 if not raw and raw != '':
1332 return {}
1332 return {}
1333 capsblob = urlreq.unquote(remote.capable('bundle2'))
1333 capsblob = urlreq.unquote(remote.capable('bundle2'))
1334 return decodecaps(capsblob)
1334 return decodecaps(capsblob)
1335
1335
1336 def obsmarkersversion(caps):
1336 def obsmarkersversion(caps):
1337 """extract the list of supported obsmarkers versions from a bundle2caps dict
1337 """extract the list of supported obsmarkers versions from a bundle2caps dict
1338 """
1338 """
1339 obscaps = caps.get('obsmarkers', ())
1339 obscaps = caps.get('obsmarkers', ())
1340 return [int(c[1:]) for c in obscaps if c.startswith('V')]
1340 return [int(c[1:]) for c in obscaps if c.startswith('V')]
1341
1341
1342 def writenewbundle(ui, repo, source, filename, bundletype, outgoing, opts,
1342 def writenewbundle(ui, repo, source, filename, bundletype, outgoing, opts,
1343 vfs=None, compression=None, compopts=None):
1343 vfs=None, compression=None, compopts=None):
1344 if bundletype.startswith('HG10'):
1344 if bundletype.startswith('HG10'):
1345 cg = changegroup.getchangegroup(repo, source, outgoing, version='01')
1345 cg = changegroup.getchangegroup(repo, source, outgoing, version='01')
1346 return writebundle(ui, cg, filename, bundletype, vfs=vfs,
1346 return writebundle(ui, cg, filename, bundletype, vfs=vfs,
1347 compression=compression, compopts=compopts)
1347 compression=compression, compopts=compopts)
1348 elif not bundletype.startswith('HG20'):
1348 elif not bundletype.startswith('HG20'):
1349 raise error.ProgrammingError('unknown bundle type: %s' % bundletype)
1349 raise error.ProgrammingError('unknown bundle type: %s' % bundletype)
1350
1350
1351 bundle = bundle20(ui)
1351 caps = {}
1352 if 'obsolescence' in opts:
1353 caps['obsmarkers'] = ('V1',)
1354 bundle = bundle20(ui, caps)
1352 bundle.setcompression(compression, compopts)
1355 bundle.setcompression(compression, compopts)
1353 _addpartsfromopts(ui, repo, bundle, source, outgoing, opts)
1356 _addpartsfromopts(ui, repo, bundle, source, outgoing, opts)
1354 chunkiter = bundle.getchunks()
1357 chunkiter = bundle.getchunks()
1355
1358
1356 return changegroup.writechunks(ui, chunkiter, filename, vfs=vfs)
1359 return changegroup.writechunks(ui, chunkiter, filename, vfs=vfs)
1357
1360
1358 def _addpartsfromopts(ui, repo, bundler, source, outgoing, opts):
1361 def _addpartsfromopts(ui, repo, bundler, source, outgoing, opts):
1359 # We should eventually reconcile this logic with the one behind
1362 # We should eventually reconcile this logic with the one behind
1360 # 'exchange.getbundle2partsgenerator'.
1363 # 'exchange.getbundle2partsgenerator'.
1361 #
1364 #
1362 # The type of input from 'getbundle' and 'writenewbundle' are a bit
1365 # The type of input from 'getbundle' and 'writenewbundle' are a bit
1363 # different right now. So we keep them separated for now for the sake of
1366 # different right now. So we keep them separated for now for the sake of
1364 # simplicity.
1367 # simplicity.
1365
1368
1366 # we always want a changegroup in such bundle
1369 # we always want a changegroup in such bundle
1367 cgversion = opts.get('cg.version')
1370 cgversion = opts.get('cg.version')
1368 if cgversion is None:
1371 if cgversion is None:
1369 cgversion = changegroup.safeversion(repo)
1372 cgversion = changegroup.safeversion(repo)
1370 cg = changegroup.getchangegroup(repo, source, outgoing,
1373 cg = changegroup.getchangegroup(repo, source, outgoing,
1371 version=cgversion)
1374 version=cgversion)
1372 part = bundler.newpart('changegroup', data=cg.getchunks())
1375 part = bundler.newpart('changegroup', data=cg.getchunks())
1373 part.addparam('version', cg.version)
1376 part.addparam('version', cg.version)
1374 if 'clcount' in cg.extras:
1377 if 'clcount' in cg.extras:
1375 part.addparam('nbchanges', str(cg.extras['clcount']),
1378 part.addparam('nbchanges', str(cg.extras['clcount']),
1376 mandatory=False)
1379 mandatory=False)
1377
1380
1378 addparttagsfnodescache(repo, bundler, outgoing)
1381 addparttagsfnodescache(repo, bundler, outgoing)
1379
1382
1383 if opts.get('obsolescence', False):
1384 obsmarkers = repo.obsstore.relevantmarkers(outgoing.missing)
1385 buildobsmarkerspart(bundler, obsmarkers)
1386
1380 def addparttagsfnodescache(repo, bundler, outgoing):
1387 def addparttagsfnodescache(repo, bundler, outgoing):
1381 # we include the tags fnode cache for the bundle changeset
1388 # we include the tags fnode cache for the bundle changeset
1382 # (as an optional parts)
1389 # (as an optional parts)
1383 cache = tags.hgtagsfnodescache(repo.unfiltered())
1390 cache = tags.hgtagsfnodescache(repo.unfiltered())
1384 chunks = []
1391 chunks = []
1385
1392
1386 # .hgtags fnodes are only relevant for head changesets. While we could
1393 # .hgtags fnodes are only relevant for head changesets. While we could
1387 # transfer values for all known nodes, there will likely be little to
1394 # transfer values for all known nodes, there will likely be little to
1388 # no benefit.
1395 # no benefit.
1389 #
1396 #
1390 # We don't bother using a generator to produce output data because
1397 # We don't bother using a generator to produce output data because
1391 # a) we only have 40 bytes per head and even esoteric numbers of heads
1398 # a) we only have 40 bytes per head and even esoteric numbers of heads
1392 # consume little memory (1M heads is 40MB) b) we don't want to send the
1399 # consume little memory (1M heads is 40MB) b) we don't want to send the
1393 # part if we don't have entries and knowing if we have entries requires
1400 # part if we don't have entries and knowing if we have entries requires
1394 # cache lookups.
1401 # cache lookups.
1395 for node in outgoing.missingheads:
1402 for node in outgoing.missingheads:
1396 # Don't compute missing, as this may slow down serving.
1403 # Don't compute missing, as this may slow down serving.
1397 fnode = cache.getfnode(node, computemissing=False)
1404 fnode = cache.getfnode(node, computemissing=False)
1398 if fnode is not None:
1405 if fnode is not None:
1399 chunks.extend([node, fnode])
1406 chunks.extend([node, fnode])
1400
1407
1401 if chunks:
1408 if chunks:
1402 bundler.newpart('hgtagsfnodes', data=''.join(chunks))
1409 bundler.newpart('hgtagsfnodes', data=''.join(chunks))
1403
1410
1404 def buildobsmarkerspart(bundler, markers):
1411 def buildobsmarkerspart(bundler, markers):
1405 """add an obsmarker part to the bundler with <markers>
1412 """add an obsmarker part to the bundler with <markers>
1406
1413
1407 No part is created if markers is empty.
1414 No part is created if markers is empty.
1408 Raises ValueError if the bundler doesn't support any known obsmarker format.
1415 Raises ValueError if the bundler doesn't support any known obsmarker format.
1409 """
1416 """
1410 if not markers:
1417 if not markers:
1411 return None
1418 return None
1412
1419
1413 remoteversions = obsmarkersversion(bundler.capabilities)
1420 remoteversions = obsmarkersversion(bundler.capabilities)
1414 version = obsolete.commonversion(remoteversions)
1421 version = obsolete.commonversion(remoteversions)
1415 if version is None:
1422 if version is None:
1416 raise ValueError('bundler does not support common obsmarker format')
1423 raise ValueError('bundler does not support common obsmarker format')
1417 stream = obsolete.encodemarkers(markers, True, version=version)
1424 stream = obsolete.encodemarkers(markers, True, version=version)
1418 return bundler.newpart('obsmarkers', data=stream)
1425 return bundler.newpart('obsmarkers', data=stream)
1419
1426
1420 def writebundle(ui, cg, filename, bundletype, vfs=None, compression=None,
1427 def writebundle(ui, cg, filename, bundletype, vfs=None, compression=None,
1421 compopts=None):
1428 compopts=None):
1422 """Write a bundle file and return its filename.
1429 """Write a bundle file and return its filename.
1423
1430
1424 Existing files will not be overwritten.
1431 Existing files will not be overwritten.
1425 If no filename is specified, a temporary file is created.
1432 If no filename is specified, a temporary file is created.
1426 bz2 compression can be turned off.
1433 bz2 compression can be turned off.
1427 The bundle file will be deleted in case of errors.
1434 The bundle file will be deleted in case of errors.
1428 """
1435 """
1429
1436
1430 if bundletype == "HG20":
1437 if bundletype == "HG20":
1431 bundle = bundle20(ui)
1438 bundle = bundle20(ui)
1432 bundle.setcompression(compression, compopts)
1439 bundle.setcompression(compression, compopts)
1433 part = bundle.newpart('changegroup', data=cg.getchunks())
1440 part = bundle.newpart('changegroup', data=cg.getchunks())
1434 part.addparam('version', cg.version)
1441 part.addparam('version', cg.version)
1435 if 'clcount' in cg.extras:
1442 if 'clcount' in cg.extras:
1436 part.addparam('nbchanges', str(cg.extras['clcount']),
1443 part.addparam('nbchanges', str(cg.extras['clcount']),
1437 mandatory=False)
1444 mandatory=False)
1438 chunkiter = bundle.getchunks()
1445 chunkiter = bundle.getchunks()
1439 else:
1446 else:
1440 # compression argument is only for the bundle2 case
1447 # compression argument is only for the bundle2 case
1441 assert compression is None
1448 assert compression is None
1442 if cg.version != '01':
1449 if cg.version != '01':
1443 raise error.Abort(_('old bundle types only supports v1 '
1450 raise error.Abort(_('old bundle types only supports v1 '
1444 'changegroups'))
1451 'changegroups'))
1445 header, comp = bundletypes[bundletype]
1452 header, comp = bundletypes[bundletype]
1446 if comp not in util.compengines.supportedbundletypes:
1453 if comp not in util.compengines.supportedbundletypes:
1447 raise error.Abort(_('unknown stream compression type: %s')
1454 raise error.Abort(_('unknown stream compression type: %s')
1448 % comp)
1455 % comp)
1449 compengine = util.compengines.forbundletype(comp)
1456 compengine = util.compengines.forbundletype(comp)
1450 def chunkiter():
1457 def chunkiter():
1451 yield header
1458 yield header
1452 for chunk in compengine.compressstream(cg.getchunks(), compopts):
1459 for chunk in compengine.compressstream(cg.getchunks(), compopts):
1453 yield chunk
1460 yield chunk
1454 chunkiter = chunkiter()
1461 chunkiter = chunkiter()
1455
1462
1456 # parse the changegroup data, otherwise we will block
1463 # parse the changegroup data, otherwise we will block
1457 # in case of sshrepo because we don't know the end of the stream
1464 # in case of sshrepo because we don't know the end of the stream
1458 return changegroup.writechunks(ui, chunkiter, filename, vfs=vfs)
1465 return changegroup.writechunks(ui, chunkiter, filename, vfs=vfs)
1459
1466
1460 @parthandler('changegroup', ('version', 'nbchanges', 'treemanifest'))
1467 @parthandler('changegroup', ('version', 'nbchanges', 'treemanifest'))
1461 def handlechangegroup(op, inpart):
1468 def handlechangegroup(op, inpart):
1462 """apply a changegroup part on the repo
1469 """apply a changegroup part on the repo
1463
1470
1464 This is a very early implementation that will massive rework before being
1471 This is a very early implementation that will massive rework before being
1465 inflicted to any end-user.
1472 inflicted to any end-user.
1466 """
1473 """
1467 # Make sure we trigger a transaction creation
1474 # Make sure we trigger a transaction creation
1468 #
1475 #
1469 # The addchangegroup function will get a transaction object by itself, but
1476 # The addchangegroup function will get a transaction object by itself, but
1470 # we need to make sure we trigger the creation of a transaction object used
1477 # we need to make sure we trigger the creation of a transaction object used
1471 # for the whole processing scope.
1478 # for the whole processing scope.
1472 op.gettransaction()
1479 op.gettransaction()
1473 unpackerversion = inpart.params.get('version', '01')
1480 unpackerversion = inpart.params.get('version', '01')
1474 # We should raise an appropriate exception here
1481 # We should raise an appropriate exception here
1475 cg = changegroup.getunbundler(unpackerversion, inpart, None)
1482 cg = changegroup.getunbundler(unpackerversion, inpart, None)
1476 # the source and url passed here are overwritten by the one contained in
1483 # the source and url passed here are overwritten by the one contained in
1477 # the transaction.hookargs argument. So 'bundle2' is a placeholder
1484 # the transaction.hookargs argument. So 'bundle2' is a placeholder
1478 nbchangesets = None
1485 nbchangesets = None
1479 if 'nbchanges' in inpart.params:
1486 if 'nbchanges' in inpart.params:
1480 nbchangesets = int(inpart.params.get('nbchanges'))
1487 nbchangesets = int(inpart.params.get('nbchanges'))
1481 if ('treemanifest' in inpart.params and
1488 if ('treemanifest' in inpart.params and
1482 'treemanifest' not in op.repo.requirements):
1489 'treemanifest' not in op.repo.requirements):
1483 if len(op.repo.changelog) != 0:
1490 if len(op.repo.changelog) != 0:
1484 raise error.Abort(_(
1491 raise error.Abort(_(
1485 "bundle contains tree manifests, but local repo is "
1492 "bundle contains tree manifests, but local repo is "
1486 "non-empty and does not use tree manifests"))
1493 "non-empty and does not use tree manifests"))
1487 op.repo.requirements.add('treemanifest')
1494 op.repo.requirements.add('treemanifest')
1488 op.repo._applyopenerreqs()
1495 op.repo._applyopenerreqs()
1489 op.repo._writerequirements()
1496 op.repo._writerequirements()
1490 ret = cg.apply(op.repo, 'bundle2', 'bundle2', expectedtotal=nbchangesets)
1497 ret = cg.apply(op.repo, 'bundle2', 'bundle2', expectedtotal=nbchangesets)
1491 op.records.add('changegroup', {'return': ret})
1498 op.records.add('changegroup', {'return': ret})
1492 if op.reply is not None:
1499 if op.reply is not None:
1493 # This is definitely not the final form of this
1500 # This is definitely not the final form of this
1494 # return. But one need to start somewhere.
1501 # return. But one need to start somewhere.
1495 part = op.reply.newpart('reply:changegroup', mandatory=False)
1502 part = op.reply.newpart('reply:changegroup', mandatory=False)
1496 part.addparam('in-reply-to', str(inpart.id), mandatory=False)
1503 part.addparam('in-reply-to', str(inpart.id), mandatory=False)
1497 part.addparam('return', '%i' % ret, mandatory=False)
1504 part.addparam('return', '%i' % ret, mandatory=False)
1498 assert not inpart.read()
1505 assert not inpart.read()
1499
1506
1500 _remotechangegroupparams = tuple(['url', 'size', 'digests'] +
1507 _remotechangegroupparams = tuple(['url', 'size', 'digests'] +
1501 ['digest:%s' % k for k in util.DIGESTS.keys()])
1508 ['digest:%s' % k for k in util.DIGESTS.keys()])
1502 @parthandler('remote-changegroup', _remotechangegroupparams)
1509 @parthandler('remote-changegroup', _remotechangegroupparams)
1503 def handleremotechangegroup(op, inpart):
1510 def handleremotechangegroup(op, inpart):
1504 """apply a bundle10 on the repo, given an url and validation information
1511 """apply a bundle10 on the repo, given an url and validation information
1505
1512
1506 All the information about the remote bundle to import are given as
1513 All the information about the remote bundle to import are given as
1507 parameters. The parameters include:
1514 parameters. The parameters include:
1508 - url: the url to the bundle10.
1515 - url: the url to the bundle10.
1509 - size: the bundle10 file size. It is used to validate what was
1516 - size: the bundle10 file size. It is used to validate what was
1510 retrieved by the client matches the server knowledge about the bundle.
1517 retrieved by the client matches the server knowledge about the bundle.
1511 - digests: a space separated list of the digest types provided as
1518 - digests: a space separated list of the digest types provided as
1512 parameters.
1519 parameters.
1513 - digest:<digest-type>: the hexadecimal representation of the digest with
1520 - digest:<digest-type>: the hexadecimal representation of the digest with
1514 that name. Like the size, it is used to validate what was retrieved by
1521 that name. Like the size, it is used to validate what was retrieved by
1515 the client matches what the server knows about the bundle.
1522 the client matches what the server knows about the bundle.
1516
1523
1517 When multiple digest types are given, all of them are checked.
1524 When multiple digest types are given, all of them are checked.
1518 """
1525 """
1519 try:
1526 try:
1520 raw_url = inpart.params['url']
1527 raw_url = inpart.params['url']
1521 except KeyError:
1528 except KeyError:
1522 raise error.Abort(_('remote-changegroup: missing "%s" param') % 'url')
1529 raise error.Abort(_('remote-changegroup: missing "%s" param') % 'url')
1523 parsed_url = util.url(raw_url)
1530 parsed_url = util.url(raw_url)
1524 if parsed_url.scheme not in capabilities['remote-changegroup']:
1531 if parsed_url.scheme not in capabilities['remote-changegroup']:
1525 raise error.Abort(_('remote-changegroup does not support %s urls') %
1532 raise error.Abort(_('remote-changegroup does not support %s urls') %
1526 parsed_url.scheme)
1533 parsed_url.scheme)
1527
1534
1528 try:
1535 try:
1529 size = int(inpart.params['size'])
1536 size = int(inpart.params['size'])
1530 except ValueError:
1537 except ValueError:
1531 raise error.Abort(_('remote-changegroup: invalid value for param "%s"')
1538 raise error.Abort(_('remote-changegroup: invalid value for param "%s"')
1532 % 'size')
1539 % 'size')
1533 except KeyError:
1540 except KeyError:
1534 raise error.Abort(_('remote-changegroup: missing "%s" param') % 'size')
1541 raise error.Abort(_('remote-changegroup: missing "%s" param') % 'size')
1535
1542
1536 digests = {}
1543 digests = {}
1537 for typ in inpart.params.get('digests', '').split():
1544 for typ in inpart.params.get('digests', '').split():
1538 param = 'digest:%s' % typ
1545 param = 'digest:%s' % typ
1539 try:
1546 try:
1540 value = inpart.params[param]
1547 value = inpart.params[param]
1541 except KeyError:
1548 except KeyError:
1542 raise error.Abort(_('remote-changegroup: missing "%s" param') %
1549 raise error.Abort(_('remote-changegroup: missing "%s" param') %
1543 param)
1550 param)
1544 digests[typ] = value
1551 digests[typ] = value
1545
1552
1546 real_part = util.digestchecker(url.open(op.ui, raw_url), size, digests)
1553 real_part = util.digestchecker(url.open(op.ui, raw_url), size, digests)
1547
1554
1548 # Make sure we trigger a transaction creation
1555 # Make sure we trigger a transaction creation
1549 #
1556 #
1550 # The addchangegroup function will get a transaction object by itself, but
1557 # The addchangegroup function will get a transaction object by itself, but
1551 # we need to make sure we trigger the creation of a transaction object used
1558 # we need to make sure we trigger the creation of a transaction object used
1552 # for the whole processing scope.
1559 # for the whole processing scope.
1553 op.gettransaction()
1560 op.gettransaction()
1554 from . import exchange
1561 from . import exchange
1555 cg = exchange.readbundle(op.repo.ui, real_part, raw_url)
1562 cg = exchange.readbundle(op.repo.ui, real_part, raw_url)
1556 if not isinstance(cg, changegroup.cg1unpacker):
1563 if not isinstance(cg, changegroup.cg1unpacker):
1557 raise error.Abort(_('%s: not a bundle version 1.0') %
1564 raise error.Abort(_('%s: not a bundle version 1.0') %
1558 util.hidepassword(raw_url))
1565 util.hidepassword(raw_url))
1559 ret = cg.apply(op.repo, 'bundle2', 'bundle2')
1566 ret = cg.apply(op.repo, 'bundle2', 'bundle2')
1560 op.records.add('changegroup', {'return': ret})
1567 op.records.add('changegroup', {'return': ret})
1561 if op.reply is not None:
1568 if op.reply is not None:
1562 # This is definitely not the final form of this
1569 # This is definitely not the final form of this
1563 # return. But one need to start somewhere.
1570 # return. But one need to start somewhere.
1564 part = op.reply.newpart('reply:changegroup')
1571 part = op.reply.newpart('reply:changegroup')
1565 part.addparam('in-reply-to', str(inpart.id), mandatory=False)
1572 part.addparam('in-reply-to', str(inpart.id), mandatory=False)
1566 part.addparam('return', '%i' % ret, mandatory=False)
1573 part.addparam('return', '%i' % ret, mandatory=False)
1567 try:
1574 try:
1568 real_part.validate()
1575 real_part.validate()
1569 except error.Abort as e:
1576 except error.Abort as e:
1570 raise error.Abort(_('bundle at %s is corrupted:\n%s') %
1577 raise error.Abort(_('bundle at %s is corrupted:\n%s') %
1571 (util.hidepassword(raw_url), str(e)))
1578 (util.hidepassword(raw_url), str(e)))
1572 assert not inpart.read()
1579 assert not inpart.read()
1573
1580
1574 @parthandler('reply:changegroup', ('return', 'in-reply-to'))
1581 @parthandler('reply:changegroup', ('return', 'in-reply-to'))
1575 def handlereplychangegroup(op, inpart):
1582 def handlereplychangegroup(op, inpart):
1576 ret = int(inpart.params['return'])
1583 ret = int(inpart.params['return'])
1577 replyto = int(inpart.params['in-reply-to'])
1584 replyto = int(inpart.params['in-reply-to'])
1578 op.records.add('changegroup', {'return': ret}, replyto)
1585 op.records.add('changegroup', {'return': ret}, replyto)
1579
1586
1580 @parthandler('check:heads')
1587 @parthandler('check:heads')
1581 def handlecheckheads(op, inpart):
1588 def handlecheckheads(op, inpart):
1582 """check that head of the repo did not change
1589 """check that head of the repo did not change
1583
1590
1584 This is used to detect a push race when using unbundle.
1591 This is used to detect a push race when using unbundle.
1585 This replaces the "heads" argument of unbundle."""
1592 This replaces the "heads" argument of unbundle."""
1586 h = inpart.read(20)
1593 h = inpart.read(20)
1587 heads = []
1594 heads = []
1588 while len(h) == 20:
1595 while len(h) == 20:
1589 heads.append(h)
1596 heads.append(h)
1590 h = inpart.read(20)
1597 h = inpart.read(20)
1591 assert not h
1598 assert not h
1592 # Trigger a transaction so that we are guaranteed to have the lock now.
1599 # Trigger a transaction so that we are guaranteed to have the lock now.
1593 if op.ui.configbool('experimental', 'bundle2lazylocking'):
1600 if op.ui.configbool('experimental', 'bundle2lazylocking'):
1594 op.gettransaction()
1601 op.gettransaction()
1595 if sorted(heads) != sorted(op.repo.heads()):
1602 if sorted(heads) != sorted(op.repo.heads()):
1596 raise error.PushRaced('repository changed while pushing - '
1603 raise error.PushRaced('repository changed while pushing - '
1597 'please try again')
1604 'please try again')
1598
1605
1599 @parthandler('output')
1606 @parthandler('output')
1600 def handleoutput(op, inpart):
1607 def handleoutput(op, inpart):
1601 """forward output captured on the server to the client"""
1608 """forward output captured on the server to the client"""
1602 for line in inpart.read().splitlines():
1609 for line in inpart.read().splitlines():
1603 op.ui.status(_('remote: %s\n') % line)
1610 op.ui.status(_('remote: %s\n') % line)
1604
1611
1605 @parthandler('replycaps')
1612 @parthandler('replycaps')
1606 def handlereplycaps(op, inpart):
1613 def handlereplycaps(op, inpart):
1607 """Notify that a reply bundle should be created
1614 """Notify that a reply bundle should be created
1608
1615
1609 The payload contains the capabilities information for the reply"""
1616 The payload contains the capabilities information for the reply"""
1610 caps = decodecaps(inpart.read())
1617 caps = decodecaps(inpart.read())
1611 if op.reply is None:
1618 if op.reply is None:
1612 op.reply = bundle20(op.ui, caps)
1619 op.reply = bundle20(op.ui, caps)
1613
1620
1614 class AbortFromPart(error.Abort):
1621 class AbortFromPart(error.Abort):
1615 """Sub-class of Abort that denotes an error from a bundle2 part."""
1622 """Sub-class of Abort that denotes an error from a bundle2 part."""
1616
1623
1617 @parthandler('error:abort', ('message', 'hint'))
1624 @parthandler('error:abort', ('message', 'hint'))
1618 def handleerrorabort(op, inpart):
1625 def handleerrorabort(op, inpart):
1619 """Used to transmit abort error over the wire"""
1626 """Used to transmit abort error over the wire"""
1620 raise AbortFromPart(inpart.params['message'],
1627 raise AbortFromPart(inpart.params['message'],
1621 hint=inpart.params.get('hint'))
1628 hint=inpart.params.get('hint'))
1622
1629
1623 @parthandler('error:pushkey', ('namespace', 'key', 'new', 'old', 'ret',
1630 @parthandler('error:pushkey', ('namespace', 'key', 'new', 'old', 'ret',
1624 'in-reply-to'))
1631 'in-reply-to'))
1625 def handleerrorpushkey(op, inpart):
1632 def handleerrorpushkey(op, inpart):
1626 """Used to transmit failure of a mandatory pushkey over the wire"""
1633 """Used to transmit failure of a mandatory pushkey over the wire"""
1627 kwargs = {}
1634 kwargs = {}
1628 for name in ('namespace', 'key', 'new', 'old', 'ret'):
1635 for name in ('namespace', 'key', 'new', 'old', 'ret'):
1629 value = inpart.params.get(name)
1636 value = inpart.params.get(name)
1630 if value is not None:
1637 if value is not None:
1631 kwargs[name] = value
1638 kwargs[name] = value
1632 raise error.PushkeyFailed(inpart.params['in-reply-to'], **kwargs)
1639 raise error.PushkeyFailed(inpart.params['in-reply-to'], **kwargs)
1633
1640
1634 @parthandler('error:unsupportedcontent', ('parttype', 'params'))
1641 @parthandler('error:unsupportedcontent', ('parttype', 'params'))
1635 def handleerrorunsupportedcontent(op, inpart):
1642 def handleerrorunsupportedcontent(op, inpart):
1636 """Used to transmit unknown content error over the wire"""
1643 """Used to transmit unknown content error over the wire"""
1637 kwargs = {}
1644 kwargs = {}
1638 parttype = inpart.params.get('parttype')
1645 parttype = inpart.params.get('parttype')
1639 if parttype is not None:
1646 if parttype is not None:
1640 kwargs['parttype'] = parttype
1647 kwargs['parttype'] = parttype
1641 params = inpart.params.get('params')
1648 params = inpart.params.get('params')
1642 if params is not None:
1649 if params is not None:
1643 kwargs['params'] = params.split('\0')
1650 kwargs['params'] = params.split('\0')
1644
1651
1645 raise error.BundleUnknownFeatureError(**kwargs)
1652 raise error.BundleUnknownFeatureError(**kwargs)
1646
1653
1647 @parthandler('error:pushraced', ('message',))
1654 @parthandler('error:pushraced', ('message',))
1648 def handleerrorpushraced(op, inpart):
1655 def handleerrorpushraced(op, inpart):
1649 """Used to transmit push race error over the wire"""
1656 """Used to transmit push race error over the wire"""
1650 raise error.ResponseError(_('push failed:'), inpart.params['message'])
1657 raise error.ResponseError(_('push failed:'), inpart.params['message'])
1651
1658
1652 @parthandler('listkeys', ('namespace',))
1659 @parthandler('listkeys', ('namespace',))
1653 def handlelistkeys(op, inpart):
1660 def handlelistkeys(op, inpart):
1654 """retrieve pushkey namespace content stored in a bundle2"""
1661 """retrieve pushkey namespace content stored in a bundle2"""
1655 namespace = inpart.params['namespace']
1662 namespace = inpart.params['namespace']
1656 r = pushkey.decodekeys(inpart.read())
1663 r = pushkey.decodekeys(inpart.read())
1657 op.records.add('listkeys', (namespace, r))
1664 op.records.add('listkeys', (namespace, r))
1658
1665
1659 @parthandler('pushkey', ('namespace', 'key', 'old', 'new'))
1666 @parthandler('pushkey', ('namespace', 'key', 'old', 'new'))
1660 def handlepushkey(op, inpart):
1667 def handlepushkey(op, inpart):
1661 """process a pushkey request"""
1668 """process a pushkey request"""
1662 dec = pushkey.decode
1669 dec = pushkey.decode
1663 namespace = dec(inpart.params['namespace'])
1670 namespace = dec(inpart.params['namespace'])
1664 key = dec(inpart.params['key'])
1671 key = dec(inpart.params['key'])
1665 old = dec(inpart.params['old'])
1672 old = dec(inpart.params['old'])
1666 new = dec(inpart.params['new'])
1673 new = dec(inpart.params['new'])
1667 # Grab the transaction to ensure that we have the lock before performing the
1674 # Grab the transaction to ensure that we have the lock before performing the
1668 # pushkey.
1675 # pushkey.
1669 if op.ui.configbool('experimental', 'bundle2lazylocking'):
1676 if op.ui.configbool('experimental', 'bundle2lazylocking'):
1670 op.gettransaction()
1677 op.gettransaction()
1671 ret = op.repo.pushkey(namespace, key, old, new)
1678 ret = op.repo.pushkey(namespace, key, old, new)
1672 record = {'namespace': namespace,
1679 record = {'namespace': namespace,
1673 'key': key,
1680 'key': key,
1674 'old': old,
1681 'old': old,
1675 'new': new}
1682 'new': new}
1676 op.records.add('pushkey', record)
1683 op.records.add('pushkey', record)
1677 if op.reply is not None:
1684 if op.reply is not None:
1678 rpart = op.reply.newpart('reply:pushkey')
1685 rpart = op.reply.newpart('reply:pushkey')
1679 rpart.addparam('in-reply-to', str(inpart.id), mandatory=False)
1686 rpart.addparam('in-reply-to', str(inpart.id), mandatory=False)
1680 rpart.addparam('return', '%i' % ret, mandatory=False)
1687 rpart.addparam('return', '%i' % ret, mandatory=False)
1681 if inpart.mandatory and not ret:
1688 if inpart.mandatory and not ret:
1682 kwargs = {}
1689 kwargs = {}
1683 for key in ('namespace', 'key', 'new', 'old', 'ret'):
1690 for key in ('namespace', 'key', 'new', 'old', 'ret'):
1684 if key in inpart.params:
1691 if key in inpart.params:
1685 kwargs[key] = inpart.params[key]
1692 kwargs[key] = inpart.params[key]
1686 raise error.PushkeyFailed(partid=str(inpart.id), **kwargs)
1693 raise error.PushkeyFailed(partid=str(inpart.id), **kwargs)
1687
1694
1688 @parthandler('reply:pushkey', ('return', 'in-reply-to'))
1695 @parthandler('reply:pushkey', ('return', 'in-reply-to'))
1689 def handlepushkeyreply(op, inpart):
1696 def handlepushkeyreply(op, inpart):
1690 """retrieve the result of a pushkey request"""
1697 """retrieve the result of a pushkey request"""
1691 ret = int(inpart.params['return'])
1698 ret = int(inpart.params['return'])
1692 partid = int(inpart.params['in-reply-to'])
1699 partid = int(inpart.params['in-reply-to'])
1693 op.records.add('pushkey', {'return': ret}, partid)
1700 op.records.add('pushkey', {'return': ret}, partid)
1694
1701
1695 @parthandler('obsmarkers')
1702 @parthandler('obsmarkers')
1696 def handleobsmarker(op, inpart):
1703 def handleobsmarker(op, inpart):
1697 """add a stream of obsmarkers to the repo"""
1704 """add a stream of obsmarkers to the repo"""
1698 tr = op.gettransaction()
1705 tr = op.gettransaction()
1699 markerdata = inpart.read()
1706 markerdata = inpart.read()
1700 if op.ui.config('experimental', 'obsmarkers-exchange-debug', False):
1707 if op.ui.config('experimental', 'obsmarkers-exchange-debug', False):
1701 op.ui.write(('obsmarker-exchange: %i bytes received\n')
1708 op.ui.write(('obsmarker-exchange: %i bytes received\n')
1702 % len(markerdata))
1709 % len(markerdata))
1703 # The mergemarkers call will crash if marker creation is not enabled.
1710 # The mergemarkers call will crash if marker creation is not enabled.
1704 # we want to avoid this if the part is advisory.
1711 # we want to avoid this if the part is advisory.
1705 if not inpart.mandatory and op.repo.obsstore.readonly:
1712 if not inpart.mandatory and op.repo.obsstore.readonly:
1706 op.repo.ui.debug('ignoring obsolescence markers, feature not enabled')
1713 op.repo.ui.debug('ignoring obsolescence markers, feature not enabled')
1707 return
1714 return
1708 new = op.repo.obsstore.mergemarkers(tr, markerdata)
1715 new = op.repo.obsstore.mergemarkers(tr, markerdata)
1709 op.repo.invalidatevolatilesets()
1716 op.repo.invalidatevolatilesets()
1710 if new:
1717 if new:
1711 op.repo.ui.status(_('%i new obsolescence markers\n') % new)
1718 op.repo.ui.status(_('%i new obsolescence markers\n') % new)
1712 op.records.add('obsmarkers', {'new': new})
1719 op.records.add('obsmarkers', {'new': new})
1713 if op.reply is not None:
1720 if op.reply is not None:
1714 rpart = op.reply.newpart('reply:obsmarkers')
1721 rpart = op.reply.newpart('reply:obsmarkers')
1715 rpart.addparam('in-reply-to', str(inpart.id), mandatory=False)
1722 rpart.addparam('in-reply-to', str(inpart.id), mandatory=False)
1716 rpart.addparam('new', '%i' % new, mandatory=False)
1723 rpart.addparam('new', '%i' % new, mandatory=False)
1717
1724
1718
1725
1719 @parthandler('reply:obsmarkers', ('new', 'in-reply-to'))
1726 @parthandler('reply:obsmarkers', ('new', 'in-reply-to'))
1720 def handleobsmarkerreply(op, inpart):
1727 def handleobsmarkerreply(op, inpart):
1721 """retrieve the result of a pushkey request"""
1728 """retrieve the result of a pushkey request"""
1722 ret = int(inpart.params['new'])
1729 ret = int(inpart.params['new'])
1723 partid = int(inpart.params['in-reply-to'])
1730 partid = int(inpart.params['in-reply-to'])
1724 op.records.add('obsmarkers', {'new': ret}, partid)
1731 op.records.add('obsmarkers', {'new': ret}, partid)
1725
1732
1726 @parthandler('hgtagsfnodes')
1733 @parthandler('hgtagsfnodes')
1727 def handlehgtagsfnodes(op, inpart):
1734 def handlehgtagsfnodes(op, inpart):
1728 """Applies .hgtags fnodes cache entries to the local repo.
1735 """Applies .hgtags fnodes cache entries to the local repo.
1729
1736
1730 Payload is pairs of 20 byte changeset nodes and filenodes.
1737 Payload is pairs of 20 byte changeset nodes and filenodes.
1731 """
1738 """
1732 # Grab the transaction so we ensure that we have the lock at this point.
1739 # Grab the transaction so we ensure that we have the lock at this point.
1733 if op.ui.configbool('experimental', 'bundle2lazylocking'):
1740 if op.ui.configbool('experimental', 'bundle2lazylocking'):
1734 op.gettransaction()
1741 op.gettransaction()
1735 cache = tags.hgtagsfnodescache(op.repo.unfiltered())
1742 cache = tags.hgtagsfnodescache(op.repo.unfiltered())
1736
1743
1737 count = 0
1744 count = 0
1738 while True:
1745 while True:
1739 node = inpart.read(20)
1746 node = inpart.read(20)
1740 fnode = inpart.read(20)
1747 fnode = inpart.read(20)
1741 if len(node) < 20 or len(fnode) < 20:
1748 if len(node) < 20 or len(fnode) < 20:
1742 op.ui.debug('ignoring incomplete received .hgtags fnodes data\n')
1749 op.ui.debug('ignoring incomplete received .hgtags fnodes data\n')
1743 break
1750 break
1744 cache.setfnode(node, fnode)
1751 cache.setfnode(node, fnode)
1745 count += 1
1752 count += 1
1746
1753
1747 cache.write()
1754 cache.write()
1748 op.ui.debug('applied %i hgtags fnodes cache entries\n' % count)
1755 op.ui.debug('applied %i hgtags fnodes cache entries\n' % count)
@@ -1,5487 +1,5489 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import difflib
10 import difflib
11 import errno
11 import errno
12 import os
12 import os
13 import re
13 import re
14
14
15 from .i18n import _
15 from .i18n import _
16 from .node import (
16 from .node import (
17 hex,
17 hex,
18 nullid,
18 nullid,
19 nullrev,
19 nullrev,
20 short,
20 short,
21 )
21 )
22 from . import (
22 from . import (
23 archival,
23 archival,
24 bookmarks,
24 bookmarks,
25 bundle2,
25 bundle2,
26 changegroup,
26 changegroup,
27 cmdutil,
27 cmdutil,
28 copies,
28 copies,
29 debugcommands as debugcommandsmod,
29 debugcommands as debugcommandsmod,
30 destutil,
30 destutil,
31 dirstateguard,
31 dirstateguard,
32 discovery,
32 discovery,
33 encoding,
33 encoding,
34 error,
34 error,
35 exchange,
35 exchange,
36 extensions,
36 extensions,
37 graphmod,
37 graphmod,
38 hbisect,
38 hbisect,
39 help,
39 help,
40 hg,
40 hg,
41 lock as lockmod,
41 lock as lockmod,
42 merge as mergemod,
42 merge as mergemod,
43 obsolete,
43 obsolete,
44 patch,
44 patch,
45 phases,
45 phases,
46 pycompat,
46 pycompat,
47 rcutil,
47 rcutil,
48 registrar,
48 registrar,
49 revsetlang,
49 revsetlang,
50 scmutil,
50 scmutil,
51 server,
51 server,
52 sshserver,
52 sshserver,
53 streamclone,
53 streamclone,
54 tags as tagsmod,
54 tags as tagsmod,
55 templatekw,
55 templatekw,
56 ui as uimod,
56 ui as uimod,
57 util,
57 util,
58 )
58 )
59
59
60 release = lockmod.release
60 release = lockmod.release
61
61
62 table = {}
62 table = {}
63 table.update(debugcommandsmod.command._table)
63 table.update(debugcommandsmod.command._table)
64
64
65 command = registrar.command(table)
65 command = registrar.command(table)
66
66
67 # label constants
67 # label constants
68 # until 3.5, bookmarks.current was the advertised name, not
68 # until 3.5, bookmarks.current was the advertised name, not
69 # bookmarks.active, so we must use both to avoid breaking old
69 # bookmarks.active, so we must use both to avoid breaking old
70 # custom styles
70 # custom styles
71 activebookmarklabel = 'bookmarks.active bookmarks.current'
71 activebookmarklabel = 'bookmarks.active bookmarks.current'
72
72
73 # common command options
73 # common command options
74
74
75 globalopts = [
75 globalopts = [
76 ('R', 'repository', '',
76 ('R', 'repository', '',
77 _('repository root directory or name of overlay bundle file'),
77 _('repository root directory or name of overlay bundle file'),
78 _('REPO')),
78 _('REPO')),
79 ('', 'cwd', '',
79 ('', 'cwd', '',
80 _('change working directory'), _('DIR')),
80 _('change working directory'), _('DIR')),
81 ('y', 'noninteractive', None,
81 ('y', 'noninteractive', None,
82 _('do not prompt, automatically pick the first choice for all prompts')),
82 _('do not prompt, automatically pick the first choice for all prompts')),
83 ('q', 'quiet', None, _('suppress output')),
83 ('q', 'quiet', None, _('suppress output')),
84 ('v', 'verbose', None, _('enable additional output')),
84 ('v', 'verbose', None, _('enable additional output')),
85 ('', 'color', '',
85 ('', 'color', '',
86 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
86 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
87 # and should not be translated
87 # and should not be translated
88 _("when to colorize (boolean, always, auto, never, or debug)"),
88 _("when to colorize (boolean, always, auto, never, or debug)"),
89 _('TYPE')),
89 _('TYPE')),
90 ('', 'config', [],
90 ('', 'config', [],
91 _('set/override config option (use \'section.name=value\')'),
91 _('set/override config option (use \'section.name=value\')'),
92 _('CONFIG')),
92 _('CONFIG')),
93 ('', 'debug', None, _('enable debugging output')),
93 ('', 'debug', None, _('enable debugging output')),
94 ('', 'debugger', None, _('start debugger')),
94 ('', 'debugger', None, _('start debugger')),
95 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
95 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
96 _('ENCODE')),
96 _('ENCODE')),
97 ('', 'encodingmode', encoding.encodingmode,
97 ('', 'encodingmode', encoding.encodingmode,
98 _('set the charset encoding mode'), _('MODE')),
98 _('set the charset encoding mode'), _('MODE')),
99 ('', 'traceback', None, _('always print a traceback on exception')),
99 ('', 'traceback', None, _('always print a traceback on exception')),
100 ('', 'time', None, _('time how long the command takes')),
100 ('', 'time', None, _('time how long the command takes')),
101 ('', 'profile', None, _('print command execution profile')),
101 ('', 'profile', None, _('print command execution profile')),
102 ('', 'version', None, _('output version information and exit')),
102 ('', 'version', None, _('output version information and exit')),
103 ('h', 'help', None, _('display help and exit')),
103 ('h', 'help', None, _('display help and exit')),
104 ('', 'hidden', False, _('consider hidden changesets')),
104 ('', 'hidden', False, _('consider hidden changesets')),
105 ('', 'pager', 'auto',
105 ('', 'pager', 'auto',
106 _("when to paginate (boolean, always, auto, or never)"), _('TYPE')),
106 _("when to paginate (boolean, always, auto, or never)"), _('TYPE')),
107 ]
107 ]
108
108
109 dryrunopts = cmdutil.dryrunopts
109 dryrunopts = cmdutil.dryrunopts
110 remoteopts = cmdutil.remoteopts
110 remoteopts = cmdutil.remoteopts
111 walkopts = cmdutil.walkopts
111 walkopts = cmdutil.walkopts
112 commitopts = cmdutil.commitopts
112 commitopts = cmdutil.commitopts
113 commitopts2 = cmdutil.commitopts2
113 commitopts2 = cmdutil.commitopts2
114 formatteropts = cmdutil.formatteropts
114 formatteropts = cmdutil.formatteropts
115 templateopts = cmdutil.templateopts
115 templateopts = cmdutil.templateopts
116 logopts = cmdutil.logopts
116 logopts = cmdutil.logopts
117 diffopts = cmdutil.diffopts
117 diffopts = cmdutil.diffopts
118 diffwsopts = cmdutil.diffwsopts
118 diffwsopts = cmdutil.diffwsopts
119 diffopts2 = cmdutil.diffopts2
119 diffopts2 = cmdutil.diffopts2
120 mergetoolopts = cmdutil.mergetoolopts
120 mergetoolopts = cmdutil.mergetoolopts
121 similarityopts = cmdutil.similarityopts
121 similarityopts = cmdutil.similarityopts
122 subrepoopts = cmdutil.subrepoopts
122 subrepoopts = cmdutil.subrepoopts
123 debugrevlogopts = cmdutil.debugrevlogopts
123 debugrevlogopts = cmdutil.debugrevlogopts
124
124
125 # Commands start here, listed alphabetically
125 # Commands start here, listed alphabetically
126
126
127 @command('^add',
127 @command('^add',
128 walkopts + subrepoopts + dryrunopts,
128 walkopts + subrepoopts + dryrunopts,
129 _('[OPTION]... [FILE]...'),
129 _('[OPTION]... [FILE]...'),
130 inferrepo=True)
130 inferrepo=True)
131 def add(ui, repo, *pats, **opts):
131 def add(ui, repo, *pats, **opts):
132 """add the specified files on the next commit
132 """add the specified files on the next commit
133
133
134 Schedule files to be version controlled and added to the
134 Schedule files to be version controlled and added to the
135 repository.
135 repository.
136
136
137 The files will be added to the repository at the next commit. To
137 The files will be added to the repository at the next commit. To
138 undo an add before that, see :hg:`forget`.
138 undo an add before that, see :hg:`forget`.
139
139
140 If no names are given, add all files to the repository (except
140 If no names are given, add all files to the repository (except
141 files matching ``.hgignore``).
141 files matching ``.hgignore``).
142
142
143 .. container:: verbose
143 .. container:: verbose
144
144
145 Examples:
145 Examples:
146
146
147 - New (unknown) files are added
147 - New (unknown) files are added
148 automatically by :hg:`add`::
148 automatically by :hg:`add`::
149
149
150 $ ls
150 $ ls
151 foo.c
151 foo.c
152 $ hg status
152 $ hg status
153 ? foo.c
153 ? foo.c
154 $ hg add
154 $ hg add
155 adding foo.c
155 adding foo.c
156 $ hg status
156 $ hg status
157 A foo.c
157 A foo.c
158
158
159 - Specific files to be added can be specified::
159 - Specific files to be added can be specified::
160
160
161 $ ls
161 $ ls
162 bar.c foo.c
162 bar.c foo.c
163 $ hg status
163 $ hg status
164 ? bar.c
164 ? bar.c
165 ? foo.c
165 ? foo.c
166 $ hg add bar.c
166 $ hg add bar.c
167 $ hg status
167 $ hg status
168 A bar.c
168 A bar.c
169 ? foo.c
169 ? foo.c
170
170
171 Returns 0 if all files are successfully added.
171 Returns 0 if all files are successfully added.
172 """
172 """
173
173
174 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
174 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
175 rejected = cmdutil.add(ui, repo, m, "", False, **opts)
175 rejected = cmdutil.add(ui, repo, m, "", False, **opts)
176 return rejected and 1 or 0
176 return rejected and 1 or 0
177
177
178 @command('addremove',
178 @command('addremove',
179 similarityopts + subrepoopts + walkopts + dryrunopts,
179 similarityopts + subrepoopts + walkopts + dryrunopts,
180 _('[OPTION]... [FILE]...'),
180 _('[OPTION]... [FILE]...'),
181 inferrepo=True)
181 inferrepo=True)
182 def addremove(ui, repo, *pats, **opts):
182 def addremove(ui, repo, *pats, **opts):
183 """add all new files, delete all missing files
183 """add all new files, delete all missing files
184
184
185 Add all new files and remove all missing files from the
185 Add all new files and remove all missing files from the
186 repository.
186 repository.
187
187
188 Unless names are given, new files are ignored if they match any of
188 Unless names are given, new files are ignored if they match any of
189 the patterns in ``.hgignore``. As with add, these changes take
189 the patterns in ``.hgignore``. As with add, these changes take
190 effect at the next commit.
190 effect at the next commit.
191
191
192 Use the -s/--similarity option to detect renamed files. This
192 Use the -s/--similarity option to detect renamed files. This
193 option takes a percentage between 0 (disabled) and 100 (files must
193 option takes a percentage between 0 (disabled) and 100 (files must
194 be identical) as its parameter. With a parameter greater than 0,
194 be identical) as its parameter. With a parameter greater than 0,
195 this compares every removed file with every added file and records
195 this compares every removed file with every added file and records
196 those similar enough as renames. Detecting renamed files this way
196 those similar enough as renames. Detecting renamed files this way
197 can be expensive. After using this option, :hg:`status -C` can be
197 can be expensive. After using this option, :hg:`status -C` can be
198 used to check which files were identified as moved or renamed. If
198 used to check which files were identified as moved or renamed. If
199 not specified, -s/--similarity defaults to 100 and only renames of
199 not specified, -s/--similarity defaults to 100 and only renames of
200 identical files are detected.
200 identical files are detected.
201
201
202 .. container:: verbose
202 .. container:: verbose
203
203
204 Examples:
204 Examples:
205
205
206 - A number of files (bar.c and foo.c) are new,
206 - A number of files (bar.c and foo.c) are new,
207 while foobar.c has been removed (without using :hg:`remove`)
207 while foobar.c has been removed (without using :hg:`remove`)
208 from the repository::
208 from the repository::
209
209
210 $ ls
210 $ ls
211 bar.c foo.c
211 bar.c foo.c
212 $ hg status
212 $ hg status
213 ! foobar.c
213 ! foobar.c
214 ? bar.c
214 ? bar.c
215 ? foo.c
215 ? foo.c
216 $ hg addremove
216 $ hg addremove
217 adding bar.c
217 adding bar.c
218 adding foo.c
218 adding foo.c
219 removing foobar.c
219 removing foobar.c
220 $ hg status
220 $ hg status
221 A bar.c
221 A bar.c
222 A foo.c
222 A foo.c
223 R foobar.c
223 R foobar.c
224
224
225 - A file foobar.c was moved to foo.c without using :hg:`rename`.
225 - A file foobar.c was moved to foo.c without using :hg:`rename`.
226 Afterwards, it was edited slightly::
226 Afterwards, it was edited slightly::
227
227
228 $ ls
228 $ ls
229 foo.c
229 foo.c
230 $ hg status
230 $ hg status
231 ! foobar.c
231 ! foobar.c
232 ? foo.c
232 ? foo.c
233 $ hg addremove --similarity 90
233 $ hg addremove --similarity 90
234 removing foobar.c
234 removing foobar.c
235 adding foo.c
235 adding foo.c
236 recording removal of foobar.c as rename to foo.c (94% similar)
236 recording removal of foobar.c as rename to foo.c (94% similar)
237 $ hg status -C
237 $ hg status -C
238 A foo.c
238 A foo.c
239 foobar.c
239 foobar.c
240 R foobar.c
240 R foobar.c
241
241
242 Returns 0 if all files are successfully added.
242 Returns 0 if all files are successfully added.
243 """
243 """
244 opts = pycompat.byteskwargs(opts)
244 opts = pycompat.byteskwargs(opts)
245 try:
245 try:
246 sim = float(opts.get('similarity') or 100)
246 sim = float(opts.get('similarity') or 100)
247 except ValueError:
247 except ValueError:
248 raise error.Abort(_('similarity must be a number'))
248 raise error.Abort(_('similarity must be a number'))
249 if sim < 0 or sim > 100:
249 if sim < 0 or sim > 100:
250 raise error.Abort(_('similarity must be between 0 and 100'))
250 raise error.Abort(_('similarity must be between 0 and 100'))
251 matcher = scmutil.match(repo[None], pats, opts)
251 matcher = scmutil.match(repo[None], pats, opts)
252 return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
252 return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
253
253
254 @command('^annotate|blame',
254 @command('^annotate|blame',
255 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
255 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
256 ('', 'follow', None,
256 ('', 'follow', None,
257 _('follow copies/renames and list the filename (DEPRECATED)')),
257 _('follow copies/renames and list the filename (DEPRECATED)')),
258 ('', 'no-follow', None, _("don't follow copies and renames")),
258 ('', 'no-follow', None, _("don't follow copies and renames")),
259 ('a', 'text', None, _('treat all files as text')),
259 ('a', 'text', None, _('treat all files as text')),
260 ('u', 'user', None, _('list the author (long with -v)')),
260 ('u', 'user', None, _('list the author (long with -v)')),
261 ('f', 'file', None, _('list the filename')),
261 ('f', 'file', None, _('list the filename')),
262 ('d', 'date', None, _('list the date (short with -q)')),
262 ('d', 'date', None, _('list the date (short with -q)')),
263 ('n', 'number', None, _('list the revision number (default)')),
263 ('n', 'number', None, _('list the revision number (default)')),
264 ('c', 'changeset', None, _('list the changeset')),
264 ('c', 'changeset', None, _('list the changeset')),
265 ('l', 'line-number', None, _('show line number at the first appearance')),
265 ('l', 'line-number', None, _('show line number at the first appearance')),
266 ('', 'skip', [], _('revision to not display (EXPERIMENTAL)'), _('REV')),
266 ('', 'skip', [], _('revision to not display (EXPERIMENTAL)'), _('REV')),
267 ] + diffwsopts + walkopts + formatteropts,
267 ] + diffwsopts + walkopts + formatteropts,
268 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
268 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
269 inferrepo=True)
269 inferrepo=True)
270 def annotate(ui, repo, *pats, **opts):
270 def annotate(ui, repo, *pats, **opts):
271 """show changeset information by line for each file
271 """show changeset information by line for each file
272
272
273 List changes in files, showing the revision id responsible for
273 List changes in files, showing the revision id responsible for
274 each line.
274 each line.
275
275
276 This command is useful for discovering when a change was made and
276 This command is useful for discovering when a change was made and
277 by whom.
277 by whom.
278
278
279 If you include --file, --user, or --date, the revision number is
279 If you include --file, --user, or --date, the revision number is
280 suppressed unless you also include --number.
280 suppressed unless you also include --number.
281
281
282 Without the -a/--text option, annotate will avoid processing files
282 Without the -a/--text option, annotate will avoid processing files
283 it detects as binary. With -a, annotate will annotate the file
283 it detects as binary. With -a, annotate will annotate the file
284 anyway, although the results will probably be neither useful
284 anyway, although the results will probably be neither useful
285 nor desirable.
285 nor desirable.
286
286
287 Returns 0 on success.
287 Returns 0 on success.
288 """
288 """
289 opts = pycompat.byteskwargs(opts)
289 opts = pycompat.byteskwargs(opts)
290 if not pats:
290 if not pats:
291 raise error.Abort(_('at least one filename or pattern is required'))
291 raise error.Abort(_('at least one filename or pattern is required'))
292
292
293 if opts.get('follow'):
293 if opts.get('follow'):
294 # --follow is deprecated and now just an alias for -f/--file
294 # --follow is deprecated and now just an alias for -f/--file
295 # to mimic the behavior of Mercurial before version 1.5
295 # to mimic the behavior of Mercurial before version 1.5
296 opts['file'] = True
296 opts['file'] = True
297
297
298 ctx = scmutil.revsingle(repo, opts.get('rev'))
298 ctx = scmutil.revsingle(repo, opts.get('rev'))
299
299
300 fm = ui.formatter('annotate', opts)
300 fm = ui.formatter('annotate', opts)
301 if ui.quiet:
301 if ui.quiet:
302 datefunc = util.shortdate
302 datefunc = util.shortdate
303 else:
303 else:
304 datefunc = util.datestr
304 datefunc = util.datestr
305 if ctx.rev() is None:
305 if ctx.rev() is None:
306 def hexfn(node):
306 def hexfn(node):
307 if node is None:
307 if node is None:
308 return None
308 return None
309 else:
309 else:
310 return fm.hexfunc(node)
310 return fm.hexfunc(node)
311 if opts.get('changeset'):
311 if opts.get('changeset'):
312 # omit "+" suffix which is appended to node hex
312 # omit "+" suffix which is appended to node hex
313 def formatrev(rev):
313 def formatrev(rev):
314 if rev is None:
314 if rev is None:
315 return '%d' % ctx.p1().rev()
315 return '%d' % ctx.p1().rev()
316 else:
316 else:
317 return '%d' % rev
317 return '%d' % rev
318 else:
318 else:
319 def formatrev(rev):
319 def formatrev(rev):
320 if rev is None:
320 if rev is None:
321 return '%d+' % ctx.p1().rev()
321 return '%d+' % ctx.p1().rev()
322 else:
322 else:
323 return '%d ' % rev
323 return '%d ' % rev
324 def formathex(hex):
324 def formathex(hex):
325 if hex is None:
325 if hex is None:
326 return '%s+' % fm.hexfunc(ctx.p1().node())
326 return '%s+' % fm.hexfunc(ctx.p1().node())
327 else:
327 else:
328 return '%s ' % hex
328 return '%s ' % hex
329 else:
329 else:
330 hexfn = fm.hexfunc
330 hexfn = fm.hexfunc
331 formatrev = formathex = str
331 formatrev = formathex = str
332
332
333 opmap = [('user', ' ', lambda x: x[0].user(), ui.shortuser),
333 opmap = [('user', ' ', lambda x: x[0].user(), ui.shortuser),
334 ('number', ' ', lambda x: x[0].rev(), formatrev),
334 ('number', ' ', lambda x: x[0].rev(), formatrev),
335 ('changeset', ' ', lambda x: hexfn(x[0].node()), formathex),
335 ('changeset', ' ', lambda x: hexfn(x[0].node()), formathex),
336 ('date', ' ', lambda x: x[0].date(), util.cachefunc(datefunc)),
336 ('date', ' ', lambda x: x[0].date(), util.cachefunc(datefunc)),
337 ('file', ' ', lambda x: x[0].path(), str),
337 ('file', ' ', lambda x: x[0].path(), str),
338 ('line_number', ':', lambda x: x[1], str),
338 ('line_number', ':', lambda x: x[1], str),
339 ]
339 ]
340 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
340 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
341
341
342 if (not opts.get('user') and not opts.get('changeset')
342 if (not opts.get('user') and not opts.get('changeset')
343 and not opts.get('date') and not opts.get('file')):
343 and not opts.get('date') and not opts.get('file')):
344 opts['number'] = True
344 opts['number'] = True
345
345
346 linenumber = opts.get('line_number') is not None
346 linenumber = opts.get('line_number') is not None
347 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
347 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
348 raise error.Abort(_('at least one of -n/-c is required for -l'))
348 raise error.Abort(_('at least one of -n/-c is required for -l'))
349
349
350 ui.pager('annotate')
350 ui.pager('annotate')
351
351
352 if fm.isplain():
352 if fm.isplain():
353 def makefunc(get, fmt):
353 def makefunc(get, fmt):
354 return lambda x: fmt(get(x))
354 return lambda x: fmt(get(x))
355 else:
355 else:
356 def makefunc(get, fmt):
356 def makefunc(get, fmt):
357 return get
357 return get
358 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
358 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
359 if opts.get(op)]
359 if opts.get(op)]
360 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
360 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
361 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
361 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
362 if opts.get(op))
362 if opts.get(op))
363
363
364 def bad(x, y):
364 def bad(x, y):
365 raise error.Abort("%s: %s" % (x, y))
365 raise error.Abort("%s: %s" % (x, y))
366
366
367 m = scmutil.match(ctx, pats, opts, badfn=bad)
367 m = scmutil.match(ctx, pats, opts, badfn=bad)
368
368
369 follow = not opts.get('no_follow')
369 follow = not opts.get('no_follow')
370 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
370 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
371 whitespace=True)
371 whitespace=True)
372 skiprevs = opts.get('skip')
372 skiprevs = opts.get('skip')
373 if skiprevs:
373 if skiprevs:
374 skiprevs = scmutil.revrange(repo, skiprevs)
374 skiprevs = scmutil.revrange(repo, skiprevs)
375
375
376 for abs in ctx.walk(m):
376 for abs in ctx.walk(m):
377 fctx = ctx[abs]
377 fctx = ctx[abs]
378 if not opts.get('text') and fctx.isbinary():
378 if not opts.get('text') and fctx.isbinary():
379 fm.plain(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
379 fm.plain(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
380 continue
380 continue
381
381
382 lines = fctx.annotate(follow=follow, linenumber=linenumber,
382 lines = fctx.annotate(follow=follow, linenumber=linenumber,
383 skiprevs=skiprevs, diffopts=diffopts)
383 skiprevs=skiprevs, diffopts=diffopts)
384 if not lines:
384 if not lines:
385 continue
385 continue
386 formats = []
386 formats = []
387 pieces = []
387 pieces = []
388
388
389 for f, sep in funcmap:
389 for f, sep in funcmap:
390 l = [f(n) for n, dummy in lines]
390 l = [f(n) for n, dummy in lines]
391 if fm.isplain():
391 if fm.isplain():
392 sizes = [encoding.colwidth(x) for x in l]
392 sizes = [encoding.colwidth(x) for x in l]
393 ml = max(sizes)
393 ml = max(sizes)
394 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
394 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
395 else:
395 else:
396 formats.append(['%s' for x in l])
396 formats.append(['%s' for x in l])
397 pieces.append(l)
397 pieces.append(l)
398
398
399 for f, p, l in zip(zip(*formats), zip(*pieces), lines):
399 for f, p, l in zip(zip(*formats), zip(*pieces), lines):
400 fm.startitem()
400 fm.startitem()
401 fm.write(fields, "".join(f), *p)
401 fm.write(fields, "".join(f), *p)
402 fm.write('line', ": %s", l[1])
402 fm.write('line', ": %s", l[1])
403
403
404 if not lines[-1][1].endswith('\n'):
404 if not lines[-1][1].endswith('\n'):
405 fm.plain('\n')
405 fm.plain('\n')
406
406
407 fm.end()
407 fm.end()
408
408
409 @command('archive',
409 @command('archive',
410 [('', 'no-decode', None, _('do not pass files through decoders')),
410 [('', 'no-decode', None, _('do not pass files through decoders')),
411 ('p', 'prefix', '', _('directory prefix for files in archive'),
411 ('p', 'prefix', '', _('directory prefix for files in archive'),
412 _('PREFIX')),
412 _('PREFIX')),
413 ('r', 'rev', '', _('revision to distribute'), _('REV')),
413 ('r', 'rev', '', _('revision to distribute'), _('REV')),
414 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
414 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
415 ] + subrepoopts + walkopts,
415 ] + subrepoopts + walkopts,
416 _('[OPTION]... DEST'))
416 _('[OPTION]... DEST'))
417 def archive(ui, repo, dest, **opts):
417 def archive(ui, repo, dest, **opts):
418 '''create an unversioned archive of a repository revision
418 '''create an unversioned archive of a repository revision
419
419
420 By default, the revision used is the parent of the working
420 By default, the revision used is the parent of the working
421 directory; use -r/--rev to specify a different revision.
421 directory; use -r/--rev to specify a different revision.
422
422
423 The archive type is automatically detected based on file
423 The archive type is automatically detected based on file
424 extension (to override, use -t/--type).
424 extension (to override, use -t/--type).
425
425
426 .. container:: verbose
426 .. container:: verbose
427
427
428 Examples:
428 Examples:
429
429
430 - create a zip file containing the 1.0 release::
430 - create a zip file containing the 1.0 release::
431
431
432 hg archive -r 1.0 project-1.0.zip
432 hg archive -r 1.0 project-1.0.zip
433
433
434 - create a tarball excluding .hg files::
434 - create a tarball excluding .hg files::
435
435
436 hg archive project.tar.gz -X ".hg*"
436 hg archive project.tar.gz -X ".hg*"
437
437
438 Valid types are:
438 Valid types are:
439
439
440 :``files``: a directory full of files (default)
440 :``files``: a directory full of files (default)
441 :``tar``: tar archive, uncompressed
441 :``tar``: tar archive, uncompressed
442 :``tbz2``: tar archive, compressed using bzip2
442 :``tbz2``: tar archive, compressed using bzip2
443 :``tgz``: tar archive, compressed using gzip
443 :``tgz``: tar archive, compressed using gzip
444 :``uzip``: zip archive, uncompressed
444 :``uzip``: zip archive, uncompressed
445 :``zip``: zip archive, compressed using deflate
445 :``zip``: zip archive, compressed using deflate
446
446
447 The exact name of the destination archive or directory is given
447 The exact name of the destination archive or directory is given
448 using a format string; see :hg:`help export` for details.
448 using a format string; see :hg:`help export` for details.
449
449
450 Each member added to an archive file has a directory prefix
450 Each member added to an archive file has a directory prefix
451 prepended. Use -p/--prefix to specify a format string for the
451 prepended. Use -p/--prefix to specify a format string for the
452 prefix. The default is the basename of the archive, with suffixes
452 prefix. The default is the basename of the archive, with suffixes
453 removed.
453 removed.
454
454
455 Returns 0 on success.
455 Returns 0 on success.
456 '''
456 '''
457
457
458 opts = pycompat.byteskwargs(opts)
458 opts = pycompat.byteskwargs(opts)
459 ctx = scmutil.revsingle(repo, opts.get('rev'))
459 ctx = scmutil.revsingle(repo, opts.get('rev'))
460 if not ctx:
460 if not ctx:
461 raise error.Abort(_('no working directory: please specify a revision'))
461 raise error.Abort(_('no working directory: please specify a revision'))
462 node = ctx.node()
462 node = ctx.node()
463 dest = cmdutil.makefilename(repo, dest, node)
463 dest = cmdutil.makefilename(repo, dest, node)
464 if os.path.realpath(dest) == repo.root:
464 if os.path.realpath(dest) == repo.root:
465 raise error.Abort(_('repository root cannot be destination'))
465 raise error.Abort(_('repository root cannot be destination'))
466
466
467 kind = opts.get('type') or archival.guesskind(dest) or 'files'
467 kind = opts.get('type') or archival.guesskind(dest) or 'files'
468 prefix = opts.get('prefix')
468 prefix = opts.get('prefix')
469
469
470 if dest == '-':
470 if dest == '-':
471 if kind == 'files':
471 if kind == 'files':
472 raise error.Abort(_('cannot archive plain files to stdout'))
472 raise error.Abort(_('cannot archive plain files to stdout'))
473 dest = cmdutil.makefileobj(repo, dest)
473 dest = cmdutil.makefileobj(repo, dest)
474 if not prefix:
474 if not prefix:
475 prefix = os.path.basename(repo.root) + '-%h'
475 prefix = os.path.basename(repo.root) + '-%h'
476
476
477 prefix = cmdutil.makefilename(repo, prefix, node)
477 prefix = cmdutil.makefilename(repo, prefix, node)
478 matchfn = scmutil.match(ctx, [], opts)
478 matchfn = scmutil.match(ctx, [], opts)
479 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
479 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
480 matchfn, prefix, subrepos=opts.get('subrepos'))
480 matchfn, prefix, subrepos=opts.get('subrepos'))
481
481
482 @command('backout',
482 @command('backout',
483 [('', 'merge', None, _('merge with old dirstate parent after backout')),
483 [('', 'merge', None, _('merge with old dirstate parent after backout')),
484 ('', 'commit', None,
484 ('', 'commit', None,
485 _('commit if no conflicts were encountered (DEPRECATED)')),
485 _('commit if no conflicts were encountered (DEPRECATED)')),
486 ('', 'no-commit', None, _('do not commit')),
486 ('', 'no-commit', None, _('do not commit')),
487 ('', 'parent', '',
487 ('', 'parent', '',
488 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
488 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
489 ('r', 'rev', '', _('revision to backout'), _('REV')),
489 ('r', 'rev', '', _('revision to backout'), _('REV')),
490 ('e', 'edit', False, _('invoke editor on commit messages')),
490 ('e', 'edit', False, _('invoke editor on commit messages')),
491 ] + mergetoolopts + walkopts + commitopts + commitopts2,
491 ] + mergetoolopts + walkopts + commitopts + commitopts2,
492 _('[OPTION]... [-r] REV'))
492 _('[OPTION]... [-r] REV'))
493 def backout(ui, repo, node=None, rev=None, **opts):
493 def backout(ui, repo, node=None, rev=None, **opts):
494 '''reverse effect of earlier changeset
494 '''reverse effect of earlier changeset
495
495
496 Prepare a new changeset with the effect of REV undone in the
496 Prepare a new changeset with the effect of REV undone in the
497 current working directory. If no conflicts were encountered,
497 current working directory. If no conflicts were encountered,
498 it will be committed immediately.
498 it will be committed immediately.
499
499
500 If REV is the parent of the working directory, then this new changeset
500 If REV is the parent of the working directory, then this new changeset
501 is committed automatically (unless --no-commit is specified).
501 is committed automatically (unless --no-commit is specified).
502
502
503 .. note::
503 .. note::
504
504
505 :hg:`backout` cannot be used to fix either an unwanted or
505 :hg:`backout` cannot be used to fix either an unwanted or
506 incorrect merge.
506 incorrect merge.
507
507
508 .. container:: verbose
508 .. container:: verbose
509
509
510 Examples:
510 Examples:
511
511
512 - Reverse the effect of the parent of the working directory.
512 - Reverse the effect of the parent of the working directory.
513 This backout will be committed immediately::
513 This backout will be committed immediately::
514
514
515 hg backout -r .
515 hg backout -r .
516
516
517 - Reverse the effect of previous bad revision 23::
517 - Reverse the effect of previous bad revision 23::
518
518
519 hg backout -r 23
519 hg backout -r 23
520
520
521 - Reverse the effect of previous bad revision 23 and
521 - Reverse the effect of previous bad revision 23 and
522 leave changes uncommitted::
522 leave changes uncommitted::
523
523
524 hg backout -r 23 --no-commit
524 hg backout -r 23 --no-commit
525 hg commit -m "Backout revision 23"
525 hg commit -m "Backout revision 23"
526
526
527 By default, the pending changeset will have one parent,
527 By default, the pending changeset will have one parent,
528 maintaining a linear history. With --merge, the pending
528 maintaining a linear history. With --merge, the pending
529 changeset will instead have two parents: the old parent of the
529 changeset will instead have two parents: the old parent of the
530 working directory and a new child of REV that simply undoes REV.
530 working directory and a new child of REV that simply undoes REV.
531
531
532 Before version 1.7, the behavior without --merge was equivalent
532 Before version 1.7, the behavior without --merge was equivalent
533 to specifying --merge followed by :hg:`update --clean .` to
533 to specifying --merge followed by :hg:`update --clean .` to
534 cancel the merge and leave the child of REV as a head to be
534 cancel the merge and leave the child of REV as a head to be
535 merged separately.
535 merged separately.
536
536
537 See :hg:`help dates` for a list of formats valid for -d/--date.
537 See :hg:`help dates` for a list of formats valid for -d/--date.
538
538
539 See :hg:`help revert` for a way to restore files to the state
539 See :hg:`help revert` for a way to restore files to the state
540 of another revision.
540 of another revision.
541
541
542 Returns 0 on success, 1 if nothing to backout or there are unresolved
542 Returns 0 on success, 1 if nothing to backout or there are unresolved
543 files.
543 files.
544 '''
544 '''
545 wlock = lock = None
545 wlock = lock = None
546 try:
546 try:
547 wlock = repo.wlock()
547 wlock = repo.wlock()
548 lock = repo.lock()
548 lock = repo.lock()
549 return _dobackout(ui, repo, node, rev, **opts)
549 return _dobackout(ui, repo, node, rev, **opts)
550 finally:
550 finally:
551 release(lock, wlock)
551 release(lock, wlock)
552
552
553 def _dobackout(ui, repo, node=None, rev=None, **opts):
553 def _dobackout(ui, repo, node=None, rev=None, **opts):
554 opts = pycompat.byteskwargs(opts)
554 opts = pycompat.byteskwargs(opts)
555 if opts.get('commit') and opts.get('no_commit'):
555 if opts.get('commit') and opts.get('no_commit'):
556 raise error.Abort(_("cannot use --commit with --no-commit"))
556 raise error.Abort(_("cannot use --commit with --no-commit"))
557 if opts.get('merge') and opts.get('no_commit'):
557 if opts.get('merge') and opts.get('no_commit'):
558 raise error.Abort(_("cannot use --merge with --no-commit"))
558 raise error.Abort(_("cannot use --merge with --no-commit"))
559
559
560 if rev and node:
560 if rev and node:
561 raise error.Abort(_("please specify just one revision"))
561 raise error.Abort(_("please specify just one revision"))
562
562
563 if not rev:
563 if not rev:
564 rev = node
564 rev = node
565
565
566 if not rev:
566 if not rev:
567 raise error.Abort(_("please specify a revision to backout"))
567 raise error.Abort(_("please specify a revision to backout"))
568
568
569 date = opts.get('date')
569 date = opts.get('date')
570 if date:
570 if date:
571 opts['date'] = util.parsedate(date)
571 opts['date'] = util.parsedate(date)
572
572
573 cmdutil.checkunfinished(repo)
573 cmdutil.checkunfinished(repo)
574 cmdutil.bailifchanged(repo)
574 cmdutil.bailifchanged(repo)
575 node = scmutil.revsingle(repo, rev).node()
575 node = scmutil.revsingle(repo, rev).node()
576
576
577 op1, op2 = repo.dirstate.parents()
577 op1, op2 = repo.dirstate.parents()
578 if not repo.changelog.isancestor(node, op1):
578 if not repo.changelog.isancestor(node, op1):
579 raise error.Abort(_('cannot backout change that is not an ancestor'))
579 raise error.Abort(_('cannot backout change that is not an ancestor'))
580
580
581 p1, p2 = repo.changelog.parents(node)
581 p1, p2 = repo.changelog.parents(node)
582 if p1 == nullid:
582 if p1 == nullid:
583 raise error.Abort(_('cannot backout a change with no parents'))
583 raise error.Abort(_('cannot backout a change with no parents'))
584 if p2 != nullid:
584 if p2 != nullid:
585 if not opts.get('parent'):
585 if not opts.get('parent'):
586 raise error.Abort(_('cannot backout a merge changeset'))
586 raise error.Abort(_('cannot backout a merge changeset'))
587 p = repo.lookup(opts['parent'])
587 p = repo.lookup(opts['parent'])
588 if p not in (p1, p2):
588 if p not in (p1, p2):
589 raise error.Abort(_('%s is not a parent of %s') %
589 raise error.Abort(_('%s is not a parent of %s') %
590 (short(p), short(node)))
590 (short(p), short(node)))
591 parent = p
591 parent = p
592 else:
592 else:
593 if opts.get('parent'):
593 if opts.get('parent'):
594 raise error.Abort(_('cannot use --parent on non-merge changeset'))
594 raise error.Abort(_('cannot use --parent on non-merge changeset'))
595 parent = p1
595 parent = p1
596
596
597 # the backout should appear on the same branch
597 # the backout should appear on the same branch
598 branch = repo.dirstate.branch()
598 branch = repo.dirstate.branch()
599 bheads = repo.branchheads(branch)
599 bheads = repo.branchheads(branch)
600 rctx = scmutil.revsingle(repo, hex(parent))
600 rctx = scmutil.revsingle(repo, hex(parent))
601 if not opts.get('merge') and op1 != node:
601 if not opts.get('merge') and op1 != node:
602 dsguard = dirstateguard.dirstateguard(repo, 'backout')
602 dsguard = dirstateguard.dirstateguard(repo, 'backout')
603 try:
603 try:
604 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
604 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
605 'backout')
605 'backout')
606 stats = mergemod.update(repo, parent, True, True, node, False)
606 stats = mergemod.update(repo, parent, True, True, node, False)
607 repo.setparents(op1, op2)
607 repo.setparents(op1, op2)
608 dsguard.close()
608 dsguard.close()
609 hg._showstats(repo, stats)
609 hg._showstats(repo, stats)
610 if stats[3]:
610 if stats[3]:
611 repo.ui.status(_("use 'hg resolve' to retry unresolved "
611 repo.ui.status(_("use 'hg resolve' to retry unresolved "
612 "file merges\n"))
612 "file merges\n"))
613 return 1
613 return 1
614 finally:
614 finally:
615 ui.setconfig('ui', 'forcemerge', '', '')
615 ui.setconfig('ui', 'forcemerge', '', '')
616 lockmod.release(dsguard)
616 lockmod.release(dsguard)
617 else:
617 else:
618 hg.clean(repo, node, show_stats=False)
618 hg.clean(repo, node, show_stats=False)
619 repo.dirstate.setbranch(branch)
619 repo.dirstate.setbranch(branch)
620 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
620 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
621
621
622 if opts.get('no_commit'):
622 if opts.get('no_commit'):
623 msg = _("changeset %s backed out, "
623 msg = _("changeset %s backed out, "
624 "don't forget to commit.\n")
624 "don't forget to commit.\n")
625 ui.status(msg % short(node))
625 ui.status(msg % short(node))
626 return 0
626 return 0
627
627
628 def commitfunc(ui, repo, message, match, opts):
628 def commitfunc(ui, repo, message, match, opts):
629 editform = 'backout'
629 editform = 'backout'
630 e = cmdutil.getcommiteditor(editform=editform,
630 e = cmdutil.getcommiteditor(editform=editform,
631 **pycompat.strkwargs(opts))
631 **pycompat.strkwargs(opts))
632 if not message:
632 if not message:
633 # we don't translate commit messages
633 # we don't translate commit messages
634 message = "Backed out changeset %s" % short(node)
634 message = "Backed out changeset %s" % short(node)
635 e = cmdutil.getcommiteditor(edit=True, editform=editform)
635 e = cmdutil.getcommiteditor(edit=True, editform=editform)
636 return repo.commit(message, opts.get('user'), opts.get('date'),
636 return repo.commit(message, opts.get('user'), opts.get('date'),
637 match, editor=e)
637 match, editor=e)
638 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
638 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
639 if not newnode:
639 if not newnode:
640 ui.status(_("nothing changed\n"))
640 ui.status(_("nothing changed\n"))
641 return 1
641 return 1
642 cmdutil.commitstatus(repo, newnode, branch, bheads)
642 cmdutil.commitstatus(repo, newnode, branch, bheads)
643
643
644 def nice(node):
644 def nice(node):
645 return '%d:%s' % (repo.changelog.rev(node), short(node))
645 return '%d:%s' % (repo.changelog.rev(node), short(node))
646 ui.status(_('changeset %s backs out changeset %s\n') %
646 ui.status(_('changeset %s backs out changeset %s\n') %
647 (nice(repo.changelog.tip()), nice(node)))
647 (nice(repo.changelog.tip()), nice(node)))
648 if opts.get('merge') and op1 != node:
648 if opts.get('merge') and op1 != node:
649 hg.clean(repo, op1, show_stats=False)
649 hg.clean(repo, op1, show_stats=False)
650 ui.status(_('merging with changeset %s\n')
650 ui.status(_('merging with changeset %s\n')
651 % nice(repo.changelog.tip()))
651 % nice(repo.changelog.tip()))
652 try:
652 try:
653 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
653 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
654 'backout')
654 'backout')
655 return hg.merge(repo, hex(repo.changelog.tip()))
655 return hg.merge(repo, hex(repo.changelog.tip()))
656 finally:
656 finally:
657 ui.setconfig('ui', 'forcemerge', '', '')
657 ui.setconfig('ui', 'forcemerge', '', '')
658 return 0
658 return 0
659
659
660 @command('bisect',
660 @command('bisect',
661 [('r', 'reset', False, _('reset bisect state')),
661 [('r', 'reset', False, _('reset bisect state')),
662 ('g', 'good', False, _('mark changeset good')),
662 ('g', 'good', False, _('mark changeset good')),
663 ('b', 'bad', False, _('mark changeset bad')),
663 ('b', 'bad', False, _('mark changeset bad')),
664 ('s', 'skip', False, _('skip testing changeset')),
664 ('s', 'skip', False, _('skip testing changeset')),
665 ('e', 'extend', False, _('extend the bisect range')),
665 ('e', 'extend', False, _('extend the bisect range')),
666 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
666 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
667 ('U', 'noupdate', False, _('do not update to target'))],
667 ('U', 'noupdate', False, _('do not update to target'))],
668 _("[-gbsr] [-U] [-c CMD] [REV]"))
668 _("[-gbsr] [-U] [-c CMD] [REV]"))
669 def bisect(ui, repo, rev=None, extra=None, command=None,
669 def bisect(ui, repo, rev=None, extra=None, command=None,
670 reset=None, good=None, bad=None, skip=None, extend=None,
670 reset=None, good=None, bad=None, skip=None, extend=None,
671 noupdate=None):
671 noupdate=None):
672 """subdivision search of changesets
672 """subdivision search of changesets
673
673
674 This command helps to find changesets which introduce problems. To
674 This command helps to find changesets which introduce problems. To
675 use, mark the earliest changeset you know exhibits the problem as
675 use, mark the earliest changeset you know exhibits the problem as
676 bad, then mark the latest changeset which is free from the problem
676 bad, then mark the latest changeset which is free from the problem
677 as good. Bisect will update your working directory to a revision
677 as good. Bisect will update your working directory to a revision
678 for testing (unless the -U/--noupdate option is specified). Once
678 for testing (unless the -U/--noupdate option is specified). Once
679 you have performed tests, mark the working directory as good or
679 you have performed tests, mark the working directory as good or
680 bad, and bisect will either update to another candidate changeset
680 bad, and bisect will either update to another candidate changeset
681 or announce that it has found the bad revision.
681 or announce that it has found the bad revision.
682
682
683 As a shortcut, you can also use the revision argument to mark a
683 As a shortcut, you can also use the revision argument to mark a
684 revision as good or bad without checking it out first.
684 revision as good or bad without checking it out first.
685
685
686 If you supply a command, it will be used for automatic bisection.
686 If you supply a command, it will be used for automatic bisection.
687 The environment variable HG_NODE will contain the ID of the
687 The environment variable HG_NODE will contain the ID of the
688 changeset being tested. The exit status of the command will be
688 changeset being tested. The exit status of the command will be
689 used to mark revisions as good or bad: status 0 means good, 125
689 used to mark revisions as good or bad: status 0 means good, 125
690 means to skip the revision, 127 (command not found) will abort the
690 means to skip the revision, 127 (command not found) will abort the
691 bisection, and any other non-zero exit status means the revision
691 bisection, and any other non-zero exit status means the revision
692 is bad.
692 is bad.
693
693
694 .. container:: verbose
694 .. container:: verbose
695
695
696 Some examples:
696 Some examples:
697
697
698 - start a bisection with known bad revision 34, and good revision 12::
698 - start a bisection with known bad revision 34, and good revision 12::
699
699
700 hg bisect --bad 34
700 hg bisect --bad 34
701 hg bisect --good 12
701 hg bisect --good 12
702
702
703 - advance the current bisection by marking current revision as good or
703 - advance the current bisection by marking current revision as good or
704 bad::
704 bad::
705
705
706 hg bisect --good
706 hg bisect --good
707 hg bisect --bad
707 hg bisect --bad
708
708
709 - mark the current revision, or a known revision, to be skipped (e.g. if
709 - mark the current revision, or a known revision, to be skipped (e.g. if
710 that revision is not usable because of another issue)::
710 that revision is not usable because of another issue)::
711
711
712 hg bisect --skip
712 hg bisect --skip
713 hg bisect --skip 23
713 hg bisect --skip 23
714
714
715 - skip all revisions that do not touch directories ``foo`` or ``bar``::
715 - skip all revisions that do not touch directories ``foo`` or ``bar``::
716
716
717 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
717 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
718
718
719 - forget the current bisection::
719 - forget the current bisection::
720
720
721 hg bisect --reset
721 hg bisect --reset
722
722
723 - use 'make && make tests' to automatically find the first broken
723 - use 'make && make tests' to automatically find the first broken
724 revision::
724 revision::
725
725
726 hg bisect --reset
726 hg bisect --reset
727 hg bisect --bad 34
727 hg bisect --bad 34
728 hg bisect --good 12
728 hg bisect --good 12
729 hg bisect --command "make && make tests"
729 hg bisect --command "make && make tests"
730
730
731 - see all changesets whose states are already known in the current
731 - see all changesets whose states are already known in the current
732 bisection::
732 bisection::
733
733
734 hg log -r "bisect(pruned)"
734 hg log -r "bisect(pruned)"
735
735
736 - see the changeset currently being bisected (especially useful
736 - see the changeset currently being bisected (especially useful
737 if running with -U/--noupdate)::
737 if running with -U/--noupdate)::
738
738
739 hg log -r "bisect(current)"
739 hg log -r "bisect(current)"
740
740
741 - see all changesets that took part in the current bisection::
741 - see all changesets that took part in the current bisection::
742
742
743 hg log -r "bisect(range)"
743 hg log -r "bisect(range)"
744
744
745 - you can even get a nice graph::
745 - you can even get a nice graph::
746
746
747 hg log --graph -r "bisect(range)"
747 hg log --graph -r "bisect(range)"
748
748
749 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
749 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
750
750
751 Returns 0 on success.
751 Returns 0 on success.
752 """
752 """
753 # backward compatibility
753 # backward compatibility
754 if rev in "good bad reset init".split():
754 if rev in "good bad reset init".split():
755 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
755 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
756 cmd, rev, extra = rev, extra, None
756 cmd, rev, extra = rev, extra, None
757 if cmd == "good":
757 if cmd == "good":
758 good = True
758 good = True
759 elif cmd == "bad":
759 elif cmd == "bad":
760 bad = True
760 bad = True
761 else:
761 else:
762 reset = True
762 reset = True
763 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
763 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
764 raise error.Abort(_('incompatible arguments'))
764 raise error.Abort(_('incompatible arguments'))
765
765
766 if reset:
766 if reset:
767 hbisect.resetstate(repo)
767 hbisect.resetstate(repo)
768 return
768 return
769
769
770 state = hbisect.load_state(repo)
770 state = hbisect.load_state(repo)
771
771
772 # update state
772 # update state
773 if good or bad or skip:
773 if good or bad or skip:
774 if rev:
774 if rev:
775 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
775 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
776 else:
776 else:
777 nodes = [repo.lookup('.')]
777 nodes = [repo.lookup('.')]
778 if good:
778 if good:
779 state['good'] += nodes
779 state['good'] += nodes
780 elif bad:
780 elif bad:
781 state['bad'] += nodes
781 state['bad'] += nodes
782 elif skip:
782 elif skip:
783 state['skip'] += nodes
783 state['skip'] += nodes
784 hbisect.save_state(repo, state)
784 hbisect.save_state(repo, state)
785 if not (state['good'] and state['bad']):
785 if not (state['good'] and state['bad']):
786 return
786 return
787
787
788 def mayupdate(repo, node, show_stats=True):
788 def mayupdate(repo, node, show_stats=True):
789 """common used update sequence"""
789 """common used update sequence"""
790 if noupdate:
790 if noupdate:
791 return
791 return
792 cmdutil.checkunfinished(repo)
792 cmdutil.checkunfinished(repo)
793 cmdutil.bailifchanged(repo)
793 cmdutil.bailifchanged(repo)
794 return hg.clean(repo, node, show_stats=show_stats)
794 return hg.clean(repo, node, show_stats=show_stats)
795
795
796 displayer = cmdutil.show_changeset(ui, repo, {})
796 displayer = cmdutil.show_changeset(ui, repo, {})
797
797
798 if command:
798 if command:
799 changesets = 1
799 changesets = 1
800 if noupdate:
800 if noupdate:
801 try:
801 try:
802 node = state['current'][0]
802 node = state['current'][0]
803 except LookupError:
803 except LookupError:
804 raise error.Abort(_('current bisect revision is unknown - '
804 raise error.Abort(_('current bisect revision is unknown - '
805 'start a new bisect to fix'))
805 'start a new bisect to fix'))
806 else:
806 else:
807 node, p2 = repo.dirstate.parents()
807 node, p2 = repo.dirstate.parents()
808 if p2 != nullid:
808 if p2 != nullid:
809 raise error.Abort(_('current bisect revision is a merge'))
809 raise error.Abort(_('current bisect revision is a merge'))
810 if rev:
810 if rev:
811 node = repo[scmutil.revsingle(repo, rev, node)].node()
811 node = repo[scmutil.revsingle(repo, rev, node)].node()
812 try:
812 try:
813 while changesets:
813 while changesets:
814 # update state
814 # update state
815 state['current'] = [node]
815 state['current'] = [node]
816 hbisect.save_state(repo, state)
816 hbisect.save_state(repo, state)
817 status = ui.system(command, environ={'HG_NODE': hex(node)},
817 status = ui.system(command, environ={'HG_NODE': hex(node)},
818 blockedtag='bisect_check')
818 blockedtag='bisect_check')
819 if status == 125:
819 if status == 125:
820 transition = "skip"
820 transition = "skip"
821 elif status == 0:
821 elif status == 0:
822 transition = "good"
822 transition = "good"
823 # status < 0 means process was killed
823 # status < 0 means process was killed
824 elif status == 127:
824 elif status == 127:
825 raise error.Abort(_("failed to execute %s") % command)
825 raise error.Abort(_("failed to execute %s") % command)
826 elif status < 0:
826 elif status < 0:
827 raise error.Abort(_("%s killed") % command)
827 raise error.Abort(_("%s killed") % command)
828 else:
828 else:
829 transition = "bad"
829 transition = "bad"
830 state[transition].append(node)
830 state[transition].append(node)
831 ctx = repo[node]
831 ctx = repo[node]
832 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
832 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
833 hbisect.checkstate(state)
833 hbisect.checkstate(state)
834 # bisect
834 # bisect
835 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
835 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
836 # update to next check
836 # update to next check
837 node = nodes[0]
837 node = nodes[0]
838 mayupdate(repo, node, show_stats=False)
838 mayupdate(repo, node, show_stats=False)
839 finally:
839 finally:
840 state['current'] = [node]
840 state['current'] = [node]
841 hbisect.save_state(repo, state)
841 hbisect.save_state(repo, state)
842 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
842 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
843 return
843 return
844
844
845 hbisect.checkstate(state)
845 hbisect.checkstate(state)
846
846
847 # actually bisect
847 # actually bisect
848 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
848 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
849 if extend:
849 if extend:
850 if not changesets:
850 if not changesets:
851 extendnode = hbisect.extendrange(repo, state, nodes, good)
851 extendnode = hbisect.extendrange(repo, state, nodes, good)
852 if extendnode is not None:
852 if extendnode is not None:
853 ui.write(_("Extending search to changeset %d:%s\n")
853 ui.write(_("Extending search to changeset %d:%s\n")
854 % (extendnode.rev(), extendnode))
854 % (extendnode.rev(), extendnode))
855 state['current'] = [extendnode.node()]
855 state['current'] = [extendnode.node()]
856 hbisect.save_state(repo, state)
856 hbisect.save_state(repo, state)
857 return mayupdate(repo, extendnode.node())
857 return mayupdate(repo, extendnode.node())
858 raise error.Abort(_("nothing to extend"))
858 raise error.Abort(_("nothing to extend"))
859
859
860 if changesets == 0:
860 if changesets == 0:
861 hbisect.printresult(ui, repo, state, displayer, nodes, good)
861 hbisect.printresult(ui, repo, state, displayer, nodes, good)
862 else:
862 else:
863 assert len(nodes) == 1 # only a single node can be tested next
863 assert len(nodes) == 1 # only a single node can be tested next
864 node = nodes[0]
864 node = nodes[0]
865 # compute the approximate number of remaining tests
865 # compute the approximate number of remaining tests
866 tests, size = 0, 2
866 tests, size = 0, 2
867 while size <= changesets:
867 while size <= changesets:
868 tests, size = tests + 1, size * 2
868 tests, size = tests + 1, size * 2
869 rev = repo.changelog.rev(node)
869 rev = repo.changelog.rev(node)
870 ui.write(_("Testing changeset %d:%s "
870 ui.write(_("Testing changeset %d:%s "
871 "(%d changesets remaining, ~%d tests)\n")
871 "(%d changesets remaining, ~%d tests)\n")
872 % (rev, short(node), changesets, tests))
872 % (rev, short(node), changesets, tests))
873 state['current'] = [node]
873 state['current'] = [node]
874 hbisect.save_state(repo, state)
874 hbisect.save_state(repo, state)
875 return mayupdate(repo, node)
875 return mayupdate(repo, node)
876
876
877 @command('bookmarks|bookmark',
877 @command('bookmarks|bookmark',
878 [('f', 'force', False, _('force')),
878 [('f', 'force', False, _('force')),
879 ('r', 'rev', '', _('revision for bookmark action'), _('REV')),
879 ('r', 'rev', '', _('revision for bookmark action'), _('REV')),
880 ('d', 'delete', False, _('delete a given bookmark')),
880 ('d', 'delete', False, _('delete a given bookmark')),
881 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
881 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
882 ('i', 'inactive', False, _('mark a bookmark inactive')),
882 ('i', 'inactive', False, _('mark a bookmark inactive')),
883 ] + formatteropts,
883 ] + formatteropts,
884 _('hg bookmarks [OPTIONS]... [NAME]...'))
884 _('hg bookmarks [OPTIONS]... [NAME]...'))
885 def bookmark(ui, repo, *names, **opts):
885 def bookmark(ui, repo, *names, **opts):
886 '''create a new bookmark or list existing bookmarks
886 '''create a new bookmark or list existing bookmarks
887
887
888 Bookmarks are labels on changesets to help track lines of development.
888 Bookmarks are labels on changesets to help track lines of development.
889 Bookmarks are unversioned and can be moved, renamed and deleted.
889 Bookmarks are unversioned and can be moved, renamed and deleted.
890 Deleting or moving a bookmark has no effect on the associated changesets.
890 Deleting or moving a bookmark has no effect on the associated changesets.
891
891
892 Creating or updating to a bookmark causes it to be marked as 'active'.
892 Creating or updating to a bookmark causes it to be marked as 'active'.
893 The active bookmark is indicated with a '*'.
893 The active bookmark is indicated with a '*'.
894 When a commit is made, the active bookmark will advance to the new commit.
894 When a commit is made, the active bookmark will advance to the new commit.
895 A plain :hg:`update` will also advance an active bookmark, if possible.
895 A plain :hg:`update` will also advance an active bookmark, if possible.
896 Updating away from a bookmark will cause it to be deactivated.
896 Updating away from a bookmark will cause it to be deactivated.
897
897
898 Bookmarks can be pushed and pulled between repositories (see
898 Bookmarks can be pushed and pulled between repositories (see
899 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
899 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
900 diverged, a new 'divergent bookmark' of the form 'name@path' will
900 diverged, a new 'divergent bookmark' of the form 'name@path' will
901 be created. Using :hg:`merge` will resolve the divergence.
901 be created. Using :hg:`merge` will resolve the divergence.
902
902
903 A bookmark named '@' has the special property that :hg:`clone` will
903 A bookmark named '@' has the special property that :hg:`clone` will
904 check it out by default if it exists.
904 check it out by default if it exists.
905
905
906 .. container:: verbose
906 .. container:: verbose
907
907
908 Examples:
908 Examples:
909
909
910 - create an active bookmark for a new line of development::
910 - create an active bookmark for a new line of development::
911
911
912 hg book new-feature
912 hg book new-feature
913
913
914 - create an inactive bookmark as a place marker::
914 - create an inactive bookmark as a place marker::
915
915
916 hg book -i reviewed
916 hg book -i reviewed
917
917
918 - create an inactive bookmark on another changeset::
918 - create an inactive bookmark on another changeset::
919
919
920 hg book -r .^ tested
920 hg book -r .^ tested
921
921
922 - rename bookmark turkey to dinner::
922 - rename bookmark turkey to dinner::
923
923
924 hg book -m turkey dinner
924 hg book -m turkey dinner
925
925
926 - move the '@' bookmark from another branch::
926 - move the '@' bookmark from another branch::
927
927
928 hg book -f @
928 hg book -f @
929 '''
929 '''
930 opts = pycompat.byteskwargs(opts)
930 opts = pycompat.byteskwargs(opts)
931 force = opts.get('force')
931 force = opts.get('force')
932 rev = opts.get('rev')
932 rev = opts.get('rev')
933 delete = opts.get('delete')
933 delete = opts.get('delete')
934 rename = opts.get('rename')
934 rename = opts.get('rename')
935 inactive = opts.get('inactive')
935 inactive = opts.get('inactive')
936
936
937 def checkformat(mark):
937 def checkformat(mark):
938 mark = mark.strip()
938 mark = mark.strip()
939 if not mark:
939 if not mark:
940 raise error.Abort(_("bookmark names cannot consist entirely of "
940 raise error.Abort(_("bookmark names cannot consist entirely of "
941 "whitespace"))
941 "whitespace"))
942 scmutil.checknewlabel(repo, mark, 'bookmark')
942 scmutil.checknewlabel(repo, mark, 'bookmark')
943 return mark
943 return mark
944
944
945 def checkconflict(repo, mark, cur, force=False, target=None):
945 def checkconflict(repo, mark, cur, force=False, target=None):
946 if mark in marks and not force:
946 if mark in marks and not force:
947 if target:
947 if target:
948 if marks[mark] == target and target == cur:
948 if marks[mark] == target and target == cur:
949 # re-activating a bookmark
949 # re-activating a bookmark
950 return
950 return
951 anc = repo.changelog.ancestors([repo[target].rev()])
951 anc = repo.changelog.ancestors([repo[target].rev()])
952 bmctx = repo[marks[mark]]
952 bmctx = repo[marks[mark]]
953 divs = [repo[b].node() for b in marks
953 divs = [repo[b].node() for b in marks
954 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
954 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
955
955
956 # allow resolving a single divergent bookmark even if moving
956 # allow resolving a single divergent bookmark even if moving
957 # the bookmark across branches when a revision is specified
957 # the bookmark across branches when a revision is specified
958 # that contains a divergent bookmark
958 # that contains a divergent bookmark
959 if bmctx.rev() not in anc and target in divs:
959 if bmctx.rev() not in anc and target in divs:
960 bookmarks.deletedivergent(repo, [target], mark)
960 bookmarks.deletedivergent(repo, [target], mark)
961 return
961 return
962
962
963 deletefrom = [b for b in divs
963 deletefrom = [b for b in divs
964 if repo[b].rev() in anc or b == target]
964 if repo[b].rev() in anc or b == target]
965 bookmarks.deletedivergent(repo, deletefrom, mark)
965 bookmarks.deletedivergent(repo, deletefrom, mark)
966 if bookmarks.validdest(repo, bmctx, repo[target]):
966 if bookmarks.validdest(repo, bmctx, repo[target]):
967 ui.status(_("moving bookmark '%s' forward from %s\n") %
967 ui.status(_("moving bookmark '%s' forward from %s\n") %
968 (mark, short(bmctx.node())))
968 (mark, short(bmctx.node())))
969 return
969 return
970 raise error.Abort(_("bookmark '%s' already exists "
970 raise error.Abort(_("bookmark '%s' already exists "
971 "(use -f to force)") % mark)
971 "(use -f to force)") % mark)
972 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
972 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
973 and not force):
973 and not force):
974 raise error.Abort(
974 raise error.Abort(
975 _("a bookmark cannot have the name of an existing branch"))
975 _("a bookmark cannot have the name of an existing branch"))
976 if len(mark) > 3 and not force:
976 if len(mark) > 3 and not force:
977 try:
977 try:
978 shadowhash = (mark in repo)
978 shadowhash = (mark in repo)
979 except error.LookupError: # ambiguous identifier
979 except error.LookupError: # ambiguous identifier
980 shadowhash = False
980 shadowhash = False
981 if shadowhash:
981 if shadowhash:
982 repo.ui.warn(
982 repo.ui.warn(
983 _("bookmark %s matches a changeset hash\n"
983 _("bookmark %s matches a changeset hash\n"
984 "(did you leave a -r out of an 'hg bookmark' command?)\n")
984 "(did you leave a -r out of an 'hg bookmark' command?)\n")
985 % mark)
985 % mark)
986
986
987 if delete and rename:
987 if delete and rename:
988 raise error.Abort(_("--delete and --rename are incompatible"))
988 raise error.Abort(_("--delete and --rename are incompatible"))
989 if delete and rev:
989 if delete and rev:
990 raise error.Abort(_("--rev is incompatible with --delete"))
990 raise error.Abort(_("--rev is incompatible with --delete"))
991 if rename and rev:
991 if rename and rev:
992 raise error.Abort(_("--rev is incompatible with --rename"))
992 raise error.Abort(_("--rev is incompatible with --rename"))
993 if not names and (delete or rev):
993 if not names and (delete or rev):
994 raise error.Abort(_("bookmark name required"))
994 raise error.Abort(_("bookmark name required"))
995
995
996 if delete or rename or names or inactive:
996 if delete or rename or names or inactive:
997 wlock = lock = tr = None
997 wlock = lock = tr = None
998 try:
998 try:
999 wlock = repo.wlock()
999 wlock = repo.wlock()
1000 lock = repo.lock()
1000 lock = repo.lock()
1001 cur = repo.changectx('.').node()
1001 cur = repo.changectx('.').node()
1002 marks = repo._bookmarks
1002 marks = repo._bookmarks
1003 if delete:
1003 if delete:
1004 tr = repo.transaction('bookmark')
1004 tr = repo.transaction('bookmark')
1005 for mark in names:
1005 for mark in names:
1006 if mark not in marks:
1006 if mark not in marks:
1007 raise error.Abort(_("bookmark '%s' does not exist") %
1007 raise error.Abort(_("bookmark '%s' does not exist") %
1008 mark)
1008 mark)
1009 if mark == repo._activebookmark:
1009 if mark == repo._activebookmark:
1010 bookmarks.deactivate(repo)
1010 bookmarks.deactivate(repo)
1011 del marks[mark]
1011 del marks[mark]
1012
1012
1013 elif rename:
1013 elif rename:
1014 tr = repo.transaction('bookmark')
1014 tr = repo.transaction('bookmark')
1015 if not names:
1015 if not names:
1016 raise error.Abort(_("new bookmark name required"))
1016 raise error.Abort(_("new bookmark name required"))
1017 elif len(names) > 1:
1017 elif len(names) > 1:
1018 raise error.Abort(_("only one new bookmark name allowed"))
1018 raise error.Abort(_("only one new bookmark name allowed"))
1019 mark = checkformat(names[0])
1019 mark = checkformat(names[0])
1020 if rename not in marks:
1020 if rename not in marks:
1021 raise error.Abort(_("bookmark '%s' does not exist")
1021 raise error.Abort(_("bookmark '%s' does not exist")
1022 % rename)
1022 % rename)
1023 checkconflict(repo, mark, cur, force)
1023 checkconflict(repo, mark, cur, force)
1024 marks[mark] = marks[rename]
1024 marks[mark] = marks[rename]
1025 if repo._activebookmark == rename and not inactive:
1025 if repo._activebookmark == rename and not inactive:
1026 bookmarks.activate(repo, mark)
1026 bookmarks.activate(repo, mark)
1027 del marks[rename]
1027 del marks[rename]
1028 elif names:
1028 elif names:
1029 tr = repo.transaction('bookmark')
1029 tr = repo.transaction('bookmark')
1030 newact = None
1030 newact = None
1031 for mark in names:
1031 for mark in names:
1032 mark = checkformat(mark)
1032 mark = checkformat(mark)
1033 if newact is None:
1033 if newact is None:
1034 newact = mark
1034 newact = mark
1035 if inactive and mark == repo._activebookmark:
1035 if inactive and mark == repo._activebookmark:
1036 bookmarks.deactivate(repo)
1036 bookmarks.deactivate(repo)
1037 return
1037 return
1038 tgt = cur
1038 tgt = cur
1039 if rev:
1039 if rev:
1040 tgt = scmutil.revsingle(repo, rev).node()
1040 tgt = scmutil.revsingle(repo, rev).node()
1041 checkconflict(repo, mark, cur, force, tgt)
1041 checkconflict(repo, mark, cur, force, tgt)
1042 marks[mark] = tgt
1042 marks[mark] = tgt
1043 if not inactive and cur == marks[newact] and not rev:
1043 if not inactive and cur == marks[newact] and not rev:
1044 bookmarks.activate(repo, newact)
1044 bookmarks.activate(repo, newact)
1045 elif cur != tgt and newact == repo._activebookmark:
1045 elif cur != tgt and newact == repo._activebookmark:
1046 bookmarks.deactivate(repo)
1046 bookmarks.deactivate(repo)
1047 elif inactive:
1047 elif inactive:
1048 if len(marks) == 0:
1048 if len(marks) == 0:
1049 ui.status(_("no bookmarks set\n"))
1049 ui.status(_("no bookmarks set\n"))
1050 elif not repo._activebookmark:
1050 elif not repo._activebookmark:
1051 ui.status(_("no active bookmark\n"))
1051 ui.status(_("no active bookmark\n"))
1052 else:
1052 else:
1053 bookmarks.deactivate(repo)
1053 bookmarks.deactivate(repo)
1054 if tr is not None:
1054 if tr is not None:
1055 marks.recordchange(tr)
1055 marks.recordchange(tr)
1056 tr.close()
1056 tr.close()
1057 finally:
1057 finally:
1058 lockmod.release(tr, lock, wlock)
1058 lockmod.release(tr, lock, wlock)
1059 else: # show bookmarks
1059 else: # show bookmarks
1060 fm = ui.formatter('bookmarks', opts)
1060 fm = ui.formatter('bookmarks', opts)
1061 hexfn = fm.hexfunc
1061 hexfn = fm.hexfunc
1062 marks = repo._bookmarks
1062 marks = repo._bookmarks
1063 if len(marks) == 0 and fm.isplain():
1063 if len(marks) == 0 and fm.isplain():
1064 ui.status(_("no bookmarks set\n"))
1064 ui.status(_("no bookmarks set\n"))
1065 for bmark, n in sorted(marks.iteritems()):
1065 for bmark, n in sorted(marks.iteritems()):
1066 active = repo._activebookmark
1066 active = repo._activebookmark
1067 if bmark == active:
1067 if bmark == active:
1068 prefix, label = '*', activebookmarklabel
1068 prefix, label = '*', activebookmarklabel
1069 else:
1069 else:
1070 prefix, label = ' ', ''
1070 prefix, label = ' ', ''
1071
1071
1072 fm.startitem()
1072 fm.startitem()
1073 if not ui.quiet:
1073 if not ui.quiet:
1074 fm.plain(' %s ' % prefix, label=label)
1074 fm.plain(' %s ' % prefix, label=label)
1075 fm.write('bookmark', '%s', bmark, label=label)
1075 fm.write('bookmark', '%s', bmark, label=label)
1076 pad = " " * (25 - encoding.colwidth(bmark))
1076 pad = " " * (25 - encoding.colwidth(bmark))
1077 fm.condwrite(not ui.quiet, 'rev node', pad + ' %d:%s',
1077 fm.condwrite(not ui.quiet, 'rev node', pad + ' %d:%s',
1078 repo.changelog.rev(n), hexfn(n), label=label)
1078 repo.changelog.rev(n), hexfn(n), label=label)
1079 fm.data(active=(bmark == active))
1079 fm.data(active=(bmark == active))
1080 fm.plain('\n')
1080 fm.plain('\n')
1081 fm.end()
1081 fm.end()
1082
1082
1083 @command('branch',
1083 @command('branch',
1084 [('f', 'force', None,
1084 [('f', 'force', None,
1085 _('set branch name even if it shadows an existing branch')),
1085 _('set branch name even if it shadows an existing branch')),
1086 ('C', 'clean', None, _('reset branch name to parent branch name'))],
1086 ('C', 'clean', None, _('reset branch name to parent branch name'))],
1087 _('[-fC] [NAME]'))
1087 _('[-fC] [NAME]'))
1088 def branch(ui, repo, label=None, **opts):
1088 def branch(ui, repo, label=None, **opts):
1089 """set or show the current branch name
1089 """set or show the current branch name
1090
1090
1091 .. note::
1091 .. note::
1092
1092
1093 Branch names are permanent and global. Use :hg:`bookmark` to create a
1093 Branch names are permanent and global. Use :hg:`bookmark` to create a
1094 light-weight bookmark instead. See :hg:`help glossary` for more
1094 light-weight bookmark instead. See :hg:`help glossary` for more
1095 information about named branches and bookmarks.
1095 information about named branches and bookmarks.
1096
1096
1097 With no argument, show the current branch name. With one argument,
1097 With no argument, show the current branch name. With one argument,
1098 set the working directory branch name (the branch will not exist
1098 set the working directory branch name (the branch will not exist
1099 in the repository until the next commit). Standard practice
1099 in the repository until the next commit). Standard practice
1100 recommends that primary development take place on the 'default'
1100 recommends that primary development take place on the 'default'
1101 branch.
1101 branch.
1102
1102
1103 Unless -f/--force is specified, branch will not let you set a
1103 Unless -f/--force is specified, branch will not let you set a
1104 branch name that already exists.
1104 branch name that already exists.
1105
1105
1106 Use -C/--clean to reset the working directory branch to that of
1106 Use -C/--clean to reset the working directory branch to that of
1107 the parent of the working directory, negating a previous branch
1107 the parent of the working directory, negating a previous branch
1108 change.
1108 change.
1109
1109
1110 Use the command :hg:`update` to switch to an existing branch. Use
1110 Use the command :hg:`update` to switch to an existing branch. Use
1111 :hg:`commit --close-branch` to mark this branch head as closed.
1111 :hg:`commit --close-branch` to mark this branch head as closed.
1112 When all heads of a branch are closed, the branch will be
1112 When all heads of a branch are closed, the branch will be
1113 considered closed.
1113 considered closed.
1114
1114
1115 Returns 0 on success.
1115 Returns 0 on success.
1116 """
1116 """
1117 opts = pycompat.byteskwargs(opts)
1117 opts = pycompat.byteskwargs(opts)
1118 if label:
1118 if label:
1119 label = label.strip()
1119 label = label.strip()
1120
1120
1121 if not opts.get('clean') and not label:
1121 if not opts.get('clean') and not label:
1122 ui.write("%s\n" % repo.dirstate.branch())
1122 ui.write("%s\n" % repo.dirstate.branch())
1123 return
1123 return
1124
1124
1125 with repo.wlock():
1125 with repo.wlock():
1126 if opts.get('clean'):
1126 if opts.get('clean'):
1127 label = repo[None].p1().branch()
1127 label = repo[None].p1().branch()
1128 repo.dirstate.setbranch(label)
1128 repo.dirstate.setbranch(label)
1129 ui.status(_('reset working directory to branch %s\n') % label)
1129 ui.status(_('reset working directory to branch %s\n') % label)
1130 elif label:
1130 elif label:
1131 if not opts.get('force') and label in repo.branchmap():
1131 if not opts.get('force') and label in repo.branchmap():
1132 if label not in [p.branch() for p in repo[None].parents()]:
1132 if label not in [p.branch() for p in repo[None].parents()]:
1133 raise error.Abort(_('a branch of the same name already'
1133 raise error.Abort(_('a branch of the same name already'
1134 ' exists'),
1134 ' exists'),
1135 # i18n: "it" refers to an existing branch
1135 # i18n: "it" refers to an existing branch
1136 hint=_("use 'hg update' to switch to it"))
1136 hint=_("use 'hg update' to switch to it"))
1137 scmutil.checknewlabel(repo, label, 'branch')
1137 scmutil.checknewlabel(repo, label, 'branch')
1138 repo.dirstate.setbranch(label)
1138 repo.dirstate.setbranch(label)
1139 ui.status(_('marked working directory as branch %s\n') % label)
1139 ui.status(_('marked working directory as branch %s\n') % label)
1140
1140
1141 # find any open named branches aside from default
1141 # find any open named branches aside from default
1142 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1142 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1143 if n != "default" and not c]
1143 if n != "default" and not c]
1144 if not others:
1144 if not others:
1145 ui.status(_('(branches are permanent and global, '
1145 ui.status(_('(branches are permanent and global, '
1146 'did you want a bookmark?)\n'))
1146 'did you want a bookmark?)\n'))
1147
1147
1148 @command('branches',
1148 @command('branches',
1149 [('a', 'active', False,
1149 [('a', 'active', False,
1150 _('show only branches that have unmerged heads (DEPRECATED)')),
1150 _('show only branches that have unmerged heads (DEPRECATED)')),
1151 ('c', 'closed', False, _('show normal and closed branches')),
1151 ('c', 'closed', False, _('show normal and closed branches')),
1152 ] + formatteropts,
1152 ] + formatteropts,
1153 _('[-c]'))
1153 _('[-c]'))
1154 def branches(ui, repo, active=False, closed=False, **opts):
1154 def branches(ui, repo, active=False, closed=False, **opts):
1155 """list repository named branches
1155 """list repository named branches
1156
1156
1157 List the repository's named branches, indicating which ones are
1157 List the repository's named branches, indicating which ones are
1158 inactive. If -c/--closed is specified, also list branches which have
1158 inactive. If -c/--closed is specified, also list branches which have
1159 been marked closed (see :hg:`commit --close-branch`).
1159 been marked closed (see :hg:`commit --close-branch`).
1160
1160
1161 Use the command :hg:`update` to switch to an existing branch.
1161 Use the command :hg:`update` to switch to an existing branch.
1162
1162
1163 Returns 0.
1163 Returns 0.
1164 """
1164 """
1165
1165
1166 opts = pycompat.byteskwargs(opts)
1166 opts = pycompat.byteskwargs(opts)
1167 ui.pager('branches')
1167 ui.pager('branches')
1168 fm = ui.formatter('branches', opts)
1168 fm = ui.formatter('branches', opts)
1169 hexfunc = fm.hexfunc
1169 hexfunc = fm.hexfunc
1170
1170
1171 allheads = set(repo.heads())
1171 allheads = set(repo.heads())
1172 branches = []
1172 branches = []
1173 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1173 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1174 isactive = not isclosed and bool(set(heads) & allheads)
1174 isactive = not isclosed and bool(set(heads) & allheads)
1175 branches.append((tag, repo[tip], isactive, not isclosed))
1175 branches.append((tag, repo[tip], isactive, not isclosed))
1176 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1176 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1177 reverse=True)
1177 reverse=True)
1178
1178
1179 for tag, ctx, isactive, isopen in branches:
1179 for tag, ctx, isactive, isopen in branches:
1180 if active and not isactive:
1180 if active and not isactive:
1181 continue
1181 continue
1182 if isactive:
1182 if isactive:
1183 label = 'branches.active'
1183 label = 'branches.active'
1184 notice = ''
1184 notice = ''
1185 elif not isopen:
1185 elif not isopen:
1186 if not closed:
1186 if not closed:
1187 continue
1187 continue
1188 label = 'branches.closed'
1188 label = 'branches.closed'
1189 notice = _(' (closed)')
1189 notice = _(' (closed)')
1190 else:
1190 else:
1191 label = 'branches.inactive'
1191 label = 'branches.inactive'
1192 notice = _(' (inactive)')
1192 notice = _(' (inactive)')
1193 current = (tag == repo.dirstate.branch())
1193 current = (tag == repo.dirstate.branch())
1194 if current:
1194 if current:
1195 label = 'branches.current'
1195 label = 'branches.current'
1196
1196
1197 fm.startitem()
1197 fm.startitem()
1198 fm.write('branch', '%s', tag, label=label)
1198 fm.write('branch', '%s', tag, label=label)
1199 rev = ctx.rev()
1199 rev = ctx.rev()
1200 padsize = max(31 - len(str(rev)) - encoding.colwidth(tag), 0)
1200 padsize = max(31 - len(str(rev)) - encoding.colwidth(tag), 0)
1201 fmt = ' ' * padsize + ' %d:%s'
1201 fmt = ' ' * padsize + ' %d:%s'
1202 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1202 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1203 label='log.changeset changeset.%s' % ctx.phasestr())
1203 label='log.changeset changeset.%s' % ctx.phasestr())
1204 fm.context(ctx=ctx)
1204 fm.context(ctx=ctx)
1205 fm.data(active=isactive, closed=not isopen, current=current)
1205 fm.data(active=isactive, closed=not isopen, current=current)
1206 if not ui.quiet:
1206 if not ui.quiet:
1207 fm.plain(notice)
1207 fm.plain(notice)
1208 fm.plain('\n')
1208 fm.plain('\n')
1209 fm.end()
1209 fm.end()
1210
1210
1211 @command('bundle',
1211 @command('bundle',
1212 [('f', 'force', None, _('run even when the destination is unrelated')),
1212 [('f', 'force', None, _('run even when the destination is unrelated')),
1213 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1213 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1214 _('REV')),
1214 _('REV')),
1215 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1215 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1216 _('BRANCH')),
1216 _('BRANCH')),
1217 ('', 'base', [],
1217 ('', 'base', [],
1218 _('a base changeset assumed to be available at the destination'),
1218 _('a base changeset assumed to be available at the destination'),
1219 _('REV')),
1219 _('REV')),
1220 ('a', 'all', None, _('bundle all changesets in the repository')),
1220 ('a', 'all', None, _('bundle all changesets in the repository')),
1221 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1221 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1222 ] + remoteopts,
1222 ] + remoteopts,
1223 _('[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1223 _('[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1224 def bundle(ui, repo, fname, dest=None, **opts):
1224 def bundle(ui, repo, fname, dest=None, **opts):
1225 """create a bundle file
1225 """create a bundle file
1226
1226
1227 Generate a bundle file containing data to be added to a repository.
1227 Generate a bundle file containing data to be added to a repository.
1228
1228
1229 To create a bundle containing all changesets, use -a/--all
1229 To create a bundle containing all changesets, use -a/--all
1230 (or --base null). Otherwise, hg assumes the destination will have
1230 (or --base null). Otherwise, hg assumes the destination will have
1231 all the nodes you specify with --base parameters. Otherwise, hg
1231 all the nodes you specify with --base parameters. Otherwise, hg
1232 will assume the repository has all the nodes in destination, or
1232 will assume the repository has all the nodes in destination, or
1233 default-push/default if no destination is specified.
1233 default-push/default if no destination is specified.
1234
1234
1235 You can change bundle format with the -t/--type option. See
1235 You can change bundle format with the -t/--type option. See
1236 :hg:`help bundlespec` for documentation on this format. By default,
1236 :hg:`help bundlespec` for documentation on this format. By default,
1237 the most appropriate format is used and compression defaults to
1237 the most appropriate format is used and compression defaults to
1238 bzip2.
1238 bzip2.
1239
1239
1240 The bundle file can then be transferred using conventional means
1240 The bundle file can then be transferred using conventional means
1241 and applied to another repository with the unbundle or pull
1241 and applied to another repository with the unbundle or pull
1242 command. This is useful when direct push and pull are not
1242 command. This is useful when direct push and pull are not
1243 available or when exporting an entire repository is undesirable.
1243 available or when exporting an entire repository is undesirable.
1244
1244
1245 Applying bundles preserves all changeset contents including
1245 Applying bundles preserves all changeset contents including
1246 permissions, copy/rename information, and revision history.
1246 permissions, copy/rename information, and revision history.
1247
1247
1248 Returns 0 on success, 1 if no changes found.
1248 Returns 0 on success, 1 if no changes found.
1249 """
1249 """
1250 opts = pycompat.byteskwargs(opts)
1250 opts = pycompat.byteskwargs(opts)
1251 revs = None
1251 revs = None
1252 if 'rev' in opts:
1252 if 'rev' in opts:
1253 revstrings = opts['rev']
1253 revstrings = opts['rev']
1254 revs = scmutil.revrange(repo, revstrings)
1254 revs = scmutil.revrange(repo, revstrings)
1255 if revstrings and not revs:
1255 if revstrings and not revs:
1256 raise error.Abort(_('no commits to bundle'))
1256 raise error.Abort(_('no commits to bundle'))
1257
1257
1258 bundletype = opts.get('type', 'bzip2').lower()
1258 bundletype = opts.get('type', 'bzip2').lower()
1259 try:
1259 try:
1260 bcompression, cgversion, params = exchange.parsebundlespec(
1260 bcompression, cgversion, params = exchange.parsebundlespec(
1261 repo, bundletype, strict=False)
1261 repo, bundletype, strict=False)
1262 except error.UnsupportedBundleSpecification as e:
1262 except error.UnsupportedBundleSpecification as e:
1263 raise error.Abort(str(e),
1263 raise error.Abort(str(e),
1264 hint=_("see 'hg help bundlespec' for supported "
1264 hint=_("see 'hg help bundlespec' for supported "
1265 "values for --type"))
1265 "values for --type"))
1266
1266
1267 # Packed bundles are a pseudo bundle format for now.
1267 # Packed bundles are a pseudo bundle format for now.
1268 if cgversion == 's1':
1268 if cgversion == 's1':
1269 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1269 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1270 hint=_("use 'hg debugcreatestreamclonebundle'"))
1270 hint=_("use 'hg debugcreatestreamclonebundle'"))
1271
1271
1272 if opts.get('all'):
1272 if opts.get('all'):
1273 if dest:
1273 if dest:
1274 raise error.Abort(_("--all is incompatible with specifying "
1274 raise error.Abort(_("--all is incompatible with specifying "
1275 "a destination"))
1275 "a destination"))
1276 if opts.get('base'):
1276 if opts.get('base'):
1277 ui.warn(_("ignoring --base because --all was specified\n"))
1277 ui.warn(_("ignoring --base because --all was specified\n"))
1278 base = ['null']
1278 base = ['null']
1279 else:
1279 else:
1280 base = scmutil.revrange(repo, opts.get('base'))
1280 base = scmutil.revrange(repo, opts.get('base'))
1281 if cgversion not in changegroup.supportedoutgoingversions(repo):
1281 if cgversion not in changegroup.supportedoutgoingversions(repo):
1282 raise error.Abort(_("repository does not support bundle version %s") %
1282 raise error.Abort(_("repository does not support bundle version %s") %
1283 cgversion)
1283 cgversion)
1284
1284
1285 if base:
1285 if base:
1286 if dest:
1286 if dest:
1287 raise error.Abort(_("--base is incompatible with specifying "
1287 raise error.Abort(_("--base is incompatible with specifying "
1288 "a destination"))
1288 "a destination"))
1289 common = [repo.lookup(rev) for rev in base]
1289 common = [repo.lookup(rev) for rev in base]
1290 heads = revs and map(repo.lookup, revs) or None
1290 heads = revs and map(repo.lookup, revs) or None
1291 outgoing = discovery.outgoing(repo, common, heads)
1291 outgoing = discovery.outgoing(repo, common, heads)
1292 else:
1292 else:
1293 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1293 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1294 dest, branches = hg.parseurl(dest, opts.get('branch'))
1294 dest, branches = hg.parseurl(dest, opts.get('branch'))
1295 other = hg.peer(repo, opts, dest)
1295 other = hg.peer(repo, opts, dest)
1296 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1296 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1297 heads = revs and map(repo.lookup, revs) or revs
1297 heads = revs and map(repo.lookup, revs) or revs
1298 outgoing = discovery.findcommonoutgoing(repo, other,
1298 outgoing = discovery.findcommonoutgoing(repo, other,
1299 onlyheads=heads,
1299 onlyheads=heads,
1300 force=opts.get('force'),
1300 force=opts.get('force'),
1301 portable=True)
1301 portable=True)
1302
1302
1303 if not outgoing.missing:
1303 if not outgoing.missing:
1304 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1304 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1305 return 1
1305 return 1
1306
1306
1307 if cgversion == '01': #bundle1
1307 if cgversion == '01': #bundle1
1308 if bcompression is None:
1308 if bcompression is None:
1309 bcompression = 'UN'
1309 bcompression = 'UN'
1310 bversion = 'HG10' + bcompression
1310 bversion = 'HG10' + bcompression
1311 bcompression = None
1311 bcompression = None
1312 elif cgversion in ('02', '03'):
1312 elif cgversion in ('02', '03'):
1313 bversion = 'HG20'
1313 bversion = 'HG20'
1314 else:
1314 else:
1315 raise error.ProgrammingError(
1315 raise error.ProgrammingError(
1316 'bundle: unexpected changegroup version %s' % cgversion)
1316 'bundle: unexpected changegroup version %s' % cgversion)
1317
1317
1318 # TODO compression options should be derived from bundlespec parsing.
1318 # TODO compression options should be derived from bundlespec parsing.
1319 # This is a temporary hack to allow adjusting bundle compression
1319 # This is a temporary hack to allow adjusting bundle compression
1320 # level without a) formalizing the bundlespec changes to declare it
1320 # level without a) formalizing the bundlespec changes to declare it
1321 # b) introducing a command flag.
1321 # b) introducing a command flag.
1322 compopts = {}
1322 compopts = {}
1323 complevel = ui.configint('experimental', 'bundlecomplevel')
1323 complevel = ui.configint('experimental', 'bundlecomplevel')
1324 if complevel is not None:
1324 if complevel is not None:
1325 compopts['level'] = complevel
1325 compopts['level'] = complevel
1326
1326
1327
1327
1328 contentopts = {'cg.version': cgversion}
1328 contentopts = {'cg.version': cgversion}
1329 if repo.ui.configbool('experimental', 'evolution.bundle-obsmarker', False):
1330 contentopts['obsolescence'] = True
1329 bundle2.writenewbundle(ui, repo, 'bundle', fname, bversion, outgoing,
1331 bundle2.writenewbundle(ui, repo, 'bundle', fname, bversion, outgoing,
1330 contentopts, compression=bcompression,
1332 contentopts, compression=bcompression,
1331 compopts=compopts)
1333 compopts=compopts)
1332
1334
1333 @command('cat',
1335 @command('cat',
1334 [('o', 'output', '',
1336 [('o', 'output', '',
1335 _('print output to file with formatted name'), _('FORMAT')),
1337 _('print output to file with formatted name'), _('FORMAT')),
1336 ('r', 'rev', '', _('print the given revision'), _('REV')),
1338 ('r', 'rev', '', _('print the given revision'), _('REV')),
1337 ('', 'decode', None, _('apply any matching decode filter')),
1339 ('', 'decode', None, _('apply any matching decode filter')),
1338 ] + walkopts,
1340 ] + walkopts,
1339 _('[OPTION]... FILE...'),
1341 _('[OPTION]... FILE...'),
1340 inferrepo=True)
1342 inferrepo=True)
1341 def cat(ui, repo, file1, *pats, **opts):
1343 def cat(ui, repo, file1, *pats, **opts):
1342 """output the current or given revision of files
1344 """output the current or given revision of files
1343
1345
1344 Print the specified files as they were at the given revision. If
1346 Print the specified files as they were at the given revision. If
1345 no revision is given, the parent of the working directory is used.
1347 no revision is given, the parent of the working directory is used.
1346
1348
1347 Output may be to a file, in which case the name of the file is
1349 Output may be to a file, in which case the name of the file is
1348 given using a format string. The formatting rules as follows:
1350 given using a format string. The formatting rules as follows:
1349
1351
1350 :``%%``: literal "%" character
1352 :``%%``: literal "%" character
1351 :``%s``: basename of file being printed
1353 :``%s``: basename of file being printed
1352 :``%d``: dirname of file being printed, or '.' if in repository root
1354 :``%d``: dirname of file being printed, or '.' if in repository root
1353 :``%p``: root-relative path name of file being printed
1355 :``%p``: root-relative path name of file being printed
1354 :``%H``: changeset hash (40 hexadecimal digits)
1356 :``%H``: changeset hash (40 hexadecimal digits)
1355 :``%R``: changeset revision number
1357 :``%R``: changeset revision number
1356 :``%h``: short-form changeset hash (12 hexadecimal digits)
1358 :``%h``: short-form changeset hash (12 hexadecimal digits)
1357 :``%r``: zero-padded changeset revision number
1359 :``%r``: zero-padded changeset revision number
1358 :``%b``: basename of the exporting repository
1360 :``%b``: basename of the exporting repository
1359
1361
1360 Returns 0 on success.
1362 Returns 0 on success.
1361 """
1363 """
1362 ctx = scmutil.revsingle(repo, opts.get('rev'))
1364 ctx = scmutil.revsingle(repo, opts.get('rev'))
1363 m = scmutil.match(ctx, (file1,) + pats, opts)
1365 m = scmutil.match(ctx, (file1,) + pats, opts)
1364
1366
1365 ui.pager('cat')
1367 ui.pager('cat')
1366 return cmdutil.cat(ui, repo, ctx, m, '', **opts)
1368 return cmdutil.cat(ui, repo, ctx, m, '', **opts)
1367
1369
1368 @command('^clone',
1370 @command('^clone',
1369 [('U', 'noupdate', None, _('the clone will include an empty working '
1371 [('U', 'noupdate', None, _('the clone will include an empty working '
1370 'directory (only a repository)')),
1372 'directory (only a repository)')),
1371 ('u', 'updaterev', '', _('revision, tag, or branch to check out'),
1373 ('u', 'updaterev', '', _('revision, tag, or branch to check out'),
1372 _('REV')),
1374 _('REV')),
1373 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1375 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1374 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1376 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1375 ('', 'pull', None, _('use pull protocol to copy metadata')),
1377 ('', 'pull', None, _('use pull protocol to copy metadata')),
1376 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1378 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1377 ] + remoteopts,
1379 ] + remoteopts,
1378 _('[OPTION]... SOURCE [DEST]'),
1380 _('[OPTION]... SOURCE [DEST]'),
1379 norepo=True)
1381 norepo=True)
1380 def clone(ui, source, dest=None, **opts):
1382 def clone(ui, source, dest=None, **opts):
1381 """make a copy of an existing repository
1383 """make a copy of an existing repository
1382
1384
1383 Create a copy of an existing repository in a new directory.
1385 Create a copy of an existing repository in a new directory.
1384
1386
1385 If no destination directory name is specified, it defaults to the
1387 If no destination directory name is specified, it defaults to the
1386 basename of the source.
1388 basename of the source.
1387
1389
1388 The location of the source is added to the new repository's
1390 The location of the source is added to the new repository's
1389 ``.hg/hgrc`` file, as the default to be used for future pulls.
1391 ``.hg/hgrc`` file, as the default to be used for future pulls.
1390
1392
1391 Only local paths and ``ssh://`` URLs are supported as
1393 Only local paths and ``ssh://`` URLs are supported as
1392 destinations. For ``ssh://`` destinations, no working directory or
1394 destinations. For ``ssh://`` destinations, no working directory or
1393 ``.hg/hgrc`` will be created on the remote side.
1395 ``.hg/hgrc`` will be created on the remote side.
1394
1396
1395 If the source repository has a bookmark called '@' set, that
1397 If the source repository has a bookmark called '@' set, that
1396 revision will be checked out in the new repository by default.
1398 revision will be checked out in the new repository by default.
1397
1399
1398 To check out a particular version, use -u/--update, or
1400 To check out a particular version, use -u/--update, or
1399 -U/--noupdate to create a clone with no working directory.
1401 -U/--noupdate to create a clone with no working directory.
1400
1402
1401 To pull only a subset of changesets, specify one or more revisions
1403 To pull only a subset of changesets, specify one or more revisions
1402 identifiers with -r/--rev or branches with -b/--branch. The
1404 identifiers with -r/--rev or branches with -b/--branch. The
1403 resulting clone will contain only the specified changesets and
1405 resulting clone will contain only the specified changesets and
1404 their ancestors. These options (or 'clone src#rev dest') imply
1406 their ancestors. These options (or 'clone src#rev dest') imply
1405 --pull, even for local source repositories.
1407 --pull, even for local source repositories.
1406
1408
1407 .. note::
1409 .. note::
1408
1410
1409 Specifying a tag will include the tagged changeset but not the
1411 Specifying a tag will include the tagged changeset but not the
1410 changeset containing the tag.
1412 changeset containing the tag.
1411
1413
1412 .. container:: verbose
1414 .. container:: verbose
1413
1415
1414 For efficiency, hardlinks are used for cloning whenever the
1416 For efficiency, hardlinks are used for cloning whenever the
1415 source and destination are on the same filesystem (note this
1417 source and destination are on the same filesystem (note this
1416 applies only to the repository data, not to the working
1418 applies only to the repository data, not to the working
1417 directory). Some filesystems, such as AFS, implement hardlinking
1419 directory). Some filesystems, such as AFS, implement hardlinking
1418 incorrectly, but do not report errors. In these cases, use the
1420 incorrectly, but do not report errors. In these cases, use the
1419 --pull option to avoid hardlinking.
1421 --pull option to avoid hardlinking.
1420
1422
1421 In some cases, you can clone repositories and the working
1423 In some cases, you can clone repositories and the working
1422 directory using full hardlinks with ::
1424 directory using full hardlinks with ::
1423
1425
1424 $ cp -al REPO REPOCLONE
1426 $ cp -al REPO REPOCLONE
1425
1427
1426 This is the fastest way to clone, but it is not always safe. The
1428 This is the fastest way to clone, but it is not always safe. The
1427 operation is not atomic (making sure REPO is not modified during
1429 operation is not atomic (making sure REPO is not modified during
1428 the operation is up to you) and you have to make sure your
1430 the operation is up to you) and you have to make sure your
1429 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1431 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1430 so). Also, this is not compatible with certain extensions that
1432 so). Also, this is not compatible with certain extensions that
1431 place their metadata under the .hg directory, such as mq.
1433 place their metadata under the .hg directory, such as mq.
1432
1434
1433 Mercurial will update the working directory to the first applicable
1435 Mercurial will update the working directory to the first applicable
1434 revision from this list:
1436 revision from this list:
1435
1437
1436 a) null if -U or the source repository has no changesets
1438 a) null if -U or the source repository has no changesets
1437 b) if -u . and the source repository is local, the first parent of
1439 b) if -u . and the source repository is local, the first parent of
1438 the source repository's working directory
1440 the source repository's working directory
1439 c) the changeset specified with -u (if a branch name, this means the
1441 c) the changeset specified with -u (if a branch name, this means the
1440 latest head of that branch)
1442 latest head of that branch)
1441 d) the changeset specified with -r
1443 d) the changeset specified with -r
1442 e) the tipmost head specified with -b
1444 e) the tipmost head specified with -b
1443 f) the tipmost head specified with the url#branch source syntax
1445 f) the tipmost head specified with the url#branch source syntax
1444 g) the revision marked with the '@' bookmark, if present
1446 g) the revision marked with the '@' bookmark, if present
1445 h) the tipmost head of the default branch
1447 h) the tipmost head of the default branch
1446 i) tip
1448 i) tip
1447
1449
1448 When cloning from servers that support it, Mercurial may fetch
1450 When cloning from servers that support it, Mercurial may fetch
1449 pre-generated data from a server-advertised URL. When this is done,
1451 pre-generated data from a server-advertised URL. When this is done,
1450 hooks operating on incoming changesets and changegroups may fire twice,
1452 hooks operating on incoming changesets and changegroups may fire twice,
1451 once for the bundle fetched from the URL and another for any additional
1453 once for the bundle fetched from the URL and another for any additional
1452 data not fetched from this URL. In addition, if an error occurs, the
1454 data not fetched from this URL. In addition, if an error occurs, the
1453 repository may be rolled back to a partial clone. This behavior may
1455 repository may be rolled back to a partial clone. This behavior may
1454 change in future releases. See :hg:`help -e clonebundles` for more.
1456 change in future releases. See :hg:`help -e clonebundles` for more.
1455
1457
1456 Examples:
1458 Examples:
1457
1459
1458 - clone a remote repository to a new directory named hg/::
1460 - clone a remote repository to a new directory named hg/::
1459
1461
1460 hg clone https://www.mercurial-scm.org/repo/hg/
1462 hg clone https://www.mercurial-scm.org/repo/hg/
1461
1463
1462 - create a lightweight local clone::
1464 - create a lightweight local clone::
1463
1465
1464 hg clone project/ project-feature/
1466 hg clone project/ project-feature/
1465
1467
1466 - clone from an absolute path on an ssh server (note double-slash)::
1468 - clone from an absolute path on an ssh server (note double-slash)::
1467
1469
1468 hg clone ssh://user@server//home/projects/alpha/
1470 hg clone ssh://user@server//home/projects/alpha/
1469
1471
1470 - do a high-speed clone over a LAN while checking out a
1472 - do a high-speed clone over a LAN while checking out a
1471 specified version::
1473 specified version::
1472
1474
1473 hg clone --uncompressed http://server/repo -u 1.5
1475 hg clone --uncompressed http://server/repo -u 1.5
1474
1476
1475 - create a repository without changesets after a particular revision::
1477 - create a repository without changesets after a particular revision::
1476
1478
1477 hg clone -r 04e544 experimental/ good/
1479 hg clone -r 04e544 experimental/ good/
1478
1480
1479 - clone (and track) a particular named branch::
1481 - clone (and track) a particular named branch::
1480
1482
1481 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1483 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1482
1484
1483 See :hg:`help urls` for details on specifying URLs.
1485 See :hg:`help urls` for details on specifying URLs.
1484
1486
1485 Returns 0 on success.
1487 Returns 0 on success.
1486 """
1488 """
1487 opts = pycompat.byteskwargs(opts)
1489 opts = pycompat.byteskwargs(opts)
1488 if opts.get('noupdate') and opts.get('updaterev'):
1490 if opts.get('noupdate') and opts.get('updaterev'):
1489 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1491 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1490
1492
1491 r = hg.clone(ui, opts, source, dest,
1493 r = hg.clone(ui, opts, source, dest,
1492 pull=opts.get('pull'),
1494 pull=opts.get('pull'),
1493 stream=opts.get('uncompressed'),
1495 stream=opts.get('uncompressed'),
1494 rev=opts.get('rev'),
1496 rev=opts.get('rev'),
1495 update=opts.get('updaterev') or not opts.get('noupdate'),
1497 update=opts.get('updaterev') or not opts.get('noupdate'),
1496 branch=opts.get('branch'),
1498 branch=opts.get('branch'),
1497 shareopts=opts.get('shareopts'))
1499 shareopts=opts.get('shareopts'))
1498
1500
1499 return r is None
1501 return r is None
1500
1502
1501 @command('^commit|ci',
1503 @command('^commit|ci',
1502 [('A', 'addremove', None,
1504 [('A', 'addremove', None,
1503 _('mark new/missing files as added/removed before committing')),
1505 _('mark new/missing files as added/removed before committing')),
1504 ('', 'close-branch', None,
1506 ('', 'close-branch', None,
1505 _('mark a branch head as closed')),
1507 _('mark a branch head as closed')),
1506 ('', 'amend', None, _('amend the parent of the working directory')),
1508 ('', 'amend', None, _('amend the parent of the working directory')),
1507 ('s', 'secret', None, _('use the secret phase for committing')),
1509 ('s', 'secret', None, _('use the secret phase for committing')),
1508 ('e', 'edit', None, _('invoke editor on commit messages')),
1510 ('e', 'edit', None, _('invoke editor on commit messages')),
1509 ('i', 'interactive', None, _('use interactive mode')),
1511 ('i', 'interactive', None, _('use interactive mode')),
1510 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1512 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1511 _('[OPTION]... [FILE]...'),
1513 _('[OPTION]... [FILE]...'),
1512 inferrepo=True)
1514 inferrepo=True)
1513 def commit(ui, repo, *pats, **opts):
1515 def commit(ui, repo, *pats, **opts):
1514 """commit the specified files or all outstanding changes
1516 """commit the specified files or all outstanding changes
1515
1517
1516 Commit changes to the given files into the repository. Unlike a
1518 Commit changes to the given files into the repository. Unlike a
1517 centralized SCM, this operation is a local operation. See
1519 centralized SCM, this operation is a local operation. See
1518 :hg:`push` for a way to actively distribute your changes.
1520 :hg:`push` for a way to actively distribute your changes.
1519
1521
1520 If a list of files is omitted, all changes reported by :hg:`status`
1522 If a list of files is omitted, all changes reported by :hg:`status`
1521 will be committed.
1523 will be committed.
1522
1524
1523 If you are committing the result of a merge, do not provide any
1525 If you are committing the result of a merge, do not provide any
1524 filenames or -I/-X filters.
1526 filenames or -I/-X filters.
1525
1527
1526 If no commit message is specified, Mercurial starts your
1528 If no commit message is specified, Mercurial starts your
1527 configured editor where you can enter a message. In case your
1529 configured editor where you can enter a message. In case your
1528 commit fails, you will find a backup of your message in
1530 commit fails, you will find a backup of your message in
1529 ``.hg/last-message.txt``.
1531 ``.hg/last-message.txt``.
1530
1532
1531 The --close-branch flag can be used to mark the current branch
1533 The --close-branch flag can be used to mark the current branch
1532 head closed. When all heads of a branch are closed, the branch
1534 head closed. When all heads of a branch are closed, the branch
1533 will be considered closed and no longer listed.
1535 will be considered closed and no longer listed.
1534
1536
1535 The --amend flag can be used to amend the parent of the
1537 The --amend flag can be used to amend the parent of the
1536 working directory with a new commit that contains the changes
1538 working directory with a new commit that contains the changes
1537 in the parent in addition to those currently reported by :hg:`status`,
1539 in the parent in addition to those currently reported by :hg:`status`,
1538 if there are any. The old commit is stored in a backup bundle in
1540 if there are any. The old commit is stored in a backup bundle in
1539 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1541 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1540 on how to restore it).
1542 on how to restore it).
1541
1543
1542 Message, user and date are taken from the amended commit unless
1544 Message, user and date are taken from the amended commit unless
1543 specified. When a message isn't specified on the command line,
1545 specified. When a message isn't specified on the command line,
1544 the editor will open with the message of the amended commit.
1546 the editor will open with the message of the amended commit.
1545
1547
1546 It is not possible to amend public changesets (see :hg:`help phases`)
1548 It is not possible to amend public changesets (see :hg:`help phases`)
1547 or changesets that have children.
1549 or changesets that have children.
1548
1550
1549 See :hg:`help dates` for a list of formats valid for -d/--date.
1551 See :hg:`help dates` for a list of formats valid for -d/--date.
1550
1552
1551 Returns 0 on success, 1 if nothing changed.
1553 Returns 0 on success, 1 if nothing changed.
1552
1554
1553 .. container:: verbose
1555 .. container:: verbose
1554
1556
1555 Examples:
1557 Examples:
1556
1558
1557 - commit all files ending in .py::
1559 - commit all files ending in .py::
1558
1560
1559 hg commit --include "set:**.py"
1561 hg commit --include "set:**.py"
1560
1562
1561 - commit all non-binary files::
1563 - commit all non-binary files::
1562
1564
1563 hg commit --exclude "set:binary()"
1565 hg commit --exclude "set:binary()"
1564
1566
1565 - amend the current commit and set the date to now::
1567 - amend the current commit and set the date to now::
1566
1568
1567 hg commit --amend --date now
1569 hg commit --amend --date now
1568 """
1570 """
1569 wlock = lock = None
1571 wlock = lock = None
1570 try:
1572 try:
1571 wlock = repo.wlock()
1573 wlock = repo.wlock()
1572 lock = repo.lock()
1574 lock = repo.lock()
1573 return _docommit(ui, repo, *pats, **opts)
1575 return _docommit(ui, repo, *pats, **opts)
1574 finally:
1576 finally:
1575 release(lock, wlock)
1577 release(lock, wlock)
1576
1578
1577 def _docommit(ui, repo, *pats, **opts):
1579 def _docommit(ui, repo, *pats, **opts):
1578 if opts.get(r'interactive'):
1580 if opts.get(r'interactive'):
1579 opts.pop(r'interactive')
1581 opts.pop(r'interactive')
1580 ret = cmdutil.dorecord(ui, repo, commit, None, False,
1582 ret = cmdutil.dorecord(ui, repo, commit, None, False,
1581 cmdutil.recordfilter, *pats,
1583 cmdutil.recordfilter, *pats,
1582 **opts)
1584 **opts)
1583 # ret can be 0 (no changes to record) or the value returned by
1585 # ret can be 0 (no changes to record) or the value returned by
1584 # commit(), 1 if nothing changed or None on success.
1586 # commit(), 1 if nothing changed or None on success.
1585 return 1 if ret == 0 else ret
1587 return 1 if ret == 0 else ret
1586
1588
1587 opts = pycompat.byteskwargs(opts)
1589 opts = pycompat.byteskwargs(opts)
1588 if opts.get('subrepos'):
1590 if opts.get('subrepos'):
1589 if opts.get('amend'):
1591 if opts.get('amend'):
1590 raise error.Abort(_('cannot amend with --subrepos'))
1592 raise error.Abort(_('cannot amend with --subrepos'))
1591 # Let --subrepos on the command line override config setting.
1593 # Let --subrepos on the command line override config setting.
1592 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1594 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1593
1595
1594 cmdutil.checkunfinished(repo, commit=True)
1596 cmdutil.checkunfinished(repo, commit=True)
1595
1597
1596 branch = repo[None].branch()
1598 branch = repo[None].branch()
1597 bheads = repo.branchheads(branch)
1599 bheads = repo.branchheads(branch)
1598
1600
1599 extra = {}
1601 extra = {}
1600 if opts.get('close_branch'):
1602 if opts.get('close_branch'):
1601 extra['close'] = 1
1603 extra['close'] = 1
1602
1604
1603 if not bheads:
1605 if not bheads:
1604 raise error.Abort(_('can only close branch heads'))
1606 raise error.Abort(_('can only close branch heads'))
1605 elif opts.get('amend'):
1607 elif opts.get('amend'):
1606 if repo[None].parents()[0].p1().branch() != branch and \
1608 if repo[None].parents()[0].p1().branch() != branch and \
1607 repo[None].parents()[0].p2().branch() != branch:
1609 repo[None].parents()[0].p2().branch() != branch:
1608 raise error.Abort(_('can only close branch heads'))
1610 raise error.Abort(_('can only close branch heads'))
1609
1611
1610 if opts.get('amend'):
1612 if opts.get('amend'):
1611 if ui.configbool('ui', 'commitsubrepos'):
1613 if ui.configbool('ui', 'commitsubrepos'):
1612 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1614 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1613
1615
1614 old = repo['.']
1616 old = repo['.']
1615 if not old.mutable():
1617 if not old.mutable():
1616 raise error.Abort(_('cannot amend public changesets'))
1618 raise error.Abort(_('cannot amend public changesets'))
1617 if len(repo[None].parents()) > 1:
1619 if len(repo[None].parents()) > 1:
1618 raise error.Abort(_('cannot amend while merging'))
1620 raise error.Abort(_('cannot amend while merging'))
1619 allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
1621 allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
1620 if not allowunstable and old.children():
1622 if not allowunstable and old.children():
1621 raise error.Abort(_('cannot amend changeset with children'))
1623 raise error.Abort(_('cannot amend changeset with children'))
1622
1624
1623 # Currently histedit gets confused if an amend happens while histedit
1625 # Currently histedit gets confused if an amend happens while histedit
1624 # is in progress. Since we have a checkunfinished command, we are
1626 # is in progress. Since we have a checkunfinished command, we are
1625 # temporarily honoring it.
1627 # temporarily honoring it.
1626 #
1628 #
1627 # Note: eventually this guard will be removed. Please do not expect
1629 # Note: eventually this guard will be removed. Please do not expect
1628 # this behavior to remain.
1630 # this behavior to remain.
1629 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1631 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1630 cmdutil.checkunfinished(repo)
1632 cmdutil.checkunfinished(repo)
1631
1633
1632 # commitfunc is used only for temporary amend commit by cmdutil.amend
1634 # commitfunc is used only for temporary amend commit by cmdutil.amend
1633 def commitfunc(ui, repo, message, match, opts):
1635 def commitfunc(ui, repo, message, match, opts):
1634 return repo.commit(message,
1636 return repo.commit(message,
1635 opts.get('user') or old.user(),
1637 opts.get('user') or old.user(),
1636 opts.get('date') or old.date(),
1638 opts.get('date') or old.date(),
1637 match,
1639 match,
1638 extra=extra)
1640 extra=extra)
1639
1641
1640 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1642 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1641 if node == old.node():
1643 if node == old.node():
1642 ui.status(_("nothing changed\n"))
1644 ui.status(_("nothing changed\n"))
1643 return 1
1645 return 1
1644 else:
1646 else:
1645 def commitfunc(ui, repo, message, match, opts):
1647 def commitfunc(ui, repo, message, match, opts):
1646 overrides = {}
1648 overrides = {}
1647 if opts.get('secret'):
1649 if opts.get('secret'):
1648 overrides[('phases', 'new-commit')] = 'secret'
1650 overrides[('phases', 'new-commit')] = 'secret'
1649
1651
1650 baseui = repo.baseui
1652 baseui = repo.baseui
1651 with baseui.configoverride(overrides, 'commit'):
1653 with baseui.configoverride(overrides, 'commit'):
1652 with ui.configoverride(overrides, 'commit'):
1654 with ui.configoverride(overrides, 'commit'):
1653 editform = cmdutil.mergeeditform(repo[None],
1655 editform = cmdutil.mergeeditform(repo[None],
1654 'commit.normal')
1656 'commit.normal')
1655 editor = cmdutil.getcommiteditor(
1657 editor = cmdutil.getcommiteditor(
1656 editform=editform, **pycompat.strkwargs(opts))
1658 editform=editform, **pycompat.strkwargs(opts))
1657 return repo.commit(message,
1659 return repo.commit(message,
1658 opts.get('user'),
1660 opts.get('user'),
1659 opts.get('date'),
1661 opts.get('date'),
1660 match,
1662 match,
1661 editor=editor,
1663 editor=editor,
1662 extra=extra)
1664 extra=extra)
1663
1665
1664 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1666 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1665
1667
1666 if not node:
1668 if not node:
1667 stat = cmdutil.postcommitstatus(repo, pats, opts)
1669 stat = cmdutil.postcommitstatus(repo, pats, opts)
1668 if stat[3]:
1670 if stat[3]:
1669 ui.status(_("nothing changed (%d missing files, see "
1671 ui.status(_("nothing changed (%d missing files, see "
1670 "'hg status')\n") % len(stat[3]))
1672 "'hg status')\n") % len(stat[3]))
1671 else:
1673 else:
1672 ui.status(_("nothing changed\n"))
1674 ui.status(_("nothing changed\n"))
1673 return 1
1675 return 1
1674
1676
1675 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1677 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1676
1678
1677 @command('config|showconfig|debugconfig',
1679 @command('config|showconfig|debugconfig',
1678 [('u', 'untrusted', None, _('show untrusted configuration options')),
1680 [('u', 'untrusted', None, _('show untrusted configuration options')),
1679 ('e', 'edit', None, _('edit user config')),
1681 ('e', 'edit', None, _('edit user config')),
1680 ('l', 'local', None, _('edit repository config')),
1682 ('l', 'local', None, _('edit repository config')),
1681 ('g', 'global', None, _('edit global config'))] + formatteropts,
1683 ('g', 'global', None, _('edit global config'))] + formatteropts,
1682 _('[-u] [NAME]...'),
1684 _('[-u] [NAME]...'),
1683 optionalrepo=True)
1685 optionalrepo=True)
1684 def config(ui, repo, *values, **opts):
1686 def config(ui, repo, *values, **opts):
1685 """show combined config settings from all hgrc files
1687 """show combined config settings from all hgrc files
1686
1688
1687 With no arguments, print names and values of all config items.
1689 With no arguments, print names and values of all config items.
1688
1690
1689 With one argument of the form section.name, print just the value
1691 With one argument of the form section.name, print just the value
1690 of that config item.
1692 of that config item.
1691
1693
1692 With multiple arguments, print names and values of all config
1694 With multiple arguments, print names and values of all config
1693 items with matching section names.
1695 items with matching section names.
1694
1696
1695 With --edit, start an editor on the user-level config file. With
1697 With --edit, start an editor on the user-level config file. With
1696 --global, edit the system-wide config file. With --local, edit the
1698 --global, edit the system-wide config file. With --local, edit the
1697 repository-level config file.
1699 repository-level config file.
1698
1700
1699 With --debug, the source (filename and line number) is printed
1701 With --debug, the source (filename and line number) is printed
1700 for each config item.
1702 for each config item.
1701
1703
1702 See :hg:`help config` for more information about config files.
1704 See :hg:`help config` for more information about config files.
1703
1705
1704 Returns 0 on success, 1 if NAME does not exist.
1706 Returns 0 on success, 1 if NAME does not exist.
1705
1707
1706 """
1708 """
1707
1709
1708 opts = pycompat.byteskwargs(opts)
1710 opts = pycompat.byteskwargs(opts)
1709 if opts.get('edit') or opts.get('local') or opts.get('global'):
1711 if opts.get('edit') or opts.get('local') or opts.get('global'):
1710 if opts.get('local') and opts.get('global'):
1712 if opts.get('local') and opts.get('global'):
1711 raise error.Abort(_("can't use --local and --global together"))
1713 raise error.Abort(_("can't use --local and --global together"))
1712
1714
1713 if opts.get('local'):
1715 if opts.get('local'):
1714 if not repo:
1716 if not repo:
1715 raise error.Abort(_("can't use --local outside a repository"))
1717 raise error.Abort(_("can't use --local outside a repository"))
1716 paths = [repo.vfs.join('hgrc')]
1718 paths = [repo.vfs.join('hgrc')]
1717 elif opts.get('global'):
1719 elif opts.get('global'):
1718 paths = rcutil.systemrcpath()
1720 paths = rcutil.systemrcpath()
1719 else:
1721 else:
1720 paths = rcutil.userrcpath()
1722 paths = rcutil.userrcpath()
1721
1723
1722 for f in paths:
1724 for f in paths:
1723 if os.path.exists(f):
1725 if os.path.exists(f):
1724 break
1726 break
1725 else:
1727 else:
1726 if opts.get('global'):
1728 if opts.get('global'):
1727 samplehgrc = uimod.samplehgrcs['global']
1729 samplehgrc = uimod.samplehgrcs['global']
1728 elif opts.get('local'):
1730 elif opts.get('local'):
1729 samplehgrc = uimod.samplehgrcs['local']
1731 samplehgrc = uimod.samplehgrcs['local']
1730 else:
1732 else:
1731 samplehgrc = uimod.samplehgrcs['user']
1733 samplehgrc = uimod.samplehgrcs['user']
1732
1734
1733 f = paths[0]
1735 f = paths[0]
1734 fp = open(f, "w")
1736 fp = open(f, "w")
1735 fp.write(samplehgrc)
1737 fp.write(samplehgrc)
1736 fp.close()
1738 fp.close()
1737
1739
1738 editor = ui.geteditor()
1740 editor = ui.geteditor()
1739 ui.system("%s \"%s\"" % (editor, f),
1741 ui.system("%s \"%s\"" % (editor, f),
1740 onerr=error.Abort, errprefix=_("edit failed"),
1742 onerr=error.Abort, errprefix=_("edit failed"),
1741 blockedtag='config_edit')
1743 blockedtag='config_edit')
1742 return
1744 return
1743 ui.pager('config')
1745 ui.pager('config')
1744 fm = ui.formatter('config', opts)
1746 fm = ui.formatter('config', opts)
1745 for t, f in rcutil.rccomponents():
1747 for t, f in rcutil.rccomponents():
1746 if t == 'path':
1748 if t == 'path':
1747 ui.debug('read config from: %s\n' % f)
1749 ui.debug('read config from: %s\n' % f)
1748 elif t == 'items':
1750 elif t == 'items':
1749 for section, name, value, source in f:
1751 for section, name, value, source in f:
1750 ui.debug('set config by: %s\n' % source)
1752 ui.debug('set config by: %s\n' % source)
1751 else:
1753 else:
1752 raise error.ProgrammingError('unknown rctype: %s' % t)
1754 raise error.ProgrammingError('unknown rctype: %s' % t)
1753 untrusted = bool(opts.get('untrusted'))
1755 untrusted = bool(opts.get('untrusted'))
1754 if values:
1756 if values:
1755 sections = [v for v in values if '.' not in v]
1757 sections = [v for v in values if '.' not in v]
1756 items = [v for v in values if '.' in v]
1758 items = [v for v in values if '.' in v]
1757 if len(items) > 1 or items and sections:
1759 if len(items) > 1 or items and sections:
1758 raise error.Abort(_('only one config item permitted'))
1760 raise error.Abort(_('only one config item permitted'))
1759 matched = False
1761 matched = False
1760 for section, name, value in ui.walkconfig(untrusted=untrusted):
1762 for section, name, value in ui.walkconfig(untrusted=untrusted):
1761 source = ui.configsource(section, name, untrusted)
1763 source = ui.configsource(section, name, untrusted)
1762 value = pycompat.bytestr(value)
1764 value = pycompat.bytestr(value)
1763 if fm.isplain():
1765 if fm.isplain():
1764 source = source or 'none'
1766 source = source or 'none'
1765 value = value.replace('\n', '\\n')
1767 value = value.replace('\n', '\\n')
1766 entryname = section + '.' + name
1768 entryname = section + '.' + name
1767 if values:
1769 if values:
1768 for v in values:
1770 for v in values:
1769 if v == section:
1771 if v == section:
1770 fm.startitem()
1772 fm.startitem()
1771 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1773 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1772 fm.write('name value', '%s=%s\n', entryname, value)
1774 fm.write('name value', '%s=%s\n', entryname, value)
1773 matched = True
1775 matched = True
1774 elif v == entryname:
1776 elif v == entryname:
1775 fm.startitem()
1777 fm.startitem()
1776 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1778 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1777 fm.write('value', '%s\n', value)
1779 fm.write('value', '%s\n', value)
1778 fm.data(name=entryname)
1780 fm.data(name=entryname)
1779 matched = True
1781 matched = True
1780 else:
1782 else:
1781 fm.startitem()
1783 fm.startitem()
1782 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1784 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1783 fm.write('name value', '%s=%s\n', entryname, value)
1785 fm.write('name value', '%s=%s\n', entryname, value)
1784 matched = True
1786 matched = True
1785 fm.end()
1787 fm.end()
1786 if matched:
1788 if matched:
1787 return 0
1789 return 0
1788 return 1
1790 return 1
1789
1791
1790 @command('copy|cp',
1792 @command('copy|cp',
1791 [('A', 'after', None, _('record a copy that has already occurred')),
1793 [('A', 'after', None, _('record a copy that has already occurred')),
1792 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1794 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1793 ] + walkopts + dryrunopts,
1795 ] + walkopts + dryrunopts,
1794 _('[OPTION]... [SOURCE]... DEST'))
1796 _('[OPTION]... [SOURCE]... DEST'))
1795 def copy(ui, repo, *pats, **opts):
1797 def copy(ui, repo, *pats, **opts):
1796 """mark files as copied for the next commit
1798 """mark files as copied for the next commit
1797
1799
1798 Mark dest as having copies of source files. If dest is a
1800 Mark dest as having copies of source files. If dest is a
1799 directory, copies are put in that directory. If dest is a file,
1801 directory, copies are put in that directory. If dest is a file,
1800 the source must be a single file.
1802 the source must be a single file.
1801
1803
1802 By default, this command copies the contents of files as they
1804 By default, this command copies the contents of files as they
1803 exist in the working directory. If invoked with -A/--after, the
1805 exist in the working directory. If invoked with -A/--after, the
1804 operation is recorded, but no copying is performed.
1806 operation is recorded, but no copying is performed.
1805
1807
1806 This command takes effect with the next commit. To undo a copy
1808 This command takes effect with the next commit. To undo a copy
1807 before that, see :hg:`revert`.
1809 before that, see :hg:`revert`.
1808
1810
1809 Returns 0 on success, 1 if errors are encountered.
1811 Returns 0 on success, 1 if errors are encountered.
1810 """
1812 """
1811 opts = pycompat.byteskwargs(opts)
1813 opts = pycompat.byteskwargs(opts)
1812 with repo.wlock(False):
1814 with repo.wlock(False):
1813 return cmdutil.copy(ui, repo, pats, opts)
1815 return cmdutil.copy(ui, repo, pats, opts)
1814
1816
1815 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
1817 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
1816 def debugcommands(ui, cmd='', *args):
1818 def debugcommands(ui, cmd='', *args):
1817 """list all available commands and options"""
1819 """list all available commands and options"""
1818 for cmd, vals in sorted(table.iteritems()):
1820 for cmd, vals in sorted(table.iteritems()):
1819 cmd = cmd.split('|')[0].strip('^')
1821 cmd = cmd.split('|')[0].strip('^')
1820 opts = ', '.join([i[1] for i in vals[1]])
1822 opts = ', '.join([i[1] for i in vals[1]])
1821 ui.write('%s: %s\n' % (cmd, opts))
1823 ui.write('%s: %s\n' % (cmd, opts))
1822
1824
1823 @command('debugcomplete',
1825 @command('debugcomplete',
1824 [('o', 'options', None, _('show the command options'))],
1826 [('o', 'options', None, _('show the command options'))],
1825 _('[-o] CMD'),
1827 _('[-o] CMD'),
1826 norepo=True)
1828 norepo=True)
1827 def debugcomplete(ui, cmd='', **opts):
1829 def debugcomplete(ui, cmd='', **opts):
1828 """returns the completion list associated with the given command"""
1830 """returns the completion list associated with the given command"""
1829
1831
1830 if opts.get('options'):
1832 if opts.get('options'):
1831 options = []
1833 options = []
1832 otables = [globalopts]
1834 otables = [globalopts]
1833 if cmd:
1835 if cmd:
1834 aliases, entry = cmdutil.findcmd(cmd, table, False)
1836 aliases, entry = cmdutil.findcmd(cmd, table, False)
1835 otables.append(entry[1])
1837 otables.append(entry[1])
1836 for t in otables:
1838 for t in otables:
1837 for o in t:
1839 for o in t:
1838 if "(DEPRECATED)" in o[3]:
1840 if "(DEPRECATED)" in o[3]:
1839 continue
1841 continue
1840 if o[0]:
1842 if o[0]:
1841 options.append('-%s' % o[0])
1843 options.append('-%s' % o[0])
1842 options.append('--%s' % o[1])
1844 options.append('--%s' % o[1])
1843 ui.write("%s\n" % "\n".join(options))
1845 ui.write("%s\n" % "\n".join(options))
1844 return
1846 return
1845
1847
1846 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
1848 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
1847 if ui.verbose:
1849 if ui.verbose:
1848 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1850 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1849 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1851 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1850
1852
1851 @command('^diff',
1853 @command('^diff',
1852 [('r', 'rev', [], _('revision'), _('REV')),
1854 [('r', 'rev', [], _('revision'), _('REV')),
1853 ('c', 'change', '', _('change made by revision'), _('REV'))
1855 ('c', 'change', '', _('change made by revision'), _('REV'))
1854 ] + diffopts + diffopts2 + walkopts + subrepoopts,
1856 ] + diffopts + diffopts2 + walkopts + subrepoopts,
1855 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
1857 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
1856 inferrepo=True)
1858 inferrepo=True)
1857 def diff(ui, repo, *pats, **opts):
1859 def diff(ui, repo, *pats, **opts):
1858 """diff repository (or selected files)
1860 """diff repository (or selected files)
1859
1861
1860 Show differences between revisions for the specified files.
1862 Show differences between revisions for the specified files.
1861
1863
1862 Differences between files are shown using the unified diff format.
1864 Differences between files are shown using the unified diff format.
1863
1865
1864 .. note::
1866 .. note::
1865
1867
1866 :hg:`diff` may generate unexpected results for merges, as it will
1868 :hg:`diff` may generate unexpected results for merges, as it will
1867 default to comparing against the working directory's first
1869 default to comparing against the working directory's first
1868 parent changeset if no revisions are specified.
1870 parent changeset if no revisions are specified.
1869
1871
1870 When two revision arguments are given, then changes are shown
1872 When two revision arguments are given, then changes are shown
1871 between those revisions. If only one revision is specified then
1873 between those revisions. If only one revision is specified then
1872 that revision is compared to the working directory, and, when no
1874 that revision is compared to the working directory, and, when no
1873 revisions are specified, the working directory files are compared
1875 revisions are specified, the working directory files are compared
1874 to its first parent.
1876 to its first parent.
1875
1877
1876 Alternatively you can specify -c/--change with a revision to see
1878 Alternatively you can specify -c/--change with a revision to see
1877 the changes in that changeset relative to its first parent.
1879 the changes in that changeset relative to its first parent.
1878
1880
1879 Without the -a/--text option, diff will avoid generating diffs of
1881 Without the -a/--text option, diff will avoid generating diffs of
1880 files it detects as binary. With -a, diff will generate a diff
1882 files it detects as binary. With -a, diff will generate a diff
1881 anyway, probably with undesirable results.
1883 anyway, probably with undesirable results.
1882
1884
1883 Use the -g/--git option to generate diffs in the git extended diff
1885 Use the -g/--git option to generate diffs in the git extended diff
1884 format. For more information, read :hg:`help diffs`.
1886 format. For more information, read :hg:`help diffs`.
1885
1887
1886 .. container:: verbose
1888 .. container:: verbose
1887
1889
1888 Examples:
1890 Examples:
1889
1891
1890 - compare a file in the current working directory to its parent::
1892 - compare a file in the current working directory to its parent::
1891
1893
1892 hg diff foo.c
1894 hg diff foo.c
1893
1895
1894 - compare two historical versions of a directory, with rename info::
1896 - compare two historical versions of a directory, with rename info::
1895
1897
1896 hg diff --git -r 1.0:1.2 lib/
1898 hg diff --git -r 1.0:1.2 lib/
1897
1899
1898 - get change stats relative to the last change on some date::
1900 - get change stats relative to the last change on some date::
1899
1901
1900 hg diff --stat -r "date('may 2')"
1902 hg diff --stat -r "date('may 2')"
1901
1903
1902 - diff all newly-added files that contain a keyword::
1904 - diff all newly-added files that contain a keyword::
1903
1905
1904 hg diff "set:added() and grep(GNU)"
1906 hg diff "set:added() and grep(GNU)"
1905
1907
1906 - compare a revision and its parents::
1908 - compare a revision and its parents::
1907
1909
1908 hg diff -c 9353 # compare against first parent
1910 hg diff -c 9353 # compare against first parent
1909 hg diff -r 9353^:9353 # same using revset syntax
1911 hg diff -r 9353^:9353 # same using revset syntax
1910 hg diff -r 9353^2:9353 # compare against the second parent
1912 hg diff -r 9353^2:9353 # compare against the second parent
1911
1913
1912 Returns 0 on success.
1914 Returns 0 on success.
1913 """
1915 """
1914
1916
1915 opts = pycompat.byteskwargs(opts)
1917 opts = pycompat.byteskwargs(opts)
1916 revs = opts.get('rev')
1918 revs = opts.get('rev')
1917 change = opts.get('change')
1919 change = opts.get('change')
1918 stat = opts.get('stat')
1920 stat = opts.get('stat')
1919 reverse = opts.get('reverse')
1921 reverse = opts.get('reverse')
1920
1922
1921 if revs and change:
1923 if revs and change:
1922 msg = _('cannot specify --rev and --change at the same time')
1924 msg = _('cannot specify --rev and --change at the same time')
1923 raise error.Abort(msg)
1925 raise error.Abort(msg)
1924 elif change:
1926 elif change:
1925 node2 = scmutil.revsingle(repo, change, None).node()
1927 node2 = scmutil.revsingle(repo, change, None).node()
1926 node1 = repo[node2].p1().node()
1928 node1 = repo[node2].p1().node()
1927 else:
1929 else:
1928 node1, node2 = scmutil.revpair(repo, revs)
1930 node1, node2 = scmutil.revpair(repo, revs)
1929
1931
1930 if reverse:
1932 if reverse:
1931 node1, node2 = node2, node1
1933 node1, node2 = node2, node1
1932
1934
1933 diffopts = patch.diffallopts(ui, opts)
1935 diffopts = patch.diffallopts(ui, opts)
1934 m = scmutil.match(repo[node2], pats, opts)
1936 m = scmutil.match(repo[node2], pats, opts)
1935 ui.pager('diff')
1937 ui.pager('diff')
1936 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
1938 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
1937 listsubrepos=opts.get('subrepos'),
1939 listsubrepos=opts.get('subrepos'),
1938 root=opts.get('root'))
1940 root=opts.get('root'))
1939
1941
1940 @command('^export',
1942 @command('^export',
1941 [('o', 'output', '',
1943 [('o', 'output', '',
1942 _('print output to file with formatted name'), _('FORMAT')),
1944 _('print output to file with formatted name'), _('FORMAT')),
1943 ('', 'switch-parent', None, _('diff against the second parent')),
1945 ('', 'switch-parent', None, _('diff against the second parent')),
1944 ('r', 'rev', [], _('revisions to export'), _('REV')),
1946 ('r', 'rev', [], _('revisions to export'), _('REV')),
1945 ] + diffopts,
1947 ] + diffopts,
1946 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
1948 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
1947 def export(ui, repo, *changesets, **opts):
1949 def export(ui, repo, *changesets, **opts):
1948 """dump the header and diffs for one or more changesets
1950 """dump the header and diffs for one or more changesets
1949
1951
1950 Print the changeset header and diffs for one or more revisions.
1952 Print the changeset header and diffs for one or more revisions.
1951 If no revision is given, the parent of the working directory is used.
1953 If no revision is given, the parent of the working directory is used.
1952
1954
1953 The information shown in the changeset header is: author, date,
1955 The information shown in the changeset header is: author, date,
1954 branch name (if non-default), changeset hash, parent(s) and commit
1956 branch name (if non-default), changeset hash, parent(s) and commit
1955 comment.
1957 comment.
1956
1958
1957 .. note::
1959 .. note::
1958
1960
1959 :hg:`export` may generate unexpected diff output for merge
1961 :hg:`export` may generate unexpected diff output for merge
1960 changesets, as it will compare the merge changeset against its
1962 changesets, as it will compare the merge changeset against its
1961 first parent only.
1963 first parent only.
1962
1964
1963 Output may be to a file, in which case the name of the file is
1965 Output may be to a file, in which case the name of the file is
1964 given using a format string. The formatting rules are as follows:
1966 given using a format string. The formatting rules are as follows:
1965
1967
1966 :``%%``: literal "%" character
1968 :``%%``: literal "%" character
1967 :``%H``: changeset hash (40 hexadecimal digits)
1969 :``%H``: changeset hash (40 hexadecimal digits)
1968 :``%N``: number of patches being generated
1970 :``%N``: number of patches being generated
1969 :``%R``: changeset revision number
1971 :``%R``: changeset revision number
1970 :``%b``: basename of the exporting repository
1972 :``%b``: basename of the exporting repository
1971 :``%h``: short-form changeset hash (12 hexadecimal digits)
1973 :``%h``: short-form changeset hash (12 hexadecimal digits)
1972 :``%m``: first line of the commit message (only alphanumeric characters)
1974 :``%m``: first line of the commit message (only alphanumeric characters)
1973 :``%n``: zero-padded sequence number, starting at 1
1975 :``%n``: zero-padded sequence number, starting at 1
1974 :``%r``: zero-padded changeset revision number
1976 :``%r``: zero-padded changeset revision number
1975
1977
1976 Without the -a/--text option, export will avoid generating diffs
1978 Without the -a/--text option, export will avoid generating diffs
1977 of files it detects as binary. With -a, export will generate a
1979 of files it detects as binary. With -a, export will generate a
1978 diff anyway, probably with undesirable results.
1980 diff anyway, probably with undesirable results.
1979
1981
1980 Use the -g/--git option to generate diffs in the git extended diff
1982 Use the -g/--git option to generate diffs in the git extended diff
1981 format. See :hg:`help diffs` for more information.
1983 format. See :hg:`help diffs` for more information.
1982
1984
1983 With the --switch-parent option, the diff will be against the
1985 With the --switch-parent option, the diff will be against the
1984 second parent. It can be useful to review a merge.
1986 second parent. It can be useful to review a merge.
1985
1987
1986 .. container:: verbose
1988 .. container:: verbose
1987
1989
1988 Examples:
1990 Examples:
1989
1991
1990 - use export and import to transplant a bugfix to the current
1992 - use export and import to transplant a bugfix to the current
1991 branch::
1993 branch::
1992
1994
1993 hg export -r 9353 | hg import -
1995 hg export -r 9353 | hg import -
1994
1996
1995 - export all the changesets between two revisions to a file with
1997 - export all the changesets between two revisions to a file with
1996 rename information::
1998 rename information::
1997
1999
1998 hg export --git -r 123:150 > changes.txt
2000 hg export --git -r 123:150 > changes.txt
1999
2001
2000 - split outgoing changes into a series of patches with
2002 - split outgoing changes into a series of patches with
2001 descriptive names::
2003 descriptive names::
2002
2004
2003 hg export -r "outgoing()" -o "%n-%m.patch"
2005 hg export -r "outgoing()" -o "%n-%m.patch"
2004
2006
2005 Returns 0 on success.
2007 Returns 0 on success.
2006 """
2008 """
2007 opts = pycompat.byteskwargs(opts)
2009 opts = pycompat.byteskwargs(opts)
2008 changesets += tuple(opts.get('rev', []))
2010 changesets += tuple(opts.get('rev', []))
2009 if not changesets:
2011 if not changesets:
2010 changesets = ['.']
2012 changesets = ['.']
2011 revs = scmutil.revrange(repo, changesets)
2013 revs = scmutil.revrange(repo, changesets)
2012 if not revs:
2014 if not revs:
2013 raise error.Abort(_("export requires at least one changeset"))
2015 raise error.Abort(_("export requires at least one changeset"))
2014 if len(revs) > 1:
2016 if len(revs) > 1:
2015 ui.note(_('exporting patches:\n'))
2017 ui.note(_('exporting patches:\n'))
2016 else:
2018 else:
2017 ui.note(_('exporting patch:\n'))
2019 ui.note(_('exporting patch:\n'))
2018 ui.pager('export')
2020 ui.pager('export')
2019 cmdutil.export(repo, revs, fntemplate=opts.get('output'),
2021 cmdutil.export(repo, revs, fntemplate=opts.get('output'),
2020 switch_parent=opts.get('switch_parent'),
2022 switch_parent=opts.get('switch_parent'),
2021 opts=patch.diffallopts(ui, opts))
2023 opts=patch.diffallopts(ui, opts))
2022
2024
2023 @command('files',
2025 @command('files',
2024 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
2026 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
2025 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
2027 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
2026 ] + walkopts + formatteropts + subrepoopts,
2028 ] + walkopts + formatteropts + subrepoopts,
2027 _('[OPTION]... [FILE]...'))
2029 _('[OPTION]... [FILE]...'))
2028 def files(ui, repo, *pats, **opts):
2030 def files(ui, repo, *pats, **opts):
2029 """list tracked files
2031 """list tracked files
2030
2032
2031 Print files under Mercurial control in the working directory or
2033 Print files under Mercurial control in the working directory or
2032 specified revision for given files (excluding removed files).
2034 specified revision for given files (excluding removed files).
2033 Files can be specified as filenames or filesets.
2035 Files can be specified as filenames or filesets.
2034
2036
2035 If no files are given to match, this command prints the names
2037 If no files are given to match, this command prints the names
2036 of all files under Mercurial control.
2038 of all files under Mercurial control.
2037
2039
2038 .. container:: verbose
2040 .. container:: verbose
2039
2041
2040 Examples:
2042 Examples:
2041
2043
2042 - list all files under the current directory::
2044 - list all files under the current directory::
2043
2045
2044 hg files .
2046 hg files .
2045
2047
2046 - shows sizes and flags for current revision::
2048 - shows sizes and flags for current revision::
2047
2049
2048 hg files -vr .
2050 hg files -vr .
2049
2051
2050 - list all files named README::
2052 - list all files named README::
2051
2053
2052 hg files -I "**/README"
2054 hg files -I "**/README"
2053
2055
2054 - list all binary files::
2056 - list all binary files::
2055
2057
2056 hg files "set:binary()"
2058 hg files "set:binary()"
2057
2059
2058 - find files containing a regular expression::
2060 - find files containing a regular expression::
2059
2061
2060 hg files "set:grep('bob')"
2062 hg files "set:grep('bob')"
2061
2063
2062 - search tracked file contents with xargs and grep::
2064 - search tracked file contents with xargs and grep::
2063
2065
2064 hg files -0 | xargs -0 grep foo
2066 hg files -0 | xargs -0 grep foo
2065
2067
2066 See :hg:`help patterns` and :hg:`help filesets` for more information
2068 See :hg:`help patterns` and :hg:`help filesets` for more information
2067 on specifying file patterns.
2069 on specifying file patterns.
2068
2070
2069 Returns 0 if a match is found, 1 otherwise.
2071 Returns 0 if a match is found, 1 otherwise.
2070
2072
2071 """
2073 """
2072
2074
2073 opts = pycompat.byteskwargs(opts)
2075 opts = pycompat.byteskwargs(opts)
2074 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
2076 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
2075
2077
2076 end = '\n'
2078 end = '\n'
2077 if opts.get('print0'):
2079 if opts.get('print0'):
2078 end = '\0'
2080 end = '\0'
2079 fmt = '%s' + end
2081 fmt = '%s' + end
2080
2082
2081 m = scmutil.match(ctx, pats, opts)
2083 m = scmutil.match(ctx, pats, opts)
2082 ui.pager('files')
2084 ui.pager('files')
2083 with ui.formatter('files', opts) as fm:
2085 with ui.formatter('files', opts) as fm:
2084 return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
2086 return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
2085
2087
2086 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
2088 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
2087 def forget(ui, repo, *pats, **opts):
2089 def forget(ui, repo, *pats, **opts):
2088 """forget the specified files on the next commit
2090 """forget the specified files on the next commit
2089
2091
2090 Mark the specified files so they will no longer be tracked
2092 Mark the specified files so they will no longer be tracked
2091 after the next commit.
2093 after the next commit.
2092
2094
2093 This only removes files from the current branch, not from the
2095 This only removes files from the current branch, not from the
2094 entire project history, and it does not delete them from the
2096 entire project history, and it does not delete them from the
2095 working directory.
2097 working directory.
2096
2098
2097 To delete the file from the working directory, see :hg:`remove`.
2099 To delete the file from the working directory, see :hg:`remove`.
2098
2100
2099 To undo a forget before the next commit, see :hg:`add`.
2101 To undo a forget before the next commit, see :hg:`add`.
2100
2102
2101 .. container:: verbose
2103 .. container:: verbose
2102
2104
2103 Examples:
2105 Examples:
2104
2106
2105 - forget newly-added binary files::
2107 - forget newly-added binary files::
2106
2108
2107 hg forget "set:added() and binary()"
2109 hg forget "set:added() and binary()"
2108
2110
2109 - forget files that would be excluded by .hgignore::
2111 - forget files that would be excluded by .hgignore::
2110
2112
2111 hg forget "set:hgignore()"
2113 hg forget "set:hgignore()"
2112
2114
2113 Returns 0 on success.
2115 Returns 0 on success.
2114 """
2116 """
2115
2117
2116 opts = pycompat.byteskwargs(opts)
2118 opts = pycompat.byteskwargs(opts)
2117 if not pats:
2119 if not pats:
2118 raise error.Abort(_('no files specified'))
2120 raise error.Abort(_('no files specified'))
2119
2121
2120 m = scmutil.match(repo[None], pats, opts)
2122 m = scmutil.match(repo[None], pats, opts)
2121 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2123 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2122 return rejected and 1 or 0
2124 return rejected and 1 or 0
2123
2125
2124 @command(
2126 @command(
2125 'graft',
2127 'graft',
2126 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2128 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2127 ('c', 'continue', False, _('resume interrupted graft')),
2129 ('c', 'continue', False, _('resume interrupted graft')),
2128 ('e', 'edit', False, _('invoke editor on commit messages')),
2130 ('e', 'edit', False, _('invoke editor on commit messages')),
2129 ('', 'log', None, _('append graft info to log message')),
2131 ('', 'log', None, _('append graft info to log message')),
2130 ('f', 'force', False, _('force graft')),
2132 ('f', 'force', False, _('force graft')),
2131 ('D', 'currentdate', False,
2133 ('D', 'currentdate', False,
2132 _('record the current date as commit date')),
2134 _('record the current date as commit date')),
2133 ('U', 'currentuser', False,
2135 ('U', 'currentuser', False,
2134 _('record the current user as committer'), _('DATE'))]
2136 _('record the current user as committer'), _('DATE'))]
2135 + commitopts2 + mergetoolopts + dryrunopts,
2137 + commitopts2 + mergetoolopts + dryrunopts,
2136 _('[OPTION]... [-r REV]... REV...'))
2138 _('[OPTION]... [-r REV]... REV...'))
2137 def graft(ui, repo, *revs, **opts):
2139 def graft(ui, repo, *revs, **opts):
2138 '''copy changes from other branches onto the current branch
2140 '''copy changes from other branches onto the current branch
2139
2141
2140 This command uses Mercurial's merge logic to copy individual
2142 This command uses Mercurial's merge logic to copy individual
2141 changes from other branches without merging branches in the
2143 changes from other branches without merging branches in the
2142 history graph. This is sometimes known as 'backporting' or
2144 history graph. This is sometimes known as 'backporting' or
2143 'cherry-picking'. By default, graft will copy user, date, and
2145 'cherry-picking'. By default, graft will copy user, date, and
2144 description from the source changesets.
2146 description from the source changesets.
2145
2147
2146 Changesets that are ancestors of the current revision, that have
2148 Changesets that are ancestors of the current revision, that have
2147 already been grafted, or that are merges will be skipped.
2149 already been grafted, or that are merges will be skipped.
2148
2150
2149 If --log is specified, log messages will have a comment appended
2151 If --log is specified, log messages will have a comment appended
2150 of the form::
2152 of the form::
2151
2153
2152 (grafted from CHANGESETHASH)
2154 (grafted from CHANGESETHASH)
2153
2155
2154 If --force is specified, revisions will be grafted even if they
2156 If --force is specified, revisions will be grafted even if they
2155 are already ancestors of or have been grafted to the destination.
2157 are already ancestors of or have been grafted to the destination.
2156 This is useful when the revisions have since been backed out.
2158 This is useful when the revisions have since been backed out.
2157
2159
2158 If a graft merge results in conflicts, the graft process is
2160 If a graft merge results in conflicts, the graft process is
2159 interrupted so that the current merge can be manually resolved.
2161 interrupted so that the current merge can be manually resolved.
2160 Once all conflicts are addressed, the graft process can be
2162 Once all conflicts are addressed, the graft process can be
2161 continued with the -c/--continue option.
2163 continued with the -c/--continue option.
2162
2164
2163 .. note::
2165 .. note::
2164
2166
2165 The -c/--continue option does not reapply earlier options, except
2167 The -c/--continue option does not reapply earlier options, except
2166 for --force.
2168 for --force.
2167
2169
2168 .. container:: verbose
2170 .. container:: verbose
2169
2171
2170 Examples:
2172 Examples:
2171
2173
2172 - copy a single change to the stable branch and edit its description::
2174 - copy a single change to the stable branch and edit its description::
2173
2175
2174 hg update stable
2176 hg update stable
2175 hg graft --edit 9393
2177 hg graft --edit 9393
2176
2178
2177 - graft a range of changesets with one exception, updating dates::
2179 - graft a range of changesets with one exception, updating dates::
2178
2180
2179 hg graft -D "2085::2093 and not 2091"
2181 hg graft -D "2085::2093 and not 2091"
2180
2182
2181 - continue a graft after resolving conflicts::
2183 - continue a graft after resolving conflicts::
2182
2184
2183 hg graft -c
2185 hg graft -c
2184
2186
2185 - show the source of a grafted changeset::
2187 - show the source of a grafted changeset::
2186
2188
2187 hg log --debug -r .
2189 hg log --debug -r .
2188
2190
2189 - show revisions sorted by date::
2191 - show revisions sorted by date::
2190
2192
2191 hg log -r "sort(all(), date)"
2193 hg log -r "sort(all(), date)"
2192
2194
2193 See :hg:`help revisions` for more about specifying revisions.
2195 See :hg:`help revisions` for more about specifying revisions.
2194
2196
2195 Returns 0 on successful completion.
2197 Returns 0 on successful completion.
2196 '''
2198 '''
2197 with repo.wlock():
2199 with repo.wlock():
2198 return _dograft(ui, repo, *revs, **opts)
2200 return _dograft(ui, repo, *revs, **opts)
2199
2201
2200 def _dograft(ui, repo, *revs, **opts):
2202 def _dograft(ui, repo, *revs, **opts):
2201 opts = pycompat.byteskwargs(opts)
2203 opts = pycompat.byteskwargs(opts)
2202 if revs and opts.get('rev'):
2204 if revs and opts.get('rev'):
2203 ui.warn(_('warning: inconsistent use of --rev might give unexpected '
2205 ui.warn(_('warning: inconsistent use of --rev might give unexpected '
2204 'revision ordering!\n'))
2206 'revision ordering!\n'))
2205
2207
2206 revs = list(revs)
2208 revs = list(revs)
2207 revs.extend(opts.get('rev'))
2209 revs.extend(opts.get('rev'))
2208
2210
2209 if not opts.get('user') and opts.get('currentuser'):
2211 if not opts.get('user') and opts.get('currentuser'):
2210 opts['user'] = ui.username()
2212 opts['user'] = ui.username()
2211 if not opts.get('date') and opts.get('currentdate'):
2213 if not opts.get('date') and opts.get('currentdate'):
2212 opts['date'] = "%d %d" % util.makedate()
2214 opts['date'] = "%d %d" % util.makedate()
2213
2215
2214 editor = cmdutil.getcommiteditor(editform='graft',
2216 editor = cmdutil.getcommiteditor(editform='graft',
2215 **pycompat.strkwargs(opts))
2217 **pycompat.strkwargs(opts))
2216
2218
2217 cont = False
2219 cont = False
2218 if opts.get('continue'):
2220 if opts.get('continue'):
2219 cont = True
2221 cont = True
2220 if revs:
2222 if revs:
2221 raise error.Abort(_("can't specify --continue and revisions"))
2223 raise error.Abort(_("can't specify --continue and revisions"))
2222 # read in unfinished revisions
2224 # read in unfinished revisions
2223 try:
2225 try:
2224 nodes = repo.vfs.read('graftstate').splitlines()
2226 nodes = repo.vfs.read('graftstate').splitlines()
2225 revs = [repo[node].rev() for node in nodes]
2227 revs = [repo[node].rev() for node in nodes]
2226 except IOError as inst:
2228 except IOError as inst:
2227 if inst.errno != errno.ENOENT:
2229 if inst.errno != errno.ENOENT:
2228 raise
2230 raise
2229 cmdutil.wrongtooltocontinue(repo, _('graft'))
2231 cmdutil.wrongtooltocontinue(repo, _('graft'))
2230 else:
2232 else:
2231 cmdutil.checkunfinished(repo)
2233 cmdutil.checkunfinished(repo)
2232 cmdutil.bailifchanged(repo)
2234 cmdutil.bailifchanged(repo)
2233 if not revs:
2235 if not revs:
2234 raise error.Abort(_('no revisions specified'))
2236 raise error.Abort(_('no revisions specified'))
2235 revs = scmutil.revrange(repo, revs)
2237 revs = scmutil.revrange(repo, revs)
2236
2238
2237 skipped = set()
2239 skipped = set()
2238 # check for merges
2240 # check for merges
2239 for rev in repo.revs('%ld and merge()', revs):
2241 for rev in repo.revs('%ld and merge()', revs):
2240 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
2242 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
2241 skipped.add(rev)
2243 skipped.add(rev)
2242 revs = [r for r in revs if r not in skipped]
2244 revs = [r for r in revs if r not in skipped]
2243 if not revs:
2245 if not revs:
2244 return -1
2246 return -1
2245
2247
2246 # Don't check in the --continue case, in effect retaining --force across
2248 # Don't check in the --continue case, in effect retaining --force across
2247 # --continues. That's because without --force, any revisions we decided to
2249 # --continues. That's because without --force, any revisions we decided to
2248 # skip would have been filtered out here, so they wouldn't have made their
2250 # skip would have been filtered out here, so they wouldn't have made their
2249 # way to the graftstate. With --force, any revisions we would have otherwise
2251 # way to the graftstate. With --force, any revisions we would have otherwise
2250 # skipped would not have been filtered out, and if they hadn't been applied
2252 # skipped would not have been filtered out, and if they hadn't been applied
2251 # already, they'd have been in the graftstate.
2253 # already, they'd have been in the graftstate.
2252 if not (cont or opts.get('force')):
2254 if not (cont or opts.get('force')):
2253 # check for ancestors of dest branch
2255 # check for ancestors of dest branch
2254 crev = repo['.'].rev()
2256 crev = repo['.'].rev()
2255 ancestors = repo.changelog.ancestors([crev], inclusive=True)
2257 ancestors = repo.changelog.ancestors([crev], inclusive=True)
2256 # XXX make this lazy in the future
2258 # XXX make this lazy in the future
2257 # don't mutate while iterating, create a copy
2259 # don't mutate while iterating, create a copy
2258 for rev in list(revs):
2260 for rev in list(revs):
2259 if rev in ancestors:
2261 if rev in ancestors:
2260 ui.warn(_('skipping ancestor revision %d:%s\n') %
2262 ui.warn(_('skipping ancestor revision %d:%s\n') %
2261 (rev, repo[rev]))
2263 (rev, repo[rev]))
2262 # XXX remove on list is slow
2264 # XXX remove on list is slow
2263 revs.remove(rev)
2265 revs.remove(rev)
2264 if not revs:
2266 if not revs:
2265 return -1
2267 return -1
2266
2268
2267 # analyze revs for earlier grafts
2269 # analyze revs for earlier grafts
2268 ids = {}
2270 ids = {}
2269 for ctx in repo.set("%ld", revs):
2271 for ctx in repo.set("%ld", revs):
2270 ids[ctx.hex()] = ctx.rev()
2272 ids[ctx.hex()] = ctx.rev()
2271 n = ctx.extra().get('source')
2273 n = ctx.extra().get('source')
2272 if n:
2274 if n:
2273 ids[n] = ctx.rev()
2275 ids[n] = ctx.rev()
2274
2276
2275 # check ancestors for earlier grafts
2277 # check ancestors for earlier grafts
2276 ui.debug('scanning for duplicate grafts\n')
2278 ui.debug('scanning for duplicate grafts\n')
2277
2279
2278 # The only changesets we can be sure doesn't contain grafts of any
2280 # The only changesets we can be sure doesn't contain grafts of any
2279 # revs, are the ones that are common ancestors of *all* revs:
2281 # revs, are the ones that are common ancestors of *all* revs:
2280 for rev in repo.revs('only(%d,ancestor(%ld))', crev, revs):
2282 for rev in repo.revs('only(%d,ancestor(%ld))', crev, revs):
2281 ctx = repo[rev]
2283 ctx = repo[rev]
2282 n = ctx.extra().get('source')
2284 n = ctx.extra().get('source')
2283 if n in ids:
2285 if n in ids:
2284 try:
2286 try:
2285 r = repo[n].rev()
2287 r = repo[n].rev()
2286 except error.RepoLookupError:
2288 except error.RepoLookupError:
2287 r = None
2289 r = None
2288 if r in revs:
2290 if r in revs:
2289 ui.warn(_('skipping revision %d:%s '
2291 ui.warn(_('skipping revision %d:%s '
2290 '(already grafted to %d:%s)\n')
2292 '(already grafted to %d:%s)\n')
2291 % (r, repo[r], rev, ctx))
2293 % (r, repo[r], rev, ctx))
2292 revs.remove(r)
2294 revs.remove(r)
2293 elif ids[n] in revs:
2295 elif ids[n] in revs:
2294 if r is None:
2296 if r is None:
2295 ui.warn(_('skipping already grafted revision %d:%s '
2297 ui.warn(_('skipping already grafted revision %d:%s '
2296 '(%d:%s also has unknown origin %s)\n')
2298 '(%d:%s also has unknown origin %s)\n')
2297 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
2299 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
2298 else:
2300 else:
2299 ui.warn(_('skipping already grafted revision %d:%s '
2301 ui.warn(_('skipping already grafted revision %d:%s '
2300 '(%d:%s also has origin %d:%s)\n')
2302 '(%d:%s also has origin %d:%s)\n')
2301 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
2303 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
2302 revs.remove(ids[n])
2304 revs.remove(ids[n])
2303 elif ctx.hex() in ids:
2305 elif ctx.hex() in ids:
2304 r = ids[ctx.hex()]
2306 r = ids[ctx.hex()]
2305 ui.warn(_('skipping already grafted revision %d:%s '
2307 ui.warn(_('skipping already grafted revision %d:%s '
2306 '(was grafted from %d:%s)\n') %
2308 '(was grafted from %d:%s)\n') %
2307 (r, repo[r], rev, ctx))
2309 (r, repo[r], rev, ctx))
2308 revs.remove(r)
2310 revs.remove(r)
2309 if not revs:
2311 if not revs:
2310 return -1
2312 return -1
2311
2313
2312 for pos, ctx in enumerate(repo.set("%ld", revs)):
2314 for pos, ctx in enumerate(repo.set("%ld", revs)):
2313 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
2315 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
2314 ctx.description().split('\n', 1)[0])
2316 ctx.description().split('\n', 1)[0])
2315 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
2317 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
2316 if names:
2318 if names:
2317 desc += ' (%s)' % ' '.join(names)
2319 desc += ' (%s)' % ' '.join(names)
2318 ui.status(_('grafting %s\n') % desc)
2320 ui.status(_('grafting %s\n') % desc)
2319 if opts.get('dry_run'):
2321 if opts.get('dry_run'):
2320 continue
2322 continue
2321
2323
2322 source = ctx.extra().get('source')
2324 source = ctx.extra().get('source')
2323 extra = {}
2325 extra = {}
2324 if source:
2326 if source:
2325 extra['source'] = source
2327 extra['source'] = source
2326 extra['intermediate-source'] = ctx.hex()
2328 extra['intermediate-source'] = ctx.hex()
2327 else:
2329 else:
2328 extra['source'] = ctx.hex()
2330 extra['source'] = ctx.hex()
2329 user = ctx.user()
2331 user = ctx.user()
2330 if opts.get('user'):
2332 if opts.get('user'):
2331 user = opts['user']
2333 user = opts['user']
2332 date = ctx.date()
2334 date = ctx.date()
2333 if opts.get('date'):
2335 if opts.get('date'):
2334 date = opts['date']
2336 date = opts['date']
2335 message = ctx.description()
2337 message = ctx.description()
2336 if opts.get('log'):
2338 if opts.get('log'):
2337 message += '\n(grafted from %s)' % ctx.hex()
2339 message += '\n(grafted from %s)' % ctx.hex()
2338
2340
2339 # we don't merge the first commit when continuing
2341 # we don't merge the first commit when continuing
2340 if not cont:
2342 if not cont:
2341 # perform the graft merge with p1(rev) as 'ancestor'
2343 # perform the graft merge with p1(rev) as 'ancestor'
2342 try:
2344 try:
2343 # ui.forcemerge is an internal variable, do not document
2345 # ui.forcemerge is an internal variable, do not document
2344 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
2346 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
2345 'graft')
2347 'graft')
2346 stats = mergemod.graft(repo, ctx, ctx.p1(),
2348 stats = mergemod.graft(repo, ctx, ctx.p1(),
2347 ['local', 'graft'])
2349 ['local', 'graft'])
2348 finally:
2350 finally:
2349 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
2351 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
2350 # report any conflicts
2352 # report any conflicts
2351 if stats and stats[3] > 0:
2353 if stats and stats[3] > 0:
2352 # write out state for --continue
2354 # write out state for --continue
2353 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2355 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2354 repo.vfs.write('graftstate', ''.join(nodelines))
2356 repo.vfs.write('graftstate', ''.join(nodelines))
2355 extra = ''
2357 extra = ''
2356 if opts.get('user'):
2358 if opts.get('user'):
2357 extra += ' --user %s' % util.shellquote(opts['user'])
2359 extra += ' --user %s' % util.shellquote(opts['user'])
2358 if opts.get('date'):
2360 if opts.get('date'):
2359 extra += ' --date %s' % util.shellquote(opts['date'])
2361 extra += ' --date %s' % util.shellquote(opts['date'])
2360 if opts.get('log'):
2362 if opts.get('log'):
2361 extra += ' --log'
2363 extra += ' --log'
2362 hint=_("use 'hg resolve' and 'hg graft --continue%s'") % extra
2364 hint=_("use 'hg resolve' and 'hg graft --continue%s'") % extra
2363 raise error.Abort(
2365 raise error.Abort(
2364 _("unresolved conflicts, can't continue"),
2366 _("unresolved conflicts, can't continue"),
2365 hint=hint)
2367 hint=hint)
2366 else:
2368 else:
2367 cont = False
2369 cont = False
2368
2370
2369 # commit
2371 # commit
2370 node = repo.commit(text=message, user=user,
2372 node = repo.commit(text=message, user=user,
2371 date=date, extra=extra, editor=editor)
2373 date=date, extra=extra, editor=editor)
2372 if node is None:
2374 if node is None:
2373 ui.warn(
2375 ui.warn(
2374 _('note: graft of %d:%s created no changes to commit\n') %
2376 _('note: graft of %d:%s created no changes to commit\n') %
2375 (ctx.rev(), ctx))
2377 (ctx.rev(), ctx))
2376
2378
2377 # remove state when we complete successfully
2379 # remove state when we complete successfully
2378 if not opts.get('dry_run'):
2380 if not opts.get('dry_run'):
2379 repo.vfs.unlinkpath('graftstate', ignoremissing=True)
2381 repo.vfs.unlinkpath('graftstate', ignoremissing=True)
2380
2382
2381 return 0
2383 return 0
2382
2384
2383 @command('grep',
2385 @command('grep',
2384 [('0', 'print0', None, _('end fields with NUL')),
2386 [('0', 'print0', None, _('end fields with NUL')),
2385 ('', 'all', None, _('print all revisions that match')),
2387 ('', 'all', None, _('print all revisions that match')),
2386 ('a', 'text', None, _('treat all files as text')),
2388 ('a', 'text', None, _('treat all files as text')),
2387 ('f', 'follow', None,
2389 ('f', 'follow', None,
2388 _('follow changeset history,'
2390 _('follow changeset history,'
2389 ' or file history across copies and renames')),
2391 ' or file history across copies and renames')),
2390 ('i', 'ignore-case', None, _('ignore case when matching')),
2392 ('i', 'ignore-case', None, _('ignore case when matching')),
2391 ('l', 'files-with-matches', None,
2393 ('l', 'files-with-matches', None,
2392 _('print only filenames and revisions that match')),
2394 _('print only filenames and revisions that match')),
2393 ('n', 'line-number', None, _('print matching line numbers')),
2395 ('n', 'line-number', None, _('print matching line numbers')),
2394 ('r', 'rev', [],
2396 ('r', 'rev', [],
2395 _('only search files changed within revision range'), _('REV')),
2397 _('only search files changed within revision range'), _('REV')),
2396 ('u', 'user', None, _('list the author (long with -v)')),
2398 ('u', 'user', None, _('list the author (long with -v)')),
2397 ('d', 'date', None, _('list the date (short with -q)')),
2399 ('d', 'date', None, _('list the date (short with -q)')),
2398 ] + formatteropts + walkopts,
2400 ] + formatteropts + walkopts,
2399 _('[OPTION]... PATTERN [FILE]...'),
2401 _('[OPTION]... PATTERN [FILE]...'),
2400 inferrepo=True)
2402 inferrepo=True)
2401 def grep(ui, repo, pattern, *pats, **opts):
2403 def grep(ui, repo, pattern, *pats, **opts):
2402 """search revision history for a pattern in specified files
2404 """search revision history for a pattern in specified files
2403
2405
2404 Search revision history for a regular expression in the specified
2406 Search revision history for a regular expression in the specified
2405 files or the entire project.
2407 files or the entire project.
2406
2408
2407 By default, grep prints the most recent revision number for each
2409 By default, grep prints the most recent revision number for each
2408 file in which it finds a match. To get it to print every revision
2410 file in which it finds a match. To get it to print every revision
2409 that contains a change in match status ("-" for a match that becomes
2411 that contains a change in match status ("-" for a match that becomes
2410 a non-match, or "+" for a non-match that becomes a match), use the
2412 a non-match, or "+" for a non-match that becomes a match), use the
2411 --all flag.
2413 --all flag.
2412
2414
2413 PATTERN can be any Python (roughly Perl-compatible) regular
2415 PATTERN can be any Python (roughly Perl-compatible) regular
2414 expression.
2416 expression.
2415
2417
2416 If no FILEs are specified (and -f/--follow isn't set), all files in
2418 If no FILEs are specified (and -f/--follow isn't set), all files in
2417 the repository are searched, including those that don't exist in the
2419 the repository are searched, including those that don't exist in the
2418 current branch or have been deleted in a prior changeset.
2420 current branch or have been deleted in a prior changeset.
2419
2421
2420 Returns 0 if a match is found, 1 otherwise.
2422 Returns 0 if a match is found, 1 otherwise.
2421 """
2423 """
2422 opts = pycompat.byteskwargs(opts)
2424 opts = pycompat.byteskwargs(opts)
2423 reflags = re.M
2425 reflags = re.M
2424 if opts.get('ignore_case'):
2426 if opts.get('ignore_case'):
2425 reflags |= re.I
2427 reflags |= re.I
2426 try:
2428 try:
2427 regexp = util.re.compile(pattern, reflags)
2429 regexp = util.re.compile(pattern, reflags)
2428 except re.error as inst:
2430 except re.error as inst:
2429 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2431 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2430 return 1
2432 return 1
2431 sep, eol = ':', '\n'
2433 sep, eol = ':', '\n'
2432 if opts.get('print0'):
2434 if opts.get('print0'):
2433 sep = eol = '\0'
2435 sep = eol = '\0'
2434
2436
2435 getfile = util.lrucachefunc(repo.file)
2437 getfile = util.lrucachefunc(repo.file)
2436
2438
2437 def matchlines(body):
2439 def matchlines(body):
2438 begin = 0
2440 begin = 0
2439 linenum = 0
2441 linenum = 0
2440 while begin < len(body):
2442 while begin < len(body):
2441 match = regexp.search(body, begin)
2443 match = regexp.search(body, begin)
2442 if not match:
2444 if not match:
2443 break
2445 break
2444 mstart, mend = match.span()
2446 mstart, mend = match.span()
2445 linenum += body.count('\n', begin, mstart) + 1
2447 linenum += body.count('\n', begin, mstart) + 1
2446 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2448 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2447 begin = body.find('\n', mend) + 1 or len(body) + 1
2449 begin = body.find('\n', mend) + 1 or len(body) + 1
2448 lend = begin - 1
2450 lend = begin - 1
2449 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2451 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2450
2452
2451 class linestate(object):
2453 class linestate(object):
2452 def __init__(self, line, linenum, colstart, colend):
2454 def __init__(self, line, linenum, colstart, colend):
2453 self.line = line
2455 self.line = line
2454 self.linenum = linenum
2456 self.linenum = linenum
2455 self.colstart = colstart
2457 self.colstart = colstart
2456 self.colend = colend
2458 self.colend = colend
2457
2459
2458 def __hash__(self):
2460 def __hash__(self):
2459 return hash((self.linenum, self.line))
2461 return hash((self.linenum, self.line))
2460
2462
2461 def __eq__(self, other):
2463 def __eq__(self, other):
2462 return self.line == other.line
2464 return self.line == other.line
2463
2465
2464 def findpos(self):
2466 def findpos(self):
2465 """Iterate all (start, end) indices of matches"""
2467 """Iterate all (start, end) indices of matches"""
2466 yield self.colstart, self.colend
2468 yield self.colstart, self.colend
2467 p = self.colend
2469 p = self.colend
2468 while p < len(self.line):
2470 while p < len(self.line):
2469 m = regexp.search(self.line, p)
2471 m = regexp.search(self.line, p)
2470 if not m:
2472 if not m:
2471 break
2473 break
2472 yield m.span()
2474 yield m.span()
2473 p = m.end()
2475 p = m.end()
2474
2476
2475 matches = {}
2477 matches = {}
2476 copies = {}
2478 copies = {}
2477 def grepbody(fn, rev, body):
2479 def grepbody(fn, rev, body):
2478 matches[rev].setdefault(fn, [])
2480 matches[rev].setdefault(fn, [])
2479 m = matches[rev][fn]
2481 m = matches[rev][fn]
2480 for lnum, cstart, cend, line in matchlines(body):
2482 for lnum, cstart, cend, line in matchlines(body):
2481 s = linestate(line, lnum, cstart, cend)
2483 s = linestate(line, lnum, cstart, cend)
2482 m.append(s)
2484 m.append(s)
2483
2485
2484 def difflinestates(a, b):
2486 def difflinestates(a, b):
2485 sm = difflib.SequenceMatcher(None, a, b)
2487 sm = difflib.SequenceMatcher(None, a, b)
2486 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2488 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2487 if tag == 'insert':
2489 if tag == 'insert':
2488 for i in xrange(blo, bhi):
2490 for i in xrange(blo, bhi):
2489 yield ('+', b[i])
2491 yield ('+', b[i])
2490 elif tag == 'delete':
2492 elif tag == 'delete':
2491 for i in xrange(alo, ahi):
2493 for i in xrange(alo, ahi):
2492 yield ('-', a[i])
2494 yield ('-', a[i])
2493 elif tag == 'replace':
2495 elif tag == 'replace':
2494 for i in xrange(alo, ahi):
2496 for i in xrange(alo, ahi):
2495 yield ('-', a[i])
2497 yield ('-', a[i])
2496 for i in xrange(blo, bhi):
2498 for i in xrange(blo, bhi):
2497 yield ('+', b[i])
2499 yield ('+', b[i])
2498
2500
2499 def display(fm, fn, ctx, pstates, states):
2501 def display(fm, fn, ctx, pstates, states):
2500 rev = ctx.rev()
2502 rev = ctx.rev()
2501 if fm.isplain():
2503 if fm.isplain():
2502 formatuser = ui.shortuser
2504 formatuser = ui.shortuser
2503 else:
2505 else:
2504 formatuser = str
2506 formatuser = str
2505 if ui.quiet:
2507 if ui.quiet:
2506 datefmt = '%Y-%m-%d'
2508 datefmt = '%Y-%m-%d'
2507 else:
2509 else:
2508 datefmt = '%a %b %d %H:%M:%S %Y %1%2'
2510 datefmt = '%a %b %d %H:%M:%S %Y %1%2'
2509 found = False
2511 found = False
2510 @util.cachefunc
2512 @util.cachefunc
2511 def binary():
2513 def binary():
2512 flog = getfile(fn)
2514 flog = getfile(fn)
2513 return util.binary(flog.read(ctx.filenode(fn)))
2515 return util.binary(flog.read(ctx.filenode(fn)))
2514
2516
2515 fieldnamemap = {'filename': 'file', 'linenumber': 'line_number'}
2517 fieldnamemap = {'filename': 'file', 'linenumber': 'line_number'}
2516 if opts.get('all'):
2518 if opts.get('all'):
2517 iter = difflinestates(pstates, states)
2519 iter = difflinestates(pstates, states)
2518 else:
2520 else:
2519 iter = [('', l) for l in states]
2521 iter = [('', l) for l in states]
2520 for change, l in iter:
2522 for change, l in iter:
2521 fm.startitem()
2523 fm.startitem()
2522 fm.data(node=fm.hexfunc(ctx.node()))
2524 fm.data(node=fm.hexfunc(ctx.node()))
2523 cols = [
2525 cols = [
2524 ('filename', fn, True),
2526 ('filename', fn, True),
2525 ('rev', rev, True),
2527 ('rev', rev, True),
2526 ('linenumber', l.linenum, opts.get('line_number')),
2528 ('linenumber', l.linenum, opts.get('line_number')),
2527 ]
2529 ]
2528 if opts.get('all'):
2530 if opts.get('all'):
2529 cols.append(('change', change, True))
2531 cols.append(('change', change, True))
2530 cols.extend([
2532 cols.extend([
2531 ('user', formatuser(ctx.user()), opts.get('user')),
2533 ('user', formatuser(ctx.user()), opts.get('user')),
2532 ('date', fm.formatdate(ctx.date(), datefmt), opts.get('date')),
2534 ('date', fm.formatdate(ctx.date(), datefmt), opts.get('date')),
2533 ])
2535 ])
2534 lastcol = next(name for name, data, cond in reversed(cols) if cond)
2536 lastcol = next(name for name, data, cond in reversed(cols) if cond)
2535 for name, data, cond in cols:
2537 for name, data, cond in cols:
2536 field = fieldnamemap.get(name, name)
2538 field = fieldnamemap.get(name, name)
2537 fm.condwrite(cond, field, '%s', data, label='grep.%s' % name)
2539 fm.condwrite(cond, field, '%s', data, label='grep.%s' % name)
2538 if cond and name != lastcol:
2540 if cond and name != lastcol:
2539 fm.plain(sep, label='grep.sep')
2541 fm.plain(sep, label='grep.sep')
2540 if not opts.get('files_with_matches'):
2542 if not opts.get('files_with_matches'):
2541 fm.plain(sep, label='grep.sep')
2543 fm.plain(sep, label='grep.sep')
2542 if not opts.get('text') and binary():
2544 if not opts.get('text') and binary():
2543 fm.plain(_(" Binary file matches"))
2545 fm.plain(_(" Binary file matches"))
2544 else:
2546 else:
2545 displaymatches(fm.nested('texts'), l)
2547 displaymatches(fm.nested('texts'), l)
2546 fm.plain(eol)
2548 fm.plain(eol)
2547 found = True
2549 found = True
2548 if opts.get('files_with_matches'):
2550 if opts.get('files_with_matches'):
2549 break
2551 break
2550 return found
2552 return found
2551
2553
2552 def displaymatches(fm, l):
2554 def displaymatches(fm, l):
2553 p = 0
2555 p = 0
2554 for s, e in l.findpos():
2556 for s, e in l.findpos():
2555 if p < s:
2557 if p < s:
2556 fm.startitem()
2558 fm.startitem()
2557 fm.write('text', '%s', l.line[p:s])
2559 fm.write('text', '%s', l.line[p:s])
2558 fm.data(matched=False)
2560 fm.data(matched=False)
2559 fm.startitem()
2561 fm.startitem()
2560 fm.write('text', '%s', l.line[s:e], label='grep.match')
2562 fm.write('text', '%s', l.line[s:e], label='grep.match')
2561 fm.data(matched=True)
2563 fm.data(matched=True)
2562 p = e
2564 p = e
2563 if p < len(l.line):
2565 if p < len(l.line):
2564 fm.startitem()
2566 fm.startitem()
2565 fm.write('text', '%s', l.line[p:])
2567 fm.write('text', '%s', l.line[p:])
2566 fm.data(matched=False)
2568 fm.data(matched=False)
2567 fm.end()
2569 fm.end()
2568
2570
2569 skip = {}
2571 skip = {}
2570 revfiles = {}
2572 revfiles = {}
2571 matchfn = scmutil.match(repo[None], pats, opts)
2573 matchfn = scmutil.match(repo[None], pats, opts)
2572 found = False
2574 found = False
2573 follow = opts.get('follow')
2575 follow = opts.get('follow')
2574
2576
2575 def prep(ctx, fns):
2577 def prep(ctx, fns):
2576 rev = ctx.rev()
2578 rev = ctx.rev()
2577 pctx = ctx.p1()
2579 pctx = ctx.p1()
2578 parent = pctx.rev()
2580 parent = pctx.rev()
2579 matches.setdefault(rev, {})
2581 matches.setdefault(rev, {})
2580 matches.setdefault(parent, {})
2582 matches.setdefault(parent, {})
2581 files = revfiles.setdefault(rev, [])
2583 files = revfiles.setdefault(rev, [])
2582 for fn in fns:
2584 for fn in fns:
2583 flog = getfile(fn)
2585 flog = getfile(fn)
2584 try:
2586 try:
2585 fnode = ctx.filenode(fn)
2587 fnode = ctx.filenode(fn)
2586 except error.LookupError:
2588 except error.LookupError:
2587 continue
2589 continue
2588
2590
2589 copied = flog.renamed(fnode)
2591 copied = flog.renamed(fnode)
2590 copy = follow and copied and copied[0]
2592 copy = follow and copied and copied[0]
2591 if copy:
2593 if copy:
2592 copies.setdefault(rev, {})[fn] = copy
2594 copies.setdefault(rev, {})[fn] = copy
2593 if fn in skip:
2595 if fn in skip:
2594 if copy:
2596 if copy:
2595 skip[copy] = True
2597 skip[copy] = True
2596 continue
2598 continue
2597 files.append(fn)
2599 files.append(fn)
2598
2600
2599 if fn not in matches[rev]:
2601 if fn not in matches[rev]:
2600 grepbody(fn, rev, flog.read(fnode))
2602 grepbody(fn, rev, flog.read(fnode))
2601
2603
2602 pfn = copy or fn
2604 pfn = copy or fn
2603 if pfn not in matches[parent]:
2605 if pfn not in matches[parent]:
2604 try:
2606 try:
2605 fnode = pctx.filenode(pfn)
2607 fnode = pctx.filenode(pfn)
2606 grepbody(pfn, parent, flog.read(fnode))
2608 grepbody(pfn, parent, flog.read(fnode))
2607 except error.LookupError:
2609 except error.LookupError:
2608 pass
2610 pass
2609
2611
2610 ui.pager('grep')
2612 ui.pager('grep')
2611 fm = ui.formatter('grep', opts)
2613 fm = ui.formatter('grep', opts)
2612 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2614 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2613 rev = ctx.rev()
2615 rev = ctx.rev()
2614 parent = ctx.p1().rev()
2616 parent = ctx.p1().rev()
2615 for fn in sorted(revfiles.get(rev, [])):
2617 for fn in sorted(revfiles.get(rev, [])):
2616 states = matches[rev][fn]
2618 states = matches[rev][fn]
2617 copy = copies.get(rev, {}).get(fn)
2619 copy = copies.get(rev, {}).get(fn)
2618 if fn in skip:
2620 if fn in skip:
2619 if copy:
2621 if copy:
2620 skip[copy] = True
2622 skip[copy] = True
2621 continue
2623 continue
2622 pstates = matches.get(parent, {}).get(copy or fn, [])
2624 pstates = matches.get(parent, {}).get(copy or fn, [])
2623 if pstates or states:
2625 if pstates or states:
2624 r = display(fm, fn, ctx, pstates, states)
2626 r = display(fm, fn, ctx, pstates, states)
2625 found = found or r
2627 found = found or r
2626 if r and not opts.get('all'):
2628 if r and not opts.get('all'):
2627 skip[fn] = True
2629 skip[fn] = True
2628 if copy:
2630 if copy:
2629 skip[copy] = True
2631 skip[copy] = True
2630 del matches[rev]
2632 del matches[rev]
2631 del revfiles[rev]
2633 del revfiles[rev]
2632 fm.end()
2634 fm.end()
2633
2635
2634 return not found
2636 return not found
2635
2637
2636 @command('heads',
2638 @command('heads',
2637 [('r', 'rev', '',
2639 [('r', 'rev', '',
2638 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2640 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2639 ('t', 'topo', False, _('show topological heads only')),
2641 ('t', 'topo', False, _('show topological heads only')),
2640 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2642 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2641 ('c', 'closed', False, _('show normal and closed branch heads')),
2643 ('c', 'closed', False, _('show normal and closed branch heads')),
2642 ] + templateopts,
2644 ] + templateopts,
2643 _('[-ct] [-r STARTREV] [REV]...'))
2645 _('[-ct] [-r STARTREV] [REV]...'))
2644 def heads(ui, repo, *branchrevs, **opts):
2646 def heads(ui, repo, *branchrevs, **opts):
2645 """show branch heads
2647 """show branch heads
2646
2648
2647 With no arguments, show all open branch heads in the repository.
2649 With no arguments, show all open branch heads in the repository.
2648 Branch heads are changesets that have no descendants on the
2650 Branch heads are changesets that have no descendants on the
2649 same branch. They are where development generally takes place and
2651 same branch. They are where development generally takes place and
2650 are the usual targets for update and merge operations.
2652 are the usual targets for update and merge operations.
2651
2653
2652 If one or more REVs are given, only open branch heads on the
2654 If one or more REVs are given, only open branch heads on the
2653 branches associated with the specified changesets are shown. This
2655 branches associated with the specified changesets are shown. This
2654 means that you can use :hg:`heads .` to see the heads on the
2656 means that you can use :hg:`heads .` to see the heads on the
2655 currently checked-out branch.
2657 currently checked-out branch.
2656
2658
2657 If -c/--closed is specified, also show branch heads marked closed
2659 If -c/--closed is specified, also show branch heads marked closed
2658 (see :hg:`commit --close-branch`).
2660 (see :hg:`commit --close-branch`).
2659
2661
2660 If STARTREV is specified, only those heads that are descendants of
2662 If STARTREV is specified, only those heads that are descendants of
2661 STARTREV will be displayed.
2663 STARTREV will be displayed.
2662
2664
2663 If -t/--topo is specified, named branch mechanics will be ignored and only
2665 If -t/--topo is specified, named branch mechanics will be ignored and only
2664 topological heads (changesets with no children) will be shown.
2666 topological heads (changesets with no children) will be shown.
2665
2667
2666 Returns 0 if matching heads are found, 1 if not.
2668 Returns 0 if matching heads are found, 1 if not.
2667 """
2669 """
2668
2670
2669 opts = pycompat.byteskwargs(opts)
2671 opts = pycompat.byteskwargs(opts)
2670 start = None
2672 start = None
2671 if 'rev' in opts:
2673 if 'rev' in opts:
2672 start = scmutil.revsingle(repo, opts['rev'], None).node()
2674 start = scmutil.revsingle(repo, opts['rev'], None).node()
2673
2675
2674 if opts.get('topo'):
2676 if opts.get('topo'):
2675 heads = [repo[h] for h in repo.heads(start)]
2677 heads = [repo[h] for h in repo.heads(start)]
2676 else:
2678 else:
2677 heads = []
2679 heads = []
2678 for branch in repo.branchmap():
2680 for branch in repo.branchmap():
2679 heads += repo.branchheads(branch, start, opts.get('closed'))
2681 heads += repo.branchheads(branch, start, opts.get('closed'))
2680 heads = [repo[h] for h in heads]
2682 heads = [repo[h] for h in heads]
2681
2683
2682 if branchrevs:
2684 if branchrevs:
2683 branches = set(repo[br].branch() for br in branchrevs)
2685 branches = set(repo[br].branch() for br in branchrevs)
2684 heads = [h for h in heads if h.branch() in branches]
2686 heads = [h for h in heads if h.branch() in branches]
2685
2687
2686 if opts.get('active') and branchrevs:
2688 if opts.get('active') and branchrevs:
2687 dagheads = repo.heads(start)
2689 dagheads = repo.heads(start)
2688 heads = [h for h in heads if h.node() in dagheads]
2690 heads = [h for h in heads if h.node() in dagheads]
2689
2691
2690 if branchrevs:
2692 if branchrevs:
2691 haveheads = set(h.branch() for h in heads)
2693 haveheads = set(h.branch() for h in heads)
2692 if branches - haveheads:
2694 if branches - haveheads:
2693 headless = ', '.join(b for b in branches - haveheads)
2695 headless = ', '.join(b for b in branches - haveheads)
2694 msg = _('no open branch heads found on branches %s')
2696 msg = _('no open branch heads found on branches %s')
2695 if opts.get('rev'):
2697 if opts.get('rev'):
2696 msg += _(' (started at %s)') % opts['rev']
2698 msg += _(' (started at %s)') % opts['rev']
2697 ui.warn((msg + '\n') % headless)
2699 ui.warn((msg + '\n') % headless)
2698
2700
2699 if not heads:
2701 if not heads:
2700 return 1
2702 return 1
2701
2703
2702 ui.pager('heads')
2704 ui.pager('heads')
2703 heads = sorted(heads, key=lambda x: -x.rev())
2705 heads = sorted(heads, key=lambda x: -x.rev())
2704 displayer = cmdutil.show_changeset(ui, repo, opts)
2706 displayer = cmdutil.show_changeset(ui, repo, opts)
2705 for ctx in heads:
2707 for ctx in heads:
2706 displayer.show(ctx)
2708 displayer.show(ctx)
2707 displayer.close()
2709 displayer.close()
2708
2710
2709 @command('help',
2711 @command('help',
2710 [('e', 'extension', None, _('show only help for extensions')),
2712 [('e', 'extension', None, _('show only help for extensions')),
2711 ('c', 'command', None, _('show only help for commands')),
2713 ('c', 'command', None, _('show only help for commands')),
2712 ('k', 'keyword', None, _('show topics matching keyword')),
2714 ('k', 'keyword', None, _('show topics matching keyword')),
2713 ('s', 'system', [], _('show help for specific platform(s)')),
2715 ('s', 'system', [], _('show help for specific platform(s)')),
2714 ],
2716 ],
2715 _('[-ecks] [TOPIC]'),
2717 _('[-ecks] [TOPIC]'),
2716 norepo=True)
2718 norepo=True)
2717 def help_(ui, name=None, **opts):
2719 def help_(ui, name=None, **opts):
2718 """show help for a given topic or a help overview
2720 """show help for a given topic or a help overview
2719
2721
2720 With no arguments, print a list of commands with short help messages.
2722 With no arguments, print a list of commands with short help messages.
2721
2723
2722 Given a topic, extension, or command name, print help for that
2724 Given a topic, extension, or command name, print help for that
2723 topic.
2725 topic.
2724
2726
2725 Returns 0 if successful.
2727 Returns 0 if successful.
2726 """
2728 """
2727
2729
2728 keep = opts.get(r'system') or []
2730 keep = opts.get(r'system') or []
2729 if len(keep) == 0:
2731 if len(keep) == 0:
2730 if pycompat.sysplatform.startswith('win'):
2732 if pycompat.sysplatform.startswith('win'):
2731 keep.append('windows')
2733 keep.append('windows')
2732 elif pycompat.sysplatform == 'OpenVMS':
2734 elif pycompat.sysplatform == 'OpenVMS':
2733 keep.append('vms')
2735 keep.append('vms')
2734 elif pycompat.sysplatform == 'plan9':
2736 elif pycompat.sysplatform == 'plan9':
2735 keep.append('plan9')
2737 keep.append('plan9')
2736 else:
2738 else:
2737 keep.append('unix')
2739 keep.append('unix')
2738 keep.append(pycompat.sysplatform.lower())
2740 keep.append(pycompat.sysplatform.lower())
2739 if ui.verbose:
2741 if ui.verbose:
2740 keep.append('verbose')
2742 keep.append('verbose')
2741
2743
2742 formatted = help.formattedhelp(ui, name, keep=keep, **opts)
2744 formatted = help.formattedhelp(ui, name, keep=keep, **opts)
2743 ui.pager('help')
2745 ui.pager('help')
2744 ui.write(formatted)
2746 ui.write(formatted)
2745
2747
2746
2748
2747 @command('identify|id',
2749 @command('identify|id',
2748 [('r', 'rev', '',
2750 [('r', 'rev', '',
2749 _('identify the specified revision'), _('REV')),
2751 _('identify the specified revision'), _('REV')),
2750 ('n', 'num', None, _('show local revision number')),
2752 ('n', 'num', None, _('show local revision number')),
2751 ('i', 'id', None, _('show global revision id')),
2753 ('i', 'id', None, _('show global revision id')),
2752 ('b', 'branch', None, _('show branch')),
2754 ('b', 'branch', None, _('show branch')),
2753 ('t', 'tags', None, _('show tags')),
2755 ('t', 'tags', None, _('show tags')),
2754 ('B', 'bookmarks', None, _('show bookmarks')),
2756 ('B', 'bookmarks', None, _('show bookmarks')),
2755 ] + remoteopts,
2757 ] + remoteopts,
2756 _('[-nibtB] [-r REV] [SOURCE]'),
2758 _('[-nibtB] [-r REV] [SOURCE]'),
2757 optionalrepo=True)
2759 optionalrepo=True)
2758 def identify(ui, repo, source=None, rev=None,
2760 def identify(ui, repo, source=None, rev=None,
2759 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
2761 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
2760 """identify the working directory or specified revision
2762 """identify the working directory or specified revision
2761
2763
2762 Print a summary identifying the repository state at REV using one or
2764 Print a summary identifying the repository state at REV using one or
2763 two parent hash identifiers, followed by a "+" if the working
2765 two parent hash identifiers, followed by a "+" if the working
2764 directory has uncommitted changes, the branch name (if not default),
2766 directory has uncommitted changes, the branch name (if not default),
2765 a list of tags, and a list of bookmarks.
2767 a list of tags, and a list of bookmarks.
2766
2768
2767 When REV is not given, print a summary of the current state of the
2769 When REV is not given, print a summary of the current state of the
2768 repository.
2770 repository.
2769
2771
2770 Specifying a path to a repository root or Mercurial bundle will
2772 Specifying a path to a repository root or Mercurial bundle will
2771 cause lookup to operate on that repository/bundle.
2773 cause lookup to operate on that repository/bundle.
2772
2774
2773 .. container:: verbose
2775 .. container:: verbose
2774
2776
2775 Examples:
2777 Examples:
2776
2778
2777 - generate a build identifier for the working directory::
2779 - generate a build identifier for the working directory::
2778
2780
2779 hg id --id > build-id.dat
2781 hg id --id > build-id.dat
2780
2782
2781 - find the revision corresponding to a tag::
2783 - find the revision corresponding to a tag::
2782
2784
2783 hg id -n -r 1.3
2785 hg id -n -r 1.3
2784
2786
2785 - check the most recent revision of a remote repository::
2787 - check the most recent revision of a remote repository::
2786
2788
2787 hg id -r tip https://www.mercurial-scm.org/repo/hg/
2789 hg id -r tip https://www.mercurial-scm.org/repo/hg/
2788
2790
2789 See :hg:`log` for generating more information about specific revisions,
2791 See :hg:`log` for generating more information about specific revisions,
2790 including full hash identifiers.
2792 including full hash identifiers.
2791
2793
2792 Returns 0 if successful.
2794 Returns 0 if successful.
2793 """
2795 """
2794
2796
2795 opts = pycompat.byteskwargs(opts)
2797 opts = pycompat.byteskwargs(opts)
2796 if not repo and not source:
2798 if not repo and not source:
2797 raise error.Abort(_("there is no Mercurial repository here "
2799 raise error.Abort(_("there is no Mercurial repository here "
2798 "(.hg not found)"))
2800 "(.hg not found)"))
2799
2801
2800 if ui.debugflag:
2802 if ui.debugflag:
2801 hexfunc = hex
2803 hexfunc = hex
2802 else:
2804 else:
2803 hexfunc = short
2805 hexfunc = short
2804 default = not (num or id or branch or tags or bookmarks)
2806 default = not (num or id or branch or tags or bookmarks)
2805 output = []
2807 output = []
2806 revs = []
2808 revs = []
2807
2809
2808 if source:
2810 if source:
2809 source, branches = hg.parseurl(ui.expandpath(source))
2811 source, branches = hg.parseurl(ui.expandpath(source))
2810 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
2812 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
2811 repo = peer.local()
2813 repo = peer.local()
2812 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
2814 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
2813
2815
2814 if not repo:
2816 if not repo:
2815 if num or branch or tags:
2817 if num or branch or tags:
2816 raise error.Abort(
2818 raise error.Abort(
2817 _("can't query remote revision number, branch, or tags"))
2819 _("can't query remote revision number, branch, or tags"))
2818 if not rev and revs:
2820 if not rev and revs:
2819 rev = revs[0]
2821 rev = revs[0]
2820 if not rev:
2822 if not rev:
2821 rev = "tip"
2823 rev = "tip"
2822
2824
2823 remoterev = peer.lookup(rev)
2825 remoterev = peer.lookup(rev)
2824 if default or id:
2826 if default or id:
2825 output = [hexfunc(remoterev)]
2827 output = [hexfunc(remoterev)]
2826
2828
2827 def getbms():
2829 def getbms():
2828 bms = []
2830 bms = []
2829
2831
2830 if 'bookmarks' in peer.listkeys('namespaces'):
2832 if 'bookmarks' in peer.listkeys('namespaces'):
2831 hexremoterev = hex(remoterev)
2833 hexremoterev = hex(remoterev)
2832 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
2834 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
2833 if bmr == hexremoterev]
2835 if bmr == hexremoterev]
2834
2836
2835 return sorted(bms)
2837 return sorted(bms)
2836
2838
2837 if bookmarks:
2839 if bookmarks:
2838 output.extend(getbms())
2840 output.extend(getbms())
2839 elif default and not ui.quiet:
2841 elif default and not ui.quiet:
2840 # multiple bookmarks for a single parent separated by '/'
2842 # multiple bookmarks for a single parent separated by '/'
2841 bm = '/'.join(getbms())
2843 bm = '/'.join(getbms())
2842 if bm:
2844 if bm:
2843 output.append(bm)
2845 output.append(bm)
2844 else:
2846 else:
2845 ctx = scmutil.revsingle(repo, rev, None)
2847 ctx = scmutil.revsingle(repo, rev, None)
2846
2848
2847 if ctx.rev() is None:
2849 if ctx.rev() is None:
2848 ctx = repo[None]
2850 ctx = repo[None]
2849 parents = ctx.parents()
2851 parents = ctx.parents()
2850 taglist = []
2852 taglist = []
2851 for p in parents:
2853 for p in parents:
2852 taglist.extend(p.tags())
2854 taglist.extend(p.tags())
2853
2855
2854 changed = ""
2856 changed = ""
2855 if default or id or num:
2857 if default or id or num:
2856 if (any(repo.status())
2858 if (any(repo.status())
2857 or any(ctx.sub(s).dirty() for s in ctx.substate)):
2859 or any(ctx.sub(s).dirty() for s in ctx.substate)):
2858 changed = '+'
2860 changed = '+'
2859 if default or id:
2861 if default or id:
2860 output = ["%s%s" %
2862 output = ["%s%s" %
2861 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
2863 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
2862 if num:
2864 if num:
2863 output.append("%s%s" %
2865 output.append("%s%s" %
2864 ('+'.join([str(p.rev()) for p in parents]), changed))
2866 ('+'.join([str(p.rev()) for p in parents]), changed))
2865 else:
2867 else:
2866 if default or id:
2868 if default or id:
2867 output = [hexfunc(ctx.node())]
2869 output = [hexfunc(ctx.node())]
2868 if num:
2870 if num:
2869 output.append(str(ctx.rev()))
2871 output.append(str(ctx.rev()))
2870 taglist = ctx.tags()
2872 taglist = ctx.tags()
2871
2873
2872 if default and not ui.quiet:
2874 if default and not ui.quiet:
2873 b = ctx.branch()
2875 b = ctx.branch()
2874 if b != 'default':
2876 if b != 'default':
2875 output.append("(%s)" % b)
2877 output.append("(%s)" % b)
2876
2878
2877 # multiple tags for a single parent separated by '/'
2879 # multiple tags for a single parent separated by '/'
2878 t = '/'.join(taglist)
2880 t = '/'.join(taglist)
2879 if t:
2881 if t:
2880 output.append(t)
2882 output.append(t)
2881
2883
2882 # multiple bookmarks for a single parent separated by '/'
2884 # multiple bookmarks for a single parent separated by '/'
2883 bm = '/'.join(ctx.bookmarks())
2885 bm = '/'.join(ctx.bookmarks())
2884 if bm:
2886 if bm:
2885 output.append(bm)
2887 output.append(bm)
2886 else:
2888 else:
2887 if branch:
2889 if branch:
2888 output.append(ctx.branch())
2890 output.append(ctx.branch())
2889
2891
2890 if tags:
2892 if tags:
2891 output.extend(taglist)
2893 output.extend(taglist)
2892
2894
2893 if bookmarks:
2895 if bookmarks:
2894 output.extend(ctx.bookmarks())
2896 output.extend(ctx.bookmarks())
2895
2897
2896 ui.write("%s\n" % ' '.join(output))
2898 ui.write("%s\n" % ' '.join(output))
2897
2899
2898 @command('import|patch',
2900 @command('import|patch',
2899 [('p', 'strip', 1,
2901 [('p', 'strip', 1,
2900 _('directory strip option for patch. This has the same '
2902 _('directory strip option for patch. This has the same '
2901 'meaning as the corresponding patch option'), _('NUM')),
2903 'meaning as the corresponding patch option'), _('NUM')),
2902 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
2904 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
2903 ('e', 'edit', False, _('invoke editor on commit messages')),
2905 ('e', 'edit', False, _('invoke editor on commit messages')),
2904 ('f', 'force', None,
2906 ('f', 'force', None,
2905 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
2907 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
2906 ('', 'no-commit', None,
2908 ('', 'no-commit', None,
2907 _("don't commit, just update the working directory")),
2909 _("don't commit, just update the working directory")),
2908 ('', 'bypass', None,
2910 ('', 'bypass', None,
2909 _("apply patch without touching the working directory")),
2911 _("apply patch without touching the working directory")),
2910 ('', 'partial', None,
2912 ('', 'partial', None,
2911 _('commit even if some hunks fail')),
2913 _('commit even if some hunks fail')),
2912 ('', 'exact', None,
2914 ('', 'exact', None,
2913 _('abort if patch would apply lossily')),
2915 _('abort if patch would apply lossily')),
2914 ('', 'prefix', '',
2916 ('', 'prefix', '',
2915 _('apply patch to subdirectory'), _('DIR')),
2917 _('apply patch to subdirectory'), _('DIR')),
2916 ('', 'import-branch', None,
2918 ('', 'import-branch', None,
2917 _('use any branch information in patch (implied by --exact)'))] +
2919 _('use any branch information in patch (implied by --exact)'))] +
2918 commitopts + commitopts2 + similarityopts,
2920 commitopts + commitopts2 + similarityopts,
2919 _('[OPTION]... PATCH...'))
2921 _('[OPTION]... PATCH...'))
2920 def import_(ui, repo, patch1=None, *patches, **opts):
2922 def import_(ui, repo, patch1=None, *patches, **opts):
2921 """import an ordered set of patches
2923 """import an ordered set of patches
2922
2924
2923 Import a list of patches and commit them individually (unless
2925 Import a list of patches and commit them individually (unless
2924 --no-commit is specified).
2926 --no-commit is specified).
2925
2927
2926 To read a patch from standard input (stdin), use "-" as the patch
2928 To read a patch from standard input (stdin), use "-" as the patch
2927 name. If a URL is specified, the patch will be downloaded from
2929 name. If a URL is specified, the patch will be downloaded from
2928 there.
2930 there.
2929
2931
2930 Import first applies changes to the working directory (unless
2932 Import first applies changes to the working directory (unless
2931 --bypass is specified), import will abort if there are outstanding
2933 --bypass is specified), import will abort if there are outstanding
2932 changes.
2934 changes.
2933
2935
2934 Use --bypass to apply and commit patches directly to the
2936 Use --bypass to apply and commit patches directly to the
2935 repository, without affecting the working directory. Without
2937 repository, without affecting the working directory. Without
2936 --exact, patches will be applied on top of the working directory
2938 --exact, patches will be applied on top of the working directory
2937 parent revision.
2939 parent revision.
2938
2940
2939 You can import a patch straight from a mail message. Even patches
2941 You can import a patch straight from a mail message. Even patches
2940 as attachments work (to use the body part, it must have type
2942 as attachments work (to use the body part, it must have type
2941 text/plain or text/x-patch). From and Subject headers of email
2943 text/plain or text/x-patch). From and Subject headers of email
2942 message are used as default committer and commit message. All
2944 message are used as default committer and commit message. All
2943 text/plain body parts before first diff are added to the commit
2945 text/plain body parts before first diff are added to the commit
2944 message.
2946 message.
2945
2947
2946 If the imported patch was generated by :hg:`export`, user and
2948 If the imported patch was generated by :hg:`export`, user and
2947 description from patch override values from message headers and
2949 description from patch override values from message headers and
2948 body. Values given on command line with -m/--message and -u/--user
2950 body. Values given on command line with -m/--message and -u/--user
2949 override these.
2951 override these.
2950
2952
2951 If --exact is specified, import will set the working directory to
2953 If --exact is specified, import will set the working directory to
2952 the parent of each patch before applying it, and will abort if the
2954 the parent of each patch before applying it, and will abort if the
2953 resulting changeset has a different ID than the one recorded in
2955 resulting changeset has a different ID than the one recorded in
2954 the patch. This will guard against various ways that portable
2956 the patch. This will guard against various ways that portable
2955 patch formats and mail systems might fail to transfer Mercurial
2957 patch formats and mail systems might fail to transfer Mercurial
2956 data or metadata. See :hg:`bundle` for lossless transmission.
2958 data or metadata. See :hg:`bundle` for lossless transmission.
2957
2959
2958 Use --partial to ensure a changeset will be created from the patch
2960 Use --partial to ensure a changeset will be created from the patch
2959 even if some hunks fail to apply. Hunks that fail to apply will be
2961 even if some hunks fail to apply. Hunks that fail to apply will be
2960 written to a <target-file>.rej file. Conflicts can then be resolved
2962 written to a <target-file>.rej file. Conflicts can then be resolved
2961 by hand before :hg:`commit --amend` is run to update the created
2963 by hand before :hg:`commit --amend` is run to update the created
2962 changeset. This flag exists to let people import patches that
2964 changeset. This flag exists to let people import patches that
2963 partially apply without losing the associated metadata (author,
2965 partially apply without losing the associated metadata (author,
2964 date, description, ...).
2966 date, description, ...).
2965
2967
2966 .. note::
2968 .. note::
2967
2969
2968 When no hunks apply cleanly, :hg:`import --partial` will create
2970 When no hunks apply cleanly, :hg:`import --partial` will create
2969 an empty changeset, importing only the patch metadata.
2971 an empty changeset, importing only the patch metadata.
2970
2972
2971 With -s/--similarity, hg will attempt to discover renames and
2973 With -s/--similarity, hg will attempt to discover renames and
2972 copies in the patch in the same way as :hg:`addremove`.
2974 copies in the patch in the same way as :hg:`addremove`.
2973
2975
2974 It is possible to use external patch programs to perform the patch
2976 It is possible to use external patch programs to perform the patch
2975 by setting the ``ui.patch`` configuration option. For the default
2977 by setting the ``ui.patch`` configuration option. For the default
2976 internal tool, the fuzz can also be configured via ``patch.fuzz``.
2978 internal tool, the fuzz can also be configured via ``patch.fuzz``.
2977 See :hg:`help config` for more information about configuration
2979 See :hg:`help config` for more information about configuration
2978 files and how to use these options.
2980 files and how to use these options.
2979
2981
2980 See :hg:`help dates` for a list of formats valid for -d/--date.
2982 See :hg:`help dates` for a list of formats valid for -d/--date.
2981
2983
2982 .. container:: verbose
2984 .. container:: verbose
2983
2985
2984 Examples:
2986 Examples:
2985
2987
2986 - import a traditional patch from a website and detect renames::
2988 - import a traditional patch from a website and detect renames::
2987
2989
2988 hg import -s 80 http://example.com/bugfix.patch
2990 hg import -s 80 http://example.com/bugfix.patch
2989
2991
2990 - import a changeset from an hgweb server::
2992 - import a changeset from an hgweb server::
2991
2993
2992 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
2994 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
2993
2995
2994 - import all the patches in an Unix-style mbox::
2996 - import all the patches in an Unix-style mbox::
2995
2997
2996 hg import incoming-patches.mbox
2998 hg import incoming-patches.mbox
2997
2999
2998 - import patches from stdin::
3000 - import patches from stdin::
2999
3001
3000 hg import -
3002 hg import -
3001
3003
3002 - attempt to exactly restore an exported changeset (not always
3004 - attempt to exactly restore an exported changeset (not always
3003 possible)::
3005 possible)::
3004
3006
3005 hg import --exact proposed-fix.patch
3007 hg import --exact proposed-fix.patch
3006
3008
3007 - use an external tool to apply a patch which is too fuzzy for
3009 - use an external tool to apply a patch which is too fuzzy for
3008 the default internal tool.
3010 the default internal tool.
3009
3011
3010 hg import --config ui.patch="patch --merge" fuzzy.patch
3012 hg import --config ui.patch="patch --merge" fuzzy.patch
3011
3013
3012 - change the default fuzzing from 2 to a less strict 7
3014 - change the default fuzzing from 2 to a less strict 7
3013
3015
3014 hg import --config ui.fuzz=7 fuzz.patch
3016 hg import --config ui.fuzz=7 fuzz.patch
3015
3017
3016 Returns 0 on success, 1 on partial success (see --partial).
3018 Returns 0 on success, 1 on partial success (see --partial).
3017 """
3019 """
3018
3020
3019 opts = pycompat.byteskwargs(opts)
3021 opts = pycompat.byteskwargs(opts)
3020 if not patch1:
3022 if not patch1:
3021 raise error.Abort(_('need at least one patch to import'))
3023 raise error.Abort(_('need at least one patch to import'))
3022
3024
3023 patches = (patch1,) + patches
3025 patches = (patch1,) + patches
3024
3026
3025 date = opts.get('date')
3027 date = opts.get('date')
3026 if date:
3028 if date:
3027 opts['date'] = util.parsedate(date)
3029 opts['date'] = util.parsedate(date)
3028
3030
3029 exact = opts.get('exact')
3031 exact = opts.get('exact')
3030 update = not opts.get('bypass')
3032 update = not opts.get('bypass')
3031 if not update and opts.get('no_commit'):
3033 if not update and opts.get('no_commit'):
3032 raise error.Abort(_('cannot use --no-commit with --bypass'))
3034 raise error.Abort(_('cannot use --no-commit with --bypass'))
3033 try:
3035 try:
3034 sim = float(opts.get('similarity') or 0)
3036 sim = float(opts.get('similarity') or 0)
3035 except ValueError:
3037 except ValueError:
3036 raise error.Abort(_('similarity must be a number'))
3038 raise error.Abort(_('similarity must be a number'))
3037 if sim < 0 or sim > 100:
3039 if sim < 0 or sim > 100:
3038 raise error.Abort(_('similarity must be between 0 and 100'))
3040 raise error.Abort(_('similarity must be between 0 and 100'))
3039 if sim and not update:
3041 if sim and not update:
3040 raise error.Abort(_('cannot use --similarity with --bypass'))
3042 raise error.Abort(_('cannot use --similarity with --bypass'))
3041 if exact:
3043 if exact:
3042 if opts.get('edit'):
3044 if opts.get('edit'):
3043 raise error.Abort(_('cannot use --exact with --edit'))
3045 raise error.Abort(_('cannot use --exact with --edit'))
3044 if opts.get('prefix'):
3046 if opts.get('prefix'):
3045 raise error.Abort(_('cannot use --exact with --prefix'))
3047 raise error.Abort(_('cannot use --exact with --prefix'))
3046
3048
3047 base = opts["base"]
3049 base = opts["base"]
3048 wlock = dsguard = lock = tr = None
3050 wlock = dsguard = lock = tr = None
3049 msgs = []
3051 msgs = []
3050 ret = 0
3052 ret = 0
3051
3053
3052
3054
3053 try:
3055 try:
3054 wlock = repo.wlock()
3056 wlock = repo.wlock()
3055
3057
3056 if update:
3058 if update:
3057 cmdutil.checkunfinished(repo)
3059 cmdutil.checkunfinished(repo)
3058 if (exact or not opts.get('force')):
3060 if (exact or not opts.get('force')):
3059 cmdutil.bailifchanged(repo)
3061 cmdutil.bailifchanged(repo)
3060
3062
3061 if not opts.get('no_commit'):
3063 if not opts.get('no_commit'):
3062 lock = repo.lock()
3064 lock = repo.lock()
3063 tr = repo.transaction('import')
3065 tr = repo.transaction('import')
3064 else:
3066 else:
3065 dsguard = dirstateguard.dirstateguard(repo, 'import')
3067 dsguard = dirstateguard.dirstateguard(repo, 'import')
3066 parents = repo[None].parents()
3068 parents = repo[None].parents()
3067 for patchurl in patches:
3069 for patchurl in patches:
3068 if patchurl == '-':
3070 if patchurl == '-':
3069 ui.status(_('applying patch from stdin\n'))
3071 ui.status(_('applying patch from stdin\n'))
3070 patchfile = ui.fin
3072 patchfile = ui.fin
3071 patchurl = 'stdin' # for error message
3073 patchurl = 'stdin' # for error message
3072 else:
3074 else:
3073 patchurl = os.path.join(base, patchurl)
3075 patchurl = os.path.join(base, patchurl)
3074 ui.status(_('applying %s\n') % patchurl)
3076 ui.status(_('applying %s\n') % patchurl)
3075 patchfile = hg.openpath(ui, patchurl)
3077 patchfile = hg.openpath(ui, patchurl)
3076
3078
3077 haspatch = False
3079 haspatch = False
3078 for hunk in patch.split(patchfile):
3080 for hunk in patch.split(patchfile):
3079 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
3081 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
3080 parents, opts,
3082 parents, opts,
3081 msgs, hg.clean)
3083 msgs, hg.clean)
3082 if msg:
3084 if msg:
3083 haspatch = True
3085 haspatch = True
3084 ui.note(msg + '\n')
3086 ui.note(msg + '\n')
3085 if update or exact:
3087 if update or exact:
3086 parents = repo[None].parents()
3088 parents = repo[None].parents()
3087 else:
3089 else:
3088 parents = [repo[node]]
3090 parents = [repo[node]]
3089 if rej:
3091 if rej:
3090 ui.write_err(_("patch applied partially\n"))
3092 ui.write_err(_("patch applied partially\n"))
3091 ui.write_err(_("(fix the .rej files and run "
3093 ui.write_err(_("(fix the .rej files and run "
3092 "`hg commit --amend`)\n"))
3094 "`hg commit --amend`)\n"))
3093 ret = 1
3095 ret = 1
3094 break
3096 break
3095
3097
3096 if not haspatch:
3098 if not haspatch:
3097 raise error.Abort(_('%s: no diffs found') % patchurl)
3099 raise error.Abort(_('%s: no diffs found') % patchurl)
3098
3100
3099 if tr:
3101 if tr:
3100 tr.close()
3102 tr.close()
3101 if msgs:
3103 if msgs:
3102 repo.savecommitmessage('\n* * *\n'.join(msgs))
3104 repo.savecommitmessage('\n* * *\n'.join(msgs))
3103 if dsguard:
3105 if dsguard:
3104 dsguard.close()
3106 dsguard.close()
3105 return ret
3107 return ret
3106 finally:
3108 finally:
3107 if tr:
3109 if tr:
3108 tr.release()
3110 tr.release()
3109 release(lock, dsguard, wlock)
3111 release(lock, dsguard, wlock)
3110
3112
3111 @command('incoming|in',
3113 @command('incoming|in',
3112 [('f', 'force', None,
3114 [('f', 'force', None,
3113 _('run even if remote repository is unrelated')),
3115 _('run even if remote repository is unrelated')),
3114 ('n', 'newest-first', None, _('show newest record first')),
3116 ('n', 'newest-first', None, _('show newest record first')),
3115 ('', 'bundle', '',
3117 ('', 'bundle', '',
3116 _('file to store the bundles into'), _('FILE')),
3118 _('file to store the bundles into'), _('FILE')),
3117 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3119 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3118 ('B', 'bookmarks', False, _("compare bookmarks")),
3120 ('B', 'bookmarks', False, _("compare bookmarks")),
3119 ('b', 'branch', [],
3121 ('b', 'branch', [],
3120 _('a specific branch you would like to pull'), _('BRANCH')),
3122 _('a specific branch you would like to pull'), _('BRANCH')),
3121 ] + logopts + remoteopts + subrepoopts,
3123 ] + logopts + remoteopts + subrepoopts,
3122 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3124 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3123 def incoming(ui, repo, source="default", **opts):
3125 def incoming(ui, repo, source="default", **opts):
3124 """show new changesets found in source
3126 """show new changesets found in source
3125
3127
3126 Show new changesets found in the specified path/URL or the default
3128 Show new changesets found in the specified path/URL or the default
3127 pull location. These are the changesets that would have been pulled
3129 pull location. These are the changesets that would have been pulled
3128 if a pull at the time you issued this command.
3130 if a pull at the time you issued this command.
3129
3131
3130 See pull for valid source format details.
3132 See pull for valid source format details.
3131
3133
3132 .. container:: verbose
3134 .. container:: verbose
3133
3135
3134 With -B/--bookmarks, the result of bookmark comparison between
3136 With -B/--bookmarks, the result of bookmark comparison between
3135 local and remote repositories is displayed. With -v/--verbose,
3137 local and remote repositories is displayed. With -v/--verbose,
3136 status is also displayed for each bookmark like below::
3138 status is also displayed for each bookmark like below::
3137
3139
3138 BM1 01234567890a added
3140 BM1 01234567890a added
3139 BM2 1234567890ab advanced
3141 BM2 1234567890ab advanced
3140 BM3 234567890abc diverged
3142 BM3 234567890abc diverged
3141 BM4 34567890abcd changed
3143 BM4 34567890abcd changed
3142
3144
3143 The action taken locally when pulling depends on the
3145 The action taken locally when pulling depends on the
3144 status of each bookmark:
3146 status of each bookmark:
3145
3147
3146 :``added``: pull will create it
3148 :``added``: pull will create it
3147 :``advanced``: pull will update it
3149 :``advanced``: pull will update it
3148 :``diverged``: pull will create a divergent bookmark
3150 :``diverged``: pull will create a divergent bookmark
3149 :``changed``: result depends on remote changesets
3151 :``changed``: result depends on remote changesets
3150
3152
3151 From the point of view of pulling behavior, bookmark
3153 From the point of view of pulling behavior, bookmark
3152 existing only in the remote repository are treated as ``added``,
3154 existing only in the remote repository are treated as ``added``,
3153 even if it is in fact locally deleted.
3155 even if it is in fact locally deleted.
3154
3156
3155 .. container:: verbose
3157 .. container:: verbose
3156
3158
3157 For remote repository, using --bundle avoids downloading the
3159 For remote repository, using --bundle avoids downloading the
3158 changesets twice if the incoming is followed by a pull.
3160 changesets twice if the incoming is followed by a pull.
3159
3161
3160 Examples:
3162 Examples:
3161
3163
3162 - show incoming changes with patches and full description::
3164 - show incoming changes with patches and full description::
3163
3165
3164 hg incoming -vp
3166 hg incoming -vp
3165
3167
3166 - show incoming changes excluding merges, store a bundle::
3168 - show incoming changes excluding merges, store a bundle::
3167
3169
3168 hg in -vpM --bundle incoming.hg
3170 hg in -vpM --bundle incoming.hg
3169 hg pull incoming.hg
3171 hg pull incoming.hg
3170
3172
3171 - briefly list changes inside a bundle::
3173 - briefly list changes inside a bundle::
3172
3174
3173 hg in changes.hg -T "{desc|firstline}\\n"
3175 hg in changes.hg -T "{desc|firstline}\\n"
3174
3176
3175 Returns 0 if there are incoming changes, 1 otherwise.
3177 Returns 0 if there are incoming changes, 1 otherwise.
3176 """
3178 """
3177 opts = pycompat.byteskwargs(opts)
3179 opts = pycompat.byteskwargs(opts)
3178 if opts.get('graph'):
3180 if opts.get('graph'):
3179 cmdutil.checkunsupportedgraphflags([], opts)
3181 cmdutil.checkunsupportedgraphflags([], opts)
3180 def display(other, chlist, displayer):
3182 def display(other, chlist, displayer):
3181 revdag = cmdutil.graphrevs(other, chlist, opts)
3183 revdag = cmdutil.graphrevs(other, chlist, opts)
3182 cmdutil.displaygraph(ui, repo, revdag, displayer,
3184 cmdutil.displaygraph(ui, repo, revdag, displayer,
3183 graphmod.asciiedges)
3185 graphmod.asciiedges)
3184
3186
3185 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3187 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3186 return 0
3188 return 0
3187
3189
3188 if opts.get('bundle') and opts.get('subrepos'):
3190 if opts.get('bundle') and opts.get('subrepos'):
3189 raise error.Abort(_('cannot combine --bundle and --subrepos'))
3191 raise error.Abort(_('cannot combine --bundle and --subrepos'))
3190
3192
3191 if opts.get('bookmarks'):
3193 if opts.get('bookmarks'):
3192 source, branches = hg.parseurl(ui.expandpath(source),
3194 source, branches = hg.parseurl(ui.expandpath(source),
3193 opts.get('branch'))
3195 opts.get('branch'))
3194 other = hg.peer(repo, opts, source)
3196 other = hg.peer(repo, opts, source)
3195 if 'bookmarks' not in other.listkeys('namespaces'):
3197 if 'bookmarks' not in other.listkeys('namespaces'):
3196 ui.warn(_("remote doesn't support bookmarks\n"))
3198 ui.warn(_("remote doesn't support bookmarks\n"))
3197 return 0
3199 return 0
3198 ui.pager('incoming')
3200 ui.pager('incoming')
3199 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3201 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3200 return bookmarks.incoming(ui, repo, other)
3202 return bookmarks.incoming(ui, repo, other)
3201
3203
3202 repo._subtoppath = ui.expandpath(source)
3204 repo._subtoppath = ui.expandpath(source)
3203 try:
3205 try:
3204 return hg.incoming(ui, repo, source, opts)
3206 return hg.incoming(ui, repo, source, opts)
3205 finally:
3207 finally:
3206 del repo._subtoppath
3208 del repo._subtoppath
3207
3209
3208
3210
3209 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
3211 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
3210 norepo=True)
3212 norepo=True)
3211 def init(ui, dest=".", **opts):
3213 def init(ui, dest=".", **opts):
3212 """create a new repository in the given directory
3214 """create a new repository in the given directory
3213
3215
3214 Initialize a new repository in the given directory. If the given
3216 Initialize a new repository in the given directory. If the given
3215 directory does not exist, it will be created.
3217 directory does not exist, it will be created.
3216
3218
3217 If no directory is given, the current directory is used.
3219 If no directory is given, the current directory is used.
3218
3220
3219 It is possible to specify an ``ssh://`` URL as the destination.
3221 It is possible to specify an ``ssh://`` URL as the destination.
3220 See :hg:`help urls` for more information.
3222 See :hg:`help urls` for more information.
3221
3223
3222 Returns 0 on success.
3224 Returns 0 on success.
3223 """
3225 """
3224 opts = pycompat.byteskwargs(opts)
3226 opts = pycompat.byteskwargs(opts)
3225 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3227 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3226
3228
3227 @command('locate',
3229 @command('locate',
3228 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3230 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3229 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3231 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3230 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3232 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3231 ] + walkopts,
3233 ] + walkopts,
3232 _('[OPTION]... [PATTERN]...'))
3234 _('[OPTION]... [PATTERN]...'))
3233 def locate(ui, repo, *pats, **opts):
3235 def locate(ui, repo, *pats, **opts):
3234 """locate files matching specific patterns (DEPRECATED)
3236 """locate files matching specific patterns (DEPRECATED)
3235
3237
3236 Print files under Mercurial control in the working directory whose
3238 Print files under Mercurial control in the working directory whose
3237 names match the given patterns.
3239 names match the given patterns.
3238
3240
3239 By default, this command searches all directories in the working
3241 By default, this command searches all directories in the working
3240 directory. To search just the current directory and its
3242 directory. To search just the current directory and its
3241 subdirectories, use "--include .".
3243 subdirectories, use "--include .".
3242
3244
3243 If no patterns are given to match, this command prints the names
3245 If no patterns are given to match, this command prints the names
3244 of all files under Mercurial control in the working directory.
3246 of all files under Mercurial control in the working directory.
3245
3247
3246 If you want to feed the output of this command into the "xargs"
3248 If you want to feed the output of this command into the "xargs"
3247 command, use the -0 option to both this command and "xargs". This
3249 command, use the -0 option to both this command and "xargs". This
3248 will avoid the problem of "xargs" treating single filenames that
3250 will avoid the problem of "xargs" treating single filenames that
3249 contain whitespace as multiple filenames.
3251 contain whitespace as multiple filenames.
3250
3252
3251 See :hg:`help files` for a more versatile command.
3253 See :hg:`help files` for a more versatile command.
3252
3254
3253 Returns 0 if a match is found, 1 otherwise.
3255 Returns 0 if a match is found, 1 otherwise.
3254 """
3256 """
3255 opts = pycompat.byteskwargs(opts)
3257 opts = pycompat.byteskwargs(opts)
3256 if opts.get('print0'):
3258 if opts.get('print0'):
3257 end = '\0'
3259 end = '\0'
3258 else:
3260 else:
3259 end = '\n'
3261 end = '\n'
3260 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3262 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3261
3263
3262 ret = 1
3264 ret = 1
3263 ctx = repo[rev]
3265 ctx = repo[rev]
3264 m = scmutil.match(ctx, pats, opts, default='relglob',
3266 m = scmutil.match(ctx, pats, opts, default='relglob',
3265 badfn=lambda x, y: False)
3267 badfn=lambda x, y: False)
3266
3268
3267 ui.pager('locate')
3269 ui.pager('locate')
3268 for abs in ctx.matches(m):
3270 for abs in ctx.matches(m):
3269 if opts.get('fullpath'):
3271 if opts.get('fullpath'):
3270 ui.write(repo.wjoin(abs), end)
3272 ui.write(repo.wjoin(abs), end)
3271 else:
3273 else:
3272 ui.write(((pats and m.rel(abs)) or abs), end)
3274 ui.write(((pats and m.rel(abs)) or abs), end)
3273 ret = 0
3275 ret = 0
3274
3276
3275 return ret
3277 return ret
3276
3278
3277 @command('^log|history',
3279 @command('^log|history',
3278 [('f', 'follow', None,
3280 [('f', 'follow', None,
3279 _('follow changeset history, or file history across copies and renames')),
3281 _('follow changeset history, or file history across copies and renames')),
3280 ('', 'follow-first', None,
3282 ('', 'follow-first', None,
3281 _('only follow the first parent of merge changesets (DEPRECATED)')),
3283 _('only follow the first parent of merge changesets (DEPRECATED)')),
3282 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3284 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3283 ('C', 'copies', None, _('show copied files')),
3285 ('C', 'copies', None, _('show copied files')),
3284 ('k', 'keyword', [],
3286 ('k', 'keyword', [],
3285 _('do case-insensitive search for a given text'), _('TEXT')),
3287 _('do case-insensitive search for a given text'), _('TEXT')),
3286 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
3288 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
3287 ('', 'removed', None, _('include revisions where files were removed')),
3289 ('', 'removed', None, _('include revisions where files were removed')),
3288 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3290 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3289 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3291 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3290 ('', 'only-branch', [],
3292 ('', 'only-branch', [],
3291 _('show only changesets within the given named branch (DEPRECATED)'),
3293 _('show only changesets within the given named branch (DEPRECATED)'),
3292 _('BRANCH')),
3294 _('BRANCH')),
3293 ('b', 'branch', [],
3295 ('b', 'branch', [],
3294 _('show changesets within the given named branch'), _('BRANCH')),
3296 _('show changesets within the given named branch'), _('BRANCH')),
3295 ('P', 'prune', [],
3297 ('P', 'prune', [],
3296 _('do not display revision or any of its ancestors'), _('REV')),
3298 _('do not display revision or any of its ancestors'), _('REV')),
3297 ] + logopts + walkopts,
3299 ] + logopts + walkopts,
3298 _('[OPTION]... [FILE]'),
3300 _('[OPTION]... [FILE]'),
3299 inferrepo=True)
3301 inferrepo=True)
3300 def log(ui, repo, *pats, **opts):
3302 def log(ui, repo, *pats, **opts):
3301 """show revision history of entire repository or files
3303 """show revision history of entire repository or files
3302
3304
3303 Print the revision history of the specified files or the entire
3305 Print the revision history of the specified files or the entire
3304 project.
3306 project.
3305
3307
3306 If no revision range is specified, the default is ``tip:0`` unless
3308 If no revision range is specified, the default is ``tip:0`` unless
3307 --follow is set, in which case the working directory parent is
3309 --follow is set, in which case the working directory parent is
3308 used as the starting revision.
3310 used as the starting revision.
3309
3311
3310 File history is shown without following rename or copy history of
3312 File history is shown without following rename or copy history of
3311 files. Use -f/--follow with a filename to follow history across
3313 files. Use -f/--follow with a filename to follow history across
3312 renames and copies. --follow without a filename will only show
3314 renames and copies. --follow without a filename will only show
3313 ancestors or descendants of the starting revision.
3315 ancestors or descendants of the starting revision.
3314
3316
3315 By default this command prints revision number and changeset id,
3317 By default this command prints revision number and changeset id,
3316 tags, non-trivial parents, user, date and time, and a summary for
3318 tags, non-trivial parents, user, date and time, and a summary for
3317 each commit. When the -v/--verbose switch is used, the list of
3319 each commit. When the -v/--verbose switch is used, the list of
3318 changed files and full commit message are shown.
3320 changed files and full commit message are shown.
3319
3321
3320 With --graph the revisions are shown as an ASCII art DAG with the most
3322 With --graph the revisions are shown as an ASCII art DAG with the most
3321 recent changeset at the top.
3323 recent changeset at the top.
3322 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
3324 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
3323 and '+' represents a fork where the changeset from the lines below is a
3325 and '+' represents a fork where the changeset from the lines below is a
3324 parent of the 'o' merge on the same line.
3326 parent of the 'o' merge on the same line.
3325 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
3327 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
3326 of a '|' indicates one or more revisions in a path are omitted.
3328 of a '|' indicates one or more revisions in a path are omitted.
3327
3329
3328 .. note::
3330 .. note::
3329
3331
3330 :hg:`log --patch` may generate unexpected diff output for merge
3332 :hg:`log --patch` may generate unexpected diff output for merge
3331 changesets, as it will only compare the merge changeset against
3333 changesets, as it will only compare the merge changeset against
3332 its first parent. Also, only files different from BOTH parents
3334 its first parent. Also, only files different from BOTH parents
3333 will appear in files:.
3335 will appear in files:.
3334
3336
3335 .. note::
3337 .. note::
3336
3338
3337 For performance reasons, :hg:`log FILE` may omit duplicate changes
3339 For performance reasons, :hg:`log FILE` may omit duplicate changes
3338 made on branches and will not show removals or mode changes. To
3340 made on branches and will not show removals or mode changes. To
3339 see all such changes, use the --removed switch.
3341 see all such changes, use the --removed switch.
3340
3342
3341 .. container:: verbose
3343 .. container:: verbose
3342
3344
3343 Some examples:
3345 Some examples:
3344
3346
3345 - changesets with full descriptions and file lists::
3347 - changesets with full descriptions and file lists::
3346
3348
3347 hg log -v
3349 hg log -v
3348
3350
3349 - changesets ancestral to the working directory::
3351 - changesets ancestral to the working directory::
3350
3352
3351 hg log -f
3353 hg log -f
3352
3354
3353 - last 10 commits on the current branch::
3355 - last 10 commits on the current branch::
3354
3356
3355 hg log -l 10 -b .
3357 hg log -l 10 -b .
3356
3358
3357 - changesets showing all modifications of a file, including removals::
3359 - changesets showing all modifications of a file, including removals::
3358
3360
3359 hg log --removed file.c
3361 hg log --removed file.c
3360
3362
3361 - all changesets that touch a directory, with diffs, excluding merges::
3363 - all changesets that touch a directory, with diffs, excluding merges::
3362
3364
3363 hg log -Mp lib/
3365 hg log -Mp lib/
3364
3366
3365 - all revision numbers that match a keyword::
3367 - all revision numbers that match a keyword::
3366
3368
3367 hg log -k bug --template "{rev}\\n"
3369 hg log -k bug --template "{rev}\\n"
3368
3370
3369 - the full hash identifier of the working directory parent::
3371 - the full hash identifier of the working directory parent::
3370
3372
3371 hg log -r . --template "{node}\\n"
3373 hg log -r . --template "{node}\\n"
3372
3374
3373 - list available log templates::
3375 - list available log templates::
3374
3376
3375 hg log -T list
3377 hg log -T list
3376
3378
3377 - check if a given changeset is included in a tagged release::
3379 - check if a given changeset is included in a tagged release::
3378
3380
3379 hg log -r "a21ccf and ancestor(1.9)"
3381 hg log -r "a21ccf and ancestor(1.9)"
3380
3382
3381 - find all changesets by some user in a date range::
3383 - find all changesets by some user in a date range::
3382
3384
3383 hg log -k alice -d "may 2008 to jul 2008"
3385 hg log -k alice -d "may 2008 to jul 2008"
3384
3386
3385 - summary of all changesets after the last tag::
3387 - summary of all changesets after the last tag::
3386
3388
3387 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3389 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3388
3390
3389 See :hg:`help dates` for a list of formats valid for -d/--date.
3391 See :hg:`help dates` for a list of formats valid for -d/--date.
3390
3392
3391 See :hg:`help revisions` for more about specifying and ordering
3393 See :hg:`help revisions` for more about specifying and ordering
3392 revisions.
3394 revisions.
3393
3395
3394 See :hg:`help templates` for more about pre-packaged styles and
3396 See :hg:`help templates` for more about pre-packaged styles and
3395 specifying custom templates.
3397 specifying custom templates.
3396
3398
3397 Returns 0 on success.
3399 Returns 0 on success.
3398
3400
3399 """
3401 """
3400 opts = pycompat.byteskwargs(opts)
3402 opts = pycompat.byteskwargs(opts)
3401 if opts.get('follow') and opts.get('rev'):
3403 if opts.get('follow') and opts.get('rev'):
3402 opts['rev'] = [revsetlang.formatspec('reverse(::%lr)', opts.get('rev'))]
3404 opts['rev'] = [revsetlang.formatspec('reverse(::%lr)', opts.get('rev'))]
3403 del opts['follow']
3405 del opts['follow']
3404
3406
3405 if opts.get('graph'):
3407 if opts.get('graph'):
3406 return cmdutil.graphlog(ui, repo, pats, opts)
3408 return cmdutil.graphlog(ui, repo, pats, opts)
3407
3409
3408 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
3410 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
3409 limit = cmdutil.loglimit(opts)
3411 limit = cmdutil.loglimit(opts)
3410 count = 0
3412 count = 0
3411
3413
3412 getrenamed = None
3414 getrenamed = None
3413 if opts.get('copies'):
3415 if opts.get('copies'):
3414 endrev = None
3416 endrev = None
3415 if opts.get('rev'):
3417 if opts.get('rev'):
3416 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
3418 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
3417 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3419 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3418
3420
3419 ui.pager('log')
3421 ui.pager('log')
3420 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
3422 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
3421 for rev in revs:
3423 for rev in revs:
3422 if count == limit:
3424 if count == limit:
3423 break
3425 break
3424 ctx = repo[rev]
3426 ctx = repo[rev]
3425 copies = None
3427 copies = None
3426 if getrenamed is not None and rev:
3428 if getrenamed is not None and rev:
3427 copies = []
3429 copies = []
3428 for fn in ctx.files():
3430 for fn in ctx.files():
3429 rename = getrenamed(fn, rev)
3431 rename = getrenamed(fn, rev)
3430 if rename:
3432 if rename:
3431 copies.append((fn, rename[0]))
3433 copies.append((fn, rename[0]))
3432 if filematcher:
3434 if filematcher:
3433 revmatchfn = filematcher(ctx.rev())
3435 revmatchfn = filematcher(ctx.rev())
3434 else:
3436 else:
3435 revmatchfn = None
3437 revmatchfn = None
3436 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3438 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3437 if displayer.flush(ctx):
3439 if displayer.flush(ctx):
3438 count += 1
3440 count += 1
3439
3441
3440 displayer.close()
3442 displayer.close()
3441
3443
3442 @command('manifest',
3444 @command('manifest',
3443 [('r', 'rev', '', _('revision to display'), _('REV')),
3445 [('r', 'rev', '', _('revision to display'), _('REV')),
3444 ('', 'all', False, _("list files from all revisions"))]
3446 ('', 'all', False, _("list files from all revisions"))]
3445 + formatteropts,
3447 + formatteropts,
3446 _('[-r REV]'))
3448 _('[-r REV]'))
3447 def manifest(ui, repo, node=None, rev=None, **opts):
3449 def manifest(ui, repo, node=None, rev=None, **opts):
3448 """output the current or given revision of the project manifest
3450 """output the current or given revision of the project manifest
3449
3451
3450 Print a list of version controlled files for the given revision.
3452 Print a list of version controlled files for the given revision.
3451 If no revision is given, the first parent of the working directory
3453 If no revision is given, the first parent of the working directory
3452 is used, or the null revision if no revision is checked out.
3454 is used, or the null revision if no revision is checked out.
3453
3455
3454 With -v, print file permissions, symlink and executable bits.
3456 With -v, print file permissions, symlink and executable bits.
3455 With --debug, print file revision hashes.
3457 With --debug, print file revision hashes.
3456
3458
3457 If option --all is specified, the list of all files from all revisions
3459 If option --all is specified, the list of all files from all revisions
3458 is printed. This includes deleted and renamed files.
3460 is printed. This includes deleted and renamed files.
3459
3461
3460 Returns 0 on success.
3462 Returns 0 on success.
3461 """
3463 """
3462 opts = pycompat.byteskwargs(opts)
3464 opts = pycompat.byteskwargs(opts)
3463 fm = ui.formatter('manifest', opts)
3465 fm = ui.formatter('manifest', opts)
3464
3466
3465 if opts.get('all'):
3467 if opts.get('all'):
3466 if rev or node:
3468 if rev or node:
3467 raise error.Abort(_("can't specify a revision with --all"))
3469 raise error.Abort(_("can't specify a revision with --all"))
3468
3470
3469 res = []
3471 res = []
3470 prefix = "data/"
3472 prefix = "data/"
3471 suffix = ".i"
3473 suffix = ".i"
3472 plen = len(prefix)
3474 plen = len(prefix)
3473 slen = len(suffix)
3475 slen = len(suffix)
3474 with repo.lock():
3476 with repo.lock():
3475 for fn, b, size in repo.store.datafiles():
3477 for fn, b, size in repo.store.datafiles():
3476 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3478 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3477 res.append(fn[plen:-slen])
3479 res.append(fn[plen:-slen])
3478 ui.pager('manifest')
3480 ui.pager('manifest')
3479 for f in res:
3481 for f in res:
3480 fm.startitem()
3482 fm.startitem()
3481 fm.write("path", '%s\n', f)
3483 fm.write("path", '%s\n', f)
3482 fm.end()
3484 fm.end()
3483 return
3485 return
3484
3486
3485 if rev and node:
3487 if rev and node:
3486 raise error.Abort(_("please specify just one revision"))
3488 raise error.Abort(_("please specify just one revision"))
3487
3489
3488 if not node:
3490 if not node:
3489 node = rev
3491 node = rev
3490
3492
3491 char = {'l': '@', 'x': '*', '': ''}
3493 char = {'l': '@', 'x': '*', '': ''}
3492 mode = {'l': '644', 'x': '755', '': '644'}
3494 mode = {'l': '644', 'x': '755', '': '644'}
3493 ctx = scmutil.revsingle(repo, node)
3495 ctx = scmutil.revsingle(repo, node)
3494 mf = ctx.manifest()
3496 mf = ctx.manifest()
3495 ui.pager('manifest')
3497 ui.pager('manifest')
3496 for f in ctx:
3498 for f in ctx:
3497 fm.startitem()
3499 fm.startitem()
3498 fl = ctx[f].flags()
3500 fl = ctx[f].flags()
3499 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
3501 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
3500 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
3502 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
3501 fm.write('path', '%s\n', f)
3503 fm.write('path', '%s\n', f)
3502 fm.end()
3504 fm.end()
3503
3505
3504 @command('^merge',
3506 @command('^merge',
3505 [('f', 'force', None,
3507 [('f', 'force', None,
3506 _('force a merge including outstanding changes (DEPRECATED)')),
3508 _('force a merge including outstanding changes (DEPRECATED)')),
3507 ('r', 'rev', '', _('revision to merge'), _('REV')),
3509 ('r', 'rev', '', _('revision to merge'), _('REV')),
3508 ('P', 'preview', None,
3510 ('P', 'preview', None,
3509 _('review revisions to merge (no merge is performed)'))
3511 _('review revisions to merge (no merge is performed)'))
3510 ] + mergetoolopts,
3512 ] + mergetoolopts,
3511 _('[-P] [[-r] REV]'))
3513 _('[-P] [[-r] REV]'))
3512 def merge(ui, repo, node=None, **opts):
3514 def merge(ui, repo, node=None, **opts):
3513 """merge another revision into working directory
3515 """merge another revision into working directory
3514
3516
3515 The current working directory is updated with all changes made in
3517 The current working directory is updated with all changes made in
3516 the requested revision since the last common predecessor revision.
3518 the requested revision since the last common predecessor revision.
3517
3519
3518 Files that changed between either parent are marked as changed for
3520 Files that changed between either parent are marked as changed for
3519 the next commit and a commit must be performed before any further
3521 the next commit and a commit must be performed before any further
3520 updates to the repository are allowed. The next commit will have
3522 updates to the repository are allowed. The next commit will have
3521 two parents.
3523 two parents.
3522
3524
3523 ``--tool`` can be used to specify the merge tool used for file
3525 ``--tool`` can be used to specify the merge tool used for file
3524 merges. It overrides the HGMERGE environment variable and your
3526 merges. It overrides the HGMERGE environment variable and your
3525 configuration files. See :hg:`help merge-tools` for options.
3527 configuration files. See :hg:`help merge-tools` for options.
3526
3528
3527 If no revision is specified, the working directory's parent is a
3529 If no revision is specified, the working directory's parent is a
3528 head revision, and the current branch contains exactly one other
3530 head revision, and the current branch contains exactly one other
3529 head, the other head is merged with by default. Otherwise, an
3531 head, the other head is merged with by default. Otherwise, an
3530 explicit revision with which to merge with must be provided.
3532 explicit revision with which to merge with must be provided.
3531
3533
3532 See :hg:`help resolve` for information on handling file conflicts.
3534 See :hg:`help resolve` for information on handling file conflicts.
3533
3535
3534 To undo an uncommitted merge, use :hg:`update --clean .` which
3536 To undo an uncommitted merge, use :hg:`update --clean .` which
3535 will check out a clean copy of the original merge parent, losing
3537 will check out a clean copy of the original merge parent, losing
3536 all changes.
3538 all changes.
3537
3539
3538 Returns 0 on success, 1 if there are unresolved files.
3540 Returns 0 on success, 1 if there are unresolved files.
3539 """
3541 """
3540
3542
3541 opts = pycompat.byteskwargs(opts)
3543 opts = pycompat.byteskwargs(opts)
3542 if opts.get('rev') and node:
3544 if opts.get('rev') and node:
3543 raise error.Abort(_("please specify just one revision"))
3545 raise error.Abort(_("please specify just one revision"))
3544 if not node:
3546 if not node:
3545 node = opts.get('rev')
3547 node = opts.get('rev')
3546
3548
3547 if node:
3549 if node:
3548 node = scmutil.revsingle(repo, node).node()
3550 node = scmutil.revsingle(repo, node).node()
3549
3551
3550 if not node:
3552 if not node:
3551 node = repo[destutil.destmerge(repo)].node()
3553 node = repo[destutil.destmerge(repo)].node()
3552
3554
3553 if opts.get('preview'):
3555 if opts.get('preview'):
3554 # find nodes that are ancestors of p2 but not of p1
3556 # find nodes that are ancestors of p2 but not of p1
3555 p1 = repo.lookup('.')
3557 p1 = repo.lookup('.')
3556 p2 = repo.lookup(node)
3558 p2 = repo.lookup(node)
3557 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3559 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3558
3560
3559 displayer = cmdutil.show_changeset(ui, repo, opts)
3561 displayer = cmdutil.show_changeset(ui, repo, opts)
3560 for node in nodes:
3562 for node in nodes:
3561 displayer.show(repo[node])
3563 displayer.show(repo[node])
3562 displayer.close()
3564 displayer.close()
3563 return 0
3565 return 0
3564
3566
3565 try:
3567 try:
3566 # ui.forcemerge is an internal variable, do not document
3568 # ui.forcemerge is an internal variable, do not document
3567 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
3569 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
3568 force = opts.get('force')
3570 force = opts.get('force')
3569 labels = ['working copy', 'merge rev']
3571 labels = ['working copy', 'merge rev']
3570 return hg.merge(repo, node, force=force, mergeforce=force,
3572 return hg.merge(repo, node, force=force, mergeforce=force,
3571 labels=labels)
3573 labels=labels)
3572 finally:
3574 finally:
3573 ui.setconfig('ui', 'forcemerge', '', 'merge')
3575 ui.setconfig('ui', 'forcemerge', '', 'merge')
3574
3576
3575 @command('outgoing|out',
3577 @command('outgoing|out',
3576 [('f', 'force', None, _('run even when the destination is unrelated')),
3578 [('f', 'force', None, _('run even when the destination is unrelated')),
3577 ('r', 'rev', [],
3579 ('r', 'rev', [],
3578 _('a changeset intended to be included in the destination'), _('REV')),
3580 _('a changeset intended to be included in the destination'), _('REV')),
3579 ('n', 'newest-first', None, _('show newest record first')),
3581 ('n', 'newest-first', None, _('show newest record first')),
3580 ('B', 'bookmarks', False, _('compare bookmarks')),
3582 ('B', 'bookmarks', False, _('compare bookmarks')),
3581 ('b', 'branch', [], _('a specific branch you would like to push'),
3583 ('b', 'branch', [], _('a specific branch you would like to push'),
3582 _('BRANCH')),
3584 _('BRANCH')),
3583 ] + logopts + remoteopts + subrepoopts,
3585 ] + logopts + remoteopts + subrepoopts,
3584 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3586 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3585 def outgoing(ui, repo, dest=None, **opts):
3587 def outgoing(ui, repo, dest=None, **opts):
3586 """show changesets not found in the destination
3588 """show changesets not found in the destination
3587
3589
3588 Show changesets not found in the specified destination repository
3590 Show changesets not found in the specified destination repository
3589 or the default push location. These are the changesets that would
3591 or the default push location. These are the changesets that would
3590 be pushed if a push was requested.
3592 be pushed if a push was requested.
3591
3593
3592 See pull for details of valid destination formats.
3594 See pull for details of valid destination formats.
3593
3595
3594 .. container:: verbose
3596 .. container:: verbose
3595
3597
3596 With -B/--bookmarks, the result of bookmark comparison between
3598 With -B/--bookmarks, the result of bookmark comparison between
3597 local and remote repositories is displayed. With -v/--verbose,
3599 local and remote repositories is displayed. With -v/--verbose,
3598 status is also displayed for each bookmark like below::
3600 status is also displayed for each bookmark like below::
3599
3601
3600 BM1 01234567890a added
3602 BM1 01234567890a added
3601 BM2 deleted
3603 BM2 deleted
3602 BM3 234567890abc advanced
3604 BM3 234567890abc advanced
3603 BM4 34567890abcd diverged
3605 BM4 34567890abcd diverged
3604 BM5 4567890abcde changed
3606 BM5 4567890abcde changed
3605
3607
3606 The action taken when pushing depends on the
3608 The action taken when pushing depends on the
3607 status of each bookmark:
3609 status of each bookmark:
3608
3610
3609 :``added``: push with ``-B`` will create it
3611 :``added``: push with ``-B`` will create it
3610 :``deleted``: push with ``-B`` will delete it
3612 :``deleted``: push with ``-B`` will delete it
3611 :``advanced``: push will update it
3613 :``advanced``: push will update it
3612 :``diverged``: push with ``-B`` will update it
3614 :``diverged``: push with ``-B`` will update it
3613 :``changed``: push with ``-B`` will update it
3615 :``changed``: push with ``-B`` will update it
3614
3616
3615 From the point of view of pushing behavior, bookmarks
3617 From the point of view of pushing behavior, bookmarks
3616 existing only in the remote repository are treated as
3618 existing only in the remote repository are treated as
3617 ``deleted``, even if it is in fact added remotely.
3619 ``deleted``, even if it is in fact added remotely.
3618
3620
3619 Returns 0 if there are outgoing changes, 1 otherwise.
3621 Returns 0 if there are outgoing changes, 1 otherwise.
3620 """
3622 """
3621 opts = pycompat.byteskwargs(opts)
3623 opts = pycompat.byteskwargs(opts)
3622 if opts.get('graph'):
3624 if opts.get('graph'):
3623 cmdutil.checkunsupportedgraphflags([], opts)
3625 cmdutil.checkunsupportedgraphflags([], opts)
3624 o, other = hg._outgoing(ui, repo, dest, opts)
3626 o, other = hg._outgoing(ui, repo, dest, opts)
3625 if not o:
3627 if not o:
3626 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3628 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3627 return
3629 return
3628
3630
3629 revdag = cmdutil.graphrevs(repo, o, opts)
3631 revdag = cmdutil.graphrevs(repo, o, opts)
3630 ui.pager('outgoing')
3632 ui.pager('outgoing')
3631 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
3633 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
3632 cmdutil.displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges)
3634 cmdutil.displaygraph(ui, repo, revdag, displayer, graphmod.asciiedges)
3633 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3635 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3634 return 0
3636 return 0
3635
3637
3636 if opts.get('bookmarks'):
3638 if opts.get('bookmarks'):
3637 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3639 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3638 dest, branches = hg.parseurl(dest, opts.get('branch'))
3640 dest, branches = hg.parseurl(dest, opts.get('branch'))
3639 other = hg.peer(repo, opts, dest)
3641 other = hg.peer(repo, opts, dest)
3640 if 'bookmarks' not in other.listkeys('namespaces'):
3642 if 'bookmarks' not in other.listkeys('namespaces'):
3641 ui.warn(_("remote doesn't support bookmarks\n"))
3643 ui.warn(_("remote doesn't support bookmarks\n"))
3642 return 0
3644 return 0
3643 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3645 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3644 ui.pager('outgoing')
3646 ui.pager('outgoing')
3645 return bookmarks.outgoing(ui, repo, other)
3647 return bookmarks.outgoing(ui, repo, other)
3646
3648
3647 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3649 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3648 try:
3650 try:
3649 return hg.outgoing(ui, repo, dest, opts)
3651 return hg.outgoing(ui, repo, dest, opts)
3650 finally:
3652 finally:
3651 del repo._subtoppath
3653 del repo._subtoppath
3652
3654
3653 @command('parents',
3655 @command('parents',
3654 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3656 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3655 ] + templateopts,
3657 ] + templateopts,
3656 _('[-r REV] [FILE]'),
3658 _('[-r REV] [FILE]'),
3657 inferrepo=True)
3659 inferrepo=True)
3658 def parents(ui, repo, file_=None, **opts):
3660 def parents(ui, repo, file_=None, **opts):
3659 """show the parents of the working directory or revision (DEPRECATED)
3661 """show the parents of the working directory or revision (DEPRECATED)
3660
3662
3661 Print the working directory's parent revisions. If a revision is
3663 Print the working directory's parent revisions. If a revision is
3662 given via -r/--rev, the parent of that revision will be printed.
3664 given via -r/--rev, the parent of that revision will be printed.
3663 If a file argument is given, the revision in which the file was
3665 If a file argument is given, the revision in which the file was
3664 last changed (before the working directory revision or the
3666 last changed (before the working directory revision or the
3665 argument to --rev if given) is printed.
3667 argument to --rev if given) is printed.
3666
3668
3667 This command is equivalent to::
3669 This command is equivalent to::
3668
3670
3669 hg log -r "p1()+p2()" or
3671 hg log -r "p1()+p2()" or
3670 hg log -r "p1(REV)+p2(REV)" or
3672 hg log -r "p1(REV)+p2(REV)" or
3671 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
3673 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
3672 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
3674 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
3673
3675
3674 See :hg:`summary` and :hg:`help revsets` for related information.
3676 See :hg:`summary` and :hg:`help revsets` for related information.
3675
3677
3676 Returns 0 on success.
3678 Returns 0 on success.
3677 """
3679 """
3678
3680
3679 opts = pycompat.byteskwargs(opts)
3681 opts = pycompat.byteskwargs(opts)
3680 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3682 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3681
3683
3682 if file_:
3684 if file_:
3683 m = scmutil.match(ctx, (file_,), opts)
3685 m = scmutil.match(ctx, (file_,), opts)
3684 if m.anypats() or len(m.files()) != 1:
3686 if m.anypats() or len(m.files()) != 1:
3685 raise error.Abort(_('can only specify an explicit filename'))
3687 raise error.Abort(_('can only specify an explicit filename'))
3686 file_ = m.files()[0]
3688 file_ = m.files()[0]
3687 filenodes = []
3689 filenodes = []
3688 for cp in ctx.parents():
3690 for cp in ctx.parents():
3689 if not cp:
3691 if not cp:
3690 continue
3692 continue
3691 try:
3693 try:
3692 filenodes.append(cp.filenode(file_))
3694 filenodes.append(cp.filenode(file_))
3693 except error.LookupError:
3695 except error.LookupError:
3694 pass
3696 pass
3695 if not filenodes:
3697 if not filenodes:
3696 raise error.Abort(_("'%s' not found in manifest!") % file_)
3698 raise error.Abort(_("'%s' not found in manifest!") % file_)
3697 p = []
3699 p = []
3698 for fn in filenodes:
3700 for fn in filenodes:
3699 fctx = repo.filectx(file_, fileid=fn)
3701 fctx = repo.filectx(file_, fileid=fn)
3700 p.append(fctx.node())
3702 p.append(fctx.node())
3701 else:
3703 else:
3702 p = [cp.node() for cp in ctx.parents()]
3704 p = [cp.node() for cp in ctx.parents()]
3703
3705
3704 displayer = cmdutil.show_changeset(ui, repo, opts)
3706 displayer = cmdutil.show_changeset(ui, repo, opts)
3705 for n in p:
3707 for n in p:
3706 if n != nullid:
3708 if n != nullid:
3707 displayer.show(repo[n])
3709 displayer.show(repo[n])
3708 displayer.close()
3710 displayer.close()
3709
3711
3710 @command('paths', formatteropts, _('[NAME]'), optionalrepo=True)
3712 @command('paths', formatteropts, _('[NAME]'), optionalrepo=True)
3711 def paths(ui, repo, search=None, **opts):
3713 def paths(ui, repo, search=None, **opts):
3712 """show aliases for remote repositories
3714 """show aliases for remote repositories
3713
3715
3714 Show definition of symbolic path name NAME. If no name is given,
3716 Show definition of symbolic path name NAME. If no name is given,
3715 show definition of all available names.
3717 show definition of all available names.
3716
3718
3717 Option -q/--quiet suppresses all output when searching for NAME
3719 Option -q/--quiet suppresses all output when searching for NAME
3718 and shows only the path names when listing all definitions.
3720 and shows only the path names when listing all definitions.
3719
3721
3720 Path names are defined in the [paths] section of your
3722 Path names are defined in the [paths] section of your
3721 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3723 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3722 repository, ``.hg/hgrc`` is used, too.
3724 repository, ``.hg/hgrc`` is used, too.
3723
3725
3724 The path names ``default`` and ``default-push`` have a special
3726 The path names ``default`` and ``default-push`` have a special
3725 meaning. When performing a push or pull operation, they are used
3727 meaning. When performing a push or pull operation, they are used
3726 as fallbacks if no location is specified on the command-line.
3728 as fallbacks if no location is specified on the command-line.
3727 When ``default-push`` is set, it will be used for push and
3729 When ``default-push`` is set, it will be used for push and
3728 ``default`` will be used for pull; otherwise ``default`` is used
3730 ``default`` will be used for pull; otherwise ``default`` is used
3729 as the fallback for both. When cloning a repository, the clone
3731 as the fallback for both. When cloning a repository, the clone
3730 source is written as ``default`` in ``.hg/hgrc``.
3732 source is written as ``default`` in ``.hg/hgrc``.
3731
3733
3732 .. note::
3734 .. note::
3733
3735
3734 ``default`` and ``default-push`` apply to all inbound (e.g.
3736 ``default`` and ``default-push`` apply to all inbound (e.g.
3735 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
3737 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
3736 and :hg:`bundle`) operations.
3738 and :hg:`bundle`) operations.
3737
3739
3738 See :hg:`help urls` for more information.
3740 See :hg:`help urls` for more information.
3739
3741
3740 Returns 0 on success.
3742 Returns 0 on success.
3741 """
3743 """
3742
3744
3743 opts = pycompat.byteskwargs(opts)
3745 opts = pycompat.byteskwargs(opts)
3744 ui.pager('paths')
3746 ui.pager('paths')
3745 if search:
3747 if search:
3746 pathitems = [(name, path) for name, path in ui.paths.iteritems()
3748 pathitems = [(name, path) for name, path in ui.paths.iteritems()
3747 if name == search]
3749 if name == search]
3748 else:
3750 else:
3749 pathitems = sorted(ui.paths.iteritems())
3751 pathitems = sorted(ui.paths.iteritems())
3750
3752
3751 fm = ui.formatter('paths', opts)
3753 fm = ui.formatter('paths', opts)
3752 if fm.isplain():
3754 if fm.isplain():
3753 hidepassword = util.hidepassword
3755 hidepassword = util.hidepassword
3754 else:
3756 else:
3755 hidepassword = str
3757 hidepassword = str
3756 if ui.quiet:
3758 if ui.quiet:
3757 namefmt = '%s\n'
3759 namefmt = '%s\n'
3758 else:
3760 else:
3759 namefmt = '%s = '
3761 namefmt = '%s = '
3760 showsubopts = not search and not ui.quiet
3762 showsubopts = not search and not ui.quiet
3761
3763
3762 for name, path in pathitems:
3764 for name, path in pathitems:
3763 fm.startitem()
3765 fm.startitem()
3764 fm.condwrite(not search, 'name', namefmt, name)
3766 fm.condwrite(not search, 'name', namefmt, name)
3765 fm.condwrite(not ui.quiet, 'url', '%s\n', hidepassword(path.rawloc))
3767 fm.condwrite(not ui.quiet, 'url', '%s\n', hidepassword(path.rawloc))
3766 for subopt, value in sorted(path.suboptions.items()):
3768 for subopt, value in sorted(path.suboptions.items()):
3767 assert subopt not in ('name', 'url')
3769 assert subopt not in ('name', 'url')
3768 if showsubopts:
3770 if showsubopts:
3769 fm.plain('%s:%s = ' % (name, subopt))
3771 fm.plain('%s:%s = ' % (name, subopt))
3770 fm.condwrite(showsubopts, subopt, '%s\n', value)
3772 fm.condwrite(showsubopts, subopt, '%s\n', value)
3771
3773
3772 fm.end()
3774 fm.end()
3773
3775
3774 if search and not pathitems:
3776 if search and not pathitems:
3775 if not ui.quiet:
3777 if not ui.quiet:
3776 ui.warn(_("not found!\n"))
3778 ui.warn(_("not found!\n"))
3777 return 1
3779 return 1
3778 else:
3780 else:
3779 return 0
3781 return 0
3780
3782
3781 @command('phase',
3783 @command('phase',
3782 [('p', 'public', False, _('set changeset phase to public')),
3784 [('p', 'public', False, _('set changeset phase to public')),
3783 ('d', 'draft', False, _('set changeset phase to draft')),
3785 ('d', 'draft', False, _('set changeset phase to draft')),
3784 ('s', 'secret', False, _('set changeset phase to secret')),
3786 ('s', 'secret', False, _('set changeset phase to secret')),
3785 ('f', 'force', False, _('allow to move boundary backward')),
3787 ('f', 'force', False, _('allow to move boundary backward')),
3786 ('r', 'rev', [], _('target revision'), _('REV')),
3788 ('r', 'rev', [], _('target revision'), _('REV')),
3787 ],
3789 ],
3788 _('[-p|-d|-s] [-f] [-r] [REV...]'))
3790 _('[-p|-d|-s] [-f] [-r] [REV...]'))
3789 def phase(ui, repo, *revs, **opts):
3791 def phase(ui, repo, *revs, **opts):
3790 """set or show the current phase name
3792 """set or show the current phase name
3791
3793
3792 With no argument, show the phase name of the current revision(s).
3794 With no argument, show the phase name of the current revision(s).
3793
3795
3794 With one of -p/--public, -d/--draft or -s/--secret, change the
3796 With one of -p/--public, -d/--draft or -s/--secret, change the
3795 phase value of the specified revisions.
3797 phase value of the specified revisions.
3796
3798
3797 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
3799 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
3798 lower phase to an higher phase. Phases are ordered as follows::
3800 lower phase to an higher phase. Phases are ordered as follows::
3799
3801
3800 public < draft < secret
3802 public < draft < secret
3801
3803
3802 Returns 0 on success, 1 if some phases could not be changed.
3804 Returns 0 on success, 1 if some phases could not be changed.
3803
3805
3804 (For more information about the phases concept, see :hg:`help phases`.)
3806 (For more information about the phases concept, see :hg:`help phases`.)
3805 """
3807 """
3806 opts = pycompat.byteskwargs(opts)
3808 opts = pycompat.byteskwargs(opts)
3807 # search for a unique phase argument
3809 # search for a unique phase argument
3808 targetphase = None
3810 targetphase = None
3809 for idx, name in enumerate(phases.phasenames):
3811 for idx, name in enumerate(phases.phasenames):
3810 if opts[name]:
3812 if opts[name]:
3811 if targetphase is not None:
3813 if targetphase is not None:
3812 raise error.Abort(_('only one phase can be specified'))
3814 raise error.Abort(_('only one phase can be specified'))
3813 targetphase = idx
3815 targetphase = idx
3814
3816
3815 # look for specified revision
3817 # look for specified revision
3816 revs = list(revs)
3818 revs = list(revs)
3817 revs.extend(opts['rev'])
3819 revs.extend(opts['rev'])
3818 if not revs:
3820 if not revs:
3819 # display both parents as the second parent phase can influence
3821 # display both parents as the second parent phase can influence
3820 # the phase of a merge commit
3822 # the phase of a merge commit
3821 revs = [c.rev() for c in repo[None].parents()]
3823 revs = [c.rev() for c in repo[None].parents()]
3822
3824
3823 revs = scmutil.revrange(repo, revs)
3825 revs = scmutil.revrange(repo, revs)
3824
3826
3825 lock = None
3827 lock = None
3826 ret = 0
3828 ret = 0
3827 if targetphase is None:
3829 if targetphase is None:
3828 # display
3830 # display
3829 for r in revs:
3831 for r in revs:
3830 ctx = repo[r]
3832 ctx = repo[r]
3831 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
3833 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
3832 else:
3834 else:
3833 tr = None
3835 tr = None
3834 lock = repo.lock()
3836 lock = repo.lock()
3835 try:
3837 try:
3836 tr = repo.transaction("phase")
3838 tr = repo.transaction("phase")
3837 # set phase
3839 # set phase
3838 if not revs:
3840 if not revs:
3839 raise error.Abort(_('empty revision set'))
3841 raise error.Abort(_('empty revision set'))
3840 nodes = [repo[r].node() for r in revs]
3842 nodes = [repo[r].node() for r in revs]
3841 # moving revision from public to draft may hide them
3843 # moving revision from public to draft may hide them
3842 # We have to check result on an unfiltered repository
3844 # We have to check result on an unfiltered repository
3843 unfi = repo.unfiltered()
3845 unfi = repo.unfiltered()
3844 getphase = unfi._phasecache.phase
3846 getphase = unfi._phasecache.phase
3845 olddata = [getphase(unfi, r) for r in unfi]
3847 olddata = [getphase(unfi, r) for r in unfi]
3846 phases.advanceboundary(repo, tr, targetphase, nodes)
3848 phases.advanceboundary(repo, tr, targetphase, nodes)
3847 if opts['force']:
3849 if opts['force']:
3848 phases.retractboundary(repo, tr, targetphase, nodes)
3850 phases.retractboundary(repo, tr, targetphase, nodes)
3849 tr.close()
3851 tr.close()
3850 finally:
3852 finally:
3851 if tr is not None:
3853 if tr is not None:
3852 tr.release()
3854 tr.release()
3853 lock.release()
3855 lock.release()
3854 getphase = unfi._phasecache.phase
3856 getphase = unfi._phasecache.phase
3855 newdata = [getphase(unfi, r) for r in unfi]
3857 newdata = [getphase(unfi, r) for r in unfi]
3856 changes = sum(newdata[r] != olddata[r] for r in unfi)
3858 changes = sum(newdata[r] != olddata[r] for r in unfi)
3857 cl = unfi.changelog
3859 cl = unfi.changelog
3858 rejected = [n for n in nodes
3860 rejected = [n for n in nodes
3859 if newdata[cl.rev(n)] < targetphase]
3861 if newdata[cl.rev(n)] < targetphase]
3860 if rejected:
3862 if rejected:
3861 ui.warn(_('cannot move %i changesets to a higher '
3863 ui.warn(_('cannot move %i changesets to a higher '
3862 'phase, use --force\n') % len(rejected))
3864 'phase, use --force\n') % len(rejected))
3863 ret = 1
3865 ret = 1
3864 if changes:
3866 if changes:
3865 msg = _('phase changed for %i changesets\n') % changes
3867 msg = _('phase changed for %i changesets\n') % changes
3866 if ret:
3868 if ret:
3867 ui.status(msg)
3869 ui.status(msg)
3868 else:
3870 else:
3869 ui.note(msg)
3871 ui.note(msg)
3870 else:
3872 else:
3871 ui.warn(_('no phases changed\n'))
3873 ui.warn(_('no phases changed\n'))
3872 return ret
3874 return ret
3873
3875
3874 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
3876 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
3875 """Run after a changegroup has been added via pull/unbundle
3877 """Run after a changegroup has been added via pull/unbundle
3876
3878
3877 This takes arguments below:
3879 This takes arguments below:
3878
3880
3879 :modheads: change of heads by pull/unbundle
3881 :modheads: change of heads by pull/unbundle
3880 :optupdate: updating working directory is needed or not
3882 :optupdate: updating working directory is needed or not
3881 :checkout: update destination revision (or None to default destination)
3883 :checkout: update destination revision (or None to default destination)
3882 :brev: a name, which might be a bookmark to be activated after updating
3884 :brev: a name, which might be a bookmark to be activated after updating
3883 """
3885 """
3884 if modheads == 0:
3886 if modheads == 0:
3885 return
3887 return
3886 if optupdate:
3888 if optupdate:
3887 try:
3889 try:
3888 return hg.updatetotally(ui, repo, checkout, brev)
3890 return hg.updatetotally(ui, repo, checkout, brev)
3889 except error.UpdateAbort as inst:
3891 except error.UpdateAbort as inst:
3890 msg = _("not updating: %s") % str(inst)
3892 msg = _("not updating: %s") % str(inst)
3891 hint = inst.hint
3893 hint = inst.hint
3892 raise error.UpdateAbort(msg, hint=hint)
3894 raise error.UpdateAbort(msg, hint=hint)
3893 if modheads > 1:
3895 if modheads > 1:
3894 currentbranchheads = len(repo.branchheads())
3896 currentbranchheads = len(repo.branchheads())
3895 if currentbranchheads == modheads:
3897 if currentbranchheads == modheads:
3896 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3898 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3897 elif currentbranchheads > 1:
3899 elif currentbranchheads > 1:
3898 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
3900 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
3899 "merge)\n"))
3901 "merge)\n"))
3900 else:
3902 else:
3901 ui.status(_("(run 'hg heads' to see heads)\n"))
3903 ui.status(_("(run 'hg heads' to see heads)\n"))
3902 else:
3904 else:
3903 ui.status(_("(run 'hg update' to get a working copy)\n"))
3905 ui.status(_("(run 'hg update' to get a working copy)\n"))
3904
3906
3905 @command('^pull',
3907 @command('^pull',
3906 [('u', 'update', None,
3908 [('u', 'update', None,
3907 _('update to new branch head if changesets were pulled')),
3909 _('update to new branch head if changesets were pulled')),
3908 ('f', 'force', None, _('run even when remote repository is unrelated')),
3910 ('f', 'force', None, _('run even when remote repository is unrelated')),
3909 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3911 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3910 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3912 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3911 ('b', 'branch', [], _('a specific branch you would like to pull'),
3913 ('b', 'branch', [], _('a specific branch you would like to pull'),
3912 _('BRANCH')),
3914 _('BRANCH')),
3913 ] + remoteopts,
3915 ] + remoteopts,
3914 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3916 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3915 def pull(ui, repo, source="default", **opts):
3917 def pull(ui, repo, source="default", **opts):
3916 """pull changes from the specified source
3918 """pull changes from the specified source
3917
3919
3918 Pull changes from a remote repository to a local one.
3920 Pull changes from a remote repository to a local one.
3919
3921
3920 This finds all changes from the repository at the specified path
3922 This finds all changes from the repository at the specified path
3921 or URL and adds them to a local repository (the current one unless
3923 or URL and adds them to a local repository (the current one unless
3922 -R is specified). By default, this does not update the copy of the
3924 -R is specified). By default, this does not update the copy of the
3923 project in the working directory.
3925 project in the working directory.
3924
3926
3925 Use :hg:`incoming` if you want to see what would have been added
3927 Use :hg:`incoming` if you want to see what would have been added
3926 by a pull at the time you issued this command. If you then decide
3928 by a pull at the time you issued this command. If you then decide
3927 to add those changes to the repository, you should use :hg:`pull
3929 to add those changes to the repository, you should use :hg:`pull
3928 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3930 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3929
3931
3930 If SOURCE is omitted, the 'default' path will be used.
3932 If SOURCE is omitted, the 'default' path will be used.
3931 See :hg:`help urls` for more information.
3933 See :hg:`help urls` for more information.
3932
3934
3933 Specifying bookmark as ``.`` is equivalent to specifying the active
3935 Specifying bookmark as ``.`` is equivalent to specifying the active
3934 bookmark's name.
3936 bookmark's name.
3935
3937
3936 Returns 0 on success, 1 if an update had unresolved files.
3938 Returns 0 on success, 1 if an update had unresolved files.
3937 """
3939 """
3938
3940
3939 opts = pycompat.byteskwargs(opts)
3941 opts = pycompat.byteskwargs(opts)
3940 if ui.configbool('commands', 'update.requiredest') and opts.get('update'):
3942 if ui.configbool('commands', 'update.requiredest') and opts.get('update'):
3941 msg = _('update destination required by configuration')
3943 msg = _('update destination required by configuration')
3942 hint = _('use hg pull followed by hg update DEST')
3944 hint = _('use hg pull followed by hg update DEST')
3943 raise error.Abort(msg, hint=hint)
3945 raise error.Abort(msg, hint=hint)
3944
3946
3945 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3947 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3946 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3948 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3947 other = hg.peer(repo, opts, source)
3949 other = hg.peer(repo, opts, source)
3948 try:
3950 try:
3949 revs, checkout = hg.addbranchrevs(repo, other, branches,
3951 revs, checkout = hg.addbranchrevs(repo, other, branches,
3950 opts.get('rev'))
3952 opts.get('rev'))
3951
3953
3952
3954
3953 pullopargs = {}
3955 pullopargs = {}
3954 if opts.get('bookmark'):
3956 if opts.get('bookmark'):
3955 if not revs:
3957 if not revs:
3956 revs = []
3958 revs = []
3957 # The list of bookmark used here is not the one used to actually
3959 # The list of bookmark used here is not the one used to actually
3958 # update the bookmark name. This can result in the revision pulled
3960 # update the bookmark name. This can result in the revision pulled
3959 # not ending up with the name of the bookmark because of a race
3961 # not ending up with the name of the bookmark because of a race
3960 # condition on the server. (See issue 4689 for details)
3962 # condition on the server. (See issue 4689 for details)
3961 remotebookmarks = other.listkeys('bookmarks')
3963 remotebookmarks = other.listkeys('bookmarks')
3962 pullopargs['remotebookmarks'] = remotebookmarks
3964 pullopargs['remotebookmarks'] = remotebookmarks
3963 for b in opts['bookmark']:
3965 for b in opts['bookmark']:
3964 b = repo._bookmarks.expandname(b)
3966 b = repo._bookmarks.expandname(b)
3965 if b not in remotebookmarks:
3967 if b not in remotebookmarks:
3966 raise error.Abort(_('remote bookmark %s not found!') % b)
3968 raise error.Abort(_('remote bookmark %s not found!') % b)
3967 revs.append(remotebookmarks[b])
3969 revs.append(remotebookmarks[b])
3968
3970
3969 if revs:
3971 if revs:
3970 try:
3972 try:
3971 # When 'rev' is a bookmark name, we cannot guarantee that it
3973 # When 'rev' is a bookmark name, we cannot guarantee that it
3972 # will be updated with that name because of a race condition
3974 # will be updated with that name because of a race condition
3973 # server side. (See issue 4689 for details)
3975 # server side. (See issue 4689 for details)
3974 oldrevs = revs
3976 oldrevs = revs
3975 revs = [] # actually, nodes
3977 revs = [] # actually, nodes
3976 for r in oldrevs:
3978 for r in oldrevs:
3977 node = other.lookup(r)
3979 node = other.lookup(r)
3978 revs.append(node)
3980 revs.append(node)
3979 if r == checkout:
3981 if r == checkout:
3980 checkout = node
3982 checkout = node
3981 except error.CapabilityError:
3983 except error.CapabilityError:
3982 err = _("other repository doesn't support revision lookup, "
3984 err = _("other repository doesn't support revision lookup, "
3983 "so a rev cannot be specified.")
3985 "so a rev cannot be specified.")
3984 raise error.Abort(err)
3986 raise error.Abort(err)
3985
3987
3986 pullopargs.update(opts.get('opargs', {}))
3988 pullopargs.update(opts.get('opargs', {}))
3987 modheads = exchange.pull(repo, other, heads=revs,
3989 modheads = exchange.pull(repo, other, heads=revs,
3988 force=opts.get('force'),
3990 force=opts.get('force'),
3989 bookmarks=opts.get('bookmark', ()),
3991 bookmarks=opts.get('bookmark', ()),
3990 opargs=pullopargs).cgresult
3992 opargs=pullopargs).cgresult
3991
3993
3992 # brev is a name, which might be a bookmark to be activated at
3994 # brev is a name, which might be a bookmark to be activated at
3993 # the end of the update. In other words, it is an explicit
3995 # the end of the update. In other words, it is an explicit
3994 # destination of the update
3996 # destination of the update
3995 brev = None
3997 brev = None
3996
3998
3997 if checkout:
3999 if checkout:
3998 checkout = str(repo.changelog.rev(checkout))
4000 checkout = str(repo.changelog.rev(checkout))
3999
4001
4000 # order below depends on implementation of
4002 # order below depends on implementation of
4001 # hg.addbranchrevs(). opts['bookmark'] is ignored,
4003 # hg.addbranchrevs(). opts['bookmark'] is ignored,
4002 # because 'checkout' is determined without it.
4004 # because 'checkout' is determined without it.
4003 if opts.get('rev'):
4005 if opts.get('rev'):
4004 brev = opts['rev'][0]
4006 brev = opts['rev'][0]
4005 elif opts.get('branch'):
4007 elif opts.get('branch'):
4006 brev = opts['branch'][0]
4008 brev = opts['branch'][0]
4007 else:
4009 else:
4008 brev = branches[0]
4010 brev = branches[0]
4009 repo._subtoppath = source
4011 repo._subtoppath = source
4010 try:
4012 try:
4011 ret = postincoming(ui, repo, modheads, opts.get('update'),
4013 ret = postincoming(ui, repo, modheads, opts.get('update'),
4012 checkout, brev)
4014 checkout, brev)
4013
4015
4014 finally:
4016 finally:
4015 del repo._subtoppath
4017 del repo._subtoppath
4016
4018
4017 finally:
4019 finally:
4018 other.close()
4020 other.close()
4019 return ret
4021 return ret
4020
4022
4021 @command('^push',
4023 @command('^push',
4022 [('f', 'force', None, _('force push')),
4024 [('f', 'force', None, _('force push')),
4023 ('r', 'rev', [],
4025 ('r', 'rev', [],
4024 _('a changeset intended to be included in the destination'),
4026 _('a changeset intended to be included in the destination'),
4025 _('REV')),
4027 _('REV')),
4026 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4028 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4027 ('b', 'branch', [],
4029 ('b', 'branch', [],
4028 _('a specific branch you would like to push'), _('BRANCH')),
4030 _('a specific branch you would like to push'), _('BRANCH')),
4029 ('', 'new-branch', False, _('allow pushing a new branch')),
4031 ('', 'new-branch', False, _('allow pushing a new branch')),
4030 ] + remoteopts,
4032 ] + remoteopts,
4031 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4033 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4032 def push(ui, repo, dest=None, **opts):
4034 def push(ui, repo, dest=None, **opts):
4033 """push changes to the specified destination
4035 """push changes to the specified destination
4034
4036
4035 Push changesets from the local repository to the specified
4037 Push changesets from the local repository to the specified
4036 destination.
4038 destination.
4037
4039
4038 This operation is symmetrical to pull: it is identical to a pull
4040 This operation is symmetrical to pull: it is identical to a pull
4039 in the destination repository from the current one.
4041 in the destination repository from the current one.
4040
4042
4041 By default, push will not allow creation of new heads at the
4043 By default, push will not allow creation of new heads at the
4042 destination, since multiple heads would make it unclear which head
4044 destination, since multiple heads would make it unclear which head
4043 to use. In this situation, it is recommended to pull and merge
4045 to use. In this situation, it is recommended to pull and merge
4044 before pushing.
4046 before pushing.
4045
4047
4046 Use --new-branch if you want to allow push to create a new named
4048 Use --new-branch if you want to allow push to create a new named
4047 branch that is not present at the destination. This allows you to
4049 branch that is not present at the destination. This allows you to
4048 only create a new branch without forcing other changes.
4050 only create a new branch without forcing other changes.
4049
4051
4050 .. note::
4052 .. note::
4051
4053
4052 Extra care should be taken with the -f/--force option,
4054 Extra care should be taken with the -f/--force option,
4053 which will push all new heads on all branches, an action which will
4055 which will push all new heads on all branches, an action which will
4054 almost always cause confusion for collaborators.
4056 almost always cause confusion for collaborators.
4055
4057
4056 If -r/--rev is used, the specified revision and all its ancestors
4058 If -r/--rev is used, the specified revision and all its ancestors
4057 will be pushed to the remote repository.
4059 will be pushed to the remote repository.
4058
4060
4059 If -B/--bookmark is used, the specified bookmarked revision, its
4061 If -B/--bookmark is used, the specified bookmarked revision, its
4060 ancestors, and the bookmark will be pushed to the remote
4062 ancestors, and the bookmark will be pushed to the remote
4061 repository. Specifying ``.`` is equivalent to specifying the active
4063 repository. Specifying ``.`` is equivalent to specifying the active
4062 bookmark's name.
4064 bookmark's name.
4063
4065
4064 Please see :hg:`help urls` for important details about ``ssh://``
4066 Please see :hg:`help urls` for important details about ``ssh://``
4065 URLs. If DESTINATION is omitted, a default path will be used.
4067 URLs. If DESTINATION is omitted, a default path will be used.
4066
4068
4067 Returns 0 if push was successful, 1 if nothing to push.
4069 Returns 0 if push was successful, 1 if nothing to push.
4068 """
4070 """
4069
4071
4070 opts = pycompat.byteskwargs(opts)
4072 opts = pycompat.byteskwargs(opts)
4071 if opts.get('bookmark'):
4073 if opts.get('bookmark'):
4072 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4074 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4073 for b in opts['bookmark']:
4075 for b in opts['bookmark']:
4074 # translate -B options to -r so changesets get pushed
4076 # translate -B options to -r so changesets get pushed
4075 b = repo._bookmarks.expandname(b)
4077 b = repo._bookmarks.expandname(b)
4076 if b in repo._bookmarks:
4078 if b in repo._bookmarks:
4077 opts.setdefault('rev', []).append(b)
4079 opts.setdefault('rev', []).append(b)
4078 else:
4080 else:
4079 # if we try to push a deleted bookmark, translate it to null
4081 # if we try to push a deleted bookmark, translate it to null
4080 # this lets simultaneous -r, -b options continue working
4082 # this lets simultaneous -r, -b options continue working
4081 opts.setdefault('rev', []).append("null")
4083 opts.setdefault('rev', []).append("null")
4082
4084
4083 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4085 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4084 if not path:
4086 if not path:
4085 raise error.Abort(_('default repository not configured!'),
4087 raise error.Abort(_('default repository not configured!'),
4086 hint=_("see 'hg help config.paths'"))
4088 hint=_("see 'hg help config.paths'"))
4087 dest = path.pushloc or path.loc
4089 dest = path.pushloc or path.loc
4088 branches = (path.branch, opts.get('branch') or [])
4090 branches = (path.branch, opts.get('branch') or [])
4089 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4091 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4090 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4092 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4091 other = hg.peer(repo, opts, dest)
4093 other = hg.peer(repo, opts, dest)
4092
4094
4093 if revs:
4095 if revs:
4094 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4096 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4095 if not revs:
4097 if not revs:
4096 raise error.Abort(_("specified revisions evaluate to an empty set"),
4098 raise error.Abort(_("specified revisions evaluate to an empty set"),
4097 hint=_("use different revision arguments"))
4099 hint=_("use different revision arguments"))
4098 elif path.pushrev:
4100 elif path.pushrev:
4099 # It doesn't make any sense to specify ancestor revisions. So limit
4101 # It doesn't make any sense to specify ancestor revisions. So limit
4100 # to DAG heads to make discovery simpler.
4102 # to DAG heads to make discovery simpler.
4101 expr = revsetlang.formatspec('heads(%r)', path.pushrev)
4103 expr = revsetlang.formatspec('heads(%r)', path.pushrev)
4102 revs = scmutil.revrange(repo, [expr])
4104 revs = scmutil.revrange(repo, [expr])
4103 revs = [repo[rev].node() for rev in revs]
4105 revs = [repo[rev].node() for rev in revs]
4104 if not revs:
4106 if not revs:
4105 raise error.Abort(_('default push revset for path evaluates to an '
4107 raise error.Abort(_('default push revset for path evaluates to an '
4106 'empty set'))
4108 'empty set'))
4107
4109
4108 repo._subtoppath = dest
4110 repo._subtoppath = dest
4109 try:
4111 try:
4110 # push subrepos depth-first for coherent ordering
4112 # push subrepos depth-first for coherent ordering
4111 c = repo['']
4113 c = repo['']
4112 subs = c.substate # only repos that are committed
4114 subs = c.substate # only repos that are committed
4113 for s in sorted(subs):
4115 for s in sorted(subs):
4114 result = c.sub(s).push(opts)
4116 result = c.sub(s).push(opts)
4115 if result == 0:
4117 if result == 0:
4116 return not result
4118 return not result
4117 finally:
4119 finally:
4118 del repo._subtoppath
4120 del repo._subtoppath
4119 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
4121 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
4120 newbranch=opts.get('new_branch'),
4122 newbranch=opts.get('new_branch'),
4121 bookmarks=opts.get('bookmark', ()),
4123 bookmarks=opts.get('bookmark', ()),
4122 opargs=opts.get('opargs'))
4124 opargs=opts.get('opargs'))
4123
4125
4124 result = not pushop.cgresult
4126 result = not pushop.cgresult
4125
4127
4126 if pushop.bkresult is not None:
4128 if pushop.bkresult is not None:
4127 if pushop.bkresult == 2:
4129 if pushop.bkresult == 2:
4128 result = 2
4130 result = 2
4129 elif not result and pushop.bkresult:
4131 elif not result and pushop.bkresult:
4130 result = 2
4132 result = 2
4131
4133
4132 return result
4134 return result
4133
4135
4134 @command('recover', [])
4136 @command('recover', [])
4135 def recover(ui, repo):
4137 def recover(ui, repo):
4136 """roll back an interrupted transaction
4138 """roll back an interrupted transaction
4137
4139
4138 Recover from an interrupted commit or pull.
4140 Recover from an interrupted commit or pull.
4139
4141
4140 This command tries to fix the repository status after an
4142 This command tries to fix the repository status after an
4141 interrupted operation. It should only be necessary when Mercurial
4143 interrupted operation. It should only be necessary when Mercurial
4142 suggests it.
4144 suggests it.
4143
4145
4144 Returns 0 if successful, 1 if nothing to recover or verify fails.
4146 Returns 0 if successful, 1 if nothing to recover or verify fails.
4145 """
4147 """
4146 if repo.recover():
4148 if repo.recover():
4147 return hg.verify(repo)
4149 return hg.verify(repo)
4148 return 1
4150 return 1
4149
4151
4150 @command('^remove|rm',
4152 @command('^remove|rm',
4151 [('A', 'after', None, _('record delete for missing files')),
4153 [('A', 'after', None, _('record delete for missing files')),
4152 ('f', 'force', None,
4154 ('f', 'force', None,
4153 _('forget added files, delete modified files')),
4155 _('forget added files, delete modified files')),
4154 ] + subrepoopts + walkopts,
4156 ] + subrepoopts + walkopts,
4155 _('[OPTION]... FILE...'),
4157 _('[OPTION]... FILE...'),
4156 inferrepo=True)
4158 inferrepo=True)
4157 def remove(ui, repo, *pats, **opts):
4159 def remove(ui, repo, *pats, **opts):
4158 """remove the specified files on the next commit
4160 """remove the specified files on the next commit
4159
4161
4160 Schedule the indicated files for removal from the current branch.
4162 Schedule the indicated files for removal from the current branch.
4161
4163
4162 This command schedules the files to be removed at the next commit.
4164 This command schedules the files to be removed at the next commit.
4163 To undo a remove before that, see :hg:`revert`. To undo added
4165 To undo a remove before that, see :hg:`revert`. To undo added
4164 files, see :hg:`forget`.
4166 files, see :hg:`forget`.
4165
4167
4166 .. container:: verbose
4168 .. container:: verbose
4167
4169
4168 -A/--after can be used to remove only files that have already
4170 -A/--after can be used to remove only files that have already
4169 been deleted, -f/--force can be used to force deletion, and -Af
4171 been deleted, -f/--force can be used to force deletion, and -Af
4170 can be used to remove files from the next revision without
4172 can be used to remove files from the next revision without
4171 deleting them from the working directory.
4173 deleting them from the working directory.
4172
4174
4173 The following table details the behavior of remove for different
4175 The following table details the behavior of remove for different
4174 file states (columns) and option combinations (rows). The file
4176 file states (columns) and option combinations (rows). The file
4175 states are Added [A], Clean [C], Modified [M] and Missing [!]
4177 states are Added [A], Clean [C], Modified [M] and Missing [!]
4176 (as reported by :hg:`status`). The actions are Warn, Remove
4178 (as reported by :hg:`status`). The actions are Warn, Remove
4177 (from branch) and Delete (from disk):
4179 (from branch) and Delete (from disk):
4178
4180
4179 ========= == == == ==
4181 ========= == == == ==
4180 opt/state A C M !
4182 opt/state A C M !
4181 ========= == == == ==
4183 ========= == == == ==
4182 none W RD W R
4184 none W RD W R
4183 -f R RD RD R
4185 -f R RD RD R
4184 -A W W W R
4186 -A W W W R
4185 -Af R R R R
4187 -Af R R R R
4186 ========= == == == ==
4188 ========= == == == ==
4187
4189
4188 .. note::
4190 .. note::
4189
4191
4190 :hg:`remove` never deletes files in Added [A] state from the
4192 :hg:`remove` never deletes files in Added [A] state from the
4191 working directory, not even if ``--force`` is specified.
4193 working directory, not even if ``--force`` is specified.
4192
4194
4193 Returns 0 on success, 1 if any warnings encountered.
4195 Returns 0 on success, 1 if any warnings encountered.
4194 """
4196 """
4195
4197
4196 opts = pycompat.byteskwargs(opts)
4198 opts = pycompat.byteskwargs(opts)
4197 after, force = opts.get('after'), opts.get('force')
4199 after, force = opts.get('after'), opts.get('force')
4198 if not pats and not after:
4200 if not pats and not after:
4199 raise error.Abort(_('no files specified'))
4201 raise error.Abort(_('no files specified'))
4200
4202
4201 m = scmutil.match(repo[None], pats, opts)
4203 m = scmutil.match(repo[None], pats, opts)
4202 subrepos = opts.get('subrepos')
4204 subrepos = opts.get('subrepos')
4203 return cmdutil.remove(ui, repo, m, "", after, force, subrepos)
4205 return cmdutil.remove(ui, repo, m, "", after, force, subrepos)
4204
4206
4205 @command('rename|move|mv',
4207 @command('rename|move|mv',
4206 [('A', 'after', None, _('record a rename that has already occurred')),
4208 [('A', 'after', None, _('record a rename that has already occurred')),
4207 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4209 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4208 ] + walkopts + dryrunopts,
4210 ] + walkopts + dryrunopts,
4209 _('[OPTION]... SOURCE... DEST'))
4211 _('[OPTION]... SOURCE... DEST'))
4210 def rename(ui, repo, *pats, **opts):
4212 def rename(ui, repo, *pats, **opts):
4211 """rename files; equivalent of copy + remove
4213 """rename files; equivalent of copy + remove
4212
4214
4213 Mark dest as copies of sources; mark sources for deletion. If dest
4215 Mark dest as copies of sources; mark sources for deletion. If dest
4214 is a directory, copies are put in that directory. If dest is a
4216 is a directory, copies are put in that directory. If dest is a
4215 file, there can only be one source.
4217 file, there can only be one source.
4216
4218
4217 By default, this command copies the contents of files as they
4219 By default, this command copies the contents of files as they
4218 exist in the working directory. If invoked with -A/--after, the
4220 exist in the working directory. If invoked with -A/--after, the
4219 operation is recorded, but no copying is performed.
4221 operation is recorded, but no copying is performed.
4220
4222
4221 This command takes effect at the next commit. To undo a rename
4223 This command takes effect at the next commit. To undo a rename
4222 before that, see :hg:`revert`.
4224 before that, see :hg:`revert`.
4223
4225
4224 Returns 0 on success, 1 if errors are encountered.
4226 Returns 0 on success, 1 if errors are encountered.
4225 """
4227 """
4226 opts = pycompat.byteskwargs(opts)
4228 opts = pycompat.byteskwargs(opts)
4227 with repo.wlock(False):
4229 with repo.wlock(False):
4228 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4230 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4229
4231
4230 @command('resolve',
4232 @command('resolve',
4231 [('a', 'all', None, _('select all unresolved files')),
4233 [('a', 'all', None, _('select all unresolved files')),
4232 ('l', 'list', None, _('list state of files needing merge')),
4234 ('l', 'list', None, _('list state of files needing merge')),
4233 ('m', 'mark', None, _('mark files as resolved')),
4235 ('m', 'mark', None, _('mark files as resolved')),
4234 ('u', 'unmark', None, _('mark files as unresolved')),
4236 ('u', 'unmark', None, _('mark files as unresolved')),
4235 ('n', 'no-status', None, _('hide status prefix'))]
4237 ('n', 'no-status', None, _('hide status prefix'))]
4236 + mergetoolopts + walkopts + formatteropts,
4238 + mergetoolopts + walkopts + formatteropts,
4237 _('[OPTION]... [FILE]...'),
4239 _('[OPTION]... [FILE]...'),
4238 inferrepo=True)
4240 inferrepo=True)
4239 def resolve(ui, repo, *pats, **opts):
4241 def resolve(ui, repo, *pats, **opts):
4240 """redo merges or set/view the merge status of files
4242 """redo merges or set/view the merge status of files
4241
4243
4242 Merges with unresolved conflicts are often the result of
4244 Merges with unresolved conflicts are often the result of
4243 non-interactive merging using the ``internal:merge`` configuration
4245 non-interactive merging using the ``internal:merge`` configuration
4244 setting, or a command-line merge tool like ``diff3``. The resolve
4246 setting, or a command-line merge tool like ``diff3``. The resolve
4245 command is used to manage the files involved in a merge, after
4247 command is used to manage the files involved in a merge, after
4246 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4248 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4247 working directory must have two parents). See :hg:`help
4249 working directory must have two parents). See :hg:`help
4248 merge-tools` for information on configuring merge tools.
4250 merge-tools` for information on configuring merge tools.
4249
4251
4250 The resolve command can be used in the following ways:
4252 The resolve command can be used in the following ways:
4251
4253
4252 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4254 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4253 files, discarding any previous merge attempts. Re-merging is not
4255 files, discarding any previous merge attempts. Re-merging is not
4254 performed for files already marked as resolved. Use ``--all/-a``
4256 performed for files already marked as resolved. Use ``--all/-a``
4255 to select all unresolved files. ``--tool`` can be used to specify
4257 to select all unresolved files. ``--tool`` can be used to specify
4256 the merge tool used for the given files. It overrides the HGMERGE
4258 the merge tool used for the given files. It overrides the HGMERGE
4257 environment variable and your configuration files. Previous file
4259 environment variable and your configuration files. Previous file
4258 contents are saved with a ``.orig`` suffix.
4260 contents are saved with a ``.orig`` suffix.
4259
4261
4260 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4262 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4261 (e.g. after having manually fixed-up the files). The default is
4263 (e.g. after having manually fixed-up the files). The default is
4262 to mark all unresolved files.
4264 to mark all unresolved files.
4263
4265
4264 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4266 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4265 default is to mark all resolved files.
4267 default is to mark all resolved files.
4266
4268
4267 - :hg:`resolve -l`: list files which had or still have conflicts.
4269 - :hg:`resolve -l`: list files which had or still have conflicts.
4268 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4270 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4269 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
4271 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
4270 the list. See :hg:`help filesets` for details.
4272 the list. See :hg:`help filesets` for details.
4271
4273
4272 .. note::
4274 .. note::
4273
4275
4274 Mercurial will not let you commit files with unresolved merge
4276 Mercurial will not let you commit files with unresolved merge
4275 conflicts. You must use :hg:`resolve -m ...` before you can
4277 conflicts. You must use :hg:`resolve -m ...` before you can
4276 commit after a conflicting merge.
4278 commit after a conflicting merge.
4277
4279
4278 Returns 0 on success, 1 if any files fail a resolve attempt.
4280 Returns 0 on success, 1 if any files fail a resolve attempt.
4279 """
4281 """
4280
4282
4281 opts = pycompat.byteskwargs(opts)
4283 opts = pycompat.byteskwargs(opts)
4282 flaglist = 'all mark unmark list no_status'.split()
4284 flaglist = 'all mark unmark list no_status'.split()
4283 all, mark, unmark, show, nostatus = \
4285 all, mark, unmark, show, nostatus = \
4284 [opts.get(o) for o in flaglist]
4286 [opts.get(o) for o in flaglist]
4285
4287
4286 if (show and (mark or unmark)) or (mark and unmark):
4288 if (show and (mark or unmark)) or (mark and unmark):
4287 raise error.Abort(_("too many options specified"))
4289 raise error.Abort(_("too many options specified"))
4288 if pats and all:
4290 if pats and all:
4289 raise error.Abort(_("can't specify --all and patterns"))
4291 raise error.Abort(_("can't specify --all and patterns"))
4290 if not (all or pats or show or mark or unmark):
4292 if not (all or pats or show or mark or unmark):
4291 raise error.Abort(_('no files or directories specified'),
4293 raise error.Abort(_('no files or directories specified'),
4292 hint=('use --all to re-merge all unresolved files'))
4294 hint=('use --all to re-merge all unresolved files'))
4293
4295
4294 if show:
4296 if show:
4295 ui.pager('resolve')
4297 ui.pager('resolve')
4296 fm = ui.formatter('resolve', opts)
4298 fm = ui.formatter('resolve', opts)
4297 ms = mergemod.mergestate.read(repo)
4299 ms = mergemod.mergestate.read(repo)
4298 m = scmutil.match(repo[None], pats, opts)
4300 m = scmutil.match(repo[None], pats, opts)
4299 for f in ms:
4301 for f in ms:
4300 if not m(f):
4302 if not m(f):
4301 continue
4303 continue
4302 l = 'resolve.' + {'u': 'unresolved', 'r': 'resolved',
4304 l = 'resolve.' + {'u': 'unresolved', 'r': 'resolved',
4303 'd': 'driverresolved'}[ms[f]]
4305 'd': 'driverresolved'}[ms[f]]
4304 fm.startitem()
4306 fm.startitem()
4305 fm.condwrite(not nostatus, 'status', '%s ', ms[f].upper(), label=l)
4307 fm.condwrite(not nostatus, 'status', '%s ', ms[f].upper(), label=l)
4306 fm.write('path', '%s\n', f, label=l)
4308 fm.write('path', '%s\n', f, label=l)
4307 fm.end()
4309 fm.end()
4308 return 0
4310 return 0
4309
4311
4310 with repo.wlock():
4312 with repo.wlock():
4311 ms = mergemod.mergestate.read(repo)
4313 ms = mergemod.mergestate.read(repo)
4312
4314
4313 if not (ms.active() or repo.dirstate.p2() != nullid):
4315 if not (ms.active() or repo.dirstate.p2() != nullid):
4314 raise error.Abort(
4316 raise error.Abort(
4315 _('resolve command not applicable when not merging'))
4317 _('resolve command not applicable when not merging'))
4316
4318
4317 wctx = repo[None]
4319 wctx = repo[None]
4318
4320
4319 if ms.mergedriver and ms.mdstate() == 'u':
4321 if ms.mergedriver and ms.mdstate() == 'u':
4320 proceed = mergemod.driverpreprocess(repo, ms, wctx)
4322 proceed = mergemod.driverpreprocess(repo, ms, wctx)
4321 ms.commit()
4323 ms.commit()
4322 # allow mark and unmark to go through
4324 # allow mark and unmark to go through
4323 if not mark and not unmark and not proceed:
4325 if not mark and not unmark and not proceed:
4324 return 1
4326 return 1
4325
4327
4326 m = scmutil.match(wctx, pats, opts)
4328 m = scmutil.match(wctx, pats, opts)
4327 ret = 0
4329 ret = 0
4328 didwork = False
4330 didwork = False
4329 runconclude = False
4331 runconclude = False
4330
4332
4331 tocomplete = []
4333 tocomplete = []
4332 for f in ms:
4334 for f in ms:
4333 if not m(f):
4335 if not m(f):
4334 continue
4336 continue
4335
4337
4336 didwork = True
4338 didwork = True
4337
4339
4338 # don't let driver-resolved files be marked, and run the conclude
4340 # don't let driver-resolved files be marked, and run the conclude
4339 # step if asked to resolve
4341 # step if asked to resolve
4340 if ms[f] == "d":
4342 if ms[f] == "d":
4341 exact = m.exact(f)
4343 exact = m.exact(f)
4342 if mark:
4344 if mark:
4343 if exact:
4345 if exact:
4344 ui.warn(_('not marking %s as it is driver-resolved\n')
4346 ui.warn(_('not marking %s as it is driver-resolved\n')
4345 % f)
4347 % f)
4346 elif unmark:
4348 elif unmark:
4347 if exact:
4349 if exact:
4348 ui.warn(_('not unmarking %s as it is driver-resolved\n')
4350 ui.warn(_('not unmarking %s as it is driver-resolved\n')
4349 % f)
4351 % f)
4350 else:
4352 else:
4351 runconclude = True
4353 runconclude = True
4352 continue
4354 continue
4353
4355
4354 if mark:
4356 if mark:
4355 ms.mark(f, "r")
4357 ms.mark(f, "r")
4356 elif unmark:
4358 elif unmark:
4357 ms.mark(f, "u")
4359 ms.mark(f, "u")
4358 else:
4360 else:
4359 # backup pre-resolve (merge uses .orig for its own purposes)
4361 # backup pre-resolve (merge uses .orig for its own purposes)
4360 a = repo.wjoin(f)
4362 a = repo.wjoin(f)
4361 try:
4363 try:
4362 util.copyfile(a, a + ".resolve")
4364 util.copyfile(a, a + ".resolve")
4363 except (IOError, OSError) as inst:
4365 except (IOError, OSError) as inst:
4364 if inst.errno != errno.ENOENT:
4366 if inst.errno != errno.ENOENT:
4365 raise
4367 raise
4366
4368
4367 try:
4369 try:
4368 # preresolve file
4370 # preresolve file
4369 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4371 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4370 'resolve')
4372 'resolve')
4371 complete, r = ms.preresolve(f, wctx)
4373 complete, r = ms.preresolve(f, wctx)
4372 if not complete:
4374 if not complete:
4373 tocomplete.append(f)
4375 tocomplete.append(f)
4374 elif r:
4376 elif r:
4375 ret = 1
4377 ret = 1
4376 finally:
4378 finally:
4377 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4379 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4378 ms.commit()
4380 ms.commit()
4379
4381
4380 # replace filemerge's .orig file with our resolve file, but only
4382 # replace filemerge's .orig file with our resolve file, but only
4381 # for merges that are complete
4383 # for merges that are complete
4382 if complete:
4384 if complete:
4383 try:
4385 try:
4384 util.rename(a + ".resolve",
4386 util.rename(a + ".resolve",
4385 scmutil.origpath(ui, repo, a))
4387 scmutil.origpath(ui, repo, a))
4386 except OSError as inst:
4388 except OSError as inst:
4387 if inst.errno != errno.ENOENT:
4389 if inst.errno != errno.ENOENT:
4388 raise
4390 raise
4389
4391
4390 for f in tocomplete:
4392 for f in tocomplete:
4391 try:
4393 try:
4392 # resolve file
4394 # resolve file
4393 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4395 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4394 'resolve')
4396 'resolve')
4395 r = ms.resolve(f, wctx)
4397 r = ms.resolve(f, wctx)
4396 if r:
4398 if r:
4397 ret = 1
4399 ret = 1
4398 finally:
4400 finally:
4399 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4401 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4400 ms.commit()
4402 ms.commit()
4401
4403
4402 # replace filemerge's .orig file with our resolve file
4404 # replace filemerge's .orig file with our resolve file
4403 a = repo.wjoin(f)
4405 a = repo.wjoin(f)
4404 try:
4406 try:
4405 util.rename(a + ".resolve", scmutil.origpath(ui, repo, a))
4407 util.rename(a + ".resolve", scmutil.origpath(ui, repo, a))
4406 except OSError as inst:
4408 except OSError as inst:
4407 if inst.errno != errno.ENOENT:
4409 if inst.errno != errno.ENOENT:
4408 raise
4410 raise
4409
4411
4410 ms.commit()
4412 ms.commit()
4411 ms.recordactions()
4413 ms.recordactions()
4412
4414
4413 if not didwork and pats:
4415 if not didwork and pats:
4414 hint = None
4416 hint = None
4415 if not any([p for p in pats if p.find(':') >= 0]):
4417 if not any([p for p in pats if p.find(':') >= 0]):
4416 pats = ['path:%s' % p for p in pats]
4418 pats = ['path:%s' % p for p in pats]
4417 m = scmutil.match(wctx, pats, opts)
4419 m = scmutil.match(wctx, pats, opts)
4418 for f in ms:
4420 for f in ms:
4419 if not m(f):
4421 if not m(f):
4420 continue
4422 continue
4421 flags = ''.join(['-%s ' % o[0] for o in flaglist
4423 flags = ''.join(['-%s ' % o[0] for o in flaglist
4422 if opts.get(o)])
4424 if opts.get(o)])
4423 hint = _("(try: hg resolve %s%s)\n") % (
4425 hint = _("(try: hg resolve %s%s)\n") % (
4424 flags,
4426 flags,
4425 ' '.join(pats))
4427 ' '.join(pats))
4426 break
4428 break
4427 ui.warn(_("arguments do not match paths that need resolving\n"))
4429 ui.warn(_("arguments do not match paths that need resolving\n"))
4428 if hint:
4430 if hint:
4429 ui.warn(hint)
4431 ui.warn(hint)
4430 elif ms.mergedriver and ms.mdstate() != 's':
4432 elif ms.mergedriver and ms.mdstate() != 's':
4431 # run conclude step when either a driver-resolved file is requested
4433 # run conclude step when either a driver-resolved file is requested
4432 # or there are no driver-resolved files
4434 # or there are no driver-resolved files
4433 # we can't use 'ret' to determine whether any files are unresolved
4435 # we can't use 'ret' to determine whether any files are unresolved
4434 # because we might not have tried to resolve some
4436 # because we might not have tried to resolve some
4435 if ((runconclude or not list(ms.driverresolved()))
4437 if ((runconclude or not list(ms.driverresolved()))
4436 and not list(ms.unresolved())):
4438 and not list(ms.unresolved())):
4437 proceed = mergemod.driverconclude(repo, ms, wctx)
4439 proceed = mergemod.driverconclude(repo, ms, wctx)
4438 ms.commit()
4440 ms.commit()
4439 if not proceed:
4441 if not proceed:
4440 return 1
4442 return 1
4441
4443
4442 # Nudge users into finishing an unfinished operation
4444 # Nudge users into finishing an unfinished operation
4443 unresolvedf = list(ms.unresolved())
4445 unresolvedf = list(ms.unresolved())
4444 driverresolvedf = list(ms.driverresolved())
4446 driverresolvedf = list(ms.driverresolved())
4445 if not unresolvedf and not driverresolvedf:
4447 if not unresolvedf and not driverresolvedf:
4446 ui.status(_('(no more unresolved files)\n'))
4448 ui.status(_('(no more unresolved files)\n'))
4447 cmdutil.checkafterresolved(repo)
4449 cmdutil.checkafterresolved(repo)
4448 elif not unresolvedf:
4450 elif not unresolvedf:
4449 ui.status(_('(no more unresolved files -- '
4451 ui.status(_('(no more unresolved files -- '
4450 'run "hg resolve --all" to conclude)\n'))
4452 'run "hg resolve --all" to conclude)\n'))
4451
4453
4452 return ret
4454 return ret
4453
4455
4454 @command('revert',
4456 @command('revert',
4455 [('a', 'all', None, _('revert all changes when no arguments given')),
4457 [('a', 'all', None, _('revert all changes when no arguments given')),
4456 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4458 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4457 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4459 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4458 ('C', 'no-backup', None, _('do not save backup copies of files')),
4460 ('C', 'no-backup', None, _('do not save backup copies of files')),
4459 ('i', 'interactive', None,
4461 ('i', 'interactive', None,
4460 _('interactively select the changes (EXPERIMENTAL)')),
4462 _('interactively select the changes (EXPERIMENTAL)')),
4461 ] + walkopts + dryrunopts,
4463 ] + walkopts + dryrunopts,
4462 _('[OPTION]... [-r REV] [NAME]...'))
4464 _('[OPTION]... [-r REV] [NAME]...'))
4463 def revert(ui, repo, *pats, **opts):
4465 def revert(ui, repo, *pats, **opts):
4464 """restore files to their checkout state
4466 """restore files to their checkout state
4465
4467
4466 .. note::
4468 .. note::
4467
4469
4468 To check out earlier revisions, you should use :hg:`update REV`.
4470 To check out earlier revisions, you should use :hg:`update REV`.
4469 To cancel an uncommitted merge (and lose your changes),
4471 To cancel an uncommitted merge (and lose your changes),
4470 use :hg:`update --clean .`.
4472 use :hg:`update --clean .`.
4471
4473
4472 With no revision specified, revert the specified files or directories
4474 With no revision specified, revert the specified files or directories
4473 to the contents they had in the parent of the working directory.
4475 to the contents they had in the parent of the working directory.
4474 This restores the contents of files to an unmodified
4476 This restores the contents of files to an unmodified
4475 state and unschedules adds, removes, copies, and renames. If the
4477 state and unschedules adds, removes, copies, and renames. If the
4476 working directory has two parents, you must explicitly specify a
4478 working directory has two parents, you must explicitly specify a
4477 revision.
4479 revision.
4478
4480
4479 Using the -r/--rev or -d/--date options, revert the given files or
4481 Using the -r/--rev or -d/--date options, revert the given files or
4480 directories to their states as of a specific revision. Because
4482 directories to their states as of a specific revision. Because
4481 revert does not change the working directory parents, this will
4483 revert does not change the working directory parents, this will
4482 cause these files to appear modified. This can be helpful to "back
4484 cause these files to appear modified. This can be helpful to "back
4483 out" some or all of an earlier change. See :hg:`backout` for a
4485 out" some or all of an earlier change. See :hg:`backout` for a
4484 related method.
4486 related method.
4485
4487
4486 Modified files are saved with a .orig suffix before reverting.
4488 Modified files are saved with a .orig suffix before reverting.
4487 To disable these backups, use --no-backup. It is possible to store
4489 To disable these backups, use --no-backup. It is possible to store
4488 the backup files in a custom directory relative to the root of the
4490 the backup files in a custom directory relative to the root of the
4489 repository by setting the ``ui.origbackuppath`` configuration
4491 repository by setting the ``ui.origbackuppath`` configuration
4490 option.
4492 option.
4491
4493
4492 See :hg:`help dates` for a list of formats valid for -d/--date.
4494 See :hg:`help dates` for a list of formats valid for -d/--date.
4493
4495
4494 See :hg:`help backout` for a way to reverse the effect of an
4496 See :hg:`help backout` for a way to reverse the effect of an
4495 earlier changeset.
4497 earlier changeset.
4496
4498
4497 Returns 0 on success.
4499 Returns 0 on success.
4498 """
4500 """
4499
4501
4500 if opts.get("date"):
4502 if opts.get("date"):
4501 if opts.get("rev"):
4503 if opts.get("rev"):
4502 raise error.Abort(_("you can't specify a revision and a date"))
4504 raise error.Abort(_("you can't specify a revision and a date"))
4503 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4505 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4504
4506
4505 parent, p2 = repo.dirstate.parents()
4507 parent, p2 = repo.dirstate.parents()
4506 if not opts.get('rev') and p2 != nullid:
4508 if not opts.get('rev') and p2 != nullid:
4507 # revert after merge is a trap for new users (issue2915)
4509 # revert after merge is a trap for new users (issue2915)
4508 raise error.Abort(_('uncommitted merge with no revision specified'),
4510 raise error.Abort(_('uncommitted merge with no revision specified'),
4509 hint=_("use 'hg update' or see 'hg help revert'"))
4511 hint=_("use 'hg update' or see 'hg help revert'"))
4510
4512
4511 ctx = scmutil.revsingle(repo, opts.get('rev'))
4513 ctx = scmutil.revsingle(repo, opts.get('rev'))
4512
4514
4513 if (not (pats or opts.get('include') or opts.get('exclude') or
4515 if (not (pats or opts.get('include') or opts.get('exclude') or
4514 opts.get('all') or opts.get('interactive'))):
4516 opts.get('all') or opts.get('interactive'))):
4515 msg = _("no files or directories specified")
4517 msg = _("no files or directories specified")
4516 if p2 != nullid:
4518 if p2 != nullid:
4517 hint = _("uncommitted merge, use --all to discard all changes,"
4519 hint = _("uncommitted merge, use --all to discard all changes,"
4518 " or 'hg update -C .' to abort the merge")
4520 " or 'hg update -C .' to abort the merge")
4519 raise error.Abort(msg, hint=hint)
4521 raise error.Abort(msg, hint=hint)
4520 dirty = any(repo.status())
4522 dirty = any(repo.status())
4521 node = ctx.node()
4523 node = ctx.node()
4522 if node != parent:
4524 if node != parent:
4523 if dirty:
4525 if dirty:
4524 hint = _("uncommitted changes, use --all to discard all"
4526 hint = _("uncommitted changes, use --all to discard all"
4525 " changes, or 'hg update %s' to update") % ctx.rev()
4527 " changes, or 'hg update %s' to update") % ctx.rev()
4526 else:
4528 else:
4527 hint = _("use --all to revert all files,"
4529 hint = _("use --all to revert all files,"
4528 " or 'hg update %s' to update") % ctx.rev()
4530 " or 'hg update %s' to update") % ctx.rev()
4529 elif dirty:
4531 elif dirty:
4530 hint = _("uncommitted changes, use --all to discard all changes")
4532 hint = _("uncommitted changes, use --all to discard all changes")
4531 else:
4533 else:
4532 hint = _("use --all to revert all files")
4534 hint = _("use --all to revert all files")
4533 raise error.Abort(msg, hint=hint)
4535 raise error.Abort(msg, hint=hint)
4534
4536
4535 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
4537 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
4536
4538
4537 @command('rollback', dryrunopts +
4539 @command('rollback', dryrunopts +
4538 [('f', 'force', False, _('ignore safety measures'))])
4540 [('f', 'force', False, _('ignore safety measures'))])
4539 def rollback(ui, repo, **opts):
4541 def rollback(ui, repo, **opts):
4540 """roll back the last transaction (DANGEROUS) (DEPRECATED)
4542 """roll back the last transaction (DANGEROUS) (DEPRECATED)
4541
4543
4542 Please use :hg:`commit --amend` instead of rollback to correct
4544 Please use :hg:`commit --amend` instead of rollback to correct
4543 mistakes in the last commit.
4545 mistakes in the last commit.
4544
4546
4545 This command should be used with care. There is only one level of
4547 This command should be used with care. There is only one level of
4546 rollback, and there is no way to undo a rollback. It will also
4548 rollback, and there is no way to undo a rollback. It will also
4547 restore the dirstate at the time of the last transaction, losing
4549 restore the dirstate at the time of the last transaction, losing
4548 any dirstate changes since that time. This command does not alter
4550 any dirstate changes since that time. This command does not alter
4549 the working directory.
4551 the working directory.
4550
4552
4551 Transactions are used to encapsulate the effects of all commands
4553 Transactions are used to encapsulate the effects of all commands
4552 that create new changesets or propagate existing changesets into a
4554 that create new changesets or propagate existing changesets into a
4553 repository.
4555 repository.
4554
4556
4555 .. container:: verbose
4557 .. container:: verbose
4556
4558
4557 For example, the following commands are transactional, and their
4559 For example, the following commands are transactional, and their
4558 effects can be rolled back:
4560 effects can be rolled back:
4559
4561
4560 - commit
4562 - commit
4561 - import
4563 - import
4562 - pull
4564 - pull
4563 - push (with this repository as the destination)
4565 - push (with this repository as the destination)
4564 - unbundle
4566 - unbundle
4565
4567
4566 To avoid permanent data loss, rollback will refuse to rollback a
4568 To avoid permanent data loss, rollback will refuse to rollback a
4567 commit transaction if it isn't checked out. Use --force to
4569 commit transaction if it isn't checked out. Use --force to
4568 override this protection.
4570 override this protection.
4569
4571
4570 The rollback command can be entirely disabled by setting the
4572 The rollback command can be entirely disabled by setting the
4571 ``ui.rollback`` configuration setting to false. If you're here
4573 ``ui.rollback`` configuration setting to false. If you're here
4572 because you want to use rollback and it's disabled, you can
4574 because you want to use rollback and it's disabled, you can
4573 re-enable the command by setting ``ui.rollback`` to true.
4575 re-enable the command by setting ``ui.rollback`` to true.
4574
4576
4575 This command is not intended for use on public repositories. Once
4577 This command is not intended for use on public repositories. Once
4576 changes are visible for pull by other users, rolling a transaction
4578 changes are visible for pull by other users, rolling a transaction
4577 back locally is ineffective (someone else may already have pulled
4579 back locally is ineffective (someone else may already have pulled
4578 the changes). Furthermore, a race is possible with readers of the
4580 the changes). Furthermore, a race is possible with readers of the
4579 repository; for example an in-progress pull from the repository
4581 repository; for example an in-progress pull from the repository
4580 may fail if a rollback is performed.
4582 may fail if a rollback is performed.
4581
4583
4582 Returns 0 on success, 1 if no rollback data is available.
4584 Returns 0 on success, 1 if no rollback data is available.
4583 """
4585 """
4584 if not ui.configbool('ui', 'rollback', True):
4586 if not ui.configbool('ui', 'rollback', True):
4585 raise error.Abort(_('rollback is disabled because it is unsafe'),
4587 raise error.Abort(_('rollback is disabled because it is unsafe'),
4586 hint=('see `hg help -v rollback` for information'))
4588 hint=('see `hg help -v rollback` for information'))
4587 return repo.rollback(dryrun=opts.get(r'dry_run'),
4589 return repo.rollback(dryrun=opts.get(r'dry_run'),
4588 force=opts.get(r'force'))
4590 force=opts.get(r'force'))
4589
4591
4590 @command('root', [])
4592 @command('root', [])
4591 def root(ui, repo):
4593 def root(ui, repo):
4592 """print the root (top) of the current working directory
4594 """print the root (top) of the current working directory
4593
4595
4594 Print the root directory of the current repository.
4596 Print the root directory of the current repository.
4595
4597
4596 Returns 0 on success.
4598 Returns 0 on success.
4597 """
4599 """
4598 ui.write(repo.root + "\n")
4600 ui.write(repo.root + "\n")
4599
4601
4600 @command('^serve',
4602 @command('^serve',
4601 [('A', 'accesslog', '', _('name of access log file to write to'),
4603 [('A', 'accesslog', '', _('name of access log file to write to'),
4602 _('FILE')),
4604 _('FILE')),
4603 ('d', 'daemon', None, _('run server in background')),
4605 ('d', 'daemon', None, _('run server in background')),
4604 ('', 'daemon-postexec', [], _('used internally by daemon mode')),
4606 ('', 'daemon-postexec', [], _('used internally by daemon mode')),
4605 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4607 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4606 # use string type, then we can check if something was passed
4608 # use string type, then we can check if something was passed
4607 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4609 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4608 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4610 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4609 _('ADDR')),
4611 _('ADDR')),
4610 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4612 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4611 _('PREFIX')),
4613 _('PREFIX')),
4612 ('n', 'name', '',
4614 ('n', 'name', '',
4613 _('name to show in web pages (default: working directory)'), _('NAME')),
4615 _('name to show in web pages (default: working directory)'), _('NAME')),
4614 ('', 'web-conf', '',
4616 ('', 'web-conf', '',
4615 _("name of the hgweb config file (see 'hg help hgweb')"), _('FILE')),
4617 _("name of the hgweb config file (see 'hg help hgweb')"), _('FILE')),
4616 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4618 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4617 _('FILE')),
4619 _('FILE')),
4618 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4620 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4619 ('', 'stdio', None, _('for remote clients (ADVANCED)')),
4621 ('', 'stdio', None, _('for remote clients (ADVANCED)')),
4620 ('', 'cmdserver', '', _('for remote clients (ADVANCED)'), _('MODE')),
4622 ('', 'cmdserver', '', _('for remote clients (ADVANCED)'), _('MODE')),
4621 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4623 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4622 ('', 'style', '', _('template style to use'), _('STYLE')),
4624 ('', 'style', '', _('template style to use'), _('STYLE')),
4623 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4625 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4624 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))]
4626 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))]
4625 + subrepoopts,
4627 + subrepoopts,
4626 _('[OPTION]...'),
4628 _('[OPTION]...'),
4627 optionalrepo=True)
4629 optionalrepo=True)
4628 def serve(ui, repo, **opts):
4630 def serve(ui, repo, **opts):
4629 """start stand-alone webserver
4631 """start stand-alone webserver
4630
4632
4631 Start a local HTTP repository browser and pull server. You can use
4633 Start a local HTTP repository browser and pull server. You can use
4632 this for ad-hoc sharing and browsing of repositories. It is
4634 this for ad-hoc sharing and browsing of repositories. It is
4633 recommended to use a real web server to serve a repository for
4635 recommended to use a real web server to serve a repository for
4634 longer periods of time.
4636 longer periods of time.
4635
4637
4636 Please note that the server does not implement access control.
4638 Please note that the server does not implement access control.
4637 This means that, by default, anybody can read from the server and
4639 This means that, by default, anybody can read from the server and
4638 nobody can write to it by default. Set the ``web.allow_push``
4640 nobody can write to it by default. Set the ``web.allow_push``
4639 option to ``*`` to allow everybody to push to the server. You
4641 option to ``*`` to allow everybody to push to the server. You
4640 should use a real web server if you need to authenticate users.
4642 should use a real web server if you need to authenticate users.
4641
4643
4642 By default, the server logs accesses to stdout and errors to
4644 By default, the server logs accesses to stdout and errors to
4643 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4645 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4644 files.
4646 files.
4645
4647
4646 To have the server choose a free port number to listen on, specify
4648 To have the server choose a free port number to listen on, specify
4647 a port number of 0; in this case, the server will print the port
4649 a port number of 0; in this case, the server will print the port
4648 number it uses.
4650 number it uses.
4649
4651
4650 Returns 0 on success.
4652 Returns 0 on success.
4651 """
4653 """
4652
4654
4653 opts = pycompat.byteskwargs(opts)
4655 opts = pycompat.byteskwargs(opts)
4654 if opts["stdio"] and opts["cmdserver"]:
4656 if opts["stdio"] and opts["cmdserver"]:
4655 raise error.Abort(_("cannot use --stdio with --cmdserver"))
4657 raise error.Abort(_("cannot use --stdio with --cmdserver"))
4656
4658
4657 if opts["stdio"]:
4659 if opts["stdio"]:
4658 if repo is None:
4660 if repo is None:
4659 raise error.RepoError(_("there is no Mercurial repository here"
4661 raise error.RepoError(_("there is no Mercurial repository here"
4660 " (.hg not found)"))
4662 " (.hg not found)"))
4661 s = sshserver.sshserver(ui, repo)
4663 s = sshserver.sshserver(ui, repo)
4662 s.serve_forever()
4664 s.serve_forever()
4663
4665
4664 service = server.createservice(ui, repo, opts)
4666 service = server.createservice(ui, repo, opts)
4665 return server.runservice(opts, initfn=service.init, runfn=service.run)
4667 return server.runservice(opts, initfn=service.init, runfn=service.run)
4666
4668
4667 @command('^status|st',
4669 @command('^status|st',
4668 [('A', 'all', None, _('show status of all files')),
4670 [('A', 'all', None, _('show status of all files')),
4669 ('m', 'modified', None, _('show only modified files')),
4671 ('m', 'modified', None, _('show only modified files')),
4670 ('a', 'added', None, _('show only added files')),
4672 ('a', 'added', None, _('show only added files')),
4671 ('r', 'removed', None, _('show only removed files')),
4673 ('r', 'removed', None, _('show only removed files')),
4672 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4674 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4673 ('c', 'clean', None, _('show only files without changes')),
4675 ('c', 'clean', None, _('show only files without changes')),
4674 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4676 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4675 ('i', 'ignored', None, _('show only ignored files')),
4677 ('i', 'ignored', None, _('show only ignored files')),
4676 ('n', 'no-status', None, _('hide status prefix')),
4678 ('n', 'no-status', None, _('hide status prefix')),
4677 ('C', 'copies', None, _('show source of copied files')),
4679 ('C', 'copies', None, _('show source of copied files')),
4678 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4680 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4679 ('', 'rev', [], _('show difference from revision'), _('REV')),
4681 ('', 'rev', [], _('show difference from revision'), _('REV')),
4680 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4682 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4681 ] + walkopts + subrepoopts + formatteropts,
4683 ] + walkopts + subrepoopts + formatteropts,
4682 _('[OPTION]... [FILE]...'),
4684 _('[OPTION]... [FILE]...'),
4683 inferrepo=True)
4685 inferrepo=True)
4684 def status(ui, repo, *pats, **opts):
4686 def status(ui, repo, *pats, **opts):
4685 """show changed files in the working directory
4687 """show changed files in the working directory
4686
4688
4687 Show status of files in the repository. If names are given, only
4689 Show status of files in the repository. If names are given, only
4688 files that match are shown. Files that are clean or ignored or
4690 files that match are shown. Files that are clean or ignored or
4689 the source of a copy/move operation, are not listed unless
4691 the source of a copy/move operation, are not listed unless
4690 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4692 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4691 Unless options described with "show only ..." are given, the
4693 Unless options described with "show only ..." are given, the
4692 options -mardu are used.
4694 options -mardu are used.
4693
4695
4694 Option -q/--quiet hides untracked (unknown and ignored) files
4696 Option -q/--quiet hides untracked (unknown and ignored) files
4695 unless explicitly requested with -u/--unknown or -i/--ignored.
4697 unless explicitly requested with -u/--unknown or -i/--ignored.
4696
4698
4697 .. note::
4699 .. note::
4698
4700
4699 :hg:`status` may appear to disagree with diff if permissions have
4701 :hg:`status` may appear to disagree with diff if permissions have
4700 changed or a merge has occurred. The standard diff format does
4702 changed or a merge has occurred. The standard diff format does
4701 not report permission changes and diff only reports changes
4703 not report permission changes and diff only reports changes
4702 relative to one merge parent.
4704 relative to one merge parent.
4703
4705
4704 If one revision is given, it is used as the base revision.
4706 If one revision is given, it is used as the base revision.
4705 If two revisions are given, the differences between them are
4707 If two revisions are given, the differences between them are
4706 shown. The --change option can also be used as a shortcut to list
4708 shown. The --change option can also be used as a shortcut to list
4707 the changed files of a revision from its first parent.
4709 the changed files of a revision from its first parent.
4708
4710
4709 The codes used to show the status of files are::
4711 The codes used to show the status of files are::
4710
4712
4711 M = modified
4713 M = modified
4712 A = added
4714 A = added
4713 R = removed
4715 R = removed
4714 C = clean
4716 C = clean
4715 ! = missing (deleted by non-hg command, but still tracked)
4717 ! = missing (deleted by non-hg command, but still tracked)
4716 ? = not tracked
4718 ? = not tracked
4717 I = ignored
4719 I = ignored
4718 = origin of the previous file (with --copies)
4720 = origin of the previous file (with --copies)
4719
4721
4720 .. container:: verbose
4722 .. container:: verbose
4721
4723
4722 Examples:
4724 Examples:
4723
4725
4724 - show changes in the working directory relative to a
4726 - show changes in the working directory relative to a
4725 changeset::
4727 changeset::
4726
4728
4727 hg status --rev 9353
4729 hg status --rev 9353
4728
4730
4729 - show changes in the working directory relative to the
4731 - show changes in the working directory relative to the
4730 current directory (see :hg:`help patterns` for more information)::
4732 current directory (see :hg:`help patterns` for more information)::
4731
4733
4732 hg status re:
4734 hg status re:
4733
4735
4734 - show all changes including copies in an existing changeset::
4736 - show all changes including copies in an existing changeset::
4735
4737
4736 hg status --copies --change 9353
4738 hg status --copies --change 9353
4737
4739
4738 - get a NUL separated list of added files, suitable for xargs::
4740 - get a NUL separated list of added files, suitable for xargs::
4739
4741
4740 hg status -an0
4742 hg status -an0
4741
4743
4742 Returns 0 on success.
4744 Returns 0 on success.
4743 """
4745 """
4744
4746
4745 opts = pycompat.byteskwargs(opts)
4747 opts = pycompat.byteskwargs(opts)
4746 revs = opts.get('rev')
4748 revs = opts.get('rev')
4747 change = opts.get('change')
4749 change = opts.get('change')
4748
4750
4749 if revs and change:
4751 if revs and change:
4750 msg = _('cannot specify --rev and --change at the same time')
4752 msg = _('cannot specify --rev and --change at the same time')
4751 raise error.Abort(msg)
4753 raise error.Abort(msg)
4752 elif change:
4754 elif change:
4753 node2 = scmutil.revsingle(repo, change, None).node()
4755 node2 = scmutil.revsingle(repo, change, None).node()
4754 node1 = repo[node2].p1().node()
4756 node1 = repo[node2].p1().node()
4755 else:
4757 else:
4756 node1, node2 = scmutil.revpair(repo, revs)
4758 node1, node2 = scmutil.revpair(repo, revs)
4757
4759
4758 if pats or ui.configbool('commands', 'status.relative'):
4760 if pats or ui.configbool('commands', 'status.relative'):
4759 cwd = repo.getcwd()
4761 cwd = repo.getcwd()
4760 else:
4762 else:
4761 cwd = ''
4763 cwd = ''
4762
4764
4763 if opts.get('print0'):
4765 if opts.get('print0'):
4764 end = '\0'
4766 end = '\0'
4765 else:
4767 else:
4766 end = '\n'
4768 end = '\n'
4767 copy = {}
4769 copy = {}
4768 states = 'modified added removed deleted unknown ignored clean'.split()
4770 states = 'modified added removed deleted unknown ignored clean'.split()
4769 show = [k for k in states if opts.get(k)]
4771 show = [k for k in states if opts.get(k)]
4770 if opts.get('all'):
4772 if opts.get('all'):
4771 show += ui.quiet and (states[:4] + ['clean']) or states
4773 show += ui.quiet and (states[:4] + ['clean']) or states
4772 if not show:
4774 if not show:
4773 if ui.quiet:
4775 if ui.quiet:
4774 show = states[:4]
4776 show = states[:4]
4775 else:
4777 else:
4776 show = states[:5]
4778 show = states[:5]
4777
4779
4778 m = scmutil.match(repo[node2], pats, opts)
4780 m = scmutil.match(repo[node2], pats, opts)
4779 stat = repo.status(node1, node2, m,
4781 stat = repo.status(node1, node2, m,
4780 'ignored' in show, 'clean' in show, 'unknown' in show,
4782 'ignored' in show, 'clean' in show, 'unknown' in show,
4781 opts.get('subrepos'))
4783 opts.get('subrepos'))
4782 changestates = zip(states, pycompat.iterbytestr('MAR!?IC'), stat)
4784 changestates = zip(states, pycompat.iterbytestr('MAR!?IC'), stat)
4783
4785
4784 if (opts.get('all') or opts.get('copies')
4786 if (opts.get('all') or opts.get('copies')
4785 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
4787 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
4786 copy = copies.pathcopies(repo[node1], repo[node2], m)
4788 copy = copies.pathcopies(repo[node1], repo[node2], m)
4787
4789
4788 ui.pager('status')
4790 ui.pager('status')
4789 fm = ui.formatter('status', opts)
4791 fm = ui.formatter('status', opts)
4790 fmt = '%s' + end
4792 fmt = '%s' + end
4791 showchar = not opts.get('no_status')
4793 showchar = not opts.get('no_status')
4792
4794
4793 for state, char, files in changestates:
4795 for state, char, files in changestates:
4794 if state in show:
4796 if state in show:
4795 label = 'status.' + state
4797 label = 'status.' + state
4796 for f in files:
4798 for f in files:
4797 fm.startitem()
4799 fm.startitem()
4798 fm.condwrite(showchar, 'status', '%s ', char, label=label)
4800 fm.condwrite(showchar, 'status', '%s ', char, label=label)
4799 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
4801 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
4800 if f in copy:
4802 if f in copy:
4801 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
4803 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
4802 label='status.copied')
4804 label='status.copied')
4803 fm.end()
4805 fm.end()
4804
4806
4805 @command('^summary|sum',
4807 @command('^summary|sum',
4806 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4808 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4807 def summary(ui, repo, **opts):
4809 def summary(ui, repo, **opts):
4808 """summarize working directory state
4810 """summarize working directory state
4809
4811
4810 This generates a brief summary of the working directory state,
4812 This generates a brief summary of the working directory state,
4811 including parents, branch, commit status, phase and available updates.
4813 including parents, branch, commit status, phase and available updates.
4812
4814
4813 With the --remote option, this will check the default paths for
4815 With the --remote option, this will check the default paths for
4814 incoming and outgoing changes. This can be time-consuming.
4816 incoming and outgoing changes. This can be time-consuming.
4815
4817
4816 Returns 0 on success.
4818 Returns 0 on success.
4817 """
4819 """
4818
4820
4819 opts = pycompat.byteskwargs(opts)
4821 opts = pycompat.byteskwargs(opts)
4820 ui.pager('summary')
4822 ui.pager('summary')
4821 ctx = repo[None]
4823 ctx = repo[None]
4822 parents = ctx.parents()
4824 parents = ctx.parents()
4823 pnode = parents[0].node()
4825 pnode = parents[0].node()
4824 marks = []
4826 marks = []
4825
4827
4826 ms = None
4828 ms = None
4827 try:
4829 try:
4828 ms = mergemod.mergestate.read(repo)
4830 ms = mergemod.mergestate.read(repo)
4829 except error.UnsupportedMergeRecords as e:
4831 except error.UnsupportedMergeRecords as e:
4830 s = ' '.join(e.recordtypes)
4832 s = ' '.join(e.recordtypes)
4831 ui.warn(
4833 ui.warn(
4832 _('warning: merge state has unsupported record types: %s\n') % s)
4834 _('warning: merge state has unsupported record types: %s\n') % s)
4833 unresolved = 0
4835 unresolved = 0
4834 else:
4836 else:
4835 unresolved = [f for f in ms if ms[f] == 'u']
4837 unresolved = [f for f in ms if ms[f] == 'u']
4836
4838
4837 for p in parents:
4839 for p in parents:
4838 # label with log.changeset (instead of log.parent) since this
4840 # label with log.changeset (instead of log.parent) since this
4839 # shows a working directory parent *changeset*:
4841 # shows a working directory parent *changeset*:
4840 # i18n: column positioning for "hg summary"
4842 # i18n: column positioning for "hg summary"
4841 ui.write(_('parent: %d:%s ') % (p.rev(), p),
4843 ui.write(_('parent: %d:%s ') % (p.rev(), p),
4842 label=cmdutil._changesetlabels(p))
4844 label=cmdutil._changesetlabels(p))
4843 ui.write(' '.join(p.tags()), label='log.tag')
4845 ui.write(' '.join(p.tags()), label='log.tag')
4844 if p.bookmarks():
4846 if p.bookmarks():
4845 marks.extend(p.bookmarks())
4847 marks.extend(p.bookmarks())
4846 if p.rev() == -1:
4848 if p.rev() == -1:
4847 if not len(repo):
4849 if not len(repo):
4848 ui.write(_(' (empty repository)'))
4850 ui.write(_(' (empty repository)'))
4849 else:
4851 else:
4850 ui.write(_(' (no revision checked out)'))
4852 ui.write(_(' (no revision checked out)'))
4851 if p.obsolete():
4853 if p.obsolete():
4852 ui.write(_(' (obsolete)'))
4854 ui.write(_(' (obsolete)'))
4853 if p.troubled():
4855 if p.troubled():
4854 ui.write(' ('
4856 ui.write(' ('
4855 + ', '.join(ui.label(trouble, 'trouble.%s' % trouble)
4857 + ', '.join(ui.label(trouble, 'trouble.%s' % trouble)
4856 for trouble in p.troubles())
4858 for trouble in p.troubles())
4857 + ')')
4859 + ')')
4858 ui.write('\n')
4860 ui.write('\n')
4859 if p.description():
4861 if p.description():
4860 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4862 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4861 label='log.summary')
4863 label='log.summary')
4862
4864
4863 branch = ctx.branch()
4865 branch = ctx.branch()
4864 bheads = repo.branchheads(branch)
4866 bheads = repo.branchheads(branch)
4865 # i18n: column positioning for "hg summary"
4867 # i18n: column positioning for "hg summary"
4866 m = _('branch: %s\n') % branch
4868 m = _('branch: %s\n') % branch
4867 if branch != 'default':
4869 if branch != 'default':
4868 ui.write(m, label='log.branch')
4870 ui.write(m, label='log.branch')
4869 else:
4871 else:
4870 ui.status(m, label='log.branch')
4872 ui.status(m, label='log.branch')
4871
4873
4872 if marks:
4874 if marks:
4873 active = repo._activebookmark
4875 active = repo._activebookmark
4874 # i18n: column positioning for "hg summary"
4876 # i18n: column positioning for "hg summary"
4875 ui.write(_('bookmarks:'), label='log.bookmark')
4877 ui.write(_('bookmarks:'), label='log.bookmark')
4876 if active is not None:
4878 if active is not None:
4877 if active in marks:
4879 if active in marks:
4878 ui.write(' *' + active, label=activebookmarklabel)
4880 ui.write(' *' + active, label=activebookmarklabel)
4879 marks.remove(active)
4881 marks.remove(active)
4880 else:
4882 else:
4881 ui.write(' [%s]' % active, label=activebookmarklabel)
4883 ui.write(' [%s]' % active, label=activebookmarklabel)
4882 for m in marks:
4884 for m in marks:
4883 ui.write(' ' + m, label='log.bookmark')
4885 ui.write(' ' + m, label='log.bookmark')
4884 ui.write('\n', label='log.bookmark')
4886 ui.write('\n', label='log.bookmark')
4885
4887
4886 status = repo.status(unknown=True)
4888 status = repo.status(unknown=True)
4887
4889
4888 c = repo.dirstate.copies()
4890 c = repo.dirstate.copies()
4889 copied, renamed = [], []
4891 copied, renamed = [], []
4890 for d, s in c.iteritems():
4892 for d, s in c.iteritems():
4891 if s in status.removed:
4893 if s in status.removed:
4892 status.removed.remove(s)
4894 status.removed.remove(s)
4893 renamed.append(d)
4895 renamed.append(d)
4894 else:
4896 else:
4895 copied.append(d)
4897 copied.append(d)
4896 if d in status.added:
4898 if d in status.added:
4897 status.added.remove(d)
4899 status.added.remove(d)
4898
4900
4899 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
4901 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
4900
4902
4901 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
4903 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
4902 (ui.label(_('%d added'), 'status.added'), status.added),
4904 (ui.label(_('%d added'), 'status.added'), status.added),
4903 (ui.label(_('%d removed'), 'status.removed'), status.removed),
4905 (ui.label(_('%d removed'), 'status.removed'), status.removed),
4904 (ui.label(_('%d renamed'), 'status.copied'), renamed),
4906 (ui.label(_('%d renamed'), 'status.copied'), renamed),
4905 (ui.label(_('%d copied'), 'status.copied'), copied),
4907 (ui.label(_('%d copied'), 'status.copied'), copied),
4906 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
4908 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
4907 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
4909 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
4908 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
4910 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
4909 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
4911 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
4910 t = []
4912 t = []
4911 for l, s in labels:
4913 for l, s in labels:
4912 if s:
4914 if s:
4913 t.append(l % len(s))
4915 t.append(l % len(s))
4914
4916
4915 t = ', '.join(t)
4917 t = ', '.join(t)
4916 cleanworkdir = False
4918 cleanworkdir = False
4917
4919
4918 if repo.vfs.exists('graftstate'):
4920 if repo.vfs.exists('graftstate'):
4919 t += _(' (graft in progress)')
4921 t += _(' (graft in progress)')
4920 if repo.vfs.exists('updatestate'):
4922 if repo.vfs.exists('updatestate'):
4921 t += _(' (interrupted update)')
4923 t += _(' (interrupted update)')
4922 elif len(parents) > 1:
4924 elif len(parents) > 1:
4923 t += _(' (merge)')
4925 t += _(' (merge)')
4924 elif branch != parents[0].branch():
4926 elif branch != parents[0].branch():
4925 t += _(' (new branch)')
4927 t += _(' (new branch)')
4926 elif (parents[0].closesbranch() and
4928 elif (parents[0].closesbranch() and
4927 pnode in repo.branchheads(branch, closed=True)):
4929 pnode in repo.branchheads(branch, closed=True)):
4928 t += _(' (head closed)')
4930 t += _(' (head closed)')
4929 elif not (status.modified or status.added or status.removed or renamed or
4931 elif not (status.modified or status.added or status.removed or renamed or
4930 copied or subs):
4932 copied or subs):
4931 t += _(' (clean)')
4933 t += _(' (clean)')
4932 cleanworkdir = True
4934 cleanworkdir = True
4933 elif pnode not in bheads:
4935 elif pnode not in bheads:
4934 t += _(' (new branch head)')
4936 t += _(' (new branch head)')
4935
4937
4936 if parents:
4938 if parents:
4937 pendingphase = max(p.phase() for p in parents)
4939 pendingphase = max(p.phase() for p in parents)
4938 else:
4940 else:
4939 pendingphase = phases.public
4941 pendingphase = phases.public
4940
4942
4941 if pendingphase > phases.newcommitphase(ui):
4943 if pendingphase > phases.newcommitphase(ui):
4942 t += ' (%s)' % phases.phasenames[pendingphase]
4944 t += ' (%s)' % phases.phasenames[pendingphase]
4943
4945
4944 if cleanworkdir:
4946 if cleanworkdir:
4945 # i18n: column positioning for "hg summary"
4947 # i18n: column positioning for "hg summary"
4946 ui.status(_('commit: %s\n') % t.strip())
4948 ui.status(_('commit: %s\n') % t.strip())
4947 else:
4949 else:
4948 # i18n: column positioning for "hg summary"
4950 # i18n: column positioning for "hg summary"
4949 ui.write(_('commit: %s\n') % t.strip())
4951 ui.write(_('commit: %s\n') % t.strip())
4950
4952
4951 # all ancestors of branch heads - all ancestors of parent = new csets
4953 # all ancestors of branch heads - all ancestors of parent = new csets
4952 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
4954 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
4953 bheads))
4955 bheads))
4954
4956
4955 if new == 0:
4957 if new == 0:
4956 # i18n: column positioning for "hg summary"
4958 # i18n: column positioning for "hg summary"
4957 ui.status(_('update: (current)\n'))
4959 ui.status(_('update: (current)\n'))
4958 elif pnode not in bheads:
4960 elif pnode not in bheads:
4959 # i18n: column positioning for "hg summary"
4961 # i18n: column positioning for "hg summary"
4960 ui.write(_('update: %d new changesets (update)\n') % new)
4962 ui.write(_('update: %d new changesets (update)\n') % new)
4961 else:
4963 else:
4962 # i18n: column positioning for "hg summary"
4964 # i18n: column positioning for "hg summary"
4963 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
4965 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
4964 (new, len(bheads)))
4966 (new, len(bheads)))
4965
4967
4966 t = []
4968 t = []
4967 draft = len(repo.revs('draft()'))
4969 draft = len(repo.revs('draft()'))
4968 if draft:
4970 if draft:
4969 t.append(_('%d draft') % draft)
4971 t.append(_('%d draft') % draft)
4970 secret = len(repo.revs('secret()'))
4972 secret = len(repo.revs('secret()'))
4971 if secret:
4973 if secret:
4972 t.append(_('%d secret') % secret)
4974 t.append(_('%d secret') % secret)
4973
4975
4974 if draft or secret:
4976 if draft or secret:
4975 ui.status(_('phases: %s\n') % ', '.join(t))
4977 ui.status(_('phases: %s\n') % ', '.join(t))
4976
4978
4977 if obsolete.isenabled(repo, obsolete.createmarkersopt):
4979 if obsolete.isenabled(repo, obsolete.createmarkersopt):
4978 for trouble in ("unstable", "divergent", "bumped"):
4980 for trouble in ("unstable", "divergent", "bumped"):
4979 numtrouble = len(repo.revs(trouble + "()"))
4981 numtrouble = len(repo.revs(trouble + "()"))
4980 # We write all the possibilities to ease translation
4982 # We write all the possibilities to ease translation
4981 troublemsg = {
4983 troublemsg = {
4982 "unstable": _("unstable: %d changesets"),
4984 "unstable": _("unstable: %d changesets"),
4983 "divergent": _("divergent: %d changesets"),
4985 "divergent": _("divergent: %d changesets"),
4984 "bumped": _("bumped: %d changesets"),
4986 "bumped": _("bumped: %d changesets"),
4985 }
4987 }
4986 if numtrouble > 0:
4988 if numtrouble > 0:
4987 ui.status(troublemsg[trouble] % numtrouble + "\n")
4989 ui.status(troublemsg[trouble] % numtrouble + "\n")
4988
4990
4989 cmdutil.summaryhooks(ui, repo)
4991 cmdutil.summaryhooks(ui, repo)
4990
4992
4991 if opts.get('remote'):
4993 if opts.get('remote'):
4992 needsincoming, needsoutgoing = True, True
4994 needsincoming, needsoutgoing = True, True
4993 else:
4995 else:
4994 needsincoming, needsoutgoing = False, False
4996 needsincoming, needsoutgoing = False, False
4995 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
4997 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
4996 if i:
4998 if i:
4997 needsincoming = True
4999 needsincoming = True
4998 if o:
5000 if o:
4999 needsoutgoing = True
5001 needsoutgoing = True
5000 if not needsincoming and not needsoutgoing:
5002 if not needsincoming and not needsoutgoing:
5001 return
5003 return
5002
5004
5003 def getincoming():
5005 def getincoming():
5004 source, branches = hg.parseurl(ui.expandpath('default'))
5006 source, branches = hg.parseurl(ui.expandpath('default'))
5005 sbranch = branches[0]
5007 sbranch = branches[0]
5006 try:
5008 try:
5007 other = hg.peer(repo, {}, source)
5009 other = hg.peer(repo, {}, source)
5008 except error.RepoError:
5010 except error.RepoError:
5009 if opts.get('remote'):
5011 if opts.get('remote'):
5010 raise
5012 raise
5011 return source, sbranch, None, None, None
5013 return source, sbranch, None, None, None
5012 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5014 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5013 if revs:
5015 if revs:
5014 revs = [other.lookup(rev) for rev in revs]
5016 revs = [other.lookup(rev) for rev in revs]
5015 ui.debug('comparing with %s\n' % util.hidepassword(source))
5017 ui.debug('comparing with %s\n' % util.hidepassword(source))
5016 repo.ui.pushbuffer()
5018 repo.ui.pushbuffer()
5017 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5019 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5018 repo.ui.popbuffer()
5020 repo.ui.popbuffer()
5019 return source, sbranch, other, commoninc, commoninc[1]
5021 return source, sbranch, other, commoninc, commoninc[1]
5020
5022
5021 if needsincoming:
5023 if needsincoming:
5022 source, sbranch, sother, commoninc, incoming = getincoming()
5024 source, sbranch, sother, commoninc, incoming = getincoming()
5023 else:
5025 else:
5024 source = sbranch = sother = commoninc = incoming = None
5026 source = sbranch = sother = commoninc = incoming = None
5025
5027
5026 def getoutgoing():
5028 def getoutgoing():
5027 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5029 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5028 dbranch = branches[0]
5030 dbranch = branches[0]
5029 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5031 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5030 if source != dest:
5032 if source != dest:
5031 try:
5033 try:
5032 dother = hg.peer(repo, {}, dest)
5034 dother = hg.peer(repo, {}, dest)
5033 except error.RepoError:
5035 except error.RepoError:
5034 if opts.get('remote'):
5036 if opts.get('remote'):
5035 raise
5037 raise
5036 return dest, dbranch, None, None
5038 return dest, dbranch, None, None
5037 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5039 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5038 elif sother is None:
5040 elif sother is None:
5039 # there is no explicit destination peer, but source one is invalid
5041 # there is no explicit destination peer, but source one is invalid
5040 return dest, dbranch, None, None
5042 return dest, dbranch, None, None
5041 else:
5043 else:
5042 dother = sother
5044 dother = sother
5043 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5045 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5044 common = None
5046 common = None
5045 else:
5047 else:
5046 common = commoninc
5048 common = commoninc
5047 if revs:
5049 if revs:
5048 revs = [repo.lookup(rev) for rev in revs]
5050 revs = [repo.lookup(rev) for rev in revs]
5049 repo.ui.pushbuffer()
5051 repo.ui.pushbuffer()
5050 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5052 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5051 commoninc=common)
5053 commoninc=common)
5052 repo.ui.popbuffer()
5054 repo.ui.popbuffer()
5053 return dest, dbranch, dother, outgoing
5055 return dest, dbranch, dother, outgoing
5054
5056
5055 if needsoutgoing:
5057 if needsoutgoing:
5056 dest, dbranch, dother, outgoing = getoutgoing()
5058 dest, dbranch, dother, outgoing = getoutgoing()
5057 else:
5059 else:
5058 dest = dbranch = dother = outgoing = None
5060 dest = dbranch = dother = outgoing = None
5059
5061
5060 if opts.get('remote'):
5062 if opts.get('remote'):
5061 t = []
5063 t = []
5062 if incoming:
5064 if incoming:
5063 t.append(_('1 or more incoming'))
5065 t.append(_('1 or more incoming'))
5064 o = outgoing.missing
5066 o = outgoing.missing
5065 if o:
5067 if o:
5066 t.append(_('%d outgoing') % len(o))
5068 t.append(_('%d outgoing') % len(o))
5067 other = dother or sother
5069 other = dother or sother
5068 if 'bookmarks' in other.listkeys('namespaces'):
5070 if 'bookmarks' in other.listkeys('namespaces'):
5069 counts = bookmarks.summary(repo, other)
5071 counts = bookmarks.summary(repo, other)
5070 if counts[0] > 0:
5072 if counts[0] > 0:
5071 t.append(_('%d incoming bookmarks') % counts[0])
5073 t.append(_('%d incoming bookmarks') % counts[0])
5072 if counts[1] > 0:
5074 if counts[1] > 0:
5073 t.append(_('%d outgoing bookmarks') % counts[1])
5075 t.append(_('%d outgoing bookmarks') % counts[1])
5074
5076
5075 if t:
5077 if t:
5076 # i18n: column positioning for "hg summary"
5078 # i18n: column positioning for "hg summary"
5077 ui.write(_('remote: %s\n') % (', '.join(t)))
5079 ui.write(_('remote: %s\n') % (', '.join(t)))
5078 else:
5080 else:
5079 # i18n: column positioning for "hg summary"
5081 # i18n: column positioning for "hg summary"
5080 ui.status(_('remote: (synced)\n'))
5082 ui.status(_('remote: (synced)\n'))
5081
5083
5082 cmdutil.summaryremotehooks(ui, repo, opts,
5084 cmdutil.summaryremotehooks(ui, repo, opts,
5083 ((source, sbranch, sother, commoninc),
5085 ((source, sbranch, sother, commoninc),
5084 (dest, dbranch, dother, outgoing)))
5086 (dest, dbranch, dother, outgoing)))
5085
5087
5086 @command('tag',
5088 @command('tag',
5087 [('f', 'force', None, _('force tag')),
5089 [('f', 'force', None, _('force tag')),
5088 ('l', 'local', None, _('make the tag local')),
5090 ('l', 'local', None, _('make the tag local')),
5089 ('r', 'rev', '', _('revision to tag'), _('REV')),
5091 ('r', 'rev', '', _('revision to tag'), _('REV')),
5090 ('', 'remove', None, _('remove a tag')),
5092 ('', 'remove', None, _('remove a tag')),
5091 # -l/--local is already there, commitopts cannot be used
5093 # -l/--local is already there, commitopts cannot be used
5092 ('e', 'edit', None, _('invoke editor on commit messages')),
5094 ('e', 'edit', None, _('invoke editor on commit messages')),
5093 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5095 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5094 ] + commitopts2,
5096 ] + commitopts2,
5095 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5097 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5096 def tag(ui, repo, name1, *names, **opts):
5098 def tag(ui, repo, name1, *names, **opts):
5097 """add one or more tags for the current or given revision
5099 """add one or more tags for the current or given revision
5098
5100
5099 Name a particular revision using <name>.
5101 Name a particular revision using <name>.
5100
5102
5101 Tags are used to name particular revisions of the repository and are
5103 Tags are used to name particular revisions of the repository and are
5102 very useful to compare different revisions, to go back to significant
5104 very useful to compare different revisions, to go back to significant
5103 earlier versions or to mark branch points as releases, etc. Changing
5105 earlier versions or to mark branch points as releases, etc. Changing
5104 an existing tag is normally disallowed; use -f/--force to override.
5106 an existing tag is normally disallowed; use -f/--force to override.
5105
5107
5106 If no revision is given, the parent of the working directory is
5108 If no revision is given, the parent of the working directory is
5107 used.
5109 used.
5108
5110
5109 To facilitate version control, distribution, and merging of tags,
5111 To facilitate version control, distribution, and merging of tags,
5110 they are stored as a file named ".hgtags" which is managed similarly
5112 they are stored as a file named ".hgtags" which is managed similarly
5111 to other project files and can be hand-edited if necessary. This
5113 to other project files and can be hand-edited if necessary. This
5112 also means that tagging creates a new commit. The file
5114 also means that tagging creates a new commit. The file
5113 ".hg/localtags" is used for local tags (not shared among
5115 ".hg/localtags" is used for local tags (not shared among
5114 repositories).
5116 repositories).
5115
5117
5116 Tag commits are usually made at the head of a branch. If the parent
5118 Tag commits are usually made at the head of a branch. If the parent
5117 of the working directory is not a branch head, :hg:`tag` aborts; use
5119 of the working directory is not a branch head, :hg:`tag` aborts; use
5118 -f/--force to force the tag commit to be based on a non-head
5120 -f/--force to force the tag commit to be based on a non-head
5119 changeset.
5121 changeset.
5120
5122
5121 See :hg:`help dates` for a list of formats valid for -d/--date.
5123 See :hg:`help dates` for a list of formats valid for -d/--date.
5122
5124
5123 Since tag names have priority over branch names during revision
5125 Since tag names have priority over branch names during revision
5124 lookup, using an existing branch name as a tag name is discouraged.
5126 lookup, using an existing branch name as a tag name is discouraged.
5125
5127
5126 Returns 0 on success.
5128 Returns 0 on success.
5127 """
5129 """
5128 opts = pycompat.byteskwargs(opts)
5130 opts = pycompat.byteskwargs(opts)
5129 wlock = lock = None
5131 wlock = lock = None
5130 try:
5132 try:
5131 wlock = repo.wlock()
5133 wlock = repo.wlock()
5132 lock = repo.lock()
5134 lock = repo.lock()
5133 rev_ = "."
5135 rev_ = "."
5134 names = [t.strip() for t in (name1,) + names]
5136 names = [t.strip() for t in (name1,) + names]
5135 if len(names) != len(set(names)):
5137 if len(names) != len(set(names)):
5136 raise error.Abort(_('tag names must be unique'))
5138 raise error.Abort(_('tag names must be unique'))
5137 for n in names:
5139 for n in names:
5138 scmutil.checknewlabel(repo, n, 'tag')
5140 scmutil.checknewlabel(repo, n, 'tag')
5139 if not n:
5141 if not n:
5140 raise error.Abort(_('tag names cannot consist entirely of '
5142 raise error.Abort(_('tag names cannot consist entirely of '
5141 'whitespace'))
5143 'whitespace'))
5142 if opts.get('rev') and opts.get('remove'):
5144 if opts.get('rev') and opts.get('remove'):
5143 raise error.Abort(_("--rev and --remove are incompatible"))
5145 raise error.Abort(_("--rev and --remove are incompatible"))
5144 if opts.get('rev'):
5146 if opts.get('rev'):
5145 rev_ = opts['rev']
5147 rev_ = opts['rev']
5146 message = opts.get('message')
5148 message = opts.get('message')
5147 if opts.get('remove'):
5149 if opts.get('remove'):
5148 if opts.get('local'):
5150 if opts.get('local'):
5149 expectedtype = 'local'
5151 expectedtype = 'local'
5150 else:
5152 else:
5151 expectedtype = 'global'
5153 expectedtype = 'global'
5152
5154
5153 for n in names:
5155 for n in names:
5154 if not repo.tagtype(n):
5156 if not repo.tagtype(n):
5155 raise error.Abort(_("tag '%s' does not exist") % n)
5157 raise error.Abort(_("tag '%s' does not exist") % n)
5156 if repo.tagtype(n) != expectedtype:
5158 if repo.tagtype(n) != expectedtype:
5157 if expectedtype == 'global':
5159 if expectedtype == 'global':
5158 raise error.Abort(_("tag '%s' is not a global tag") % n)
5160 raise error.Abort(_("tag '%s' is not a global tag") % n)
5159 else:
5161 else:
5160 raise error.Abort(_("tag '%s' is not a local tag") % n)
5162 raise error.Abort(_("tag '%s' is not a local tag") % n)
5161 rev_ = 'null'
5163 rev_ = 'null'
5162 if not message:
5164 if not message:
5163 # we don't translate commit messages
5165 # we don't translate commit messages
5164 message = 'Removed tag %s' % ', '.join(names)
5166 message = 'Removed tag %s' % ', '.join(names)
5165 elif not opts.get('force'):
5167 elif not opts.get('force'):
5166 for n in names:
5168 for n in names:
5167 if n in repo.tags():
5169 if n in repo.tags():
5168 raise error.Abort(_("tag '%s' already exists "
5170 raise error.Abort(_("tag '%s' already exists "
5169 "(use -f to force)") % n)
5171 "(use -f to force)") % n)
5170 if not opts.get('local'):
5172 if not opts.get('local'):
5171 p1, p2 = repo.dirstate.parents()
5173 p1, p2 = repo.dirstate.parents()
5172 if p2 != nullid:
5174 if p2 != nullid:
5173 raise error.Abort(_('uncommitted merge'))
5175 raise error.Abort(_('uncommitted merge'))
5174 bheads = repo.branchheads()
5176 bheads = repo.branchheads()
5175 if not opts.get('force') and bheads and p1 not in bheads:
5177 if not opts.get('force') and bheads and p1 not in bheads:
5176 raise error.Abort(_('working directory is not at a branch head '
5178 raise error.Abort(_('working directory is not at a branch head '
5177 '(use -f to force)'))
5179 '(use -f to force)'))
5178 r = scmutil.revsingle(repo, rev_).node()
5180 r = scmutil.revsingle(repo, rev_).node()
5179
5181
5180 if not message:
5182 if not message:
5181 # we don't translate commit messages
5183 # we don't translate commit messages
5182 message = ('Added tag %s for changeset %s' %
5184 message = ('Added tag %s for changeset %s' %
5183 (', '.join(names), short(r)))
5185 (', '.join(names), short(r)))
5184
5186
5185 date = opts.get('date')
5187 date = opts.get('date')
5186 if date:
5188 if date:
5187 date = util.parsedate(date)
5189 date = util.parsedate(date)
5188
5190
5189 if opts.get('remove'):
5191 if opts.get('remove'):
5190 editform = 'tag.remove'
5192 editform = 'tag.remove'
5191 else:
5193 else:
5192 editform = 'tag.add'
5194 editform = 'tag.add'
5193 editor = cmdutil.getcommiteditor(editform=editform,
5195 editor = cmdutil.getcommiteditor(editform=editform,
5194 **pycompat.strkwargs(opts))
5196 **pycompat.strkwargs(opts))
5195
5197
5196 # don't allow tagging the null rev
5198 # don't allow tagging the null rev
5197 if (not opts.get('remove') and
5199 if (not opts.get('remove') and
5198 scmutil.revsingle(repo, rev_).rev() == nullrev):
5200 scmutil.revsingle(repo, rev_).rev() == nullrev):
5199 raise error.Abort(_("cannot tag null revision"))
5201 raise error.Abort(_("cannot tag null revision"))
5200
5202
5201 tagsmod.tag(repo, names, r, message, opts.get('local'),
5203 tagsmod.tag(repo, names, r, message, opts.get('local'),
5202 opts.get('user'), date, editor=editor)
5204 opts.get('user'), date, editor=editor)
5203 finally:
5205 finally:
5204 release(lock, wlock)
5206 release(lock, wlock)
5205
5207
5206 @command('tags', formatteropts, '')
5208 @command('tags', formatteropts, '')
5207 def tags(ui, repo, **opts):
5209 def tags(ui, repo, **opts):
5208 """list repository tags
5210 """list repository tags
5209
5211
5210 This lists both regular and local tags. When the -v/--verbose
5212 This lists both regular and local tags. When the -v/--verbose
5211 switch is used, a third column "local" is printed for local tags.
5213 switch is used, a third column "local" is printed for local tags.
5212 When the -q/--quiet switch is used, only the tag name is printed.
5214 When the -q/--quiet switch is used, only the tag name is printed.
5213
5215
5214 Returns 0 on success.
5216 Returns 0 on success.
5215 """
5217 """
5216
5218
5217 opts = pycompat.byteskwargs(opts)
5219 opts = pycompat.byteskwargs(opts)
5218 ui.pager('tags')
5220 ui.pager('tags')
5219 fm = ui.formatter('tags', opts)
5221 fm = ui.formatter('tags', opts)
5220 hexfunc = fm.hexfunc
5222 hexfunc = fm.hexfunc
5221 tagtype = ""
5223 tagtype = ""
5222
5224
5223 for t, n in reversed(repo.tagslist()):
5225 for t, n in reversed(repo.tagslist()):
5224 hn = hexfunc(n)
5226 hn = hexfunc(n)
5225 label = 'tags.normal'
5227 label = 'tags.normal'
5226 tagtype = ''
5228 tagtype = ''
5227 if repo.tagtype(t) == 'local':
5229 if repo.tagtype(t) == 'local':
5228 label = 'tags.local'
5230 label = 'tags.local'
5229 tagtype = 'local'
5231 tagtype = 'local'
5230
5232
5231 fm.startitem()
5233 fm.startitem()
5232 fm.write('tag', '%s', t, label=label)
5234 fm.write('tag', '%s', t, label=label)
5233 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5235 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5234 fm.condwrite(not ui.quiet, 'rev node', fmt,
5236 fm.condwrite(not ui.quiet, 'rev node', fmt,
5235 repo.changelog.rev(n), hn, label=label)
5237 repo.changelog.rev(n), hn, label=label)
5236 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5238 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5237 tagtype, label=label)
5239 tagtype, label=label)
5238 fm.plain('\n')
5240 fm.plain('\n')
5239 fm.end()
5241 fm.end()
5240
5242
5241 @command('tip',
5243 @command('tip',
5242 [('p', 'patch', None, _('show patch')),
5244 [('p', 'patch', None, _('show patch')),
5243 ('g', 'git', None, _('use git extended diff format')),
5245 ('g', 'git', None, _('use git extended diff format')),
5244 ] + templateopts,
5246 ] + templateopts,
5245 _('[-p] [-g]'))
5247 _('[-p] [-g]'))
5246 def tip(ui, repo, **opts):
5248 def tip(ui, repo, **opts):
5247 """show the tip revision (DEPRECATED)
5249 """show the tip revision (DEPRECATED)
5248
5250
5249 The tip revision (usually just called the tip) is the changeset
5251 The tip revision (usually just called the tip) is the changeset
5250 most recently added to the repository (and therefore the most
5252 most recently added to the repository (and therefore the most
5251 recently changed head).
5253 recently changed head).
5252
5254
5253 If you have just made a commit, that commit will be the tip. If
5255 If you have just made a commit, that commit will be the tip. If
5254 you have just pulled changes from another repository, the tip of
5256 you have just pulled changes from another repository, the tip of
5255 that repository becomes the current tip. The "tip" tag is special
5257 that repository becomes the current tip. The "tip" tag is special
5256 and cannot be renamed or assigned to a different changeset.
5258 and cannot be renamed or assigned to a different changeset.
5257
5259
5258 This command is deprecated, please use :hg:`heads` instead.
5260 This command is deprecated, please use :hg:`heads` instead.
5259
5261
5260 Returns 0 on success.
5262 Returns 0 on success.
5261 """
5263 """
5262 opts = pycompat.byteskwargs(opts)
5264 opts = pycompat.byteskwargs(opts)
5263 displayer = cmdutil.show_changeset(ui, repo, opts)
5265 displayer = cmdutil.show_changeset(ui, repo, opts)
5264 displayer.show(repo['tip'])
5266 displayer.show(repo['tip'])
5265 displayer.close()
5267 displayer.close()
5266
5268
5267 @command('unbundle',
5269 @command('unbundle',
5268 [('u', 'update', None,
5270 [('u', 'update', None,
5269 _('update to new branch head if changesets were unbundled'))],
5271 _('update to new branch head if changesets were unbundled'))],
5270 _('[-u] FILE...'))
5272 _('[-u] FILE...'))
5271 def unbundle(ui, repo, fname1, *fnames, **opts):
5273 def unbundle(ui, repo, fname1, *fnames, **opts):
5272 """apply one or more bundle files
5274 """apply one or more bundle files
5273
5275
5274 Apply one or more bundle files generated by :hg:`bundle`.
5276 Apply one or more bundle files generated by :hg:`bundle`.
5275
5277
5276 Returns 0 on success, 1 if an update has unresolved files.
5278 Returns 0 on success, 1 if an update has unresolved files.
5277 """
5279 """
5278 fnames = (fname1,) + fnames
5280 fnames = (fname1,) + fnames
5279
5281
5280 with repo.lock():
5282 with repo.lock():
5281 for fname in fnames:
5283 for fname in fnames:
5282 f = hg.openpath(ui, fname)
5284 f = hg.openpath(ui, fname)
5283 gen = exchange.readbundle(ui, f, fname)
5285 gen = exchange.readbundle(ui, f, fname)
5284 if isinstance(gen, bundle2.unbundle20):
5286 if isinstance(gen, bundle2.unbundle20):
5285 tr = repo.transaction('unbundle')
5287 tr = repo.transaction('unbundle')
5286 try:
5288 try:
5287 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
5289 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
5288 url='bundle:' + fname)
5290 url='bundle:' + fname)
5289 tr.close()
5291 tr.close()
5290 except error.BundleUnknownFeatureError as exc:
5292 except error.BundleUnknownFeatureError as exc:
5291 raise error.Abort(_('%s: unknown bundle feature, %s')
5293 raise error.Abort(_('%s: unknown bundle feature, %s')
5292 % (fname, exc),
5294 % (fname, exc),
5293 hint=_("see https://mercurial-scm.org/"
5295 hint=_("see https://mercurial-scm.org/"
5294 "wiki/BundleFeature for more "
5296 "wiki/BundleFeature for more "
5295 "information"))
5297 "information"))
5296 finally:
5298 finally:
5297 if tr:
5299 if tr:
5298 tr.release()
5300 tr.release()
5299 changes = [r.get('return', 0)
5301 changes = [r.get('return', 0)
5300 for r in op.records['changegroup']]
5302 for r in op.records['changegroup']]
5301 modheads = changegroup.combineresults(changes)
5303 modheads = changegroup.combineresults(changes)
5302 elif isinstance(gen, streamclone.streamcloneapplier):
5304 elif isinstance(gen, streamclone.streamcloneapplier):
5303 raise error.Abort(
5305 raise error.Abort(
5304 _('packed bundles cannot be applied with '
5306 _('packed bundles cannot be applied with '
5305 '"hg unbundle"'),
5307 '"hg unbundle"'),
5306 hint=_('use "hg debugapplystreamclonebundle"'))
5308 hint=_('use "hg debugapplystreamclonebundle"'))
5307 else:
5309 else:
5308 modheads = gen.apply(repo, 'unbundle', 'bundle:' + fname)
5310 modheads = gen.apply(repo, 'unbundle', 'bundle:' + fname)
5309
5311
5310 return postincoming(ui, repo, modheads, opts.get(r'update'), None, None)
5312 return postincoming(ui, repo, modheads, opts.get(r'update'), None, None)
5311
5313
5312 @command('^update|up|checkout|co',
5314 @command('^update|up|checkout|co',
5313 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5315 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5314 ('c', 'check', None, _('require clean working directory')),
5316 ('c', 'check', None, _('require clean working directory')),
5315 ('m', 'merge', None, _('merge uncommitted changes')),
5317 ('m', 'merge', None, _('merge uncommitted changes')),
5316 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5318 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5317 ('r', 'rev', '', _('revision'), _('REV'))
5319 ('r', 'rev', '', _('revision'), _('REV'))
5318 ] + mergetoolopts,
5320 ] + mergetoolopts,
5319 _('[-C|-c|-m] [-d DATE] [[-r] REV]'))
5321 _('[-C|-c|-m] [-d DATE] [[-r] REV]'))
5320 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
5322 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
5321 merge=None, tool=None):
5323 merge=None, tool=None):
5322 """update working directory (or switch revisions)
5324 """update working directory (or switch revisions)
5323
5325
5324 Update the repository's working directory to the specified
5326 Update the repository's working directory to the specified
5325 changeset. If no changeset is specified, update to the tip of the
5327 changeset. If no changeset is specified, update to the tip of the
5326 current named branch and move the active bookmark (see :hg:`help
5328 current named branch and move the active bookmark (see :hg:`help
5327 bookmarks`).
5329 bookmarks`).
5328
5330
5329 Update sets the working directory's parent revision to the specified
5331 Update sets the working directory's parent revision to the specified
5330 changeset (see :hg:`help parents`).
5332 changeset (see :hg:`help parents`).
5331
5333
5332 If the changeset is not a descendant or ancestor of the working
5334 If the changeset is not a descendant or ancestor of the working
5333 directory's parent and there are uncommitted changes, the update is
5335 directory's parent and there are uncommitted changes, the update is
5334 aborted. With the -c/--check option, the working directory is checked
5336 aborted. With the -c/--check option, the working directory is checked
5335 for uncommitted changes; if none are found, the working directory is
5337 for uncommitted changes; if none are found, the working directory is
5336 updated to the specified changeset.
5338 updated to the specified changeset.
5337
5339
5338 .. container:: verbose
5340 .. container:: verbose
5339
5341
5340 The -C/--clean, -c/--check, and -m/--merge options control what
5342 The -C/--clean, -c/--check, and -m/--merge options control what
5341 happens if the working directory contains uncommitted changes.
5343 happens if the working directory contains uncommitted changes.
5342 At most of one of them can be specified.
5344 At most of one of them can be specified.
5343
5345
5344 1. If no option is specified, and if
5346 1. If no option is specified, and if
5345 the requested changeset is an ancestor or descendant of
5347 the requested changeset is an ancestor or descendant of
5346 the working directory's parent, the uncommitted changes
5348 the working directory's parent, the uncommitted changes
5347 are merged into the requested changeset and the merged
5349 are merged into the requested changeset and the merged
5348 result is left uncommitted. If the requested changeset is
5350 result is left uncommitted. If the requested changeset is
5349 not an ancestor or descendant (that is, it is on another
5351 not an ancestor or descendant (that is, it is on another
5350 branch), the update is aborted and the uncommitted changes
5352 branch), the update is aborted and the uncommitted changes
5351 are preserved.
5353 are preserved.
5352
5354
5353 2. With the -m/--merge option, the update is allowed even if the
5355 2. With the -m/--merge option, the update is allowed even if the
5354 requested changeset is not an ancestor or descendant of
5356 requested changeset is not an ancestor or descendant of
5355 the working directory's parent.
5357 the working directory's parent.
5356
5358
5357 3. With the -c/--check option, the update is aborted and the
5359 3. With the -c/--check option, the update is aborted and the
5358 uncommitted changes are preserved.
5360 uncommitted changes are preserved.
5359
5361
5360 4. With the -C/--clean option, uncommitted changes are discarded and
5362 4. With the -C/--clean option, uncommitted changes are discarded and
5361 the working directory is updated to the requested changeset.
5363 the working directory is updated to the requested changeset.
5362
5364
5363 To cancel an uncommitted merge (and lose your changes), use
5365 To cancel an uncommitted merge (and lose your changes), use
5364 :hg:`update --clean .`.
5366 :hg:`update --clean .`.
5365
5367
5366 Use null as the changeset to remove the working directory (like
5368 Use null as the changeset to remove the working directory (like
5367 :hg:`clone -U`).
5369 :hg:`clone -U`).
5368
5370
5369 If you want to revert just one file to an older revision, use
5371 If you want to revert just one file to an older revision, use
5370 :hg:`revert [-r REV] NAME`.
5372 :hg:`revert [-r REV] NAME`.
5371
5373
5372 See :hg:`help dates` for a list of formats valid for -d/--date.
5374 See :hg:`help dates` for a list of formats valid for -d/--date.
5373
5375
5374 Returns 0 on success, 1 if there are unresolved files.
5376 Returns 0 on success, 1 if there are unresolved files.
5375 """
5377 """
5376 if rev and node:
5378 if rev and node:
5377 raise error.Abort(_("please specify just one revision"))
5379 raise error.Abort(_("please specify just one revision"))
5378
5380
5379 if ui.configbool('commands', 'update.requiredest'):
5381 if ui.configbool('commands', 'update.requiredest'):
5380 if not node and not rev and not date:
5382 if not node and not rev and not date:
5381 raise error.Abort(_('you must specify a destination'),
5383 raise error.Abort(_('you must specify a destination'),
5382 hint=_('for example: hg update ".::"'))
5384 hint=_('for example: hg update ".::"'))
5383
5385
5384 if rev is None or rev == '':
5386 if rev is None or rev == '':
5385 rev = node
5387 rev = node
5386
5388
5387 if date and rev is not None:
5389 if date and rev is not None:
5388 raise error.Abort(_("you can't specify a revision and a date"))
5390 raise error.Abort(_("you can't specify a revision and a date"))
5389
5391
5390 if len([x for x in (clean, check, merge) if x]) > 1:
5392 if len([x for x in (clean, check, merge) if x]) > 1:
5391 raise error.Abort(_("can only specify one of -C/--clean, -c/--check, "
5393 raise error.Abort(_("can only specify one of -C/--clean, -c/--check, "
5392 "or -m/merge"))
5394 "or -m/merge"))
5393
5395
5394 updatecheck = None
5396 updatecheck = None
5395 if check:
5397 if check:
5396 updatecheck = 'abort'
5398 updatecheck = 'abort'
5397 elif merge:
5399 elif merge:
5398 updatecheck = 'none'
5400 updatecheck = 'none'
5399
5401
5400 with repo.wlock():
5402 with repo.wlock():
5401 cmdutil.clearunfinished(repo)
5403 cmdutil.clearunfinished(repo)
5402
5404
5403 if date:
5405 if date:
5404 rev = cmdutil.finddate(ui, repo, date)
5406 rev = cmdutil.finddate(ui, repo, date)
5405
5407
5406 # if we defined a bookmark, we have to remember the original name
5408 # if we defined a bookmark, we have to remember the original name
5407 brev = rev
5409 brev = rev
5408 rev = scmutil.revsingle(repo, rev, rev).rev()
5410 rev = scmutil.revsingle(repo, rev, rev).rev()
5409
5411
5410 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
5412 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
5411
5413
5412 return hg.updatetotally(ui, repo, rev, brev, clean=clean,
5414 return hg.updatetotally(ui, repo, rev, brev, clean=clean,
5413 updatecheck=updatecheck)
5415 updatecheck=updatecheck)
5414
5416
5415 @command('verify', [])
5417 @command('verify', [])
5416 def verify(ui, repo):
5418 def verify(ui, repo):
5417 """verify the integrity of the repository
5419 """verify the integrity of the repository
5418
5420
5419 Verify the integrity of the current repository.
5421 Verify the integrity of the current repository.
5420
5422
5421 This will perform an extensive check of the repository's
5423 This will perform an extensive check of the repository's
5422 integrity, validating the hashes and checksums of each entry in
5424 integrity, validating the hashes and checksums of each entry in
5423 the changelog, manifest, and tracked files, as well as the
5425 the changelog, manifest, and tracked files, as well as the
5424 integrity of their crosslinks and indices.
5426 integrity of their crosslinks and indices.
5425
5427
5426 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
5428 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
5427 for more information about recovery from corruption of the
5429 for more information about recovery from corruption of the
5428 repository.
5430 repository.
5429
5431
5430 Returns 0 on success, 1 if errors are encountered.
5432 Returns 0 on success, 1 if errors are encountered.
5431 """
5433 """
5432 return hg.verify(repo)
5434 return hg.verify(repo)
5433
5435
5434 @command('version', [] + formatteropts, norepo=True)
5436 @command('version', [] + formatteropts, norepo=True)
5435 def version_(ui, **opts):
5437 def version_(ui, **opts):
5436 """output version and copyright information"""
5438 """output version and copyright information"""
5437 opts = pycompat.byteskwargs(opts)
5439 opts = pycompat.byteskwargs(opts)
5438 if ui.verbose:
5440 if ui.verbose:
5439 ui.pager('version')
5441 ui.pager('version')
5440 fm = ui.formatter("version", opts)
5442 fm = ui.formatter("version", opts)
5441 fm.startitem()
5443 fm.startitem()
5442 fm.write("ver", _("Mercurial Distributed SCM (version %s)\n"),
5444 fm.write("ver", _("Mercurial Distributed SCM (version %s)\n"),
5443 util.version())
5445 util.version())
5444 license = _(
5446 license = _(
5445 "(see https://mercurial-scm.org for more information)\n"
5447 "(see https://mercurial-scm.org for more information)\n"
5446 "\nCopyright (C) 2005-2017 Matt Mackall and others\n"
5448 "\nCopyright (C) 2005-2017 Matt Mackall and others\n"
5447 "This is free software; see the source for copying conditions. "
5449 "This is free software; see the source for copying conditions. "
5448 "There is NO\nwarranty; "
5450 "There is NO\nwarranty; "
5449 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5451 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5450 )
5452 )
5451 if not ui.quiet:
5453 if not ui.quiet:
5452 fm.plain(license)
5454 fm.plain(license)
5453
5455
5454 if ui.verbose:
5456 if ui.verbose:
5455 fm.plain(_("\nEnabled extensions:\n\n"))
5457 fm.plain(_("\nEnabled extensions:\n\n"))
5456 # format names and versions into columns
5458 # format names and versions into columns
5457 names = []
5459 names = []
5458 vers = []
5460 vers = []
5459 isinternals = []
5461 isinternals = []
5460 for name, module in extensions.extensions():
5462 for name, module in extensions.extensions():
5461 names.append(name)
5463 names.append(name)
5462 vers.append(extensions.moduleversion(module) or None)
5464 vers.append(extensions.moduleversion(module) or None)
5463 isinternals.append(extensions.ismoduleinternal(module))
5465 isinternals.append(extensions.ismoduleinternal(module))
5464 fn = fm.nested("extensions")
5466 fn = fm.nested("extensions")
5465 if names:
5467 if names:
5466 namefmt = " %%-%ds " % max(len(n) for n in names)
5468 namefmt = " %%-%ds " % max(len(n) for n in names)
5467 places = [_("external"), _("internal")]
5469 places = [_("external"), _("internal")]
5468 for n, v, p in zip(names, vers, isinternals):
5470 for n, v, p in zip(names, vers, isinternals):
5469 fn.startitem()
5471 fn.startitem()
5470 fn.condwrite(ui.verbose, "name", namefmt, n)
5472 fn.condwrite(ui.verbose, "name", namefmt, n)
5471 if ui.verbose:
5473 if ui.verbose:
5472 fn.plain("%s " % places[p])
5474 fn.plain("%s " % places[p])
5473 fn.data(bundled=p)
5475 fn.data(bundled=p)
5474 fn.condwrite(ui.verbose and v, "ver", "%s", v)
5476 fn.condwrite(ui.verbose and v, "ver", "%s", v)
5475 if ui.verbose:
5477 if ui.verbose:
5476 fn.plain("\n")
5478 fn.plain("\n")
5477 fn.end()
5479 fn.end()
5478 fm.end()
5480 fm.end()
5479
5481
5480 def loadcmdtable(ui, name, cmdtable):
5482 def loadcmdtable(ui, name, cmdtable):
5481 """Load command functions from specified cmdtable
5483 """Load command functions from specified cmdtable
5482 """
5484 """
5483 overrides = [cmd for cmd in cmdtable if cmd in table]
5485 overrides = [cmd for cmd in cmdtable if cmd in table]
5484 if overrides:
5486 if overrides:
5485 ui.warn(_("extension '%s' overrides commands: %s\n")
5487 ui.warn(_("extension '%s' overrides commands: %s\n")
5486 % (name, " ".join(overrides)))
5488 % (name, " ".join(overrides)))
5487 table.update(cmdtable)
5489 table.update(cmdtable)
@@ -1,154 +1,169 b''
1 Test changesets filtering during exchanges (some tests are still in
1 Test changesets filtering during exchanges (some tests are still in
2 test-obsolete.t)
2 test-obsolete.t)
3
3
4 $ cat >> $HGRCPATH << EOF
4 $ cat >> $HGRCPATH << EOF
5 > [experimental]
5 > [experimental]
6 > evolution=createmarkers
6 > evolution=createmarkers
7 > EOF
7 > EOF
8
8
9 Push does not corrupt remote
9 Push does not corrupt remote
10 ----------------------------
10 ----------------------------
11
11
12 Create a DAG where a changeset reuses a revision from a file first used in an
12 Create a DAG where a changeset reuses a revision from a file first used in an
13 extinct changeset.
13 extinct changeset.
14
14
15 $ hg init local
15 $ hg init local
16 $ cd local
16 $ cd local
17 $ echo 'base' > base
17 $ echo 'base' > base
18 $ hg commit -Am base
18 $ hg commit -Am base
19 adding base
19 adding base
20 $ echo 'A' > A
20 $ echo 'A' > A
21 $ hg commit -Am A
21 $ hg commit -Am A
22 adding A
22 adding A
23 $ hg up 0
23 $ hg up 0
24 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
24 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
25 $ hg revert -ar 1
25 $ hg revert -ar 1
26 adding A
26 adding A
27 $ hg commit -Am "A'"
27 $ hg commit -Am "A'"
28 created new head
28 created new head
29 $ hg log -G --template='{desc} {node}'
29 $ hg log -G --template='{desc} {node}'
30 @ A' f89bcc95eba5174b1ccc3e33a82e84c96e8338ee
30 @ A' f89bcc95eba5174b1ccc3e33a82e84c96e8338ee
31 |
31 |
32 | o A 9d73aac1b2ed7d53835eaeec212ed41ea47da53a
32 | o A 9d73aac1b2ed7d53835eaeec212ed41ea47da53a
33 |/
33 |/
34 o base d20a80d4def38df63a4b330b7fb688f3d4cae1e3
34 o base d20a80d4def38df63a4b330b7fb688f3d4cae1e3
35
35
36 $ hg debugobsolete 9d73aac1b2ed7d53835eaeec212ed41ea47da53a f89bcc95eba5174b1ccc3e33a82e84c96e8338ee
36 $ hg debugobsolete 9d73aac1b2ed7d53835eaeec212ed41ea47da53a f89bcc95eba5174b1ccc3e33a82e84c96e8338ee
37
37
38 Push it. The bundle should not refer to the extinct changeset.
38 Push it. The bundle should not refer to the extinct changeset.
39
39
40 $ hg init ../other
40 $ hg init ../other
41 $ hg push ../other
41 $ hg push ../other
42 pushing to ../other
42 pushing to ../other
43 searching for changes
43 searching for changes
44 adding changesets
44 adding changesets
45 adding manifests
45 adding manifests
46 adding file changes
46 adding file changes
47 added 2 changesets with 2 changes to 2 files
47 added 2 changesets with 2 changes to 2 files
48 $ hg -R ../other verify
48 $ hg -R ../other verify
49 checking changesets
49 checking changesets
50 checking manifests
50 checking manifests
51 crosschecking files in changesets and manifests
51 crosschecking files in changesets and manifests
52 checking files
52 checking files
53 2 files, 2 changesets, 2 total revisions
53 2 files, 2 changesets, 2 total revisions
54
54
55 Adding a changeset going extinct locally
55 Adding a changeset going extinct locally
56 ------------------------------------------
56 ------------------------------------------
57
57
58 Pull a changeset that will immediatly goes extinct (because you already have a
58 Pull a changeset that will immediatly goes extinct (because you already have a
59 marker to obsolete him)
59 marker to obsolete him)
60 (test resolution of issue3788)
60 (test resolution of issue3788)
61
61
62 $ hg phase --draft --force f89bcc95eba5
62 $ hg phase --draft --force f89bcc95eba5
63 $ hg phase -R ../other --draft --force f89bcc95eba5
63 $ hg phase -R ../other --draft --force f89bcc95eba5
64 $ hg commit --amend -m "A''"
64 $ hg commit --amend -m "A''"
65 $ hg --hidden --config extensions.mq= strip --no-backup f89bcc95eba5
65 $ hg --hidden --config extensions.mq= strip --no-backup f89bcc95eba5
66 $ hg pull ../other
66 $ hg pull ../other
67 pulling from ../other
67 pulling from ../other
68 searching for changes
68 searching for changes
69 adding changesets
69 adding changesets
70 adding manifests
70 adding manifests
71 adding file changes
71 adding file changes
72 added 1 changesets with 0 changes to 1 files (+1 heads)
72 added 1 changesets with 0 changes to 1 files (+1 heads)
73 (run 'hg heads' to see heads, 'hg merge' to merge)
73 (run 'hg heads' to see heads, 'hg merge' to merge)
74
74
75 check that bundle is not affected
75 check that bundle is not affected
76
76
77 $ hg bundle --hidden --rev f89bcc95eba5 --base "f89bcc95eba5^" ../f89bcc95eba5.hg
77 $ hg bundle --hidden --rev f89bcc95eba5 --base "f89bcc95eba5^" ../f89bcc95eba5.hg
78 1 changesets found
78 1 changesets found
79 $ hg --hidden --config extensions.mq= strip --no-backup f89bcc95eba5
79 $ hg --hidden --config extensions.mq= strip --no-backup f89bcc95eba5
80 $ hg unbundle ../f89bcc95eba5.hg
80 $ hg unbundle ../f89bcc95eba5.hg
81 adding changesets
81 adding changesets
82 adding manifests
82 adding manifests
83 adding file changes
83 adding file changes
84 added 1 changesets with 0 changes to 1 files (+1 heads)
84 added 1 changesets with 0 changes to 1 files (+1 heads)
85 (run 'hg heads' to see heads)
85 (run 'hg heads' to see heads)
86
87 check-that bundle can contain markers:
88
89 $ hg bundle --hidden --rev f89bcc95eba5 --base "f89bcc95eba5^" ../f89bcc95eba5-obs.hg --config experimental.evolution.bundle-obsmarker=1
90 1 changesets found
91 $ hg debugbundle ../f89bcc95eba5.hg
92 Stream params: sortdict([('Compression', 'BZ')])
93 changegroup -- "sortdict([('version', '02'), ('nbchanges', '1')])"
94 f89bcc95eba5174b1ccc3e33a82e84c96e8338ee
95 $ hg debugbundle ../f89bcc95eba5-obs.hg
96 Stream params: sortdict([('Compression', 'BZ')])
97 changegroup -- "sortdict([('version', '02'), ('nbchanges', '1')])"
98 f89bcc95eba5174b1ccc3e33a82e84c96e8338ee
99 obsmarkers -- 'sortdict()'
100
86 $ cd ..
101 $ cd ..
87
102
88 pull does not fetch excessive changesets when common node is hidden (issue4982)
103 pull does not fetch excessive changesets when common node is hidden (issue4982)
89 -------------------------------------------------------------------------------
104 -------------------------------------------------------------------------------
90
105
91 initial repo with server and client matching
106 initial repo with server and client matching
92
107
93 $ hg init pull-hidden-common
108 $ hg init pull-hidden-common
94 $ cd pull-hidden-common
109 $ cd pull-hidden-common
95 $ touch foo
110 $ touch foo
96 $ hg -q commit -A -m initial
111 $ hg -q commit -A -m initial
97 $ echo 1 > foo
112 $ echo 1 > foo
98 $ hg commit -m 1
113 $ hg commit -m 1
99 $ echo 2a > foo
114 $ echo 2a > foo
100 $ hg commit -m 2a
115 $ hg commit -m 2a
101 $ cd ..
116 $ cd ..
102 $ hg clone --pull pull-hidden-common pull-hidden-common-client
117 $ hg clone --pull pull-hidden-common pull-hidden-common-client
103 requesting all changes
118 requesting all changes
104 adding changesets
119 adding changesets
105 adding manifests
120 adding manifests
106 adding file changes
121 adding file changes
107 added 3 changesets with 3 changes to 1 files
122 added 3 changesets with 3 changes to 1 files
108 updating to branch default
123 updating to branch default
109 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
124 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
110
125
111 server obsoletes the old head
126 server obsoletes the old head
112
127
113 $ cd pull-hidden-common
128 $ cd pull-hidden-common
114 $ hg -q up -r 1
129 $ hg -q up -r 1
115 $ echo 2b > foo
130 $ echo 2b > foo
116 $ hg -q commit -m 2b
131 $ hg -q commit -m 2b
117 $ hg debugobsolete 6a29ed9c68defff1a139e5c6fa9696fb1a75783d bec0734cd68e84477ba7fc1d13e6cff53ab70129
132 $ hg debugobsolete 6a29ed9c68defff1a139e5c6fa9696fb1a75783d bec0734cd68e84477ba7fc1d13e6cff53ab70129
118 $ cd ..
133 $ cd ..
119
134
120 client only pulls down 1 changeset
135 client only pulls down 1 changeset
121
136
122 $ cd pull-hidden-common-client
137 $ cd pull-hidden-common-client
123 $ hg pull --debug
138 $ hg pull --debug
124 pulling from $TESTTMP/pull-hidden-common (glob)
139 pulling from $TESTTMP/pull-hidden-common (glob)
125 query 1; heads
140 query 1; heads
126 searching for changes
141 searching for changes
127 taking quick initial sample
142 taking quick initial sample
128 query 2; still undecided: 2, sample size is: 2
143 query 2; still undecided: 2, sample size is: 2
129 2 total queries
144 2 total queries
130 1 changesets found
145 1 changesets found
131 list of changesets:
146 list of changesets:
132 bec0734cd68e84477ba7fc1d13e6cff53ab70129
147 bec0734cd68e84477ba7fc1d13e6cff53ab70129
133 listing keys for "phases"
148 listing keys for "phases"
134 listing keys for "bookmarks"
149 listing keys for "bookmarks"
135 bundle2-output-bundle: "HG20", 3 parts total
150 bundle2-output-bundle: "HG20", 3 parts total
136 bundle2-output-part: "changegroup" (params: 1 mandatory 1 advisory) streamed payload
151 bundle2-output-part: "changegroup" (params: 1 mandatory 1 advisory) streamed payload
137 bundle2-output-part: "listkeys" (params: 1 mandatory) 58 bytes payload
152 bundle2-output-part: "listkeys" (params: 1 mandatory) 58 bytes payload
138 bundle2-output-part: "listkeys" (params: 1 mandatory) empty payload
153 bundle2-output-part: "listkeys" (params: 1 mandatory) empty payload
139 bundle2-input-bundle: with-transaction
154 bundle2-input-bundle: with-transaction
140 bundle2-input-part: "changegroup" (params: 1 mandatory 1 advisory) supported
155 bundle2-input-part: "changegroup" (params: 1 mandatory 1 advisory) supported
141 adding changesets
156 adding changesets
142 add changeset bec0734cd68e
157 add changeset bec0734cd68e
143 adding manifests
158 adding manifests
144 adding file changes
159 adding file changes
145 adding foo revisions
160 adding foo revisions
146 added 1 changesets with 1 changes to 1 files (+1 heads)
161 added 1 changesets with 1 changes to 1 files (+1 heads)
147 bundle2-input-part: total payload size 476
162 bundle2-input-part: total payload size 476
148 bundle2-input-part: "listkeys" (params: 1 mandatory) supported
163 bundle2-input-part: "listkeys" (params: 1 mandatory) supported
149 bundle2-input-part: total payload size 58
164 bundle2-input-part: total payload size 58
150 bundle2-input-part: "listkeys" (params: 1 mandatory) supported
165 bundle2-input-part: "listkeys" (params: 1 mandatory) supported
151 bundle2-input-bundle: 2 parts total
166 bundle2-input-bundle: 2 parts total
152 checking for updated bookmarks
167 checking for updated bookmarks
153 updating the branch cache
168 updating the branch cache
154 (run 'hg heads' to see heads, 'hg merge' to merge)
169 (run 'hg heads' to see heads, 'hg merge' to merge)
General Comments 0
You need to be logged in to leave comments. Login now